Skip to content

fix(agent-status): settle stranded PTY rows through the host inventory - #22085

Closed
brennanb2025 wants to merge 6 commits into
mainfrom
brennanb2025/pty-settle-through-host-inventory
Closed

brennanb2025 wants to merge 6 commits into
mainfrom
brennanb2025/pty-settle-through-host-inventory

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​917 $\color{#cf222e}{\Huge{\mathbf{−}}}$​604 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​313
Prod 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​410 $\color{#cf222e}{\Huge{\mathbf{−}}}$​289 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​121

What this fixes

Problem: a terminal agent that was working when Orca closed kept saying "Working" in its pane and in the sidebar forever if its terminal did not survive the restart (the agent was killed, crashed, or the machine rebooted while Orca was closed). Nothing could clear it: no agent was left to send a "done" signal, and the only cleanup covered Claude alone.

Who hits it: every terminal agent other than Claude (Codex, Grok, Cursor, Copilot, Gemini, OpenCode, Droid, Amp, Pi, Antigravity and the rest) in a local or WSL terminal, in both git worktrees and folder workspaces, on the desktop app and on a headless orcad host. Claude was covered by an older startup-only cleanup, which this PR replaces.

What you see now: after Orca restarts, a pane whose agent's terminal is gone stops saying "Working" within seconds, from the terminal check Orca runs at startup. Measured live on macOS: the row cleared within 12 seconds of launch, where main left it "Working" indefinitely (still stuck after 4+ minutes). When the dead agent had a resumable session, main did eventually clear the row as a side effect of Orca auto-typing the agent's resume command (about 85-95 seconds after launch); with this PR it clears within 30 seconds either way. The agent's session is kept, so you can still resume it in that pane. The pane shows no status, which is what it already shows when a terminal exits while Orca is open, whether the agent had last said Working, Waiting, Blocked or Done. For Claude this is a small change: the old cleanup relabelled such a row "Done", which claimed a completion nobody observed; it now clears like every other agent's.

Not affected / not fixed here:

  • An agent that is still running keeps its status. Its row is only cleared when the machine that owns the terminal says that terminal no longer exists.
  • SSH terminals are not changed. A remote agent whose terminal died while Orca was closed still reads "Working", exactly as on main. The SSH relay's list of terminals is not proof: after a relay restart or an Orca update, the new relay does not list terminals the old one started, even though they may still be running. Clearing those rows needs a proven exit from the relay, which is separate work. An unreachable host's rows are never touched.
  • The floating terminal keeps today's behaviour (not cleared, same as main).
  • If the terminal daemon failed to start this session, local rows are left alone, because the fallback terminal provider cannot see the previous session's terminals and would wrongly report them gone. The old cleanup skipped this case too.
  • Structured (native) chat sessions are not touched; they have no terminal.

This is not a regression: main has never cleared these rows for non-Claude agents.

What Changed

Orca already asks each machine which terminals it is running (the host's terminal inventory) at startup, after an SSH reconnect, when the renderer starts, on a headless host, and whenever terminal list, worktree ps or the mobile app refresh. That check already tells "the machine answered" apart from "we never reached it", and already uses the answer to retire orchestration bookkeeping for terminals that are gone.

Agent status now uses the same answer. For each saved agent row whose terminal the owning machine answered for but did not list, Orca asks that machine directly about that exact terminal. Only a definite "it does not exist" (or an exit the machine itself reported) clears the row. "Still running" and "could not tell" leave it untouched.

Three checks keep a live agent from being cleared: a pane that has sent status during this run is never judged; the row must still be the exact one that was judged (a newer event cancels the clear); and if the pane got a new terminal while the check was running, the clear is dropped. A dropped clear is not lost: the next inventory check judges it again.

The old Claude-only startup cleanup (server-reaping.ts, the one-shot sweep in main-process-pty-startup.ts) is deleted, along with its entry in the legacy status-ingress manifest and a helper nothing else used.

Why

The old cleanup was the wrong shape: one vendor, one machine, one pass at startup. Adding more vendors or hosts to it would mean a second copy of logic the inventory check already has, including the hard part: telling "gone" apart from "could not ask". Reusing the inventory's answer means every agent goes through one path on every machine, it runs again on reconnect and on every list, and there is one rule for what counts as proof of death. When the SSH relay can prove a remote exit, remote rows will clear through this same path with no new mechanism.

Alternatives considered:

  • A periodic sweep or a timeout that clears rows nobody has updated for a while. Rejected: a long-running quiet agent would be wrongly cleared, and the inventory already runs at the moments that matter.
  • Clearing every restored row at startup. Rejected: it would wipe the status of agents still running in the terminal daemon, which is the main reason the daemon exists.
  • Treating "missing from the SSH relay's list" as dead. Rejected for the reason above; it would clear the status of remote agents that are still running.

Linked Issue

N/A (maintainer PR; no pre-existing issue).

Visual Proof

Live Electron QA on a macOS machine (not the author's laptop), with a stand-in agent reporting as Gemini through Orca's own status hooks. Branch arm built at 30bf581; the only production change after that is the failed-daemon guard, which does not apply when the daemon is running, as it was here. Main arm built at d0db35c.

Agent working, then Orca quit, the agent's process killed while Orca was closed, and Orca relaunched. The agent had no resumable session, so nothing else could clear the row.

Before quitting (branch; main looked the same):

Agent working before quit

Main after relaunch: the dead agent's row is still listed ("QA stub agent … is wor…", 9 minutes later):

Main: dead agent still listed after relaunch

This PR after relaunch: the row is gone (cleared about 2 seconds after launch, before the pane reattached):

PR: row cleared after relaunch

Same, with a second terminal keeping the terminal daemon alive and a resumable session (the most common real setup). Both arms clear the row eventually; this PR within 30 seconds, main after about 96 seconds via the resume path. The auto-typed resume command is existing behaviour on both arms.

Main after relaunch (cleared after ~96 s): Main 1c

This PR after relaunch: PR 1c

Must not regress: the agent is still running across the restart. Orca quit, the agent left alive, Orca relaunched, then a window reload to force another terminal check. The row stays on both arms. The grey dot, rather than a spinner, is the existing "restored, not yet reconfirmed" display on both arms.

Main: Main live agent kept

This PR: PR live agent kept

Also checked on both arms: the agent exiting while Orca is open clears the row in under half a second (unchanged). SSH live QA was blocked: the QA machine has no key for the Linux test box, and none was added. SSH behaviour is unchanged by design (see above) and covered by unit tests.

Testing

  • I manually tested these changes (live Electron QA on a macOS machine; see Visual Proof)

  • Automated tests added/updated

  • New tests cover: settling across a restart through the saved pane layout; a still-running terminal is left alone; an unreachable or never-asked host is left alone; a per-SSH-target check never touches local rows; a failed terminal daemon leaves local rows alone; each of the three checks above (each was removed in turn and the test confirmed to fail); every supported non-Claude agent type.

  • pnpm tc:node passes. Named vitest suites for the settlement, pane binding, startup ordering, legacy-ingress ratchet and orca-runtime.test.ts pass.

  • Platforms: macOS (live). Linux, Windows and WSL share the same code path through the local terminal daemon and are covered by unit tests only. SSH behaviour is unchanged and covered by unit tests.

Notes

Security: no new inputs or wire changes. Cross-platform: no platform-specific code. SSH: deliberately unchanged (see above). Mobile: a cleared row reaches paired phones through the existing status push. Compatibility: no persisted-format or wire change. Performance: the extra work runs only inside existing inventory checks: one pass over saved agent rows, and at most one direct question per missing terminal (none for SSH).

@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d8e5245b-5453-4a52-8226-da8585b4078f

📥 Commits

Reviewing files that changed from the base of the PR and between 49307ca and 30bf581.

📒 Files selected for processing (4)
  • src/main/orcad/orcad-entry.ts
  • src/main/runtime/orca-runtime-state-fields.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/startup/main-process-runtime-service.ts

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


📝 Walkthrough

Walkthrough

The change replaces restored-subagent startup reaping with PTY inventory settlement. The server now lists eligible status rows and settles rows whose PTYs are proven absent, while preserving resume identity and freshness fences. Runtime inventory refresh supplies host scope, live PTY IDs, bindings, and liveness results. Startup reaping APIs, tests, and legacy ingress metadata are removed.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 30bf5

A newly updated agent status could be incorrectly marked missing. Strengthen the row-identity fence before merging unless this timing risk is explicitly accepted.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 30bf5

An older inventory check can finish after a newer check has found a terminal running, yet still retire its activity status. The change adds no identified external privilege, but the state transition warrants review.

Retained concerns

  • Medium · reliability · inferred: An older absence probe can retire a pane after a newer inventory pass has positively observed its PTY live. The final store checks protect row identity and runtime observations, but not newer PTY-liveness evidence.
Security review details

Security Blast Radius

  • inferred — Inventory settlement can affect eligible agent-status rows for queried local or SSH execution hosts, rather than only the former local Claude startup subset. The identified stale-probe interleaving is concretely supported for an asynchronous local PTY probe; equivalent remote exposure was not established.

Security Findings and Attack Paths

  • inferred — The stale-probe interleaving can falsely clear a live pane’s activity claim. The examined paths do not establish that this grants an attacker privileges or crosses a tenant boundary; it is a state-integrity concern, not a verified security exploit.

Trust Boundaries and Controls

  • inferred — The new constructor port is internally wired to the agent-status store. The consumer separately checks connection scope and declared execution-host ownership before considering PTY evidence; this assessment did not independently re-audit authentication of upstream hook ingress.

Resilience and Maintainability Implications

  • observed — A probe that fails or cannot answer produces an unverifiable verdict and does not settle the row. Settlement errors are logged without aborting inventory listing.

Hardening Proposals

  • proposed — Before final retirement, invalidate an absence verdict if a newer inventory generation or positive liveness observation exists. Exercise the ordering with an overlap test in which the newer pass reports the PTY live before the older probe resolves.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 15 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 identifies the main change: settling stranded PTY-backed agent-status rows through host inventory.
Description check ✅ Passed The description is substantially complete. It explains the problem, affected users, behavior change, implementation, rationale, alternatives, linked-issue exception, visual proof, testing, platform co…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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: Advanced

Run ID: 69ecfde8-b3cc-48f5-b1dc-f89df453dff3

📥 Commits

Reviewing files that changed from the base of the PR and between 9267423 and 394f9e9522c119321fefeccd565bb18df211a426.

📒 Files selected for processing (18)
  • src/main/agent-hooks/agent-status-pane-binding.test.ts
  • src/main/agent-hooks/agent-status-pane-binding.ts
  • src/main/agent-hooks/agent-status-pty-inventory-settlement.test.ts
  • src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts
  • src/main/agent-hooks/server/server-hydration.ts
  • src/main/agent-hooks/server/server-pty-inventory-settlement.ts
  • src/main/agent-hooks/server/server-reaping.ts
  • src/main/orcad/orcad-entry.ts
  • src/main/runtime/agent-status-store-wiring.test-fixture.ts
  • src/main/runtime/orca-runtime-preserved-branch-cleanup.ts
  • src/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.ts
  • src/main/runtime/orca-runtime-state-fields.ts
  • src/main/runtime/pty-inventory-agent-status-settlement.test.ts
  • src/main/runtime/runtime-agent-status-inventory-settlement.ts
  • src/main/startup/desktop-startup-ordering.test.ts
  • src/main/startup/main-process-pty-startup.ts
  • src/main/startup/main-process-runtime-service.ts
  • src/shared/agent-status-legacy-ingress-manifest.ts
💤 Files with no reviewable changes (4)
  • src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts
  • src/main/agent-hooks/server/server-reaping.ts
  • src/shared/agent-status-legacy-ingress-manifest.ts
  • src/main/agent-hooks/agent-status-pane-binding.ts

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

Comment on lines +87 to +91
if (
!current ||
current.stateStartedAt !== candidate.stateStartedAt ||
current.receivedAt > candidate.receivedAt
) {

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,130p' src/main/agent-hooks/server/server-pty-inventory-settlement.ts
rg -n -C 3 'stateStartedAt|receivedAt|settlePtyInventoryAbsence|alias' src/main/agent-hooks src/main/runtime
sed -n '430,475p' src/main/agent-hooks/agent-status-pty-inventory-settlement.test.ts

Repository: stablyai/orca

Length of output: 45541


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- settlement source ---'
cat -n src/main/agent-hooks/server/server-pty-inventory-settlement.ts | sed -n '1,150p'
printf '%s\n' '--- related files ---'
rg --files src/main/agent-hooks | rg 'pty-inventory|agent-status-pty-inventory|settlement'
printf '%s\n' '--- focused symbols ---'
rg -n -C 5 'listPtyInventorySettlementCandidates|settlePtyInventoryAbsence|stateStartedAt|receivedAt|replace|alias' \
  src/main/agent-hooks/server/server-pty-inventory-settlement.ts \
  src/main/agent-hooks/agent-status-pty-inventory-settlement.test.ts \
  src/main/agent-hooks/server
printf '%s\n' '--- identity declarations and contract text ---'
rg -n -C 4 'PtyInventorySettlement|InventorySettlement|candidate contract|exact event|stateStartedAt.*receivedAt|receivedAt.*stateStartedAt' \
  src/main/agent-hooks src/main/runtime | head -n 500

Repository: stablyai/orca

Length of output: 42042


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 40548


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- alias and replacement definitions ---'
rg -n -C 8 'resolvePaneKeyAlias|paneKeyAlias|alias.*pane|pane.*alias|lastStatusByPaneKey|reconcileEndedProcessForPaneKeys' src/main/agent-hooks/server | head -n 1200
printf '%s\n' '--- status application ---'
cat -n src/main/agent-hooks/server/server-status-application.ts | sed -n '90,135p'
printf '%s\n' '--- focused settlement tests ---'
cat -n src/main/agent-hooks/agent-status-pty-inventory-settlement.test.ts | sed -n '350,510p'
printf '%s\n' '--- exact identity and eviction references ---'
rg -n -C 8 'dropPersistedStatusEntries|receivedAt.*stateStartedAt|stateStartedAt.*receivedAt|same pair|exact event instance' src/main/agent-hooks/server src/main/agent-hooks/agent-status-pty-inventory-settlement.test.ts

Repository: stablyai/orca

Length of output: 42659


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- alias maintenance and row transfer ---'
cat -n src/main/agent-hooks/server/server-authority-aliases.ts | sed -n '1,220p'
printf '%s\n' '--- alias resolution and retirement ---'
cat -n src/main/agent-hooks/server/server-authority-fences.ts | sed -n '190,245p'
printf '%s\n' '--- cache move helper ---'
rg -n -C 12 'function movePaneCacheState|movePaneCacheState|admitLegacyAgentStatus|register.*Alias|canRegisterPaneKeyAlias' src/shared/agent-hook-listener src/main/agent-hooks/server
printf '%s\n' '--- status map writes around accepted events ---'
rg -n -C 8 'lastStatusByPaneKey\.set|commitStatusRowMutation|applyNormalizedStatus|attachStatusTiming' src/main/agent-hooks/server

Repository: stablyai/orca

Length of output: 42624


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- alias registration callers ---'
rg -n -C 10 'registerPaneKeyAlias\(' src/main src/shared | head -n 800
printf '%s\n' '--- cache move implementation ---'
cat -n src/shared/agent-hook-listener/listener-state.ts | sed -n '245,285p'
printf '%s\n' '--- receivedAt ordering calculation ---'
cat -n src/main/agent-hooks/server/server-status-update.ts | sed -n '48,72p'
printf '%s\n' '--- transfer completion and alias registration ---'
cat -n src/main/agent-hooks/server/server-authority-aliases.ts | sed -n '135,270p'

Repository: stablyai/orca

Length of output: 42144


Require an exact receivedAt match before settlement.

The candidate contract uses receivedAt and stateStartedAt as the event identity. Alias resolution can expose a different row with the same stateStartedAt but an earlier receivedAt. The current comparison accepts that row and reconciles it.

-        current.receivedAt > candidate.receivedAt
+        current.receivedAt !== candidate.receivedAt
📝 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 (
!current ||
current.stateStartedAt !== candidate.stateStartedAt ||
current.receivedAt > candidate.receivedAt
) {
if (
!current ||
current.stateStartedAt !== candidate.stateStartedAt ||
current.receivedAt !== candidate.receivedAt
) {

@brennanb2025
brennanb2025 force-pushed the brennanb2025/pty-settle-through-host-inventory branch 2 times, most recently from b660a73 to 4cb5b44 Compare September 21, 2026 21:51
A terminal agent's pane could read "Working" forever after a restart its PTY
did not survive. The only reconciler was scoped to Claude, local execution
hosts, and a single startup pass, so every other vendor and every remote host
had no cleanup at all.

Agent status becomes the second consumer of the host-scoped inventory diff
`refreshPtyWorktreeRecordsWithControllerInventory`, which already distinguishes
"the host answered" from "the host was never asked" and already retires one
durable obligation from the same answer. The one-shot startup reaper and its
Claude-only sweep are deleted.

Verdicts route through the shipped `PtyLivenessVerdict` register: only `exited`
settles, and `live` / `unverifiable` do nothing at all.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/pty-settle-through-host-inventory branch from 4cb5b44 to 49307ca Compare September 21, 2026 21:57

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

Important

PR CI fails on a new max-lines error in the changed inventory file, and the candidate listing's fence-1 invariant is weaker than its comment claims. Neither is a runtime bug, but both are worth resolving before merge.

Reviewed changes

  • General settlement replaces the Claude-only startup sweep — a new store half (server-pty-inventory-settlement.ts) offers every vendor's stranded row as a candidate, and a new runtime half (runtime-agent-status-inventory-settlement.ts) settles it from the host-scoped PTY inventory diff, reusing the shipped exited | live | unverifiable verdict register.
  • Host scoping before evidence — inventoryCoversConnection + queriedHostIds + the declared-execution-host check gate each candidate, so a per-SSH-target pass cannot touch a local row and unknown provenance is never adjudicated.
  • Three fences around reconcileEndedProcessForPaneKeys — runtime-observed exclusion, receivedAt/stateStartedAt row identity, and a bound-PTY rebind check, with preserveResumeIdentity: true keeping a resumable remnant.
  • Deletions and rewiring — server-reaping.ts and the sweep removed, restored-subagent-liveness-sweep.ts renamed to agent-status-pane-binding.ts, the main-restored-status-reaping ingress entry dropped, and the daemon-authority ordering test re-pointed at probePtyLivenessFromRuntimeController.
  • Tests — 30 settlement + 5 wiring tests, all green; focused run confirmed.

⚠️ orca-runtime-refresh-pty-worktree-records-with-controller-inventory.ts now exceeds the max-lines cap, so PR CI fails

Adding the two settlement methods inline pushes this file to 366 counted lines (blank/comment lines excluded) against the repo-wide 300 cap. pnpm exec oxlint --format github — the exact command in .github/workflows/pr.yml:134-135 — now reports File has too many lines (366) as the only error in the run; the base revision of this file passes. AGENTS.md forbids a max-lines disable, so this needs a split rather than a suppression.

Technical details
# Split the settlement methods out of the capped inventory file

## Affected sites
- `src/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.ts:332-395` — the new `getBoundPtyIdForPaneKey` and `settleAgentStatusRowsAbsentFromInventory` methods, plus their imports, add the overage. The file is a `// @ts-nocheck` mechanical-split segment.

## Required outcome
- `pnpm exec oxlint --format github` is clean at this revision.
- No `max-lines` disable (per AGENTS.md); no per-file bump in `.oxlintrc.json`.

## Suggested approach (optional)
- Extract the two `protected` methods into a new mechanical-split segment (e.g. `orca-runtime-settle-agent-status-from-inventory.ts`) inserted between `OrcaRuntimeWithRefreshPtyWorktreeRecordsFromController` and this class, matching the existing split chain. `refreshPtyWorktreeRecordsWithControllerInventory` can keep calling them through inheritance.

## Open questions for the human (optional)
- Is the file at 299 counted lines on `main` deliberate headroom, or is a broader split of this segment also acceptable?

ℹ️ Nitpicks

  • A candidate whose probe returns null (unverifiable) is re-probed on every inventory pass, including the terminal list and mobile-cadence call sites, since readPtyVerdict caches no negative result. It is fire-and-forget, but for SSH that is a relay round-trip per pass per permanently-unverifiable row; consider whether the register's unverifiable should suppress a re-probe within a pass window.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

entry.structuredHost ||
// An identity-only remnant carries no state claim, so there is nothing here to retire.
entry.providerSessionOnly ||
this.runtimeObservedStatusPaneKeys.has(paneKey) ||

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.

This fence is documented as "a pane that has produced status in THIS runtime is never offered," but runtimeObservedStatusPaneKeys is not that set: an accepted event whose row is restoredUnconfirmed deletes the pane from it (server-status-update.ts:227-232), and server-last-status-restored-children.test.ts:292-320 shows a live Stop after restart leaving the pane absent (observedInCurrentRuntime: false). Such a row is still offered here, and fence 2 cannot refuse it because the candidate snapshot is taken from the already-updated row. The exited verdict gate is then the only thing between a live pane and retirement.

Technical details
# Fence 1 does not mean "produced status this runtime"

## Affected sites
- `src/main/agent-hooks/server/server-pty-inventory-settlement.ts:44` — listing-side fence 1.
- `src/main/agent-hooks/server/server-status-update.ts:227-232` — accepted `restoredUnconfirmed` events delete membership instead of adding it.
- `src/main/agent-hooks/server-last-status-restored-children.test.ts:292-320` — in-tree reproduction of a live event that leaves the pane outside the set.

## Required outcome
- Either the documented invariant holds (a pane with a live producer is never a candidate), or the comment states the actual guarantee.

## Suggested approach (optional)
- Track "produced status this runtime" separately from `runtimeObservedStatusPaneKeys` (which is intentionally cleared for restored-unconfirmed events so the old liveness reconciliation stayed eligible), and fence on that.

## Open questions for the human (optional)
- Is adjudicating a restored-unconfirmed-but-live pane intended? If so, the fence comment should say the verdict gate is the protection, not the observed set.

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

ℹ️ Follow-up changes reviewed — no new issues in the delta. The prior blocking max-lines finding is resolved; the earlier fence-1 observation is untouched by these changes and still stands.

Reviewed changes (delta since 394f9e9522)

  • Settlement extracted into a typechecked segment — orca-runtime-settle-agent-status-from-inventory.ts now holds retireObligationsAbsentFromInventory, getBoundPtyIdForPaneKey, and settleAgentStatusRowsAbsentFromInventory; the inventory file extends it and calls the grouped retire, bringing the capped file back under 300 lines. Full oxlint --format github is now 0 errors.
  • Vendor list bound to the real union — STRANDED_VENDORS: readonly TuiAgent[], so a typo fails the build instead of testing a fictional vendor.
  • Folder-workspace resolution fixed — the runtime dep now reads getFolderWorkspaces()?.find(...); the previous getFolderWorkspace?.() did not exist on RuntimeStore, so folder-workspace rows always resolved to unknown.
  • Leaf lookup made explicit — getBoundPtyIdForPaneKey compares leaf.tabId/leaf.leafId instead of the getLeafKey map lookup; behavior is equivalent.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…le-through-host-inventory

# Conflicts:
#	src/main/startup/desktop-startup-ordering.test.ts
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Refactors PTY lifecycle management and agent status settlement.

The PR does not yet appear safe to merge because an earlier absence probe can clear status after a newer inventory has seen the same PTY ID live.

Findings

  1. P1 Live PTY status can disappear ▶
  2. P1 Degraded daemon rows stay working ▶

Summary

The PR replaces a Claude-only startup sweep with host-inventory-based retirement of restored terminal-agent status rows. It checks the owning host and exact PTY, preserves resumable session identity, and leaves unverifiable or still-live terminals untouched.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Host PTY inventory] --> B{Host answered and owns row?}
  B -->|No| K[Keep status]
  B -->|Yes| C{PTY listed live?}
  C -->|Yes| K
  C -->|No| D[Read exit verdict or probe exact PTY]
  D -->|Live or unverifiable| K
  D -->|Exited| E{Status and pane binding still match?}
  E -->|No| K
  E -->|Yes| F[Clear status; retain resume identity]
Loading

Reviews (5) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

Comment on lines +148 to +153
if (
deps.getBoundPtyIdForPaneKey(candidate.paneKey) !==
boundAtVerdictByPaneKey.get(candidate.paneKey)
) {
continue
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Live PTY status can disappear

If a restored pane starts a replacement process under the same PTY ID while an earlier absence probe is pending, a newer inventory can see that PTY live before the old probe returns false. This check sees an unchanged binding, and the status store sees an unchanged restored row, so the earlier pass clears the agent status even though the replacement PTY is running. The settlement needs to account for newer positive liveness evidence or the PTY incarnation.

Knowledge Base Used:

…ocal provider

When the terminal daemon failed to start (or has not been installed yet), the
in-process fallback provider answers "absent" for every PTY id a previous
run's daemon minted, so any terminal list / ps / mobile inventory pass would
retire the hydrated rows of agents that may still be running in that daemon.
The deleted startup reaper bailed out in this case and the startup inventory
refresh already gates on canRecoverPersistentLocalPtys; the settlement now
treats the local host as unanswered under the same predicate.

Also removes reapRestoredClaudeSubagentsForDeadPane, left unused by the
deleted reaper.
Comment on lines +68 to +75
const scopedAnswer = this.canRecoverPersistentLocalPtysFn()
? answer
: {
...answer,
queriedHostIds: new Set(
[...answer.queriedHostIds].filter((hostId) => hostId !== LOCAL_EXECUTION_HOST_ID)
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Degraded daemon rows stay working

When orcad adopts a daemon in degraded mode, this check removes local from every inventory answer because fresh PTYs use the in-process fallback. The degraded provider can still list and probe its existing daemon sessions, but removing local skips those rows before their PTYs are checked. If one of those sessions died while Orca was down, its restored working status is not retired.

Knowledge Base Used: Agent integrations and hooks

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@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 in this delta.

Reviewed changes (incremental since the prior pullfrog review at 30bf581013)

  • Local rows are not adjudicated without a persistent local provider — settleAgentStatusRowsAbsentFromInventory now copies queriedHostIds with LOCAL_EXECUTION_HOST_ID removed when canRecoverPersistentLocalPtysFn() is false, so the in-process fallback's "absent" answer can no longer retire rows whose daemon-owned PTYs may still be running in a daemon this process never asked. SSH rows still settle, and the predicate is evaluated per pass.
  • Ablation-verified test — the new case pins that the same candidate which settles under a daemon provider is left alone under the fallback. I confirmed it flips to failing when the scoping is removed.
  • Dead code removed — reapRestoredClaudeSubagentsForDeadPane and its now-unused reapUnconfirmedRestoredClaudeSubagents import, left over from the deleted reaper; the underlying helper is still used by claude-events.ts.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

The class doc said only "still working" rows settle, and "for every host",
but any row with a state claim settles and a remote row settles only on a
recorded, host-certified exit. The resume-identity doc still said only a
surviving shell keeps the remnant; the inventory settlement keeps it too.
Rename the two remote tests so neither claims the relay's listing is
evidence: one injects the recorded exit, the other is a relay omission.

Also drop the deleted sweep test's CI shard timing and format two PR test
files that failed oxfmt.
…d pane layout

The runtime-level settle test bound the dead PTY in this runtime, which never
happens after a restart. Cover the persisted-layout lookup the restart case
actually takes, and name the bound-PTY test for what it exercises.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready for review (not merged)

The problem: a terminal agent that was working when Orca closed kept reading "Working" forever after a restart its terminal did not survive, for every agent except Claude. This PR clears those rows from the terminal list Orca already gets from each machine at startup.

What you see now: measured live on macOS, the stuck row clears within about 12 seconds of relaunch. On main, the same row was still listed 4+ minutes later. An agent that is still running keeps its row on both builds.

Scope decision (explicit): SSH terminals are unchanged. A remote agent whose terminal died while Orca was closed still reads "Working", as on main. The SSH relay's list of terminals is not proof of death: after a relay restart or an Orca update, the new relay does not list terminals the old one started, even though they may still be running. Clearing remote rows needs a proven exit from the relay, which is separate work. The floating terminal is also unchanged. The PR body now says all of this; the previous body claimed remote panes were fixed.

Changes made during this review:

  • Merged current main into the branch. The one conflict was in a test file; both sides were kept.
  • 523415abab8: fixed a risk this PR introduced. If the terminal daemon failed to start, the fallback terminal provider reports every terminal from the previous session as gone, which would have cleared rows for agents that may still be running. Local rows are now left alone in that case, using the same check the startup terminal recovery already uses. A new test fails without the fix. Also removed a helper that nothing calls anymore.
  • 29abf1137d2: code comments and test names now say exactly what is settled (any state, and remote rows only on a proven exit). Also removed a stale CI timing entry for a deleted test.
  • 6f2b4929435: added a test for the real restart path, where the pane's terminal is found through the layout saved by the previous run. The test fails if that lookup is removed.

Verification: three review loops (the last one clean), with readiness checks at the start and end of the session. tc:node passes at every pushed head. The named test suites pass, and CI is green at 6f2b4929435. Live Electron QA ran on a separate macOS machine against both main and this branch. Screenshots are in the PR body under Visual Proof.

Case main this PR
Agent's terminal killed while Orca closed, no resumable session still listed after 4+ min cleared about 2 s after launch
Same, second terminal keeps the daemon alive, resumable session cleared after about 96 s (via the resume path) cleared within 30 s
Agent still running across the restart row kept row kept
Agent exits while Orca is open cleared in under 0.5 s cleared in under 0.2 s
SSH live blocked (QA machine has no key for the Linux box; none added) blocked

Not caused by this PR, seen during QA (same on main):

  • After a restart, Orca auto-types the agent's resume command (for example gemini --yolo --resume <id>) into the reopened pane, even when the agent had already died before Orca closed.
  • A still-running agent's row shows a grey "Idle" dot instead of the spinner after a restart, until the agent reports again.

Not verified: a live SSH run, and Windows, Linux or WSL (the same local-daemon code path, covered by unit tests only). There was no performance measurement; by code reading, the added work runs only inside existing terminal checks, with at most one direct question per missing terminal.

…le-through-host-inventory

Conflict: src/main/startup/desktop-startup-ordering.test.ts. Main (#23976)
trimmed the file to three cases and deleted its source-order grep tests,
including the one this PR had re-pointed at the PTY liveness probe's
startup barrier. Took main's file, and moved that guard into the
behavioural swap-window suite: runtime controller probePtyLiveness now has
a test that it defers a restored daemon id until the provider swap lands
(fails with the barrier await removed). No production code changed.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Brought up to date with main (merge commit ce6ec4d2dbe). There is no behaviour change.

  • One conflict: desktop-startup-ordering.test.ts. Main (test: delete the source-grep tests an earlier detector's regex missed #23976) deleted that file's tests that check source text, including the one this PR had pointed at the PTY liveness probe's startup wait. I kept main's version and moved that check into pty-startup-swap-window-presence.test.ts as a test that runs the real code: while the terminal daemon is still starting, probePtyLiveness waits instead of answering "absent". It fails if the wait is removed. No production code changed.
  • Checked:
    • main's changes to the shared runtime and startup files don't interact with this PR;
    • nothing still refers to the members this PR deletes;
    • pnpm-lock.yaml is untouched.
  • Verified: node and web typechecks pass; this PR's tests plus nearby suites (11 files, 1467 tests) pass; the changed-code quality gate passes; CI is green on the new head.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing this older restart-cleanup implementation and rebuilding it around the current terminal owner. Create an issue for dead terminals leaving restored agent rows stuck on Working before closing.

The remaining problem is tracked in #27670.

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