Skip to content

fix(worktree): gate agent activation on the live surface census, not renderer state (STA-5701) - #17428

Merged
nwparker merged 3 commits into
mainfrom
nwparker/sta-5701-activation-gate-surface-census
Aug 31, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/sta-5701-activation-gate-surface-census

Conversation

@nwparker

@nwparker nwparker commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​544 $\color{#cf222e}{\Huge{\mathbf{−}}}$​19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​525
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​310 $\color{#cf222e}{\Huge{\mathbf{−}}}$​92 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​218

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. readWorktreeLiveTerminalSurfaceOwners returns null — unverifiable — on any of:

  • !response.ok
  • malformed or absent hostScope
  • truncated === true
  • hostScope.hostIds.length === 0

and 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 hostScope as 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.

gateWorktreeAgentActivation is not advisory. Both call sites suppress their own terminal seeding while the gate runs (primaryTabId = null) and re-seed only on outcome === 'empty' — worktree-activation.ts:148,258 and Terminal.tsx:1546. The gate used to report 'adopted' whenever liveWorkspaceSessions.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.hostIds is empty — legitimately, by design — in three shipping cases, each verified in terminal-list-execution-host-scope.test.ts:

Case Test
Paired-runtime workspace (runtime hosts are never claimed as covered) does not claim local coverage for a paired-runtime folder workspace
SSH host whose relay never answered keeps a disconnected folder-workspace SSH host omitted
Local process inventory threw marks every known host omitted when process inventory is unverifiable

adoptLiveWorkspacePtySurfaces now 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

  • Census null (unverifiable) — real, and the worst one: blank workspace. Closed above.
  • Census entry null (host named an unaddressable surface, or two surfaces claimed one PTY) — same blank-workspace path. Closed by the same change.
  • adoptHostOwnedSurface binds nothing (existing tab whose layout lacks the host's leaf, or a competing binding under another tab) — it now reports false rather than returning silently, so the seed still fires.
  • Host row spelled with an equivalent workspace path — was fail-open: indexLiveTerminalSurfaceOwners dropped the row on !==, the PTY read as unowned, and the duplicate got minted. Now folded through worktreeIdsEqual. bindLivePtyToExactSurface had 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.
  • Surface registered but dead/exited — not reachable: the census is only consulted for ptyIds pty.listSessions() already reported live, and orphaned === true rows are deliberately left absent so they stay eligible for a recovery tab.
  • Surface owned by a different host than the activation targets — not reachable: a worktree-scoped listing sets candidates = [scopedHostId], so a non-empty hostIds provably contains the workspace's own host and nothing else.
  • Stale census after a disconnect — not reachable: the census is read fresh per activation, and local ownership is re-read after the RPC returns, before anything is minted.

Proof

Revert worktree-agent-activation-gate.ts + worktree-agent-live-surface-adoption.ts to the pre-fix state:

Test Files  1 failed (1)
     Tests  8 failed | 18 passed (26)

Revert only the fail-silent guard (report 'adopted' unconditionally again) and the seam test shows the blank workspace directly:

FAIL  worktree-agent-activation-seam.test.ts > still seeds a usable pane when the census cannot prove who owns a live PTY
AssertionError: expected [] to have a length of 1 but got +0

At HEAD:

$ pnpm test src/renderer/src/lib/worktree-agent-activation-gate.test.ts \
    src/renderer/src/lib/worktree-live-terminal-surface-owners.test.ts \
    src/renderer/src/lib/worktree-agent-activation-seam.test.ts \
    src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts
 Test Files  4 passed (4)
      Tests  47 passed (47)

$ pnpm test src/main/runtime/orca-runtime.test.ts
 Test Files  1 passed (1)
      Tests  1216 passed | 1 skipped (1217)

$ pnpm test src/renderer/src/lib/worktree src/main/runtime/terminal-list-execution-host-scope.test.ts src/renderer/src/lib/terminal-tab-for-pty-id
 Test Files  49 passed (49)
      Tests  507 passed (507)

$ pnpm tc          # clean
$ oxlint           # exit 0, no findings in changed files
$ pnpm run check:code-quality:changed
code quality: 0 new finding(s) across 9 changed file(s).
type-aware code quality: 0 new finding(s) across 9 changed file(s).
React Doctor: 0 new finding(s) across 9 changed file(s).

Also here

worktreeIdsEqual is lifted from a private runtime helper into src/shared/worktree/id.ts — a byte-identical move (exact repoId, path spelling folded via normalizeRuntimePathForComparison, ::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).

The same additive helper also appears in the STA-4577 PR, which needs it independently. The additions are identical, so the two merge cleanly in either order — verified by merging all split branches together and diffing against the original combined tree (empty).

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 revert of this PR also removes worktreeIdsEqual from src/shared/worktree/id.ts, which breaks whichever STA-4577 PR (#17430 / #17445) has landed by then — they import it. To revert:

git revert -n <sha> && git checkout HEAD -- src/shared/worktree/id.ts

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 worktreeIdsEqual at the same anchor in src/shared/worktree/id.ts with different JSDoc, so git merge-tree reports a content conflict. Resolution when rebasing #17445: drop its id.ts hunk and keep this one's. #17430 merges cleanly in either order (byte-identical id.ts hunk, non-overlapping orca-runtime.ts hunks).

@greptile-apps

greptile-apps Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR changes worktree-agent activation to reconcile live PTYs against the execution host’s terminal-surface census rather than renderer-local bindings.

  • Fails closed when the host census is unavailable, truncated, unscoped, or ambiguous.
  • Rebinds host-owned panes and creates recovery surfaces only for PTYs positively reported as unowned.
  • Returns an empty outcome when no live PTY receives a surface so callers can seed a fresh shell.
  • Moves normalized worktree-ID equality into the shared worktree identity module.

Confidence Score: 5/5

The PR appears safe to merge because no blocking failure remains within the eligible follow-up-review scope.

No blocking failure remains.

Important Files Changed

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]
Loading

Reviews (3): Last reviewed commit: "fix(worktree): name the live PTYs the su..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 582cc

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the main change: gating agent activation on the live surface census instead of renderer state.
Description check ✅ Passed The description is detailed and mostly complete. It explains the problem, implementation, rationale, linked issue, testing results, performance impact, compatibility considerations, and merge dependen…
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 89a4d67 and e58b5cb.

📒 Files selected for processing (9)
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/lib/worktree-agent-activation-gate.test.ts
  • src/renderer/src/lib/worktree-agent-activation-gate.ts
  • src/renderer/src/lib/worktree-agent-activation-seam.test.ts
  • src/renderer/src/lib/worktree-agent-live-surface-adoption.ts
  • src/renderer/src/lib/worktree-live-terminal-surface-owners.test.ts
  • src/renderer/src/lib/worktree-live-terminal-surface-owners.ts
  • src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts
  • src/shared/worktree/id.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment on lines +35 to +39
if (
!value ||
typeof value !== 'object' ||
!Array.isArray((value as { terminals?: unknown }).terminals)
) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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'
) {

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • worktreeIdsEqual lifted to shared — the private runtimeWorktreeIdsEqual helper moves byte-identically into src/shared/worktree/id.ts and 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.ts calls terminal.list (id:-scoped, limit: 200, includeVisualLayouts: false) and returns a whole-index null on !response.ok, missing/malformed hostScope, truncated === true, or hostScope.hostIds.length === 0; otherwise it builds Map<ptyId, owner | null> in which a null entry means "unverifiable" (unaddressable surface or two surfaces claiming one PTY).
  • Adoption/mint rework — adoptLiveWorkspacePtySurfaces pre-filters through resolveTerminalTabPtyOwnership (which also keys persisted tab.ptyId and ptyIdsByLeafId, not just the old ptyIdsByTabId), 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 ptyIsAlreadyBound loop is replaced with the census-backed path via a new listSurfaceOwners dep; 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).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the nwparker/sta-5701-activation-gate-surface-census branch from e58b5cb to d762ef8 Compare August 31, 2026 07:01
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Fail-silent closed — adoptLiveWorkspacePtySurfaces now 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 — bindLivePtyToExactSurface and indexLiveTerminalSurfaceOwners now 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.
  • adoptHostOwnedSurface reports failure — returns false when 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…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.
@nwparker
nwparker force-pushed the nwparker/sta-5701-activation-gate-surface-census branch from d762ef8 to 582cc83 Compare August 31, 2026 08:01
@nwparker

Copy link
Copy Markdown
Contributor Author

Rebased onto origin/main (was 9 behind, clean) and pushed one hardening commit: 582cc8399fb.

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 adopted in that case — so the caller's outcome === 'empty' seam seeds an ordinary shell instead of leaving a blank workspace — but the decline itself was mute.

  • adoptLiveWorkspacePtySurfaces now returns { surfaced, declinedPtyIds }, and the gate logs [worktree-activation] live PTYs left without a surface with the workspace id and the PTY ids. A live agent the user can no longer see is now diagnosable from the console rather than silent.
  • New test for the host-named-leaf decline, which previously had no coverage in either direction.
  • New main-side test pinning the superseded-inventory race in terminal.list: two overlapping scoped listings, the loser returns hostScope.hostIds === []. That is what makes the renderer's unverifiable verdict reachable on a plain local machine, not only against a degraded or SSH host — it justifies the seeded-shell fallback rather than a bare log.

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). pnpm tc exit 0. oxlint and oxfmt --check clean on the changed files.

What was deliberately not done

The review also suggested extracting the shared shape guard between worktree-live-terminal-surface-owners.ts (isScopedTerminalListResult) and host-live-terminal-probe.ts (isTerminalListResult). Skipped: the two have deliberately opposite hostScope policies, and the refactor would pull the SSH liveness probe's live/none/unverifiable verdict into this PR's blast radius for no risk reduction. Worth a follow-up, not worth doing here.

Residual risk

A new renderer paired with a remote Orca host that predates the hostScope field will read the census as permanently unverifiable, so the decline path is the steady state for that pairing rather than an edge case. The consequence is benign — a seeded shell plus a console warning, and the user reattaches the running agent manually — but the feature does not work against those hosts, and cross-version wire compatibility is skipping on this PR. The SSH and folder-workspace paths are covered only by unit tests against a stubbed store; the e2e shards and ssh docker watcher isolation are also skipping.

Merge order: merge this before #17445 (or rebase #17445 onto it) — both add worktreeIdsEqual at the same anchor with different JSDoc. #17430 merges cleanly either way. Revert carve-out is now documented in the PR description.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts
  • src/renderer/src/lib/worktree-agent-activation-gate.test.ts
  • src/renderer/src/lib/worktree-agent-activation-gate.ts
  • src/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'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Named declined live PTYs — adoptLiveWorkspacePtySurfaces now returns { surfaced, declinedPtyIds } instead of a bare boolean, and the gate logs a console.warn when 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's unverifiable verdict 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).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 6bbed15 into main Aug 31, 2026
33 checks passed
@nwparker
nwparker deleted the nwparker/sta-5701-activation-gate-surface-census branch August 31, 2026 08:40
nwparker added a commit to nwparker/orca that referenced this pull request Aug 31, 2026
…-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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant