Repository navigation
refactor(server): route socket frames by type and build the core in createCore - #1384
Conversation
…reateCore The WebSocket object moves to server/core/socket.ts. Each frame type a client sends has one handler in FrameHandlers, so a new type without one fails the build; an unknown or non-string type is still ignored. The ping, watch, unwatch and role bodies move with it (break became return). createCore (server/core/server-core.ts) builds the registry, input lane, composer, pending delivery, connections, status hub and socket in the order they were built before, and owns the output timer and the stop of its services and terminals. createServer keeps the HTTP routes, Portal and the bridge registration, which stop through createCore's hook at the point they stopped before. server/core/index.ts exports createCore and the WebSocket's data, and ownership.test.ts fails on any other import of the core from outside. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
📝 Summary
Merge Risk: ⚪ Minimal · up to
|
…1393) Follow-ups from the merge pass's review of the `server/index.ts` split (#1365–#1384), as one PR. There is one commit per item. ## 1. Start the tailnet identity read after the Node probe again (fix) #1384 moved `createCore` after the HTTP services, and with it the PTY sidecar's Node probe. The first tailnet identity read (`identityOf(false, null)`) therefore started before the probe instead of after it. - The probe (`sidecarAvailable` → `isRealNode`) is a `Bun.spawnSync` with a 3 s timeout. - While it holds the thread, the identity read's own 2.5 s limit keeps running. - A read that is cut short leaves the owner unknown for five minutes. With no token and no paired device, that can let another tailnet user in through `open` access. Codex reproduced this with a stalled probe and a large status reply. The merge pass could not reproduce it on Linux with Bun 1.4.3, and macOS and Windows were not tried. The read now starts right after `createCore`, so it runs after the probe as it did before #1384. Nothing that `createCore` starts reads the tailnet identity. #1384 claimed the two groups were independent, and that was wrong about time: a thread blocked by one counts against the other's timeout. #1384 is unreleased, so no released behaviour changes and this PR has no changelog fragment. ## 2. Move `paneContext` out of the pane routes `server/core/input.ts` and `server/core/composer.ts` imported `paneContext` from `server/pane-routes.ts`, an HTTP route file. It now lives in `server/pane-context.ts`, and the routes, `workspace-routes.ts`, `index.ts` and the core all import it from there. The body is unchanged. ## 3. Name each frame type in the socket's handler record `createCore` used to spread `terminalFrames`, `inputFrames` and `pendingFrames` into the record that the socket looks frames up in. That had two weaknesses: - Any other key on one of those objects, such as a helper added later, would have become a frame type a client can send. - A type defined in two objects would have silently replaced one handler with the other. Each frame type is now named with its handler in an object literal passed straight to `createSocket`. I checked by editing the record and running `tsc`: - Naming a type twice fails with TS1117. - Naming a type that is not a handled frame, for example `ping`, fails with TS2353. - Leaving a type out fails with TS2741. The handlers are the same functions as before, so dispatch does not change. They are plain functions that do not use `this`. ## 4. Read the core's boundary with the TypeScript parser `ownership.test.ts` used regular expressions. They missed `require()`, a template-literal `import()` and a last export with no semicolon. Both checks now parse each file with TypeScript's parser (`typescript-api`, already in the repo for `scripts/build-xterm.ts`). - **Import check.** It reads: - import and export declarations, including type-only ones; - `import x = require()`; - `import()`, `require()`, `require.resolve()` and `mock.module()` with a string or template literal; - `import("…")` types. It resolves relative names and tsconfig's `@shared/*` alias. A template literal with substitutions counts when its fixed start already points inside `server/core/`. - **Export check.** It reads every statement of `server/core/index.ts`. `export *`, `export * as`, default exports and exported declarations all count as names. - **Fixtures.** 17 sources must be reported, including the three forms named in the review and `@shared/../server/core/…`. 9 sources must pass, among them the index in its four spellings, a mere string or comment and a template import outside the core. Every export form has its own fixture. The real scan covers `server`, `src`, `shared`, `scripts`, `site`, `telemetry` and `app`, and still asserts that it includes `server/index.ts`. ## Verification - `bun run typecheck`: clean. - `server/conventions.test.ts`, `scripts/conventions.test.ts` and `server/core/`: 29 pass, 0 fail. - Every `server/*.contract.test.ts` (39 files) with `--rerun-each 3`, run on `main` first and then on this branch: 1,602 pass, 3 skip, 0 fail on `main`, 1,602 pass, 3 skip, 0 fail on the branch. - `bun run check fast`: 4,501 pass, 0 fail, 8 skip. `bun run check integration`: 589 pass, 0 fail, 1 skip. - No `Bun.sleep` moved, and `scripts/fixed-sleeps.json` is unchanged. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This answers one open question from the `server/index.ts` split: what keeps `createServer`'s start-up order from breaking. Nothing pinned it, and #1384 broke it. That PR started the first tailnet identity read before the PTY sidecar's Node probe, and #1393 moved the read back. This PR pins the order that broke. ## The order and why it matters - The Node probe (`sidecarAvailable` → `isRealNode`) is a `Bun.spawnSync` with a 3 s timeout. - The identity read times itself (2.5 s) from the moment it starts. - If the read starts first, the probe's wait counts against the read's limit. - A read cut short leaves the owner unknown for five minutes. With no token and nothing paired, another tailnet user then gets `open` access. ## What changes - **`server/startup-order.test.ts` (new).** The test runs `createServer` with a probe that records itself and a `TailnetIdentitySource` whose status reader records itself. It waits for the read, then expects the probe first. I moved `identityOf(false, null)` back before `createCore`, as it was in #1384, and the test failed with `["identity read", "probe"]`. With the code as it is, the test passes. - **The `sidecar` option** also takes a function, a probe to run in place of the real one, the way `terminalAttach` already takes a value or a function. A boolean works exactly as before, so nothing else changes. - **No changelog fragment.** The change is a test seam and a test, and no user sees it. The handoff's other order question was about the collector's first frame carrying live OmO and Claude status. It is left to `createCore`'s comment: nothing has broken there, and it would need a much heavier test. ## Verification - `bun run typecheck` is clean. The conventions tests pass. - Pins were every contract test that passes `sidecar` (`conversation-push`, `api`, `usage-login`) plus `device-access` (the tailnet access paths). Each ran with `--rerun-each 3`, on `main` first and then on this branch: 495 pass, 0 fail on `main`, 495 pass, 0 fail on the branch. - `bun run check fast`: 4,502 pass, 0 fail, 8 skip. `bun run check integration`: 589 pass, 0 fail, 1 skip. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
Last step of the
server/index.tssplit (design PR 11). Behaviour is unchanged.What moves
server/core/socket.ts: thewebsocketobject ofBun.serve(drain,open,message,close, the backpressure cap) andSERVER_FEATURES.FrameHandlershas one handler for every type inClientMessageexceptpresence, which is read from the raw frame before parsing (presenceOf), as before. A frame type added without a handler fails the build. Theping,watch,unwatchandrolebodies move here (dedent,break;becamereturn;). They stay out ofconnections.ts:watchchecks its grid withvalidGeometryfromterminals.ts, andterminals.tsimportsconnections.ts, so putting them there would add an import cycle.server/core/server-core.ts:createCorebuilds the terminal registry, input lane, composer, pending delivery, connections, status hub and socket, in the same order and with the same same-named wrappers as before. Its header comment lists that order. It also owns the output timer and the stop of its services and terminals.server/core/index.ts: the only entrance from outside. It exportscreateCore,SocketDataandconnectionData. The last one is a function rather than a type, but the/wsupgrade infetchneeds it to build the socket's data.server/core/ownership.test.ts: fails when a file outsideserver/core/imports anything in it other thanindex.ts, and whenindex.tsexports anything besides those three names.server/index.ts(948 → 767 lines; it started at 3,703): the HTTP routes,createCore, Portal and the bridge registration.SUBMIT_DELAY_MSandSUBMIT_DEADLINE_MSstay exported here becausesubmit.contract.test.tsimports them, and the other timing constants stay beside them. All six are passed in by name, as before.What changes in the code (not in behaviour)
Dispatch. The
switchonmessage.typebecomes a lookup in the handler record. A lookup must ignore what the switch ignored, so it only calls a handler whenmessage.typeis a string that is an own key of the record:{"type":["ping"]}would coerce to"ping"without the string check.{"type":"toString"}would findObject.prototype.toStringwithoutObject.hasOwn.try, sonullstill throws there and is answeredcommand_failed, as before.Every case that was awaited is a
Promise<void>handler. Every case that was not is avoidhandler, and nothing ran after the switch, so a uniformawaitchanges nothing.Creation order. One relative order changes, and it has no effect: the sidecar check, the registry and the input lane are now created after the HTTP services (
DeviceStore, preferences, CLIProxy, usage, voice, the tailnet identity read) instead of before them.createCoreneedsdevices,usageandusageLogin. Nothing in either group reads the other:sidecarAvailable()is a memoized synchronous check,ConversationMonitor's constructor only stores its arguments, and the registry and lane only create maps. Everything inside the core keeps its order.Output timer. The timer starts where it did, after the bridge registration, through
core.start().Stop. The stop order is kept:
core.stop(beforeTerminals)runs Portal's shutdown and the registration's close at the same point as before, aftermachines?.stop()and before the watches and terminals close. OnlysettlePortalStartupmoved, to the top ofstop. It only sets a value thatfetchreads on entry, and nothing inside the synchronousstopreads it.Verification
git show origin/main:server/index.tswithsed(a different method from the generator script) and diffed. The only differences are the case-to-method lines,break;toreturn;,stoppedtostopped(), theswitchto the lookup, andconst outputTimertooutputTimer.mainand to this branch over a real socket got the same answers. The 37 probes includednull,5,[],{"type":["ping"]},{"type":"toString"},{"type":"__proto__"},{"type":"nope"},{"type":5}, and invalid frames of every type: all 37 identical.server/*.contract.test.ts(39 files) with--rerun-each 3, run onmainfirst and then on this branch: 1,602 pass, 3 skip, 0 fail onmain, 1,602 pass, 3 skip, 0 fail on the branch.bun run check fast: 4,498 pass, 0 fail, 8 skip (the two new ownership tests included).bun run check integration: 589 pass, 0 fail, 1 skip.ownership.test.tswas checked against a deliberate violation: addingimport type { Frame } from "./core/socket.ts"toserver/index.tsmakes it fail and name that line.Bun.sleepmoved, soscripts/fixed-sleeps.jsonis unchanged. There is no changelog fragment because nothing user-visible changed.Open question from the design
Nothing pins the creation order in a contract test. One option is a test that the collector's first frame already carries live OmO and Claude status. This PR relies on
createCore's order and its comment instead; is that enough, or should such a test follow?🤖 Generated with Claude Code