Repository navigation
fix(worktree): gate agent activation on the live surface census, not renderer state (STA-5701) - #17428
Conversation
Greptile SummaryThe PR changes worktree-agent activation to reconcile live PTYs against the execution host’s terminal-surface census rather than renderer-local bindings.
Confidence Score: 5/5The PR appears safe to merge because no blocking failure remains within the eligible follow-up-review scope. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/renderer/src/lib/worktree-agent-activation-gate.ts | Delegates live-PTY reconciliation to the host-aware adoption sweep and bases the gate outcome on whether a surface was produced. |
| src/renderer/src/lib/worktree-agent-live-surface-adoption.ts | Reconciles renderer bindings with host-owned terminal surfaces and declines duplicate creation when ownership is unverifiable. |
| src/renderer/src/lib/worktree-live-terminal-surface-owners.ts | Builds a worktree-scoped PTY-to-surface ownership index with fail-closed validation for incomplete census responses. |
| src/shared/worktree/id.ts | Exposes normalized worktree-ID equality for shared main-process and renderer use. |
| src/main/runtime/orca-runtime.ts | Replaces the runtime-private worktree comparator with the behaviorally equivalent shared helper. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Worktree activation] --> B[List live workspace PTYs]
B --> C{Already bound locally?}
C -->|Yes| D[Keep existing surface]
C -->|No| E[Read host surface census]
E --> F{Census verifiable?}
F -->|No| G[Decline PTY adoption]
F -->|Yes| H{Host reports an owner?}
H -->|Yes| I[Bind exact tab and leaf]
H -->|No| J[Create recovery surface]
D --> K{Any PTY surfaced?}
I --> K
J --> K
G --> K
K -->|Yes| L[Return adopted]
K -->|No| M[Return empty for caller seeding]
Reviews (3): Last reviewed commit: "fix(worktree): name the live PTYs the su..." | Re-trigger Greptile
📝 WalkthroughWalkthroughThe change adds shared worktree ID comparison and replaces runtime-local comparisons with it. The renderer now reads validated host terminal censuses and maps live PTYs to exact tabs and panes. Activation adopts existing host-owned surfaces, extends multi-pane layouts, and creates inactive tabs only for confirmed unowned PTYs. Tests cover ownership ambiguity, incomplete censuses, orphan PTYs, restoration, and duplicate-tab prevention. Merge Risk: 🔵 Low · up to The change prevents duplicate agent panes by using live host ownership, but equivalent worktree path spellings can still cause an existing pane to be missed during an unverifiable census and create an unnecessary fallback shell; a small timing window can also leave stale terminal state after a PTY exits. The PR is mergeable with explicit owner awareness and follow-up for these bounded edge cases. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description is detailed and mostly complete. It explains the problem, implementation, rationale, linked issue, testing results, performance impact, compatibility considerations, and merge dependencies. It does not include every template heading, a Visual Proof section or explicit N/A, completed checklist items, or AI disclosure, but these omissions do not make the description largely incomplete.
✨ 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e228372a-40e6-4d8a-9313-d9cdf92ae880
📒 Files selected for processing (9)
src/main/runtime/orca-runtime.tssrc/renderer/src/lib/worktree-agent-activation-gate.test.tssrc/renderer/src/lib/worktree-agent-activation-gate.tssrc/renderer/src/lib/worktree-agent-activation-seam.test.tssrc/renderer/src/lib/worktree-agent-live-surface-adoption.tssrc/renderer/src/lib/worktree-live-terminal-surface-owners.test.tssrc/renderer/src/lib/worktree-live-terminal-surface-owners.tssrc/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.tssrc/shared/worktree/id.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
| if ( | ||
| !value || | ||
| typeof value !== 'object' || | ||
| !Array.isArray((value as { terminals?: unknown }).terminals) | ||
| ) { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Reject empty and malformed terminal censuses.
This guard accepts terminals: [] and a missing or non-boolean truncated field. The reader then returns a non-null index. adoptLiveWorkspacePtySurfaces interprets an absent PTY in that index as unowned and creates a tab, so an incomplete census can recreate the duplicate-pane failure.
Require a non-empty terminal list and a boolean truncated value before returning an index. Add regression cases for both inputs.
Proposed fix
function isScopedTerminalListResult(
value: unknown
): value is RuntimeTerminalListResult & { hostScope: RuntimeTerminalListHostScope } {
+ const terminals = (value as { terminals?: unknown } | null)?.terminals
if (
!value ||
typeof value !== 'object' ||
- !Array.isArray((value as { terminals?: unknown }).terminals)
+ !Array.isArray(terminals) ||
+ terminals.length === 0 ||
+ typeof (value as { truncated?: unknown }).truncated !== 'boolean'
) {
return false
}📝 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.
| if ( | |
| !value || | |
| typeof value !== 'object' || | |
| !Array.isArray((value as { terminals?: unknown }).terminals) | |
| ) { | |
| const terminals = (value as { terminals?: unknown } | null)?.terminals | |
| if ( | |
| !value || | |
| typeof value !== 'object' || | |
| !Array.isArray(terminals) || | |
| terminals.length === 0 || | |
| typeof (value as { truncated?: unknown }).truncated !== 'boolean' | |
| ) { |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
worktreeIdsEquallifted to shared — the privateruntimeWorktreeIdsEqualhelper moves byte-identically intosrc/shared/worktree/id.tsand all ~37 main-process call sites switch over, with the private definition and its JSDoc removed. No remaining references to the old helper.- Host census reader — new
worktree-live-terminal-surface-owners.tscallsterminal.list(id:-scoped,limit: 200,includeVisualLayouts: false) and returns a whole-indexnullon!response.ok, missing/malformedhostScope,truncated === true, orhostScope.hostIds.length === 0; otherwise it buildsMap<ptyId, owner | null>in which anullentry means "unverifiable" (unaddressable surface or two surfaces claiming one PTY). - Adoption/mint rework —
adoptLiveWorkspacePtySurfacespre-filters throughresolveTerminalTabPtyOwnership(which also keys persistedtab.ptyIdandptyIdsByLeafId, not just the oldptyIdsByTabId), then mints only when a readable, untruncated, host-scoped index positively omits the PTY. The three verdicts (owner / unverifiable / absent) are enforced consistently end to end. - Gate wiring — the renderer-only
ptyIsAlreadyBoundloop is replaced with the census-backed path via a newlistSurfaceOwnersdep; the persisted-layout and tab-row binding cases are now covered without minting.
The shrink/mint logic is sound: I traced listTerminals's exact-match filtering by the id: selector and buildTerminalListHostScope's hostIds semantics (empty hostIds ⇔ the workspace's own host inventory was unverifiable, which is exactly the SSH-host-didn't-answer signal), and the exact terminal.worktreeId !== worktreeId re-filter in the index is a consistent redundant guard rather than a cross-host mismatch, since the host already scopes to the exact id. The new tests assert exact createTab/updateTabPtyId/replaceTerminalLayoutPanePtyId calls and the mint guard's fail-closed branches, so they would fail against a reintroduced bug.
One boundary worth noting (informational, no change required): with OWNER_LISTING_LIMIT = 200, a worktree holding more than 200 live PTYs yields truncated: true, so the census reads as unverifiable and the whole worktree declines both adoption and minting. That is fail-closed and consistent with the PR's stated philosophy, but it caps the census at the default terminal.list limit.
Reviewed the full diff end to end, the seam/fork-bomb/gate/surface-owner tests, and the surrounding listTerminals/terminal.list contracts; the four touched renderer suites pass locally (43 tests).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
e58b5cb to
d762ef8
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Fail-silent closed —
adoptLiveWorkspacePtySurfacesnow returns whether any live PTY ends the sweep holding a surface, and the gate only reports'adopted'when that is true; an unreadable census falls through to'empty', the caller's "seed a surface" directive, instead of standing the caller down into a blank workspace. - Spelling fixes folded through
worktreeIdsEqual—bindLivePtyToExactSurfaceandindexLiveTerminalSurfaceOwnersnow match a host row hydrated under an equivalent workspace path, closing both the unbindable-tab and the dropped-row mint bugs; the::workspace:<uuid>suffix is still preserved so folder-workspace siblings cannot steal each other's PTYs. adoptHostOwnedSurfacereports failure — returnsfalsewhen no surface could be bound (missing leaf or competing binding), so the seed still fires rather than being silently swallowed.- Tests — the seam test drives the blank-workspace repro directly, and the gate tests cover unverifiable census, two-surfaces, partial adoption, differently-spelled host ids, and the multi-pane split materialization.
I traced the surfaced bookkeeping end to end (already-bound fast path, re-read-after-census, owner-adopt, null-entry, and positive-omission mint) and re-read all three callers (worktree-activation.ts folder and worktree paths, and Terminal.tsx): every 'empty' handler re-checks hostAuthority === 'none' and shouldAutoCreateInitialTerminal, so the seeded pane is a fresh shell with its own PTY and an intentionally-emptied workspace stays empty.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…renderer state (STA-5701)
…ship (STA-5701) Failing closed must not also fail silent. When the census is unverifiable the sweep adopts nothing and mints nothing, yet the gate still reported 'adopted' — and both callers suppress their own seeding on any outcome but 'empty', so the workspace ended with zero surfaces. The sweep now reports whether any live PTY holds a surface and the gate hands the caller its seed when none does. Also folds equivalent workspace-path spellings in the census index and in exact-surface binding, so a host row spelled differently is neither dropped (mint a duplicate) nor unbindable (no pane).
The adoption sweep can leave a live PTY without a surface — an unreadable
census, two host surfaces claiming one PTY, or a host-named leaf the
persisted layout does not have. The gate already stops reporting 'adopted'
in that case so the caller seeds a shell, but the decline itself was mute.
- adoptLiveWorkspacePtySurfaces now returns { surfaced, declinedPtyIds }
and the gate warns with the workspace and the PTY ids left unsurfaced.
- Pin the host-named-leaf decline, which had no test either way.
- Pin the superseded-inventory race in terminal.list: a concurrent refresh
makes hostScope.hostIds empty, which is what makes the renderer's
'unverifiable' verdict reachable on a plain local machine.
d762ef8 to
582cc83
Compare
|
Rebased onto What changed The adoption sweep can leave a live PTY with no surface in three cases: the census is unreadable, two host surfaces claim one PTY, or the host names a leaf the persisted layout does not have. The gate already refuses to report
Both new tests were mutation-checked (production condition inverted → red, restored → green). Verification: the five affected suites pass (67 tests), plus four adjacent activation suites (22 tests). What was deliberately not done The review also suggested extracting the shared shape guard between Residual risk A new renderer paired with a remote Orca host that predates the Merge order: merge this before #17445 (or rebase #17445 onto it) — both add |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d22eda4e-83e8-4001-8156-5b4a01e9fd14
📥 Commits
Reviewing files that changed from the base of the PR and between d762ef8a9f32ee8f8bfb8bbbca1dfa03e5da3af7 and 582cc83.
📒 Files selected for processing (4)
src/main/runtime/terminal-list-execution-host-scope.test.tssrc/renderer/src/lib/worktree-agent-activation-gate.test.tssrc/renderer/src/lib/worktree-agent-activation-gate.tssrc/renderer/src/lib/worktree-agent-live-surface-adoption.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| // Why: ptyIdsByTabId holds only panes this renderer mounted, so a tab bound | ||
| // solely in tab.ptyId or the persisted layout used to read as unbound. | ||
| const unbound = livePtyIds.filter( | ||
| (ptyId) => resolveTerminalTabPtyOwnership(getState(), worktreeId, ptyId).kind === 'none' |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use normalized worktree lookup before classifying a PTY as unbound.
resolveTerminalTabPtyOwnership uses an exact tabsByWorktree[worktreeId] lookup. A PTY already bound under an equivalent worktree-path key is therefore put in unbound. If the host census then returns null, this function returns surfaced: false and activation can request an unnecessary fallback shell despite the existing surface. Normalize and deduplicate matching worktree keys in the ownership lookup before this filter. Add a regression with the aliased key, an existing PTY binding, and surfaceOwners: null.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Named declined live PTYs —
adoptLiveWorkspacePtySurfacesnow returns{ surfaced, declinedPtyIds }instead of a bare boolean, and the gate logs aconsole.warnwhen any live PTY ends the sweep without a surface (unreadable census, two surfaces claiming one PTY, or a host-named leaf the persisted layout lacks). The mint/adopt verdicts themselves are unchanged; this only makes a previously mute decline diagnosable. - Pinned the host-named-leaf decline — a new gate test drives a host surface naming a leaf the persisted layout does not have, and asserts the decline is reported, no tab is minted, and the outcome stays
'empty'. - Pinned the superseded-inventory race — a new main-process test verifies a concurrent inventory refresh yields
hostScope.hostIds === [], the mechanism that makes the renderer'sunverifiableverdict reachable on a plain local machine.
I traced the declinedPtyIds collection against the three decline paths and confirmed it only accumulates unbound PTYs that failed adoption or hit an unverifiable census; already-bound and successfully-adopted PTYs are excluded, so the warning never fires for a surfaced pane. All five touched suites pass locally (65 tests).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…-refactor main hoisted the runtime-local `runtimeWorktreeIdsEqual` into a shared `worktreeIdsEqual` (stablyai#17428) inside the file this branch split apart. Kept the split and ported the change into the module that now owns that code: runtime-worktree-path-identity.ts delegates to the shared implementation instead of keeping its own copy, so the duplicate the upstream commit was removing does not survive the merge. All 51 call sites keep their import.
…renderer state (STA-5701) (stablyai#17428) * fix(worktree): gate agent activation on the live surface census, not renderer state (STA-5701) * fix(worktree): seed a pane when the surface census cannot prove ownership (STA-5701) Failing closed must not also fail silent. When the census is unverifiable the sweep adopts nothing and mints nothing, yet the gate still reported 'adopted' — and both callers suppress their own seeding on any outcome but 'empty', so the workspace ended with zero surfaces. The sweep now reports whether any live PTY holds a surface and the gate hands the caller its seed when none does. Also folds equivalent workspace-path spellings in the census index and in exact-surface binding, so a host row spelled differently is neither dropped (mint a duplicate) nor unbindable (no pane). * fix(worktree): name the live PTYs the surface census declined (STA-5701) The adoption sweep can leave a live PTY without a surface — an unreadable census, two host surfaces claiming one PTY, or a host-named leaf the persisted layout does not have. The gate already stops reporting 'adopted' in that case so the caller seeds a shell, but the decline itself was mute. - adoptLiveWorkspacePtySurfaces now returns { surfaced, declinedPtyIds } and the gate warns with the workspace and the PTY ids left unsurfaced. - Pin the host-named-leaf decline, which had no test either way. - Pin the superseded-inventory race in terminal.list: a concurrent refresh makes hostScope.hostIds empty, which is what makes the renderer's 'unverifiable' verdict reachable on a plain local machine.

Fixes STA-5701. One of 6 real defects split out of the test-detected-bugs sweep.
ELI5
Before opening an agent pane, the app asks "is one already open?" — but it only looked at what the renderer currently knows. On an SSH host, or right after a reconnect, the renderer doesn't know everything. So it answered "nothing here" and minted a second pane for a PTY that already had one.
The check now consults the real census of live terminal surfaces instead of renderer-local state.
The part that matters for SSH
An empty census and an unreachable host are not the same answer.
readWorktreeLiveTerminalSurfaceOwnersreturnsnull— unverifiable — on any of:!response.okhostScopetruncated === truehostScope.hostIds.length === 0and the mint guard is
if (!surfaceOwners || surfaceOwners.has(ptyId)) continue. A surface is minted only when a readable, untruncated, host-scoped index positively omits the PTY. Absence of contact is never evidence of absence of a pane.An early draft of this module treated a missing
hostScopeas a complete census — the exact SSH fail-open the change exists to remove — and was caught in review.Failing closed must not also fail silent
Declining to mint is the safe direction, but it has its own user-visible failure: the pane the user asked for never appears at all. That was reachable, and is now fixed.
gateWorktreeAgentActivationis not advisory. Both call sites suppress their own terminal seeding while the gate runs (primaryTabId = null) and re-seed only onoutcome === 'empty'—worktree-activation.ts:148,258andTerminal.tsx:1546. The gate used to report'adopted'wheneverliveWorkspaceSessions.length > 0, whether or not the sweep bound anything. So on an unverifiable census the sweep adopted nothing, minted nothing, claimed'adopted', and the caller stood down: zero tabs, blank workspace.hostScope.hostIdsis empty — legitimately, by design — in three shipping cases, each verified interminal-list-execution-host-scope.test.ts:does not claim local coverage for a paired-runtime folder workspacekeeps a disconnected folder-workspace SSH host omittedmarks every known host omitted when process inventory is unverifiableadoptLiveWorkspacePtySurfacesnow returns whether any live PTY ends the sweep holding a surface — counting panes already bound, panes bound to the host's named surface, and panes minted. The gate reports'adopted'only then; otherwise it falls through and hands the caller'empty', which is the caller's directive ("this gate produced no surface, seed one"), not a claim the host had nothing. The seeded surface is a fresh shell with its own PTY — never a second surface forked onto the live agent's PTY — so the duplicate this PR exists to prevent stays prevented. Both callers re-check their own guards (shouldAutoCreateInitialTerminal, host authority, "user closed the last terminal"), so an intentionally-emptied workspace still stays empty.Holes checked and closed
null(unverifiable) — real, and the worst one: blank workspace. Closed above.null(host named an unaddressable surface, or two surfaces claimed one PTY) — same blank-workspace path. Closed by the same change.adoptHostOwnedSurfacebinds nothing (existing tab whose layout lacks the host's leaf, or a competing binding under another tab) — it now reportsfalserather than returning silently, so the seed still fires.indexLiveTerminalSurfaceOwnersdropped the row on!==, the PTY read as unowned, and the duplicate got minted. Now folded throughworktreeIdsEqual.bindLivePtyToExactSurfacehad the mirror-image bug (a tab hydrated under a differently-spelled key was unbindable, so no pane); same fix. The::workspace:<uuid>suffix is preserved, so folder-workspace siblings still cannot steal each other's PTYs.pty.listSessions()already reported live, andorphaned === truerows are deliberately left absent so they stay eligible for a recovery tab.candidates = [scopedHostId], so a non-emptyhostIdsprovably contains the workspace's own host and nothing else.Proof
Revert
worktree-agent-activation-gate.ts+worktree-agent-live-surface-adoption.tsto the pre-fix state:Revert only the fail-silent guard (report
'adopted'unconditionally again) and the seam test shows the blank workspace directly:At HEAD:
Also here
worktreeIdsEqualis lifted from a private runtime helper intosrc/shared/worktree/id.ts— a byte-identical move (exactrepoId, path spelling folded vianormalizeRuntimePathForComparison,::workspace:<uuid>suffix preserved, exact fallback for a malformed id). Windows/WSL/SSH ids still match themselves across hosts, and no folder-workspace sibling can steal another's PTYs. It now has renderer callers too (the two spelling fixes above).Performance Measurement
Deterministic host-collision fixture: stale renderer state could mint 2 surfaces for one live PTY; the host-scoped census gates that to 1 (50% fewer duplicate terminal surfaces). The census is read once per activation decision and remains bounded by the existing response contract.
User-Facing Trade-offs
None. Activation is safer on local, SSH, and paired-remote hosts. An unreachable, truncated, or ambiguous census still refuses to mint a duplicate onto a live agent's PTY — and now also refuses to leave the user staring at an empty workspace: the caller seeds an ordinary shell, exactly as it would for a workspace with no agent at all.
Reverting
A plain
git revertof this PR also removesworktreeIdsEqualfromsrc/shared/worktree/id.ts, which breaks whichever STA-4577 PR (#17430 / #17445) has landed by then — they import it. To revert:The rest of the revert is clean: 5 production files, no schema, no wire change, no persisted-state change.
Merge order
Merge this before #17445, or rebase #17445 onto it — both add
worktreeIdsEqualat the same anchor insrc/shared/worktree/id.tswith different JSDoc, sogit merge-treereports a content conflict. Resolution when rebasing #17445: drop itsid.tshunk and keep this one's. #17430 merges cleanly in either order (byte-identicalid.tshunk, non-overlappingorca-runtime.tshunks).