Skip to content

refactor(server): route socket frames by type and build the core in createCore - #1384

Merged
devswha merged 1 commit into
mainfrom
chore/core-socket-router
Oct 19, 2026
Merged

devswha merged 1 commit into
mainfrom
chore/core-socket-router

Conversation

@devswha

@devswha devswha commented Oct 19, 2026

Copy link
Copy Markdown
Owner

Last step of the server/index.ts split (design PR 11). Behaviour is unchanged.

What moves

  • server/core/socket.ts: the websocket object of Bun.serve (drain, open, message, close, the backpressure cap) and SERVER_FEATURES. FrameHandlers has one handler for every type in ClientMessage except presence, which is read from the raw frame before parsing (presenceOf), as before. A frame type added without a handler fails the build. The ping, watch, unwatch and role bodies move here (dedent, break; became return;). They stay out of connections.ts: watch checks its grid with validGeometry from terminals.ts, and terminals.ts imports connections.ts, so putting them there would add an import cycle.
  • server/core/server-core.ts: createCore builds 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 exports createCore, SocketData and connectionData. The last one is a function rather than a type, but the /ws upgrade in fetch needs it to build the socket's data.
  • server/core/ownership.test.ts: fails when a file outside server/core/ imports anything in it other than index.ts, and when index.ts exports 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_MS and SUBMIT_DEADLINE_MS stay exported here because submit.contract.test.ts imports 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 switch on message.type becomes a lookup in the handler record. A lookup must ignore what the switch ignored, so it only calls a handler when message.type is a string that is an own key of the record:

    • {"type":["ping"]} would coerce to "ping" without the string check.
    • {"type":"toString"} would find Object.prototype.toString without Object.hasOwn.
    • The lookup stays inside the try, so null still throws there and is answered command_failed, as before.

    Every case that was awaited is a Promise<void> handler. Every case that was not is a void handler, and nothing ran after the switch, so a uniform await changes 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. createCore needs devices, usage and usageLogin. 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, after machines?.stop() and before the watches and terminals close. Only settlePortalStartup moved, to the top of stop. It only sets a value that fetch reads on entry, and nothing inside the synchronous stop reads it.

Verification

  • The moved lines were rebuilt from git show origin/main:server/index.ts with sed (a different method from the generator script) and diffed. The only differences are the case-to-method lines, break; to return;, stopped to stopped(), the switch to the lookup, and const outputTimer to outputTimer.
  • Malformed frames sent to main and to this branch over a real socket got the same answers. The 37 probes included null, 5, [], {"type":["ping"]}, {"type":"toString"}, {"type":"__proto__"}, {"type":"nope"}, {"type":5}, and invalid frames of every type: all 37 identical.
  • The pins were 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,498 pass, 0 fail, 8 skip (the two new ownership tests included). bun run check integration: 589 pass, 0 fail, 1 skip.
  • ownership.test.ts was checked against a deliberate violation: adding import type { Frame } from "./core/socket.ts" to server/index.ts makes it fail and name that line.
  • No Bun.sleep moved, so scripts/fixed-sleeps.json is 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

…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]>
@coderabbitai

coderabbitai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: devswha/herdr-web-ui/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e690fb8a-0850-48f2-a2b3-719e8bba28f8
📥 Commits

Reviewing files that changed from the base of the PR and between 614dc56 and 2b0ef66.

📒 Files selected for processing: 5
  • server/core/index.ts
  • server/core/ownership.test.ts
  • server/core/server-core.ts
  • server/core/socket.ts
  • server/index.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

📝 Summary

Summary by CodeRabbit

  • Refactor
    • Consolidated server-side handling for browser connections, session updates, and pane attachment.
    • The server now coordinates startup and shutdown for these services through a shared lifecycle, while preserving existing connection and session behavior.
    • No new user-facing functionality is included in this change.

The server's terminal, input, delivery, connection, status, and WebSocket setup now runs through createCore and createSocket. server/index.ts delegates startup and shutdown to the core. The core index exports the shared API, and tests enforce imports through that index.

Changes: Server Core Composition and Access Boundary

Layer / File(s) Summary
WebSocket handling
server/core/socket.ts
createSocket handles client lifecycle, frame dispatch, presence, pane watches, role changes, and error responses.
Core composition and lifecycle
server/core/index.ts, server/core/server-core.ts
The core factory composes server services, starts delivery expiration and output reconciliation, and stops services, timers, watches, and attachments.
Server integration and access boundary
server/index.ts, server/core/ownership.test.ts
The server delegates setup, WebSocket handling, startup, and shutdown to the core. Tests check imports through the core index and its named exports.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Merge Risk: ⚪ Minimal · up to 2b0ef

No actionable behavior change or merge-blocking risk is established; the change is ready for normal merge checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description check Passed The description clearly explains the refactor, behavior-preservation goals, implementation changes, risks, and validation results. It does not use the template headings exactly, but it provides the re…
Title check Passed The title clearly identifies the two primary changes: typed socket-frame routing and construction of the server core in createCore.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description clearly explains the refactor, behavior-preservation goals, implementation changes, risks, and validation results. It does not use the template headings exactly, but it provides the required Change and Validation information.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@devswha
devswha merged commit a661220 into main Oct 19, 2026
17 checks passed
@devswha
devswha deleted the chore/core-socket-router branch October 19, 2026 11:39
devswha added a commit that referenced this pull request Oct 19, 2026
…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]>
devswha added a commit that referenced this pull request Oct 19, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant