Skip to content

fix(runtime): restore the title of daemon sessions adopted from the inventory - #22834

Closed
mmarabel wants to merge 11 commits into
stablyai:mainfrom
mmarabel:mmarabel/issues-22809
Closed

mmarabel wants to merge 11 commits into
stablyai:mainfrom
mmarabel:mmarabel/issues-22809

Conversation

@mmarabel

@mmarabel mmarabel commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When a headless Orca server restarts, the terminals that kept running in the background come back without their title. Orca works out which agent is in a terminal, and whether it is idle, partly from that title. So after a restart every idle agent showed up as "unknown" and stayed that way until it reported something new. With this change, the server reads each surviving terminal's last title back from the terminal daemon when it picks the terminal up again.

What Changed

Before: after a restart of orca serve (for example a systemd user unit or a macOS LaunchAgent, where the terminal daemon survives the restart), surviving terminals showed title: null and no agentIdentity, and terminal.agentStatus returned status: null. A terminal titled ✳ Claude Code went from claude / idle to null / not running.

After: the same terminal again reports title: ✳ Claude Code, agentIdentity: claude and status idle.

Mechanism: a headless server adopts surviving daemon sessions from the controller inventory (refreshPtyWorktreeRecordsWithControllerInventory), not through a spawn. The restore seeding added in #12579 only runs on the two spawn paths, so it never ran here. The inventory can't carry a title either, because the daemon reports a fixed shell placeholder.

The fix is a new one-concern runtime class, orca-runtime-seed-adopted-pty-restore-title.ts, called from a single line in the inventory loop. When the inventory adopts a local session whose record has seen no output and no title, it asks the provider for its buffer snapshot (serializeProviderBuffer, visible screen only, scrollbackRows: 0). It then passes the snapshot's lastTitle to the existing seedTerminalRestoreTail, which already applies seed rules: no waiters, no lastOutputAt, and a title observed live wins. The request is:

  • fire-and-forget, so the listing is never blocked;
  • repeated only while the answer has no title: at most three times per PTY incarnation, at least 10 s apart, one at a time. The provider turns a failed snapshot into null, so a single transient failure after a restart can't leave the session without a title for good. The probe count lives in a WeakMap keyed by the PTY record, so it goes away with the record;
  • dropped if the PTY exits, is replaced or disconnects while the request is in flight;
  • skipped for SSH relay sessions, whose providers serve no buffer snapshot.

Otherwise a null or rejected snapshot, as from older daemons, does nothing.

Scope: only the title is seeded, not the preview or the tail. Adopting a session does not attach it, which is deliberate (#12589). So no live bytes follow the seed, and a seeded tail would stay frozen at the moment of adoption. Two things show why that matters. With a seeded tail, terminal read would return that stale history instead of the provider's current screen. An existing legacy-worker test also showed that wait --for tui-idle would resolve as idle from the seeded ready banner while the provider screen showed the agent working. preview therefore stays empty for these terminals, as before.

Restored titles are checked against the foreground process. A restored title is historical, and many shells never reset the title when an agent exits. So a terminal whose agent quit before the restart could keep ✳ Claude Code and read as claude / idle, and terminal send would type the prompt into the bare shell. A PTY title that was restored and never observed live (lastOscTitleEpochMs is null) therefore no longer proves an agent on its own. Before agent presence, terminal.agentStatus or the permission interactive wait report a running agent, they check the foreground process:

  • if the foreground can't be read, the restored title is kept;
  • if the cheap read shows a shell, the agent is reported only when a fresh process check recognizes one.

This is the rule the hook-status path already used. That check now lives in one shared function (pty-shell-foreground-evidence.ts) that both paths call, so they can't drift. The first live title removes the check.

A renderer pane that binds to an adopted session copies the restored title from the PTY record. Whether a title is restored is therefore always decided by the PTY record, which is the only place that knows whether a title was observed live, even when the pane's title is the one being read. That covers pane handles and PTY handles, for both status and presence.

A restored title also has to belong to the current process:

  • if the inventory reports a new incarnation under the same PTY id (a respawn the runtime never saw), the old restored title is dropped from the record and its panes, so the new process restores its own. The record remembers every title it dropped this way, because a renderer pane keeps republishing the title it showed, and that echo stays under the foreground check until a live title arrives. A title observed live stays, because the new process's output can reach the runtime through a viewer before the inventory reports it;
  • its status counts only if no recognized foreground agent contradicts it. As with presence, when the cheap read shows a shell, fresh process evidence decides which agent that is. A Gemini permission title left over a Claude session reports Claude as running with an unknown status, not a Gemini prompt. Agents that share a title identity (OMP paints Pi's title) still match. A foreground that can't be read or recognized keeps an idle or working title, but a permission title then reports no prompt: a stale prompt could draw an approval typed into whatever runs now, while losing a restored one only leaves the status unknown until live evidence arrives;
  • if a live title lands while the foreground is being checked, the status is decided again from the live title.

Why

This approach needs no daemon protocol change. The daemon already tracks each session's last title and returns it in the buffer snapshot the runtime already uses for provider-backed reads. The other option in the issue was an optional lastTitle on the inventory rows (SessionInfo / PtyProcessInfo). That would change the daemon wire format, and it would not help anyone until their long-lived daemon was replaced. That is exactly the setup this bug affects, because the daemon outlives restarts of serve and of the app. The snapshot call works against daemons that are already running.

The foreground check fails closed on purpose. When the evidence is in doubt, a send is refused rather than typed into a shell. The cost is that a running agent can read as absent until it shows a live title or a hook reports it.

Known limit: for a session nothing has attached, the seeded title is the title at adoption time. It is replaced by the first live title as soon as a viewer attaches, and hook-reported status still takes precedence over it. That is the same precedence the reattach seed already uses.

Linked Issue

Fixes #22809

Visual Proof

N/A: no visual change. This restores runtime/CLI state (terminal list, terminal.agentStatus) for a headless server. No UI is touched.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New src/main/runtime/pty-inventory-adopted-title-seed.test.ts (30 tests) runs a real OrcaRuntimeService with no window attached, the way headless serve runs, against a controller that lists a surviving session with the shell placeholder title. It covers:

  • adoption restores the title, agentIdentity: claude and terminal.agentStatus idle, with lastOutputAt null and preview/tail left empty;
  • a Pi title restores idle;
  • terminal read still returns the provider's current screen;
  • a live title observed first wins;
  • records that already saw output or a title are not probed;
  • a null snapshot, a snapshot without a title, and a rejected snapshot are no-ops;
  • repeated inventory refreshes probe once per incarnation;
  • a replacement incarnation adopted mid-flight drops the old snapshot;
  • SSH relay sessions are never probed;
  • once a shell owns the foreground behind a restored title, both terminal.agentStatus and agent presence report no agent, and a live title makes the title count again;
  • the foreground failure policy: a failed read keeps the agent, while a cached shell with unavailable or failed confirmation retires it, unless fresh evidence recognizes the agent;
  • a restored permission title (✋ Gemini CLI) reports permission and an interactive wait only while the agent owns the foreground;
  • a title a renderer pane inherits from the adopted session is verified the same way, through the pane handle and through the PTY-record path;
  • a title-less answer is retried at most three times, at least 10 s apart, one at a time, and a later snapshot still restores the title;
  • a new incarnation under the same PTY id restores its own title, including on a bound pane, keeps a title observed live, and still checks a restored title a pane goes on echoing, after one missed respawn or two;
  • a restored permission title under a different agent reports no prompt, including when only fresh evidence behind a cached shell finds that agent, and a Pi title under OMP still reads as idle;
  • a restored permission title reports no prompt when the foreground read fails, the foreground isn't a recognized agent, or it is unknown;
  • a live title that lands while a restored title is checked wins.

29 of the 30 tests fail with the call site removed. The other one checks that a live title is left alone, so it passes either way. Each foreground, pane, retry, incarnation and agent-identity guard fails its own test when reverted. The existing legacy-worker test (terminal-output-and-worker-recovery-part-02.spec.ts) counts provider snapshot calls, so its counts now include the one adoption probe, and it asserts that probe's arguments.

Commands run (Linux):

  • pnpm exec vitest run --config config/vitest.config.ts src/main/runtime src/main/ipc/pty src/main/daemon: 1148 files, 11705 tests passed (rebased on current main). Two unrelated heavy tests (automation-change-publication, terminal-output-frame-chunks-equivalence) sometimes hit the 30 s timeout under full-suite load and pass when run on their own
  • pnpm tc: passes
  • pnpm exec oxlint <changed files>, pnpm exec oxfmt --check <changed files>: clean
  • ORCA_CODE_QUALITY_BASE=upstream/main pnpm run check:code-quality:changed: passes
  • check:ts-nocheck-ratchet, check:max-lines-ratchet: pass

AI Disclosure

AI-assisted implementation and review.

Review

  • Cross-platform: no platform-specific code. The change only uses runtime records and the existing controller seam.
  • SSH/remote: app-side SSH relay PTYs are skipped because their providers have no buffer snapshot. A remote orca serve host treats its own daemon sessions as local, so it benefits from the fix directly. There is no wire change between client and host.
  • Desktop: when the renderer reattaches a pane, the spawn-path seed or live bytes arrive first and the new path skips that record. If the inventory runs first, the only extra cost is one visible-screen snapshot per surviving session. It does not add durable-history compaction, because the request stays well under the daemon's live window.
  • Agents: identity and status come from the existing title classifiers. Hook-reported status still takes precedence. A restored title is verified against the foreground process before it counts as a running agent, so sends to an agent that exited are refused.
  • Windows/SSH foreground evidence: the check uses the provider's existing getForegroundProcess and confirmForegroundProcess. A foreground that can't be read keeps the restored title, which follows the rule that loss of contact is not evidence of exit.
  • Performance: one small visible-screen snapshot request per adopted PTY incarnation, and up to three only while the answer has no title, all off the listing's critical path.
  • Security: no new inputs, IPC or persistence.
  • Refactor: the hook-status path's existing shell-foreground check moved unchanged into pty-shell-foreground-evidence.ts. The handle-binding checks still run after each await.
  • Merge conflicts: the inventory file gains one line and the new class sits lower in the runtime chain, so this applies cleanly alongside fix(agent-status): settle stranded PTY rows through the host inventory #22085.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Related: #12579 (restore seeding on spawn), #12589 (subscriber-driven attach), #12346 (restored hook rows are unconfirmed), #13203.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…nventory

After an `orca serve` restart, the runtime adopts the terminals that survived
in the daemon from the controller inventory. No spawn runs on that path, so
the restore title that the spawn paths seed never arrived. Idle agents then
read as title null, no agent identity, and status null.

On adoption of a local session whose record has seen no output and no title,
ask the provider once for its snapshot (visible screen only) and seed its
lastTitle through the existing seedTerminalRestoreTail. Only the title is
seeded. Adoption does not attach the session, so a seeded tail or preview
would stay frozen, and terminal read and tui-idle waits would read stale
history instead of the provider's current screen.

A restored title can outlive its agent when the shell never resets it. So a
PTY title that was restored and never observed live no longer proves an
agent on its own. Agent presence, agent status and the permission
interactive-wait check verify the foreground first. They share one
shell-foreground check with the hook-status path, extracted into
pty-shell-foreground-evidence.ts, so a send never types a prompt into a
bare shell.

Fixes stablyai#22809
@coderabbitai

coderabbitai Bot commented Sep 25, 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: b82fa4cd-6d31-4a05-a462-4b2e47d59dde

📥 Commits

Reviewing files that changed from the base of the PR and between 812c500 and 10027f5.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime-seed-adopted-pty-restore-title.ts
  • src/main/runtime/pty-inventory-adopted-title-seed.test.ts
  • src/main/runtime/runtime-terminal-agent-status-query.ts
  • src/main/runtime/runtime-terminal-state-records.ts
  • src/main/runtime/runtime-worktree-status-projection.ts

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


📝 Walkthrough

Walkthrough

The runtime now seeds restore titles for eligible PTYs adopted from controller inventory. Agent presence and status checks distinguish restored titles from live titles and use foreground-process evidence. Interactive-wait logic probes restored permission titles before reporting a title-based wait. Tests cover title seeding, foreground checks, probe behavior, and interactive-wait results.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 10027

Restored permission titles no longer report a prompt solely because another agent is running. No actionable merge-blocking risk remains after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 10027

Restoring titles fixes agent status after a server restart, but an old title can still influence non-permission agent status when current process identity cannot be confirmed. Permission-wait reporting has stronger checks. The behavior of sessions without a reported incarnation remains uncertain.

Retained concerns

  • Medium · security · inferred: A restored non-permission title can remain authoritative for agent status when the running-agent check succeeds but foreground identity is missing, unrecognized, or unreadable. A stale or process-controlled title can therefore misstate the adopted session’s agent identity or activity under uncertain evidence; this does not establish a permission-wait bypass.
Security review details

Security Blast Radius

  • inferred — The supported exposure is an adopted local PTY’s reported agent presence, identity, and status, including readers of that status. The evidence does not establish a cross-tenant, credential, network-policy, or infrastructure-authority change.

Security Findings and Attack Paths

  • inferred — A PTY process can leave a recognizable title in its buffer. Once that title is restored on adoption, uncertain foreground evidence may leave a non-permission status attributed to it, provided the separate running-agent check succeeds. No verified exploit or permission-wait bypass is established.

Trust Boundaries and Controls

  • observed — The provider buffer title crosses from terminal-process output into runtime status evidence. Known incarnation and live-output checks constrain restoration; confirmed shell foreground and incompatible recognized agents constrain stale identity claims. Restored permission waits additionally require a successful status probe.

Resilience and Maintainability Implications

  • inferred — Known incarnation replacement has explicit title cleanup and bounded asynchronous probing. The optional inventory identity leaves cleanup after an initially unidentified session dependent on daemon identity semantics not established by the reviewed evidence.

Hardening Proposals

  • proposed — Where non-permission restored status will drive consequential automation, require affirmative current ownership evidence or expose uncertainty separately from a confirmed agent status; also establish the daemon’s missing-to-known incarnation semantics before treating that transition as the same process.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Directly linked issue [#22809] requires re-adopted terminals to retain the last title, title-based identity and status, and preview. The PR implements title seeding for local inventory-adopted PTYs an… Restore the visible-screen preview for eligible local inventory-adopted PTYs after a headless orca serve restart. Add an automated test that verifies preview restoration. Preserve the restored-title foreground safeguards.
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: restoring titles for daemon sessions adopted from inventory.
Description check ✅ Passed The description is complete and closely follows the repository template. It explains the user impact, mechanism, rationale, linked issue, testing, platform considerations, and scope. It also documents…
Out of Scope Changes check ✅ Passed The changes remain connected to [#22809]. Inventory adoption seeding addresses the restart gap. Foreground identity checks, live-title precedence, incarnation guards, retry limits, SSH exclusion, and …
Full details: Linked Issues check

Explanation

Directly linked issue [#22809] requires re-adopted terminals to retain the last title, title-based identity and status, and preview. The PR implements title seeding for local inventory-adopted PTYs and adds foreground checks and tests for identity and status. applyAdoptedPtyRestoreTitle requests scrollbackRows: 0, and the test explicitly expects terminal.preview to remain empty. Preview restoration remains unmet.


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.

@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

The new fail-closed foreground check does not apply once a renderer graph materializes a leaf for an adopted session, so terminal send and dispatch --inject can still be authorized against a bare shell. This is not a regression from main, but it leaves the PR's stated guarantee incomplete.

Reviewed changes

Initial review of b31f51e (single commit, +558/-53, 11 files).

  • Adoption title seed — new OrcaRuntimeWithSeedAdoptedPtyRestoreTitle mixin, called once per adopted PTY in the inventory loop; asks the controller for a visible-screen snapshot (scrollbackRows: 0), seeds only lastTitle via seedTerminalRestoreTail, at most once per PTY incarnation (WeakMap), skipping SSH relay sessions and non-seedable records.
  • Fail-closed foreground evidence — extracted ptyForegroundIsShell from the hook-status path and reused it in RuntimeTerminalAgentStatusQuery and RuntimeTerminalAgentPresence; added ptyTitleIsRestored and a titleIsRestored snapshot field so a restored, never-observed-live title routes through the foreground check in the status query, presence check, and interactive wait.
  • Remote/SSH — app-side SSH relay PTYs are skipped because their providers expose no buffer snapshot; no wire change.
  • Tests — new pty-inventory-adopted-title-seed.test.ts (17 tests); terminal-output-and-worker-recovery-part-02.spec.ts snapshot-call counts bumped and call arguments pinned. I confirmed locally that 11 of the new tests fail when the seedAdoptedPtyRestoreTitle(pty) call site is removed.

ℹ️ The new regression test cannot exercise the guard once a leaf exists

createHeadlessRuntime only installs a PTY controller and calls listTerminals(); it never syncs a renderer graph, so getLeavesForPty(ptyId) is empty and leafTitle is always null in every assertion. That is precisely the one condition under which the guard in the inline comment below still fires, so the suite cannot catch the bypass.

Technical details
# Guard bypass has no failing test

## Affected sites
- `src/main/runtime/pty-inventory-adopted-title-seed.test.ts:60-80` — `createHeadlessRuntime` sets a PTY controller and calls `listTerminals()`; no `syncWindowGraph` call, so no leaf is ever bound to the adopted PTY.
- `src/main/runtime/pty-inventory-adopted-title-seed.test.ts:169-196` — the "shell owns the foreground" test asserts the retire path, but only for a leaf-less runtime.

## Required outcome
- Bind a leaf to the adopted `ptyId` before or after the seed (e.g. a `syncWindowGraph` publishing one leaf for that PTY) and assert the restored title still retires when the foreground is a shell. Without it, the suite green-lights the incomplete guard.

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

…ty adoption snapshot

A renderer pane bound to an adopted session copies the seeded title from
the PTY record, and the restored-title check only ran when no pane title
existed. So a shell that kept an exited agent's title read as that agent
again once a desktop client attached. Whether a title is restored is now
read from the PTY record on every path that trusts a title: status for
pane and PTY handles, and presence for both.

The provider maps a failed snapshot to null, so one transient failure
after a restart left that session title-less for its whole incarnation.
A title-less answer now gets up to three probes per incarnation, at
least 10 s apart, with one in flight at a 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.

Reviewed changes

Incremental review of 28a03a9, the delta since the prior pullfrog review at b31f51e.

  • Restored-title guard extended to leaf-backed panes — titleIsRestored in runtime-terminal-agent-status-query.ts and the presence branches now derive provenance from the PTY record (the only place that carries the live-observation epoch) instead of being gated on leafTitle === null, so a pane that inherits the seeded title still routes through the foreground check. This closes the leaf-backed-pane bypass raised in the prior review.
  • Bounded retry for a title-less adoption snapshot — up to three probes per PTY incarnation, at least 10 s apart, one in flight at a time, tracked in a per-record WeakMap keyed on lifecycleGeneration:incarnationId. The attempt key is stable across refreshes, so the cap cannot be defeated by repeated listing.
  • Tests — new bound-pane assertions for both the renderer-handle and PTY-record paths, plus retry cap/delay, in-flight, and empty-then-recover coverage; the legacy spec's call counts were bumped and its first call pinned to the adoption seed.

I ran the new suite (21/21 pass) and orca-runtime.test.ts, which imports the modified part-02.spec.ts (1307 pass / 1 skip). I also reverted the pty-branch titleIsRestored to its pre-delta form and confirmed the bound-pane test fails, so the new coverage genuinely exercises the fix.

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 Major · Match restored-title status to the foreground agent. · runtime-terminal-agent-status-query.ts:123

src/main/runtime/runtime-terminal-agent-status-query.ts:123
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Match restored-title status to the foreground agent.

If a PTY retains ✋ Gemini CLI after Claude takes the foreground, isRunning(handle) returns true: the foreground is an agent, not a shell. This branch then reports Gemini’s permission status, and the interactive-wait path can report a title wait for that stale permission. For a restored title, confirm the foreground agent matches the title’s agent before using its status. Presence may still be true when the agents differ. (raw.githubusercontent.com)

🟠 Major · Recheck the title after the asynchronous presence… · runtime-terminal-agent-status-query.ts:123

src/main/runtime/runtime-terminal-agent-status-query.ts:123
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Recheck the title after the asynchronous presence probe.

If a live working title arrives while isRunning(handle) is pending, the probe can return true for the current agent while terminal.titleStatus still contains the earlier restored permission status. The PTY-binding assertion does not detect that title change, so this branch returns permission after the live title cleared it. Re-read the title after the await and retry the status decision if its observation changed. (raw.githubusercontent.com)


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bdc1a298-d66f-42e6-89a5-644924f36d2b

📥 Commits

Reviewing files that changed from the base of the PR and between b31f51e and 28a03a9.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime-seed-adopted-pty-restore-title.ts
  • src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
  • src/main/runtime/pty-inventory-adopted-title-seed.test.ts
  • src/main/runtime/runtime-terminal-agent-presence.ts
  • src/main/runtime/runtime-terminal-agent-status-query.ts

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

…incarnation

A restored title is only as good as the process it came from:

- When the inventory reports a new incarnation under the same PTY id (a
  respawn the runtime never saw), the predecessor's restored title is
  dropped from the record and its panes, so the successor restores its
  own. A title observed live stays: the successor's output can arrive
  through a viewer's attach before the inventory reports it.
- A restored title's status is used only when no recognized foreground
  agent outside its title identity group contradicts it, so a Gemini
  permission title left over a Claude session no longer reads as a
  prompt. An unrecognized or unreadable foreground keeps the title.
- The status read re-checks the title after the foreground probe and
  decides again once if a live title landed meanwhile.
@mmarabel

Copy link
Copy Markdown
Contributor Author

Both outside-diff findings from the review of 28a03a9 (runtime-terminal-agent-status-query.ts:123) are fixed in 6d0e86e:

  • Match restored-title status to the foreground agent. A restored title's status is used only if no recognized foreground agent outside its title identity group contradicts it (shareCompatibleTitleIdentityGroup, so OMP still owns a π title). A Gemini permission title over a Claude foreground now reports isRunningAgent: true, status: null. The interactive wait goes through the same status probe, so it reports no prompt there either. A foreground that can't be read or recognized keeps the title, and presence is unchanged.
  • Recheck the title after the asynchronous presence probe. After the foreground checks, the title branch reads the snapshot again. If the title, its status or whether it's restored has changed, it decides once more from the new snapshot. A live title that lands during the probe therefore wins.

Each has a test that fails when its guard is reverted.

@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: eac082fa-1099-4e2c-ac8c-3d5029ef34df

📥 Commits

Reviewing files that changed from the base of the PR and between 28a03a9 and 6d0e86e.

📒 Files selected for processing (4)
  • src/main/runtime/orca-runtime-record-pty-worktree.ts
  • src/main/runtime/orca-runtime-seed-adopted-pty-restore-title.ts
  • src/main/runtime/pty-inventory-adopted-title-seed.test.ts
  • src/main/runtime/runtime-terminal-agent-status-query.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime-seed-adopted-pty-restore-title.ts

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

…ached shell

Presence accepts an agent behind a cached shell only when fresh process
evidence recognizes one, but the restored-title identity check re-read
the cached shell, recognized no agent and kept the title. So a Gemini
permission title over a Claude session still reported a prompt. The
check now uses the fresh evidence on the same condition presence does.

@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

The restored-title guard can be bypassed after a same-id respawn: forgetRestoredPtyTitle clears the PTY and leaf lastOscTitle, but a renderer pane's paneTitle still carries the predecessor's restored title, so titleIsRestored flips false and the fail-closed foreground check is skipped.

Reviewed changes

Incremental review of 6d0e86e, the delta since the prior pullfrog review at 28a03a99.

  • Drops a restored title on an inventory-reported incarnation change — forgetRestoredPtyTitle runs from recordPtyWorktree when the inventory reports a new incarnation under the same PTY id, clearing the PTY's lastOscTitle/managementTitle and any leaf lastOscTitle that copied it, while keeping a title observed live.
  • Matches a restored title's status to the foreground agent — foregroundAgentMatchesTitle drops the status (presence stays true) when a recognized foreground agent sits outside the title's identity group, so a leftover Gemini permission title over a Claude session no longer reports a Gemini prompt.
  • Re-reads the title after the async verification — readStatus retries once when the title observation changes during the presence/foreground awaits, so a live title that lands mid-probe wins.
  • Tests — incarnation replacement on the record and a bound pane, live-title survival across a respawn, and the foreground identity mismatch.

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

@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 in this delta. The restored-title bypass raised against 6d0e86e is unchanged by this commit and stays open.

Reviewed changes

Incremental review of ea8b4fa, the delta since the prior pullfrog review at 6d0e86e.

  • Fresh evidence behind a cached shell — foregroundAgentMatchesTitle now calls confirmForegroundProcess when the cached foreground read is a shell, so a restored title's status is judged against the agent fresh evidence actually finds. A Gemini permission title over a Claude process behind a bash read now reports isRunningAgent: true, status: null and no interactive wait, matching the presence path's ptyForegroundIsShell rule.
  • Test — covers the cached-shell-with-fresh-agent case (getForegroundProcess returns bash, confirmForegroundProcess returns claude).

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

…spawn

A renderer pane republishes the title it showed as its own pane title on
every graph sync. Once the inventory reported a new incarnation and the
record dropped its restored title, that echo no longer matched the
record, read as live and skipped the foreground check. The record now
remembers the restored title it dropped, and that title stays restored
until a live title is observed.

Treating every title on a PTY with no live title as restored was
rejected: the renderer also publishes Orca's own hook-driven titles
(such as `Codex - action required`) as pane titles, and those are live.

@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

Incremental review of 812c500, the delta since the prior pullfrog review at ea8b4fa.

  • Keeps the fail-closed check for a pane that echoes a replaced restored title — forgetRestoredPtyTitle now records the title it drops on the PTY record (replacedRestoredTitle), and ptyTitleIsRestored treats that exact title as restored while no live title has been observed. This closes the same-id respawn bypass raised against 6d0e86e, where the renderer republished paneTitle no longer matched the nulled pty.lastOscTitle, so titleIsRestored flipped false and the foreground check was skipped.
  • Test — adopted title, a bound pane echoing it, then a replacement incarnation with a bare shell, asserting the terminal reads as not running. Reverting the assignment makes it fail with isRunningAgent: true, status: idle.

I ran the new suite (26/26) and orca-runtime.test.ts, which imports the changed part-02.spec.ts (1307 pass / 1 skip), and confirmed the new test fails without the fix. The prior Pullfrog threads are resolved.

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

@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: f52ddd14-889e-4a2c-9a2a-f00118099415

📥 Commits

Reviewing files that changed from the base of the PR and between ea8b4fa and 812c500.

📒 Files selected for processing (4)
  • src/main/runtime/orca-runtime-seed-adopted-pty-restore-title.ts
  • src/main/runtime/pty-inventory-adopted-title-seed.test.ts
  • src/main/runtime/runtime-terminal-state-records.ts
  • src/main/runtime/runtime-worktree-status-projection.ts

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

Two missed respawns with no live title between them overwrote the
single remembered title, so a pane still echoing the first one read as
live again. The record now keeps each dropped restored title (deduped)
until a live title is observed.

@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

Incremental review of a47b306, the delta since the prior pullfrog review at 812c500.

  • Accumulates every restored title dropped on a respawn — RuntimePtyWorktreeRecord.replacedRestoredTitle becomes replacedRestoredTitles?: string[]; forgetRestoredPtyTitle appends the trimmed title when absent and ptyTitleIsRestored matches any entry. This closes the case where two respawns with no live title between them leave an older renderer-pane echo unrecognized, so that pane still routes through the fail-closed foreground check.
  • Test generalized — the respawn-echo test now runs over one and two missed respawns. Reverting the accumulation to a single entry makes the two-respawn case fail with isRunningAgent: true, status: idle over a bare shell, so the new coverage is real.

I ran pty-inventory-adopted-title-seed.test.ts (27/27 pass) and verified the single-entry revert fails as described. Both earlier Pullfrog threads are resolved; no open threads remain.

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

…rts a prompt

A restored permission title still reported a prompt and an interactive
wait when the foreground could not be read or recognized. A stale prompt
can draw an approval typed into whatever runs now, while losing a
restored one only leaves the status unknown until live evidence
arrives. So a restored permission title now needs a recognized
foreground agent in its title identity group. Idle and working titles
keep the rule that missing evidence keeps the title.
@mmarabel

Copy link
Copy Markdown
Contributor Author

Addressed the Medium risk from the review summary (a restored permission title reported as a current prompt when the foreground can't be identified) in 10027f5. A restored permission title now reports permission, and an interactive wait, only when a recognized foreground agent shares its title identity. If the read fails or the process isn't recognized (node, or unknown), the terminal reports isRunningAgent: true, status: null. Restored idle and working titles keep the rule that missing evidence keeps the title, because losing one of those only leaves the status unknown. Tests cover all three missing-evidence cases, plus the idle cases that must not change.

Also fixed since the last review: every restored title a missed respawn drops is now kept (a47b306, the thread on orca-runtime-seed-adopted-pty-restore-title.ts:84).

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

Incremental review of 10027f5, the delta since the prior pullfrog review at a47b306.

  • A restored permission title now needs a recognized owner — foregroundAgentMatchesTitle gains a requireOwner flag (set when terminal.titleStatus === 'permission'); its three missing-evidence returns become !requireOwner. Idle/working restored titles are byte-identical to before, while a permission title whose foreground is a shell, an unrecognized/unknown process, or unreadable now reports status: null (presence still supplies isRunningAgent) and yields no interactive wait. The failure policy is documented on the method and matches the existing "a stale prompt must not draw an approval" reasoning.
  • Tests — an it.each over read-failure, unrecognized (node) and unknown (null) foregrounds asserts { isRunningAgent: true, status: null } and no wait. I confirmed all three fail with status: 'permission' when the !requireOwner returns are reverted to true, and that the full suite passes (30/30) with the fix in place.

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

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Restores terminal titles for sessions adopted after restart.

The PR appears safe to merge; no new actionable issue or outstanding previous finding was identified.

Summary

The PR restores titles for daemon sessions adopted after a runtime restart and checks historical titles against foreground-process evidence before using them for agent status. It also prevents restored permission titles from marking a worktree blocked and adds headless adoption tests.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Controller inventory adopts PTY] --> B[Request provider buffer snapshot]
  B --> C[Seed last title if PTY is still eligible]
  C --> D[Terminal status or presence query]
  D --> E[Check foreground evidence for restored title]
  C --> F[Worktree status projection]
  F --> G[Do not treat historical permission as a live block]
Loading

Reviews (3) · Last reviewed commit: "fix(runtime): guard restored permission ..."

@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

Incremental review of e567e12, the delta since the prior pullfrog review at 10027f5. That delta is an upstream merge plus its test reconciliation; no production source line changed.

  • Merged upstream/main into the branch — the merge resolution touched no production source file. Every PR-owned source patch (orca-runtime-seed-adopted-pty-restore-title.ts, pty-shell-foreground-evidence.ts, runtime-terminal-agent-status-query.ts, runtime-terminal-agent-presence.ts, runtime-worktree-status-projection.ts, runtime-terminal-state-records.ts, and the mixin wiring) is unchanged from the previously reviewed state.
  • Reconciled the legacy-worker spec with an extra upstream provider call — upstream now issues a scrollback read (['pty-legacy', { scrollbackRows: 120 }]) at call index 1, so terminal-output-and-worker-recovery-part-02.spec.ts bumps the vi.waitFor count 4→5, both expect(...).toHaveBeenCalledTimes(6)→(7), and splits the argument assertion into slice(0, 2) (adoption seed + scrollback read) and slice(2) (the five idle probes). The { interval: 1 } polling and its latency comment come from upstream unchanged.
  • Verified the reconciled contract — pty-inventory-adopted-title-seed.test.ts passes 30/30 and orca-runtime.test.ts (which imports the changed spec) passes 1340 with 1 skipped. The split assertion is exact toEqual, so the new call ordering is pinned rather than absorbed.
<!--
Pullfrog review metadata. These findings were written against e567e12a3b;
if commits have landed on mmarabel/issues-22809 since, treat every specific bug, file, or
line callout as POTENTIALLY STALE and re-diff before acting on it.

- Mode: IncrementalReview (delta against prior pullfrog review)
- Files reviewed: 13
- Commits reviewed: 8
- Base: main (c9918931c8)
- Head: mmarabel/issues-22809 (e567e12a3b)
- Reviewed commits:
  - e567e12a3b — Merge upstream/main into mmarabel/issues-22809
  - 10027f57f1 — fix(runtime): require a recognized owner before a restored title reports a prompt
  - a47b306397 — fix(runtime): remember every restored title a missed respawn replaced
  - 812c5003da — fix(runtime): keep checking a restored title a pane echoes after a respawn
  - ea8b4fab87 — fix(runtime): compare a restored title with fresh evidence behind a cached shell
  - 6d0e86e2e6 — fix(runtime): check restored titles against the foreground agent and incarnation
  - 28a03a99f1 — fix(runtime): verify restored titles a pane inherits and retry an empty adoption snapshot
  - b31f51e2f8 — fix(runtime): restore the title of daemon sessions adopted from the inventory
- Prior pullfrog review: 10027f5 (https://github.com/stablyai/orca/pull/22834#pullrequestreview-5319290771)
-->

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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

The restored-permission guard added for worktree ps covers only the PTY-record loop. A leaf bound to the adopted PTY still carries the restored title, and getLeafWorktreeStatus reports it as a live permission status, so the projection change is bypassed once a pane attaches.

Reviewed changes

Incremental review of 1cc6e75, the delta since the prior pullfrog review at e567e12.

  • Distrusts a restored permission title in worktree ps — getSavedTabWorktreeStatus gains a titleIsRestored argument that maps a detected permission to null; the PTY-record loop passes ptyTitleIsRestored(pty, owner.title).
  • Prefers the hook timestamp for a probed restored permission title — getTerminalInteractiveWait returns { source: 'hook', since: explicitStatus.updatedAt } when a hook permission accompanies a restored permission title the foreground probe confirms; otherwise { source: 'title' }. Non-permission paths are unchanged.
  • Tests — a new runtime-worktree-ps-restored-permission.test.ts asserts a historical permission title yields active on the PTY-record path, and the adopted-title suite covers the hook-source wait.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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

Incremental review of 89564a1, the delta since the prior pullfrog review at 1cc6e75. It closes the open IMPORTANT finding: the restored-permission guard for worktree ps covered only the PTY-record loop.

  • Guards a restored permission title on the leaf path — the leaf loop resolves provenance from args.ptysById and passes ptyTitleIsRestored(freshOwner, getLatestLeafTitle(leaf, tabTitle)) into getLeafWorktreeStatus, which gained a titleIsRestored argument that demotes a detected permission to null. getLatestLeafTitle builds the same candidate list (order and updatedAt) as getLeafWorktreeStatus's internal getLatestAgentCandidateTitle, so the flag is always computed against the exact title the projection uses. When the PTY record is absent the flag stays false, so the demotion only applies when provenance is actually known.
  • Closes the reported bypass — a leaf bound to the adopted PTY whose paneTitle/lastOscTitle (or a republished replacedRestoredTitles echo) carries the restored permission title no longer reaches worktree ps as a live permission.
  • Test — the new case binds a leaf to the adopted PTY and leaves the PTY loop skipped via countedPtyIds, so the assertion genuinely exercises the leaf path. I confirmed it fails with permission when the third argument is reverted to false, and the surrounding suites (pty-inventory-adopted-title-seed.test.ts 30/30, restored-permission 2/2) pass. Lint on the changed files is clean.

The prior Pullfrog thread on runtime-worktree-ps-activity.ts is resolved; no open Pullfrog threads remain.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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

Incremental review of e173b67, the delta since the prior pullfrog review at 89564a1. It is the merge of main (752871bd, which landed the stale-working display clear), and the conflict resolution is a real authored delta rather than a no-op: the PR's restored-title logic is re-wired through main's new display-projection seam.

  • Reconciled restored-title provenance with the display-clear projection — ptyTitleIsRestored moved out of runtime-worktree-status-projection.ts into new pty-restored-title.ts, and getTitleDisplayClear is threaded through runtime-terminal-agent-status-query.ts, runtime-terminal-agent-presence.ts, and runtime-worktree-ps-activity.ts. Display readers read through getPtyDisplayRecord/getLeafDisplayRecord, while provenance is judged against the raw PTY record (live.pty in getSnapshot, the new titleEvidence arg in isPtyRunning), so a display clear (which stamps a non-null lastOscTitleEpochMs) never reads as restored, and a restored title is still detected when a bound pane republishes a newer paneTitle.
  • Extended the fail-closed check to the leaf-handle path — presence now returns trackedPty === null || await this.titleStillProvesAgent(trackedPty, ...), and foregroundAgentMatchesTitle resolves a cached-shell foreground through controller.confirmForegroundProcess before recognizing the agent.
  • Merge wiring — new confirmForegroundProcess/getTrackedPty deps on the status query, getTitleDisplayClear on presence/ps, and replacedRestoredTitles on the PTY record.
  • Reconciled the legacy-worker spec — vi.waitFor 4→5, toHaveBeenCalledTimes(6)→(7) (×2), with the argument assertion split into slice(0, 2) (adoption seed + scrollback read) and slice(2) (the five idle probes).

I read the full diff end-to-end and the incremental range-diff. pty-inventory-adopted-title-seed.test.ts 33/33, runtime-worktree-ps-restored-permission.test.ts 4/4, stale-title-display-clear.test.ts 9/9, stale-title-display-surfaces.test.ts 16/16, and orca-runtime.test.ts (which imports the reconciled spec) 1349 passed / 1 skipped. Both prior Pullfrog threads are resolved; no open threads remain.

ℹ️ pnpm tc:node fails in a file this PR does not touch

Running pnpm tc:node on the branch head reports src/main/claude/claude-child-work-evidence-retention.test.ts:88 (Property 'prompts' is missing … Pick<ClaudeSession, "childWork" | "prompts" | "translator">). git diff origin/main HEAD -- src/main/claude/ is empty, so the entire directory is byte-identical to the merged base 752871bd — this is pre-existing breakage on main, not introduced by this PR's merge resolution. Flagging it only so the red check on the merge tree isn't mistaken for a regression here.

Technical details
# Pre-existing typecheck failure on the merged base

## Affected sites
- `src/main/claude/claude-child-work-evidence-retention.test.ts:88` — calls `drainClaudeChildWork({ childWork, translator }, …)` but the parameter is typed `Pick<ClaudeSession, 'childWork' | 'prompts' | 'translator'>`, which requires `prompts`.

## Evidence
- `git diff --stat origin/main HEAD -- src/main/claude/` returns empty; `origin/main == 752871bd` (the merge's second parent).
- `pnpm tc:node` exits 1 with only that diagnostic.

## Required outcome
- No action for this PR. The fix belongs to whichever main commit added `prompts` to `ClaudeSession` without updating this test.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Thank you, @mmarabel! Your work on adopted terminals keeping their real title and output shipped in #38760, which credits you. Closing this in favour of #38760. Thanks again for digging into it!

@nwparker nwparker closed this Nov 6, 2026
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.

[Bug]: After an orca serve restart, surviving terminals come back with no title and unknown agent status

2 participants