Skip to content

refactor(server): move the pane attach into createSpawnAttachment - #1365

Merged
devswha merged 1 commit into
mainfrom
chore/core-pane-process
Oct 19, 2026
Merged

devswha merged 1 commit into
mainfrom
chore/core-pane-process

Conversation

@devswha

@devswha devswha commented Oct 19, 2026

Copy link
Copy Markdown
Owner

Change

Step 5 of splitting the stateful core of server/index.ts by state owner. Starting a pane's terminal moves to server/core/terminal-process.ts. No behavior changes.

  • createSpawnAttachment takes spawnAttachment whole: the pty attach, the mirrored screen, the retries while herdr refuses, the take-over a user asks for and the relookup after a live handoff. terminalInfoFor and spawnFailure, which only it calls, move with it.
  • The PaneAttachment record, the ATTACH_* constants, PANE_GONE_CODES and MAX_REPLAY_BYTES move too. index.ts imports back the record type, ATTACH_HELD_MESSAGE and the four ATTACH_* defaults its options use.
  • The closure's locals (takeover, takeoverWanted, retries, refusedSince, trying, the hold buffer, attachedTerminal) stay locals of the closure, as the series' design requires.

Scope: this PR moves code and changes no type. The design's next shape for this code, an attachment that holds a PtyProcess or a MirrorProcess so that a mirror has no resize or takeOver to call, would rewrite every attachment.pty and attachment.mirror site in index.ts. It is left for the terminal registry step, which moves the attachment maps that shape is drawn against. attachments, pendingAttachments, retiringAttachments, ensureAttachment, closeAttachment, resizePty and detach stay in index.ts.

Why this is safe

  • The moved code is main's, cut by a script at each declaration's own first and last line, with its two-space indentation kept. A second check, by sequence match against main, found 429 of the 430 moved lines identical and in order.
  • The one changed line is the server-stopped check in spawnAttachment. stopped is a let that stop() sets later, so its value cannot be passed in. It is read through isStopped: () => stopped instead, and if (stopped) became if (isStopped()).
  • Every value the closure reads is passed under its old name. Each is declared above the call or is a function declaration. The call sits where terminalInfoFor was, and the factory runs nothing when it is built. ensureAttachment calls spawnAttachment only from an attach frame, after createServer returns.
  • This code decides when --takeover is passed and when an attach counts as taken, so this PR waits for a real CodeRabbit review per AGENTS.md.

server/index.ts goes from 2,330 to 1,898 lines.

Validation

  • Pins, each run 3 times (bun run check run bun test --timeout 15000 --rerun-each 3): take-over, attach-held, reattach, output and api contract tests, mirror.test and attach-output.test. 555 pass, 0 fail on an untouched main, and 555 pass, 0 fail on this branch.
  • bun run check fast: typecheck and build are ok, and 4,493 unit tests pass with 0 failures. The convention tests pass, and the fixed-sleep baseline is unchanged (no Bun.sleep moves).
  • bun run check integration: 589 pass, 0 fail, 1 skip in 44 files.

🤖 Generated with Claude Code

Step 5 of splitting the stateful core of server/index.ts by state owner.
spawnAttachment, terminalInfoFor, spawnFailure, the PaneAttachment record
and the ATTACH_* constants move as they were into createSpawnAttachment.
The closure keeps its locals. The only changed line reads the server's
stopped flag through isStopped(), as a reassigned let cannot be passed.

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: 54f646ea-c2ff-4ea3-84cb-4b1e983647db
📥 Commits

Reviewing files that changed from the base of the PR and between bf6c9d7 and 63de710.

📒 Files selected for processing: 2
  • server/core/terminal-process.ts
  • server/index.ts

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

📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved terminal attachment reliability when another connection is using the pane, including support for an interactive takeover.
    • Terminal sessions can better recover when a pane switches to a different terminal, and end cleanly when the pane is no longer available.
    • Reduced the chance of startup output or diagnostic probes appearing in the terminal, while preserving recent output for replay.
    • Terminal attachments now use the pane’s layout size when available.

The terminal attachment logic now resides in server/core/terminal-process.ts. The module defines attachment state and retry settings, creates PTY or mirrored sessions, and manages retries, takeover, handoff lookup, output, and failures. server/index.ts supplies existing state and callbacks through createSpawnAttachment.

Changes: Terminal attachment flow

Layer / File(s) Summary
Attachment state and configuration
server/core/terminal-process.ts, server/index.ts
The core module defines PaneAttachment and attachment settings. The server removes the corresponding local declarations and imports.
Session creation and lifecycle
server/core/terminal-process.ts, server/index.ts
The core module creates PTY or mirrored attachments and handles output, retries, takeover, terminal handoff lookup, and startup failures. The former local implementation is removed from the server.
Server integration
server/index.ts
The server calls createSpawnAttachment and supplies attachment state and callbacks.

Priority: ⬇️ Low

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Suggested reviewers: haeminway1

Merge Risk: ⚪ Minimal · up to 63de7

This change relocates the terminal attachment logic into its own module without changing behavior. Configuration, stop handling, and capability detection behave as before, and no outstanding issues were found, so it is ready to merge.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: moving pane attachment logic into createSpawnAttachment.
Description check Passed The description includes the required Change and Validation sections. It explains the refactor, scope, safety rationale, and reports targeted, unit, build, and integration test results.
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.
  • 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 48b356d into main Oct 19, 2026
17 checks passed
@devswha
devswha deleted the chore/core-pane-process branch October 19, 2026 05:47
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]>
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