Repository navigation
refactor(terminal): one commit module for terminal topology closes, with a boundary check - #25329
Conversation
…s into terminal-topology advanceTerminalTopologyRevision, findTerminalTabIdForLeaf and hasHostAuthoritativeTerminalMembership move verbatim from the renderer-save membership rebase into persistence/terminal-topology, the home of the commit boundary. Importers are repointed; no behavior change.
…t boundary The three session sinks now publish through one commitWorkspaceSessionPartition helper, which hands the prior and published partition to the topology write guard. Production never arms the guard, so each sink pays one global lookup. The unit suite arms it in report mode: a sink write that changes class-(a) topology (membership, root, bindings, titles, incarnations, sleeping records, remote session ids, tombstones, default-applied, revision) outside a commit scope is attributed to its writer's file by stack, and fails the test unless the writer is on the unrouted-writers allowlist that later routing PRs shrink. Renderer saves and test seeding are exempt. Deep-freeze is available but stays off suite-wide until the in-place writers return new sessions.
…seLeaf and closeTab terminal-topology-commit.ts is the boundary for class-(a) terminal topology. bindLeaf forwards to persistPtyBinding, whose write now runs in a commit scope; the spawn commits and the relay reattach bind through it. closeLeaf and closeTab wrap the existing close mutation in a commit scope and one persistence.terminal-topology span (kind, outcome, refusal reason; no ids), and the runtime close goes through them. Session output is unchanged: tests compare it byte for byte with the old writers for local, ssh: and folder workspaces.
…root The guard read a frame's file through its last /src/ segment, so a test under tests/ (folder-upgrade-identity-persistence.unit.test.ts) had no source frame and failed as an unknown writer. Frames are now taken relative to the repo root the setup passes in, tests/ counts as test seeding, Windows backslashes are normalized before the node_modules skip, and nested src/ paths keep their full path. The two runtime funnel files skip only their funnel function, so another writer in them still shows. The R9 allowlist key names the file whose frame actually writes. The class-(a) diff and the attribution move into their own files; the stack limit is restored in a finally.
…he boundary ratchet bindLeaf and the commit scope inside persistPtyBinding changed nothing: the binding write never reaches a session sink, and a scope inside the Store method would have admitted every direct caller once it did. Both return in B1-4; the spawn commits and the relay reattach call persistPtyBinding directly again. The runtime close now calls one closeLeafOrTab entry, so its callbacks keep their contextual types. A census test is the primary enforcement: only persistence/terminal-topology and the callers it lists may call persistPtyBinding, the session setters or the three sinks, and every unrouted-writer allowlist entry must name an existing file.
Under happy-dom the global URL is not Node's, so fileURLToPath(new URL(...)) threw in the setup file and failed every happy-dom test file.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (2)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughTerminal membership helpers now reside in terminal-topology persistence, and runtime and test imports use that module. The workspace-session setter is now named Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The previously reported caller-check bypasses are addressed for the cited call forms. No actionable merge-blocking risk remains after normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to Terminal ownership checks and close permissions remain unchanged. The main remaining risk is that an exceptional diagnostic failure could interrupt closing a terminal and disable further saving. No new attack path was established. Retained concerns
Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
ℹ️ No critical issues — one classification fix and one coverage note, both informational.
Reviewed changes
Foundation refactor for the single-writer terminal topology series (STA-9417, STA-9259). No user-visible behavior change; the only production delta is a new persistence.terminal-topology span on each close.
- New
persistence/terminal-topology/module.terminal-topology-commit.tswraps the existingterminalSurfaceCloseMutationincloseLeafOrTaband emits one low-cardinality span per close;terminal-topology-membership.tsreceives the revision/leaf-lookup helpers moved verbatim fromruntime/workspace-session-terminal-membership-authority.ts. - Sinks funnel through one helper.
setLocalWorkspaceSession,setHostWorkspaceSession, andpublishSessionnow publish viacommitWorkspaceSessionPartition, preserving the local-vs-host partition split. - Boundary ratchet. A new test scans non-test
src/**and asserts only an explicit allowlist callspersistPtyBinding, the session setters, the three sinks, orcommitWorkspaceSessionPartition; it also fails when a listed caller stops calling. - Test-only write guard. Armed suite-wide by a vitest setup file; classifies class-(a) topology changes and fails tests whose sink write bypasses the commit module. Freeze stays off suite-wide because the binding write still mutates in place.
- Moved call sites. Every importer of the moved membership helpers was updated; no stale imports remain. New tests pass locally (56 across the four new files), and the ratchet is green at head.
I verified that production behavior is preserved: the helper reproduces the prior assignments, setHostWorkspaceSession is only reached with a non-local host, and runDurableMutation runs the mutation exactly once so the span cannot double-emit.
ℹ️ The boundary check does not see direct session writes
The ratchet asserts that only allowlisted files call a fixed set of function names, and the write guard only observes writes that pass through commitWorkspaceSessionPartition. Neither sees a direct state.workspaceSession = … / state.workspaceSessionsByHostId = …, nor an in-place mutation of an already-published session. Several production paths do exactly that and change class-(a) fields today, so the "one writer" boundary can be crossed without either check firing.
Technical details
# Direct session writes bypass both enforcement mechanisms
## Affected sites (class-(a) impact)
- `src/main/persistence/loading-store/session-host-partitions.ts:142,145` — `removeWorkspaceSessionOwnerInPartition` (deletes tabs/layouts/incarnations/tombstones/revision via `removeWorkspaceSessionOwner`)
- `src/main/persistence/restoring-sessions/session-owner-removal.ts:84,95` — `removeWorkspaceSessionOwnerEverywhere`
- `src/main/persistence/loading-store/repo-lifecycle-operations.ts:79-88,113-131,151-155`
- `src/main/persistence/tracking-repos/repo-worktree-pruning.ts:108,117`
- `src/main/persistence/tracking-repos/worktree-identity-migration.ts:324-326` — in-place mutation of published sessions
- `src/main/persistence/loading-store/pty-binding-session-update.ts` (called from `pty-binding-persistence.ts:154`) — in-place binding mutation; the PR already acknowledges this via `freeze:false`
## Required outcome
- Decide whether these are in scope for the series. If yes, extend the ratchet to flag direct assignments to the session fields (not only calls to the named functions), or route them through `commitWorkspaceSessionPartition`; if they are deliberately out of scope, record that so "one writer" is not read as complete.deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
…ry ratchet enforces The AST boundary ratchet is the enforcement for B1. The stack-attributed runtime guard, its class-(a) diff, the unrouted-writer allowlist, the vitest setup and the freeze option are removed; it saw two writers in the whole unit suite and its real value starts only once binding reaches a sink (B1-4). Also: one closeLeafOrTab wraps the close in the span (no per-kind copies or narrowed types), the span has one finish like persistence.pty-binding, the sink helper is publishWorkspaceSessionPartition (it publishes; the commit boundary is the module), the ratchet drops the private publishSession row and checks that every listed caller file exists, and the close comparison keeps its two meaningful cases with span cases chosen by name.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/persistence/terminal-topology/terminal-topology-boundary-ratchet.test.ts (1)
62-66: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winDetect string-literal element-access calls to listed sinks.
A new production call such as
store['setWorkspaceSession'](session)passes the text prefilter, butcalleeNamereturnsnullfor its element-access expression. The caller is omitted from the exact-caller assertion. Handle string-literal element access; alias resolution is not needed for this call form.Suggested fix
function calleeName(callee: ts.Expression): string | null { if (ts.isIdentifier(callee)) { return callee.text } - return ts.isPropertyAccessExpression(callee) ? callee.name.text : null + if (ts.isPropertyAccessExpression(callee)) { + return callee.name.text + } + return ts.isElementAccessExpression(callee) && callee.argumentExpression && + ts.isStringLiteral(callee.argumentExpression) + ? callee.argumentExpression.text + : null }
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
3e93541e-fad6-49cb-96de-4d3ecde2f541
📒 Files selected for processing (8)
src/main/persistence/loading-store/session-host-partitions.tssrc/main/persistence/loading-store/session-snapshot-operations.tssrc/main/persistence/loading-store/workspace-session-partition-publication.tssrc/main/persistence/loading-store/workspace-session-snapshot-publication.tssrc/main/persistence/terminal-topology/terminal-topology-boundary-ratchet.test.tssrc/main/persistence/terminal-topology/terminal-topology-commit.test.tssrc/main/persistence/terminal-topology/terminal-topology-commit.tssrc/main/persistence/terminal-topology/terminal-topology-write-span.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Incremental re-review of the delta since the prior pullfrog review (b1f5fd6): the commit that drops the test-only runtime topology write guard and renames the publish helper. The prior review covered the other 7 commits.
- Removed the runtime write guard. Deleted the test-only guard, its class-(a) diff, writer attribution, the unrouted-writer allowlist, and the vitest setup that armed it; the AST boundary ratchet is now the sole enforcement.
- Renamed the sink helper.
commitWorkspaceSessionPartition→publishWorkspaceSessionPartition(workspace-session-partition-commit.ts→workspace-session-partition-publication.ts); the guard's observation calls are gone and the local-vs-host assignment is unchanged. - Simplified the commit wrapper and span.
closeLeafOrTabis now one wrapper (no per-kind helpers or narrowed target types), and the span exposes a singlefinish(outcome, detail)in place of the separatefinish/fail. - Updated the ratchet. Dropped the private
publishSessionrow (its call sites reach the now-tracked helper), renamed the helper row, and the existence check now covers every listed caller file. - Trimmed the close test. Byte-equality now covers a pane close and a tab close, plus the four span outcomes.
The prior titlesByLeafId classification thread is resolved by deleting the class-(a) diff. I verified the ratchet and commit tests pass (pnpm exec vitest run --config config/vitest.config.ts, 15 tests) and tsc --noEmit -p config/tsconfig.node.json is clean; a grep confirms no dangling references to the removed modules.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
…hey enforce - Point the acknowledged-tab-retirement audit fixture at the moved advanceTerminalTopologyRevision; its old import no longer resolved. - Drop publishWorkspaceSessionPartition: it was the removed guard's interception point, so the three session sinks return to origin/main. - One traced(kind, mutate) wrapper in the commit file replaces the span factory; closeLeafOrTab is one call. - The ratchet walks src/main with the shared scanSourceTree, drops the loading-store-internal rows and the redundant file-exists test; exact-set equality already fails on a missing file. - The commit test is a pure unit test of the span outcomes: no Store harness, electron mock or self-comparing close.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Incremental re-review of the delta since the prior pullfrog review (61982b0): the single trim commit d54fc73. The earlier 8 commits were covered by the two prior reviews.
- Reverted the sink funnel.
publishWorkspaceSessionPartitionand thesession-host-partitions.ts/session-snapshot-operations.ts/workspace-session-snapshot-publication.tschanges are gone, so the three sinks are back to their base implementation and the ratchet no longer tracks them. - Narrowed the boundary ratchet. It now scans
src/mainthrough the sharedscanSourceTree, uses paths relative tosrc/main, tracks onlypersistPtyBindingplus the four session setters, drops the redundant existence check, and exempts the audit fixture viaTEST_SUPPORT. - Inlined the span.
terminal-topology-write-span.tsis deleted;terminal-topology-commit.tsowns a privatetracedhelper that emits the samepersistence.terminal-topologyspan. - Trimmed the commit test. Byte-equality against
terminalSurfaceCloseMutationis dropped; the test now asserts the five span outcomes.
The one prior inline thread (titlesByLeafId) is resolved. I re-ran the ratchet/commit/membership tests (14) and the repointed close/binding suites (46), and tsc --noEmit -p config/tsconfig.node.json is clean.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
… drop stage ids from comments The controller's setter was named set, which the boundary census could not list without matching every Map.set, so a new OrcaRuntime mixin could write sessions through it unseen. Rename it setForWorktree and census it. Comments now describe state instead of citing plan stage ids.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
0c00dced-f673-4dae-a904-b15eacff1be0
📒 Files selected for processing (4)
src/main/persistence/terminal-topology/terminal-topology-boundary-ratchet.test.tssrc/main/persistence/terminal-topology/terminal-topology-commit.tssrc/main/runtime/orca-runtime-get-runtime-id.tssrc/main/runtime/runtime-workspace-session-controller.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/persistence/terminal-topology/terminal-topology-commit.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
…llback - traced() takes refusalOf instead of assuming an Error refusal, and only mutate() sits in the try, so a span outcome of threw means the write threw. - The boundary ratchet counts references, not just direct calls: non-null calls, bracket keys, aliases, destructures, .call/.bind and parenthesized callees all count; declared names and type positions do not. - Census terminalSurfaceCloseMutation (boundary-only) and the partition sinks setLocalWorkspaceSession / setHostWorkspaceSession.
…ns, skip type-only imports and local declarations The census skipped ExpressionWithTypeArguments as a type, which also holds `extends f(x)` and `x<T>` value expressions. Type-only import/export specifiers and declared names (variables, parameters, accessors, enum members) no longer count as uses. The audit fixture is listed in the table instead of a separate exemption.
…inition Telling definitions from uses per syntax kind kept missing nested and for-of destructures. Exempt only the writer's own function or class-member definition; any other mention (including object-literal keys) counts, so the census errs toward a loud false alarm rather than a silent miss. Quoted names count only in member-name position.
Member-name positions missed wrapped keys like store[('name')] and
store['name' as const]. Counting every string literal outside types is
shorter and errs toward a loud false alarm.
…initions Object-literal methods and accessors were exempt while equivalent arrow properties counted; all object-literal keys now count alike.
A name spelled with a \u escape never appears verbatim, so the text prefilter skipped it.
\x, identity and line-continuation escapes also decode to a writer name without it appearing verbatim.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Incremental re-review of the delta since the prior pullfrog review (d54fc73): the census rewrite that turns the boundary ratchet from a call-name check into a reference census, plus its supporting refactor.
- Ratchet rewritten as a reference census.
terminal-topology-boundary-ratchet.test.tsnow parses each non-testsrc/mainfile with parent nodes and records any identifier or string literal naming a listed writer, excluding the writer's own function/class-member definition and type-only nodes. This catches element-access, alias, destructure,.call/.bind, andextendsforms the prior call-only check missed. - Allowlist regrown to the reference semantics.
setWorkspaceSessionexpands to every referencing file;setLocalWorkspaceSession,setHostWorkspaceSession,setForWorktree, andterminalSurfaceCloseMutation(empty outside the boundary) gain their own rows, all relative tosrc/main. The audit fixture is now listed directly, replacing theTEST_SUPPORTexemption. - Escape-aware prefilter. Files are parsed when they contain any backslash, not just
\u, so a writer name spelled with a hex/unicode escape is still seen; the raw-text name prefilter is unchanged. setrenamedsetForWorktree. The runtime session controller's write and its single caller inorca-runtime-get-runtime-id.tsare renamed so the census can list it without matching everyMap.set.- Commit span refusal by callback.
tracednow takes arefusalOfcallback and reads the mutation result outside thetry, sotopology.outcome: 'threw'means the write threw, never tracing.
I confirmed production behavior is unchanged (the only delta is the span's shape and the rename), and verified the ratchet/commit tests (14), the repointed close/binding suites (46), and pnpm tc:node are green.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
…'s boundary ratchet (#25823) Main's #25329 added the ratchet; phase3's mobile-session-editor-projection.ts writes the host's own session through setWorkspaceSessionForWorktree, the same way the listed headless mobile-session tab writers do. Co-authored-by: m4air <[email protected]>

ELI5
The terminal layout (which tabs exist, which panes they hold, and which process each pane shows) is changed from many places in the main process. This PR adds the single place those changes are meant to go through and sends the explicit tab/pane close through it. It also adds a test that fails when new code outside that place starts calling the session or binding writers. Users see no difference.
What Changed
src/main/persistence/terminal-topology/module.terminal-topology-commit.tsexposescloseLeafOrTab. It runs today's close (terminalSurfaceCloseMutation) unchanged, inside onepersistence.terminal-topologytrace span. The span records the kind (close_leaf/close_tab), the outcome (committed/noop/refused/threw) and the fixed refusal code. It carries no ids, paths or pane keys. The runtime's close (closeTerminalSurface) now calls it.terminal-topology-membership.tstakes three helpers moved verbatim fromruntime/workspace-session-terminal-membership-authority.ts:advanceTerminalTopologyRevision,findTerminalTabIdForLeafandhasHostAuthoritativeTerminalMembership. Their importers are repointed, including thedocs/audits/acknowledged-tab-retirementfixture.terminal-topology-boundary-ratchet.test.ts). It parses every non-test file undersrc/mainand pins, as an exact set, which files reference each named layout writer: the binding writerpersistPtyBinding, the session setterssetWorkspaceSession,patchWorkspaceSession,stageWorkspaceSessionBeforeUnload,setWorkspaceSessionForWorktree, the runtime controller'ssetForWorktree, the partition sinkssetLocalWorkspaceSession/setHostWorkspaceSession, and the close transformterminalSurfaceCloseMutation(no file outside the module may use it). Code underterminal-topology/is always allowed.!call,x['name'], an alias, any destructure (renamed, quoted-key or into existing variables),.call/.bind, anextendsargument. Type-only mentions (includingimport type) and the writers' own definitions (functions, class members) don't count. Every other mention of the name does, including object-literal keys: the check prefers a loud false alarm to a silent miss. A name computed at runtime (store[key],Reflect.get) can't be seen by any name-based check.getWorkspaceSessionreturns, and lifecycle writers (repo/worktree removal, identity rekey, SSH lease marks dropping a dead PTY's binding), which delete or rekey layout but never choose it. Later PRs route the layout-choosing writers explicitly.setis renamedsetForWorktree(one caller) so the ratchet can list it without matching everyMap.set.Before/after for users: none. Every path writes the same session contents as before. The only production difference is the new trace span on every pane/tab close transaction (explicit, cleanup, or main-initiated) when diagnostic tracing is on.
Why
This is the first step of the terminal layout refactor. Later PRs move each remaining writer behind this module, deleting their ratchet rows as they go. Doing it this way leaves no parallel path behind if later steps stall: the module only wraps existing code, and the ratchet only describes today's callers.
Alternatives considered:
bindLeaf) now. Deferred to a later PR. Today the binding write never reaches a sink, so a wrapper would add nothing.Known debt: the commit module imports the close transform from
runtime/until the close logic itself moves into the module.Testing
pnpm tc, oxlint on changed files andpnpm run check:code-quality:changedpass.vitest run --config config/vitest.config.ts): the only failures also fail on base 4a41e24 on the test machine (browser-manager identity/viewport, a shell-ready repro, two fish-config-dependent shell tests, relay-region-correction).docs/audits/acknowledged-tab-retirementfixture's import is repointed. Its 20 tests fail the same way on origin/main (Writable Store construction requires a SQLite profile-state authority), so that audit was already stale before this PR.ssh-relay-session.ts.Linked Issue
Maintainer PR. Context: Linear STA-9417, STA-9259, STA-7961.
Visual Proof
N/A: no UI or behavior change (internal refactor plus a test).
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)