Repository navigation
refactor(terminal): move a dragged-out pane in main before the window opens its tab - #25380
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.
… tab mounts Ported from fix/terminal-topology-stage-a (1bafc87, 3941bd4, 2ea2070, 3e79f31, a9d428e minus the bridge comment) and exposed as the commit module's moveLeaf, which runs inside the topology commit scope and span and publishes every rewritten partition through the session sink, so the test-only write guard sees it. Store.moveTerminalLeafToNewTab only hands it the store's state. Detach-to-new-tab now asks main first: the leaf and its binding move into the new tab in every owner partition (local and ssh:), with the incarnation, sleeping session, remote session id, UI marks and SSH lease, and the topology revision bumps. pty:moveLeafToNewTab then aliases the agent-status pane key and re-keys orchestration worker resources; the renderer's repeat transfer is skipped. A refused or failed move toasts and the pane stays; a move the renderer cannot apply is undone (STA-9259). Stage A review-2 fixes: - SF1: an undo whose source tab has closed retires the moved tab instead of refusing, so no ghost tab comes back on restart. - SF2: an undo restores the split direction, ratio and position, the source tab's PTY id and its SSH remote session id, from origins main kept for the move; it never adds a second copy of a leaf the source holds again. - N1: layouts of tabs that no longer exist do not refuse a move. - N2: an undo into a tab that gained a pane is refused as target_changed, not a silent not_held. - N3: a repeat drop of a pane whose move is still committing is a no-op. Note: the move bumps the topology revision, so a revision-0 repo enters rebased membership on its first detach.
…copies - An undo ignores a target layout whose tab row is gone, as the move does. - A retired undo leaves UI marks and SSH leases on the moved pane key instead of re-keying them to the closed source tab. - When an SSH respawn bound one partition before the other caught up, the move follows the renderer's live PTY id and drops the stale copy's incarnation instead of refusing with a toast. - A test pins the late-spawn graft the renderer's in-flight guard exists for.
…in holding it - A pane whose PTY spawn is still in flight is not dragged out (no toast): the late spawn result would bind it to the source tab and graft the leaf back beside its moved copy. The IPC transport reports a pending connect. - A thrown or timed-out commit (10 s bound) sends an undo, since the write may have landed; undo answers not_held when nothing moved. The in-flight entry clears with it, so a stalled main cannot wedge the pane's drag. - A throw while opening the new tab after the pane left its source undoes the move too. - No "stays where it was" toast when the undo found the source tab closed or the source pane is gone; a failed undo says the pane may open in a new tab after a restart instead.
…main's undo If opening the moved pane's tab throws after createTab ran, the renderer now closes that tab without killing its PTY or telling main (main never had it), and restores the source layout, while main undoes the move.
…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.
# Conflicts: # src/main/persistence/terminal-topology/terminal-topology-commit.ts
Once main commits a pane move, the renderer only rolls forward: - A repeat of a committed move answers moved and writes nothing, so a thrown commit (outcome unknown) is retried, up to three attempts; the IPC skips the agent-status transfer it already made. - The renderer applies the move by leaf id. If the user closed the pane or its tab meanwhile, it closes main's new tab through the ordinary session:close-terminal-surface path; if a sibling closed and the pane is the source's last, the source tab closes without killing the PTY. - One toast, for a move main refused or never answered. Deleted: the undo planner, origin ledger, undo flag, retired and target_changed results, the commit timeout, the half-opened-tab cleanup and the second toast. Also: one request validation (distinct tabs, stable leaf id, tab ids a pane key can carry, built through makePaneKey); a two-line PTY check where the live PTY id wins; the move and close share one span wrapper; the moved tab's layout always takes the live PTY id (a stale saved id was kept before); fallbackPtyId is now livePtyId; tests are organized by behavior.
…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.
# Conflicts: # src/main/persistence/terminal-topology/terminal-topology-commit.ts # src/main/persistence/terminal-topology/terminal-topology-write-span.ts
…attempt A sibling closed while main committed the move persists the source layout down to the moved leaf, so the renderer took that for "pane gone" and closed main's new tab while the pane was live: after a restart it was held nowhere. The renderer now reads the store layout: when the moved leaf is the only one left it opens the new tab with that layout, syncs PTY ownership, and closes the source tab without killing the PTY. Main's new tab is closed only when main moved the pane and it is gone here. Also: - One commit attempt; the repeat answer, the retry loop and the IPC alias guard never ran in production (a write with an unknown outcome faults the writer, so every retry rethrows before it reaches the move). - traced takes a typed refusalOf; one write-and-restore helper and a shared partition assign replace the duplicated local/remote and rollback checks. - The planner's holders carry their source tab and layout, so the partition move cannot fail; pane-keyed UI marks are re-keyed in one loop; the request validator calls makePaneKey directly. - applyMove looks the pane up once and takes one PTY id (main's when it moved the pane); the move-commit file is inlined; duplicated renderer tests are removed and the commit-path tests live together.
There was a problem hiding this comment.
Important
One latent owner-cleanup gap in the new main-side move: a layout of a removed tab that still names the moved leaf is neither moved nor cleaned, and findTerminalTabIdForLeaf will resolve the pane to that dead tab after the move. Details inline.
Reviewed changes
- New move contract —
src/shared/terminal-leaf-move.tsaddsTerminalLeafMoveRequest/TerminalLeafMoveResult,isTerminalLeafMoveRequestvalidation, and pane-key derivation. - Main commits the move first —
pty:moveLeafToNewTab→commitLeafMoveAndRekey→moveTerminalLeafToNewTab→moveLeaf→planTerminalLeafMove, moving the leaf, its binding, and every pane-keyed record across all local/SSH owner partitions in one durable mutation with rollback. - Post-commit re-key — agent-status alias (
transferPaneAuthority, verified) and orchestration worker-terminalpane_key. - Renderer rolls forward —
detachTerminalPaneToTabmints the target tab id, awaits main, then applies locally; refusals show the failure toast, concurrent pane/tab closes close main's new tab, and a last-pane move closes the source tab without killing the PTY. - Dedup guards —
isPaneAuthorityTransferredToskips a repeat transfer;isConnectPendingblocks dragging a pane whose spawn is in flight. - Tests — 8 files covering the STA-9259 sequence, dual-partition SSH, concurrent closes, the topology span, and the renderer commit/roll-forward paths.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
| if (remainingLayout) { | ||
| terminalLayoutsByTabId[sourceTabId] = remainingLayout | ||
| } else { | ||
| // Its sibling was never bound here; the sibling's own binding mints the layout again. | ||
| delete terminalLayoutsByTabId[sourceTabId] | ||
| } |
There was a problem hiding this comment.
moveLeafInPartition rewrites only the source and target layouts, so any other layout in the same session that still contains leafId keeps it. Since planTerminalLeafMove deliberately does not refuse on a layout whose tab row is gone (leafElsewhere only considers live tabs), that stray layout stays a second owner — and the target entry is appended last, so after the move findTerminalTabIdForLeaf (which walks every layout, live or dead) can now resolve the moved leaf to the removed tab instead of the target.
A relay reattach for the moved pane then fences to that dead tab (restoreReattachedPtyRuntime at src/main/ssh/ssh-relay-session.ts:2937), producing exactly the ghost-tab/lost-pane class this PR is meant to close. The PR's own planTerminalLeafMove test builds this input ("a stray layout of a removed tab still names") but only asserts planned.result, so the leftover layout is untested.
Technical details
# A moved leaf can keep a second owner in a removed tab's layout
## Affected sites
- `src/main/persistence/terminal-topology/terminal-leaf-move.ts:102-107` — `moveLeafInPartition` rewrites only `terminalLayoutsByTabId[sourceTabId]` / `[targetTabId]`; other layouts naming `leafId` are untouched.
- `src/main/persistence/terminal-topology/terminal-leaf-move.ts:159-171` — `leafElsewhere` intentionally ignores layouts whose tab row is gone.
- `src/main/persistence/terminal-topology/terminal-topology-membership.ts:35-49` — `findTerminalTabIdForLeaf` matches the first layout containing the leaf, with no liveness check; `Object.keys` order leaves `[targetTabId]` last.
- `src/main/ssh/ssh-relay-session.ts:2936-2961` — relay reattach resolves `tabId` through `findTerminalTabIdForLeaf` before falling back to the lease.
## Required outcome
- After a committed move, `leafId` names exactly one layout per owner partition (or the resolver skips layouts whose tab row no longer exists).
## Suggested approach (optional)
- Strip `leafId` from every other layout in the session when building the target (e.g. delete it from each non-source/non-target layout that contains it), keeping the existing tab-liveness exemption for refusal. Alternatively, make `findTerminalTabIdForLeaf` ignore layouts without a matching `tabsByWorktree` row — but that changes a shared resolver used by relay and headless reconcile, so the move-side cleanup is the narrower fix.
## Open questions for the human
- Is a layout that outlives its tab row actually reachable in the field? The `leafElsewhere` comment and the `planTerminalLeafMove` test assume it is; if it can only arise from prior corruption, a documented invariant may be enough.
- Same class, across partitions: `holders` requires the source tab row AND the source layout, and `leafElsewhere` excludes `sourceTabId`. A partition with the source layout but no source tab row is neither moved nor refused, so it can keep the moved leaf while another partition moves it.… 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.
…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.
…1-1-commit-module' into refactor/terminal-topology-b1-2-move-leaf # Conflicts: # src/main/persistence/terminal-topology/terminal-topology-commit.ts
…ology-b1-2-move-leaf # Conflicts: # src/main/persistence/terminal-topology/terminal-topology-commit.ts # src/main/persistence/terminal-topology/terminal-topology-membership.ts
|
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 (5)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe change adds a terminal-leaf move request contract and persists moves across local and SSH session partitions. A new PTY IPC route invokes the durable move and then reconciles agent pane authority and worker terminal resources. Renderer detachment now runs asynchronously, sends the live or persisted PTY ID, and applies the main-process result. The renderer also tracks pending PTY connections. Tests cover move validation, persistence, restart and close scenarios, IPC reconciliation, and detachment behavior. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to No identified issue blocks merging these changes after normal checks. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to The main-first move improves saved-layout consistency, but the new request can promote an unverified terminal association into trusted pane ownership. Recovery of related ownership records is also not fully established. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 32.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 52 functions across 29 files. (1 skipped: 1 unsupported.) ✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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 new issues in this update — the commits since the last review are a merge-up, so the prior finding (still open) is the only thing standing between this and an approval.
Reviewed changes
- Merged B1-1 and
maininto B1-2 —terminal-topology-commit.ts(both merges),terminal-topology-membership.ts, and a comment interminal-leaf-move.test.tswere conflict-resolved; the result keeps B1-1'straced(refusals traced by callback) and membership helpers alongside B1-2'smoveLeaf/commitLeafMove. - Move behaviour unchanged — the PR-authored move path (
terminal-leaf-move.ts,ipc/pty/ipc/leaf-move.ts,moveTerminalLeafToNewTab, rendererdetachTerminalPaneToTab) is byte-identical to the previously reviewed head, so there is no new production surface to re-review. - Census commits are B1-1's, already on main — the 9
writer censuscommits belong to #25329 and are not new B1-2 authored work;terminal-topology-boundary-ratchet.test.tsstays out of the PR diff for the same reason.
The prior review's open thread on terminal-leaf-move.ts (a removed tab's layout can keep a second owner of the moved leaf, and findTerminalTabIdForLeaf walks it) is untouched by these commits, so it remains open and I am not approving yet.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
0aa92488-9656-4bfc-89e5-69949623c19a
📒 Files selected for processing (27)
src/main/agent-hooks/server-pane-authority.test.tssrc/main/agent-hooks/server/server-authority-aliases.tssrc/main/ipc/agent-pane-authority-ipc.tssrc/main/ipc/pty/ipc/leaf-move.test.tssrc/main/ipc/pty/ipc/leaf-move.tssrc/main/ipc/pty/register-handlers.tssrc/main/persistence/loading-store/pty-binding-persistence.tssrc/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.tssrc/main/persistence/terminal-topology/terminal-leaf-move-fixture.tssrc/main/persistence/terminal-topology/terminal-leaf-move.test.tssrc/main/persistence/terminal-topology/terminal-leaf-move.tssrc/main/persistence/terminal-topology/terminal-topology-commit.tssrc/main/persistence/terminal-topology/terminal-topology-membership.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.tssrc/preload/api/pty-api.tssrc/preload/api/pty-bridge-session-control.tssrc/renderer/src/components/terminal-pane/pty-transport-connect-spawn.test.tssrc/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/pty-transport.tssrc/renderer/src/components/terminal-pane/terminal-pane-tab-detach-commit.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-tab-detach-fixture.tssrc/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.tssrc/renderer/src/components/terminal-pane/terminal-pane-tab-detach.tssrc/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.tssrc/renderer/src/i18n/locales/en.jsonsrc/shared/terminal-leaf-move.test.tssrc/shared/terminal-leaf-move.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| getCallbacks: () => storedCallbacks | ||
| }) | ||
| } finally { | ||
| if (pendingConnectGeneration === connectGeneration) { | ||
| pendingConnectGeneration = null | ||
| } | ||
| if (lifecycleGeneration === connectGeneration) { | ||
| await flushPreconnectInput() | ||
| } | ||
| } | ||
| }, | ||
|
|
||
| isConnectPending: () => | ||
| !destroyed && ptyId === null && pendingConnectGeneration === lifecycleGeneration, | ||
|
|
||
| attach: (options) => { | ||
| const attachGeneration = advancePtyLifecycle() | ||
| try { |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '170,215p' src/renderer/src/components/terminal-pane/pty-connection/run-deferred-connect.ts
sed -n '125,182p' src/renderer/src/components/terminal-pane/pty-transport.ts
sed -n '125,146p' src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts
rg -n 'installRunDeferredConnect|runDeferredConnect|sourceConnectPending' src/renderer/src/components/terminal-pane | head -65Repository: stablyai/orca
Length of output: 6494
Include scheduled connects in sourceConnectPending.
isConnectPending() becomes true only after connect() starts, but installRunDeferredConnect schedules that call earlier. During that gap, a confirmed-CWD split can pass the detach guard and move the leaf with a null PTY ID. If the scheduled connect then binds the leaf to the source tab, persistence can leave the same leaf owned by both tabs. Have the scheduler report its queued state to the detach guard; changing only the detach helper cannot detect a state its caller does not provide.
| const persistedPtyId = | ||
| initialStore.terminalLayoutsByTabId[args.sourceTabId]?.ptyIdsByLeafId?.[sourceLeafId] | ||
| initialStore.terminalLayoutsByTabId[args.sourceTabId]?.ptyIdsByLeafId?.[leafId] | ||
| const cwdDeferred = Boolean( | ||
| args.sourcePaneCwd?.pendingCwd || args.sourcePaneCwd?.deferredSplitSpawn | ||
| ) | ||
| if (cwdDeferred && !persistedPtyId && !args.fallbackPtyId) { | ||
| // Why: a spawn result landing after the move binds SOURCE:leaf, and that bind grafts the leaf | ||
| // back into the source tab beside its moved copy. | ||
| if ((cwdDeferred || args.sourceConnectPending) && !persistedPtyId && !args.livePtyId) { | ||
| return null | ||
| } | ||
|
|
||
| args.persistLayoutSnapshot() | ||
| const store = args.getStore() | ||
| const detached = detachTerminalLayoutLeaf( | ||
| store.terminalLayoutsByTabId[args.sourceTabId], | ||
| sourceLeafId | ||
| ) | ||
| if (!detached) { | ||
| const request: TerminalLeafMoveRequest = { | ||
| worktreeId: args.worktreeId, | ||
| sourceTabId: args.sourceTabId, | ||
| targetTabId: createBrowserUuid(), | ||
| leafId, | ||
| ptyId: args.livePtyId ?? persistedPtyId ?? null | ||
| } | ||
| if (!args.commitMove) { | ||
| return applyMove(args, request, { mainMoved: false, ptyId: request.ptyId }) | ||
| } | ||
| const moved = await args.commitMove(request).catch((error: unknown) => { | ||
| console.warn('[terminal-pane-detach] main did not answer the move', error) | ||
| return null | ||
| }) | ||
| if (moved?.status === 'moved') { | ||
| return applyMove(args, request, { mainMoved: true, ptyId: moved.ptyId }) | ||
| } | ||
| if (moved?.status === 'not_held') { | ||
| return applyMove(args, request, { mainMoved: false, ptyId: request.ptyId }) | ||
| } | ||
| // A failed write rolls main back; one whose outcome is unknown faults persistence, and the next | ||
| // load converges on whichever side main kept. | ||
| console.warn('[terminal-pane-detach] main did not move the pane', moved) | ||
| reportMoveFailed() | ||
| return null | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '118,165p' src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts
sed -n '232,258p' src/renderer/src/components/terminal-pane/use-terminal-pane-close-actions.ts
sed -n '138,180p' src/renderer/src/components/terminal-pane/pty-transport.tsRepository: stablyai/orca
Length of output: 4780
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\\n' '--- detach implementation ---'
nl -ba src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts | sed -n '1,210p'
printf '%s\\n' '--- transport interface and lifecycle references ---'
rg -n -F -- 'isConnectPending' src/renderer/src
rg -n -F -- 'getPtyId:' src/renderer/src/components/terminal-pane
rg -n -F -- 'ptyId = null' src/renderer/src/components/terminal-pane/pty-transport.ts
printf '%s\\n' '--- transport lifecycle block ---'
nl -ba src/renderer/src/components/terminal-pane/pty-transport.ts | sed -n '1,245p'
printf '%s\\n' '--- move contract and implementation references ---'
rg -n -F -- 'moveLeafToNewTab' src
rg -n -F -- 'TerminalLeafMoveRequest' srcRepository: stablyai/orca
Length of output: 41851
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- detach implementation ---'
nl -ba src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts | sed -n '1,210p'
printf '%s\n' '--- transport interface and lifecycle references ---'
rg -n -F -- 'isConnectPending' src/renderer/src
rg -n -F -- 'getPtyId:' src/renderer/src/components/terminal-pane
rg -n -F -- 'ptyId = null' src/renderer/src/components/terminal-pane/pty-transport.ts
printf '%s\n' '--- transport lifecycle block ---'
nl -ba src/renderer/src/components/terminal-pane/pty-transport.ts | sed -n '1,245p'
printf '%s\n' '--- move contract and implementation references ---'
rg -n -F -- 'moveLeafToNewTab' src
rg -n -F -- 'TerminalLeafMoveRequest' srcRepository: stablyai/orca
Length of output: 42067
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- PR diff for detach routine ---'
git diff --unified=12 2a68ea94967caf926aa60ebbd2bb32797bebb146 6bb3ea2d9adc4f3f70c8e191f3688ff0267ede8d -- src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts
printf '%s\n' '--- PTY mismatch planner ---'
nl -ba src/main/persistence/terminal-topology/terminal-leaf-move.ts | sed -n '1,250p'
printf '%s\n' '--- move IPC binding ---'
nl -ba src/main/ipc/pty/ipc/leaf-move.ts | sed -n '1,100p'
printf '%s\n' '--- persisted PTY binding consumers in renderer ---'
rg -n -F -- 'ptyIdsByLeafId' src/renderer/src/components/terminal-pane src/renderer/src/store
printf '%s\n' '--- attach/reattach call sites ---'
rg -n -i -- 'reattach|transport\.connect|\.connect\(' src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
printf '%s\n' '--- detach commit tests ---'
nl -ba src/renderer/src/components/terminal-pane/terminal-pane-tab-detach-commit.test.ts | sed -n '1,260p'Repository: stablyai/orca
Length of output: 42959
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- planner mismatch and result path ---'
nl -ba src/main/persistence/terminal-topology/terminal-leaf-move.ts | sed -n '147,255p'
printf '%s\n' '--- reattach files ---'
rg --files src/renderer/src/components/terminal-pane/pty-connection | rg 'connect|restore|reattach|session'
printf '%s\n' '--- saved PTY binding references in connection code ---'
rg -n -F -- 'ptyIdsByLeafId' src/renderer/src/components/terminal-pane/pty-connection
printf '%s\n' '--- saved PTY binding references in pane lifecycle ---'
rg -n -F -- 'ptyIdsByLeafId' src/renderer/src/components/terminal-pane src/renderer/src/store
printf '%s\n' '--- persisted PTY ID selection references ---'
rg -n -i -- 'persistedPtyId|savedPtyId|initialPtyId|ptyId.*leafId|leafId.*ptyId' src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts
printf '%s\n' '--- move IPC and persistence result ---'
nl -ba src/main/ipc/pty/ipc/leaf-move.ts | sed -n '1,100p'
nl -ba src/shared/terminal-leaf-move.ts | sed -n '1,90p'Repository: stablyai/orca
Length of output: 41766
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- deferred reattach choice ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-choice.ts | sed -n '1,180p'
printf '%s\n' '--- deferred reattach call and restored binding source ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/deferred-session-attach.ts | sed -n '1,145p'
rg -n -F -- 'restoredPtyIdByLeafId' src/renderer/src/components/terminal-pane
printf '%s\n' '--- reattach result binding update ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts | sed -n '200,240p'
printf '%s\n' '--- connect binding update ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts | sed -n '170,215p'
printf '%s\n' '--- direct SSH retry: restored binding and new PTY ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts | sed -n '630,745p'Repository: stablyai/orca
Length of output: 41283
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- deferred SSH reattach reaches transport.connect ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/deferred-session-attach.ts | sed -n '135,215p'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.ts | sed -n '1,145p'
printf '%s\n' '--- reattach result receives and compares old/new IDs ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts | sed -n '65,145p'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts | sed -n '216,250p'Repository: stablyai/orca
Length of output: 17439
🏁 Script executed:
#!/bin/bash
set -e
nl -ba src/renderer/src/components/terminal-pane/pty-connection/deferred-session-reattach-connect.ts | sed -n '115,255p'Repository: stablyai/orca
Length of output: 5824
Wait for reattach before moving the pane.
When a user drops a pane onto a tab-strip target during reattach, the transport has no live PTY ID, but this guard still sends persistedPtyId. Reattach can return a different ID after an SSH respawn. The planner may refuse the saved ID with pty_mismatch; if an owner partition still retains that stale ID, it can move the pane under it. Reject a pending connection when no live ID exists, while preserving the saved-ID fallback for non-pending moves.
Suggested fix
- if ((cwdDeferred || args.sourceConnectPending) && !persistedPtyId && !args.livePtyId) {
+ if (
+ (cwdDeferred && !persistedPtyId && !args.livePtyId) ||
+ (args.sourceConnectPending && !args.livePtyId)
+ ) {
return null
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const persistedPtyId = | |
| initialStore.terminalLayoutsByTabId[args.sourceTabId]?.ptyIdsByLeafId?.[sourceLeafId] | |
| initialStore.terminalLayoutsByTabId[args.sourceTabId]?.ptyIdsByLeafId?.[leafId] | |
| const cwdDeferred = Boolean( | |
| args.sourcePaneCwd?.pendingCwd || args.sourcePaneCwd?.deferredSplitSpawn | |
| ) | |
| if (cwdDeferred && !persistedPtyId && !args.fallbackPtyId) { | |
| // Why: a spawn result landing after the move binds SOURCE:leaf, and that bind grafts the leaf | |
| // back into the source tab beside its moved copy. | |
| if ((cwdDeferred || args.sourceConnectPending) && !persistedPtyId && !args.livePtyId) { | |
| return null | |
| } | |
| args.persistLayoutSnapshot() | |
| const store = args.getStore() | |
| const detached = detachTerminalLayoutLeaf( | |
| store.terminalLayoutsByTabId[args.sourceTabId], | |
| sourceLeafId | |
| ) | |
| if (!detached) { | |
| const request: TerminalLeafMoveRequest = { | |
| worktreeId: args.worktreeId, | |
| sourceTabId: args.sourceTabId, | |
| targetTabId: createBrowserUuid(), | |
| leafId, | |
| ptyId: args.livePtyId ?? persistedPtyId ?? null | |
| } | |
| if (!args.commitMove) { | |
| return applyMove(args, request, { mainMoved: false, ptyId: request.ptyId }) | |
| } | |
| const moved = await args.commitMove(request).catch((error: unknown) => { | |
| console.warn('[terminal-pane-detach] main did not answer the move', error) | |
| return null | |
| }) | |
| if (moved?.status === 'moved') { | |
| return applyMove(args, request, { mainMoved: true, ptyId: moved.ptyId }) | |
| } | |
| if (moved?.status === 'not_held') { | |
| return applyMove(args, request, { mainMoved: false, ptyId: request.ptyId }) | |
| } | |
| // A failed write rolls main back; one whose outcome is unknown faults persistence, and the next | |
| // load converges on whichever side main kept. | |
| console.warn('[terminal-pane-detach] main did not move the pane', moved) | |
| reportMoveFailed() | |
| return null | |
| } | |
| const persistedPtyId = | |
| initialStore.terminalLayoutsByTabId[args.sourceTabId]?.ptyIdsByLeafId?.[leafId] | |
| const cwdDeferred = Boolean( | |
| args.sourcePaneCwd?.pendingCwd || args.sourcePaneCwd?.deferredSplitSpawn | |
| ) | |
| // Why: a spawn result landing after the move binds SOURCE:leaf, and that bind grafts the leaf | |
| // back into the source tab beside its moved copy. | |
| if ( | |
| (cwdDeferred && !persistedPtyId && !args.livePtyId) || | |
| (args.sourceConnectPending && !args.livePtyId) | |
| ) { | |
| return null | |
| } | |
| args.persistLayoutSnapshot() | |
| const request: TerminalLeafMoveRequest = { | |
| worktreeId: args.worktreeId, | |
| sourceTabId: args.sourceTabId, | |
| targetTabId: createBrowserUuid(), | |
| leafId, | |
| ptyId: args.livePtyId ?? persistedPtyId ?? null | |
| } | |
| if (!args.commitMove) { | |
| return applyMove(args, request, { mainMoved: false, ptyId: request.ptyId }) | |
| } | |
| const moved = await args.commitMove(request).catch((error: unknown) => { | |
| console.warn('[terminal-pane-detach] main did not answer the move', error) | |
| return null | |
| }) | |
| if (moved?.status === 'moved') { | |
| return applyMove(args, request, { mainMoved: true, ptyId: moved.ptyId }) | |
| } | |
| if (moved?.status === 'not_held') { | |
| return applyMove(args, request, { mainMoved: false, ptyId: request.ptyId }) | |
| } | |
| // A failed write rolls main back; one whose outcome is unknown faults persistence, and the next | |
| // load converges on whichever side main kept. | |
| console.warn('[terminal-pane-detach] main did not move the pane', moved) | |
| reportMoveFailed() | |
| return null | |
| } |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Fence stale mobile-session bindings at spawn commit. · terminal-pane-tab-detach.ts:127-145
src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts:127-145
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winFence stale mobile-session bindings at spawn commit.
When a main-side host spawn is outstanding,
cwdDeferredandsourceConnectPendingcan both be false even though the renderer has no persisted or live PTY. The guard then permits a move withptyId: null. If the source tab retains a sibling, the move removes the leaf from the source layout. The later host-spawn commit can still bind the captured source tab and leaf, grafting the leaf back into the source layout while it remains in the target layout. Revalidate leaf ownership at the host-spawn commit and refuse or reconcile a stale binding there; the renderer cannot observe this main-side spawn.
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
58abecb4-c288-4cb5-9564-a618d0f8536b
📒 Files selected for processing (1)
src/main/ipc/agent-hooks.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.
…ology-b1-2-move-leaf
…status transfer The pane manager decides whether the dragged pane is the last one, and a refused detach closes main's new tab like a vanished pane. Paired web clients answer the move as not held, so every client takes the same moved / not_held / refused branch. Repeating an agent-status transfer that is already in place is now a no-op where it happens, replacing the IPC special case.
There was a problem hiding this comment.
ℹ️ No new issues in this update. The new commit reworks the move and status-transfer seams cleanly; the only open item is the pre-existing
terminal-leaf-move.tsthread, which these commits do not touch.
Reviewed changes
- One move path for every client —
detachTerminalPaneToTabno longer takes an optional injectedcommitMove; it always awaitswindow.api.pty.moveLeafToNewTab. Paired web clients supply{ status: 'not_held' }increatePtyApi, so their move still falls back to the renderer-local path. - Idempotent status transfer — removed
AgentHookServer.isPaneAuthorityTransferredToand its IPC-gate short-circuit;transferPaneAuthoritynow returns early when the owner already routesfrom→toand (when supplied) the physical alias carries the same trimmedptyId. Main's direct call is now idempotent too, and the renderer still passescanTransferPaneAuthorityfirst. - Spawn-in-flight fence — added
PtyTransport.isConnectPending, true only while aconnecthas not produced a ptyId, and threaded it into the detach guard assourceConnectPendingbeside the pending-cwd check. - Last-pane detection — the concurrent-sibling path now derives "source tab emptied" from
manager.getPanes().length === 1instead of re-walking the stored layout. - Tests — new main-side
leaf-movesuite, an idempotency case onserver-pane-authority, a pending-connect case onpty-transport-connect-spawn, and the renderer commit/roll-forward suite updated for the async path.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
…ology-b1-2-move-leaf
(cherry picked from commit 1a5f687)
…ology-b1-2-move-leaf # Conflicts: # src/main/persistence/loading-store/pty-binding-persistence.ts

ELI5
When you drag a pane out of a split into its own tab, the app window used to rearrange its own notebook of "which pane shows which terminal" and tell main afterwards, one field at a time. After a restart, main's notebook could still list the pane in its old tab, so one terminal showed up in two tabs and one of them froze (Linear STA-9259).
Now the window asks main to move the pane first. Main moves it in one step, and the window then opens the tab.
Builds on #25329 (merged).
What Changed
moveLeafin main first. Main moves the leaf, its terminal binding and every record keyed by that pane, in every saved partition (local, SSH, runtime) in one write through the terminal layout module from refactor(terminal): one commit module for terminal topology closes, with a boundary check #25329. Those records are: incarnation, sleeping session, remote session id, UI marks, SSH lease, agent-status alias and orchestration worker resources. Only then does the window open the new tab.Why
This is the second step of making main the only writer of terminal layout (see #25329). Drag-out was the main writer that changed layout from the window side. Moving it into one main-side step closes the STA-9259 path at its source instead of patching the restore.
An earlier version undid the window change when main refused. Review found that undo could not be made exact: it left ghost tabs, missed in-flight spawns and lost the pane if a sibling closed. Asking main first and only rolling forward is simpler and has no partial states.
Linked Issue
Maintainer PR. Context: Linear STA-9259, STA-9417.
Visual Proof
N/A. A drag looks the same; the fix shows after a restart (one terminal no longer appears in two tabs). This is covered by the live checks below.
Testing
pnpm tc, oxlint andcheck:code-quality:changedpass on the final commit. The B1-2 test files pass (8 files, 75 tests), and the related suites ran 10,414 passing and 0 failing.Live, local, final build, real drags with output flowing:
SSH (Docker relay end-to-end), on the build just before the last-pane fix: 3/3. The flow was restart → move → 2 restarts, with output and a single owner each time. The final commit only changes the last-pane and retry paths.
Latency of the main-side move: p50 1.3 ms and p95 1.7 ms over IPC, on a copied 79-tab profile.
Parity check against main (test(e2e): terminal layout parity check against main #25681, real app, 9 scenarios): 8 identical. The drag-out-to-tab scenario (real mouse drag, then two restarts) ends with the same tabs, panes and terminal bindings as main; the only differences, on every run, are two internal bookkeeping fields. Main's move now saves the pane incarnations and terminal layout revision at the moment of the drag, so they are present at quit (main only writes them after the first restart) and the revision counter reads 1 instead of 2 after restarts.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Review
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.Notes
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)