Skip to content

fix(runtime): stop a name-only agent title from satisfying tui-idle - #20155

Merged
nwparker merged 1 commit into
mainfrom
fix/tui-idle-wait
Sep 13, 2026
Merged

nwparker merged 1 commit into
mainfrom
fix/tui-idle-wait

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​450 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​450
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​498 $\color{#cf222e}{\Huge{\mathbf{−}}}$​66 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​432

Credit

The design in this PR is @brennanb2025's, from #14642. It won a cross-review against every other open fix for #6011 — including the approach this branch previously carried — and it is reproduced here rather than merged only because #14642 shares no git history with main (different root commit; git merge refuses unrelated histories, and the same is true of #6012, #6555 and #9929). Nobody can merge that branch as it stands. This is not us taking the work: if that branch can be rebased, we will close this PR in favour of it.

Specifically theirs, and named so the merged commit does not obscure it:

  1. Rank the evidence, never infer idle from silence — the three-tier structure this PR is built on.
  2. Derive the rank at read time from lastOscTitle rather than stamping provenance onto the record. This is the part that fixes a real defect in our earlier approach: syncWindowGraph rebuilds every leaf from an explicit field list, so our bespoke field was dropped on any renderer publish and terminal wait --for tui-idle returns satisfied:true in ~0s while an agent TUI is actively working #6011 came straight back — measured: wait correctly refused before a graph sync, satisfied=true in 0ms after it.
  3. The first-party OSC 9999 veto — the agent's own account of itself outranks anything inferred from titles or bytes.
  4. quietForegroundProcessProvesTuiIdle — a quiet non-shell foreground process must not prove idle on a pane where Orca launched a known agent, because that is an agent still booting. Our earlier approach leaned on exactly that signal and so likely reintroduced the dispatch --inject prompt-loss bug in [Bug]: slow Claude startup lets tui-idle false-positive and loses injected dispatch (v1.4.149) #9976.
  5. Re-reading the live leaf on every poll tick — we missed this entirely. A record captured at registration stops advancing, its lastOutputAt freezes, and the quiescence gate then passes while the pane is still streaming: measured, settled at 4005ms during 12s of uninterrupted output.

We verified their branch standalone before adopting it, rather than taking the design on faith. It passed.

@nwparker's #6555 first drew the explicit-vs-ambiguous line the whole ranking rests on, and derived it from lastOscTitle rather than a stored field — the structural choice that makes it robust. @revofusion's #6012 was first to the root cause: a single OSC-title sample cannot prove completion, because detectAgentStatusFromTitle defaults a name-only title to idle.

Two things here are ours: the Grok scoping below, and a small tier-1 fix — tier 1 read only the renderer-synced pane title, so a daemon-hosted or background pane dropped an explicit Codex ready to the quiescence lane and waited the whole window for a result it already had (4005ms → 0ms, rows D/E below).

Fixes #6011

In plain terms

Scripts and automations can ask Orca to "wait until this coding agent has finished". Orca was answering "it's already finished" the instant it was asked, while the agent was still busy working — because it was reading the agent's terminal title, and a title showing nothing but the agent's own name (just "Codex") was being treated as a finished signal. But agents show that same bare-name title while they're mid-task, so anything chained onto that wait would charge ahead and act on half-done work.

Now a bare name on its own is no longer accepted as proof. Orca waits for the agent to actually say it's done — an explicit "ready"/"done" marker in its title, its own finished-signal, or its familiar ready prompt on screen — and if the agent reports that it is still working, that overrides everything else. For agents that never say anything more than their name, Orca falls back to checking that the pane has genuinely stopped producing output. If no such proof arrives, the wait runs out its clock and reports a timeout instead of claiming a success it cannot back up.

Evidence ladder

Tier Evidence Settles tui-idle?
1 explicit idle marker in the agent's own title (Claude ✳, Gemini ◇, Pi/OMP π - , OpenCode OC | …, ready/idle/done, * prefix), read from either the renderer-synced pane title or lastOscTitle; or a known ready-prompt body (Codex, Cursor, Antigravity); or an adopted pane's explicit title yes
2 fresh first-party OSC 9999 status saying working / blocked / waiting vetoes — never idle
3 name-only title, from an agent that announces rest explicitly (Codex, Cursor, Droid, Hermes, Devin, Pi, OMP) only once output has been quiet for TUI_IDLE_QUIESCENCE_MS
3 name-only title, from an agent with no explicit idle channel (Grok, Copilot, Aider, Mimo, openclaw, agy, OpenCode, bare claude) yes — it is the only rest signal that agent ever emits
3 quiet non-shell foreground process only on a pane where Orca did not launch a known agent (#9976)

Why the Grok scoping

Every approach in this set demanded output quiescence before accepting a name-only title. Driving the real grok binary through a real PTY shows that cannot work:

  • it emits a bare grok OSC title at rest, so it lands in tier 3;
  • it repaints a braille banner continuously — max gap between output bytes 891ms across a 22s observation, still emitting 76ms before the window closed;
  • tail-preview quiescence is no better: 79 preview changes in 20 idle seconds, longest stable window 2.1s against a 3s threshold;
  • isKnownReadyPromptPreview does not match its banner, and it has no synthetic idle title.

So a genuinely idle Grok pane had no path to tier 1 or 2 and could never clear tier 3. Measured against a real idle Grok pane through the real terminal.wait RPC:

parent commit            [+     1ms] -> satisfied=true
unscoped demotion        [+ 45003ms] -> ERROR timeout      <- tui-idle lost entirely for Grok
this PR                  [+     4ms] -> satisfied=true

Performance

The ranking is derived at read time rather than stamped at write time, so the fair question is whether reads now pay what writes used to. Measured, not asserted.

Where it runs. Three production call sites — terminal.wait (per RPC call), the idle poll (per tick per waiter, 2s), and resolveTuiIdleWaiters on the PTY-data path, which is guarded by "a waiter exists on this handle". No status-read, worktree ps, mobile-projection or render path calls it.

How often. Instrumented, 12 panes x 400 chunks, one pane under a wait:

idle title frames delivered:        4800
ranking executions, repeated title:    1
ranking executions, changing title:  400

The re-rank is gated on the status or title actually changing, so a repainted identical title costs nothing. That is the same cadence the stamped-at-write design had — once per title change, on waited panes only.

Cost per call.

ns/op
isTuiIdleSatisfied, explicit title (tier 1) 52
isTuiIdleSatisfied, name-only (tier 3) 122
detectExplicitIdleStatusFromTitle before memo 72.5
after memo 7.4
buildTerminalWaitText (200-line tail) 3,848
isKnownReadyPromptPreview (7.3 KB) 7,322
call site before the fixes below 11,243
lastAgentStatus === 'idle' (previous behaviour) 4
getLiveLeafRecord (40-leaf map) 68

The title scan was never the expensive part — the body evidence was, at ~11us and a fresh multi-KB string, computed eagerly as an argument even when the cheaper title check answers first. Three fixes: a lazy readPositiveBodyEvidence thunk with the title checked first (11,243 -> 52 ns, 216x); the change-gate above; and memoising detectExplicitIdleStatusFromTitle on the title string, matching the existing memo on detectAgentStatusFromTitle in the same family (72.5 -> 7.4 ns).

Under load, interleaved against the parent commit, 7 runs each:

no waiter     HEAD median 6751 ns (6350-7176)   PARENT median 6534 ns (6014-7058)   +217 ns
with waiter   HEAD median 6005 ns (5731-6368)   PARENT median 5934 ns (5582-6107)   + 71 ns
heap delta    18 MB / 15 MB                     18 MB / 15 MB                        0

+3.3% and +1.2% on medians, inside a ~1000 ns run-to-run spread, with byte-identical allocation. An earlier pass showed +4.9% on the no-waiter row; that was ordering bias (HEAD ran first in every pair), and reversing the order made HEAD faster. Before the change-gate the with-waiter row was +50% per chunk — though part of that was never overhead, since the parent resolves the waiter on chunk 1 (that is the bug) and stops paying, while this branch correctly keeps it alive.

Verification matrix

A  codex name-only, streaming:   refused (timeout) at 1502ms   <- #6011 fixed
A2 same, NO launch metadata:     refused (timeout) at 1501ms   <- title fallback covers adopted panes
B  before graph sync:            refused (timeout) at 1500ms
B  after  graph sync:            refused (timeout) at 1502ms   <- read-time rank cannot decay
C  grok, repaints forever:       SATISFIED=true at 0ms         <- was: never settles
D  codex explicit ready, no UI:  SATISFIED=true at 0ms         <- was 4005ms before the tier-1 fix
E  same, paneTitle published:    SATISFIED=true at 0ms

Real-PTY transcript

src/main/runtime/tui-idle-name-only-real-pty.integration.test.ts drives a real node-pty, a real long-running process emitting real \033]0;Codex\007 control bytes (verified with od -c, not literal text), a real ps foreground read through the same getForegroundProcessName the relay serves, and the real terminal.wait RPC handler.

Before (parent commit) — the process is actively streaming under a name-only title:

[+     0ms] $ orca terminal wait --for tui-idle --timeout-ms 8000
[+     0ms] -> satisfied=true condition=tui-idle

After:

[+     0ms] $ orca terminal wait --for tui-idle --timeout-ms 8000
[+  8004ms] -> ERROR timeout

[+     0ms] $ orca terminal wait --for tui-idle --timeout-ms 20000
[+  2544ms] -> satisfied=true condition=tui-idle        <- explicit idle title arrived

[+     0ms] $ orca terminal wait --for tui-idle --timeout-ms 20000
[+  6210ms] -> satisfied=true condition=tui-idle        <- went quiet, agent still foreground

Why no screenshots. The evidence here is timing: the bug is a call that returned in ~0ms instead of waiting. A still image cannot distinguish a correct wait from a broken one, so the transcripts above are the proof and a screenshot would only be decoration.

Prior art — the other four PRs for #6011

Verification

  • src/main/runtime/ src/shared/ — 15,655 passed, 148 skipped, 0 failed
  • oxlint clean, oxfmt --check clean on changed files, typecheck clean
  • src/shared/pane-agent-identity-inventory.test.ts updated for the new identity call site

Residual risk

A hookless Codex pane sitting at a bare Codex title now has only tier 3, so if Codex repaints at rest it will time out rather than falsely report completion. I could not drive that case end-to-end — the local codex binary never gets past its directory-trust prompt, where it emits no OSC title at all and the wait correctly reports blocked. Treat it as a known exposure, not a measured hang. The trade is deliberate: terminal wait has a caller-supplied timeout, and a timeout is a reportable outcome, whereas a false satisfied silently corrupts an orchestration loop.

SSH and relay paths were not exercised. pty.getForegroundProcess is pre-existing relay/SSH infrastructure and no wire surface changed here.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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
📝 Walkthrough

Walkthrough

The change adds shared TUI-idle evidence ranking. It records explicit agent status on PTY records and uses pane-agent identity, first-party status, body evidence, foreground-process state, and quiescence. Terminal wait polling and runtime waiter resolution now use the shared predicate. Tests cover streaming output, explicit idle titles, quiet processes, permission states, name-only titles, and real PTY behavior.

Priority: ⬆️ High

Merge Risk: 🟡 Moderate · up to 23b38

TUI-idle can remain blocked after a PTY replacement or report idle while first-party work is active. Resolve these evidence-refresh gaps before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Issue #6011 is addressed. Name-only titles require quiescence for agents such as Codex, live leaf records are re-read, and explicit idle titles remain immediate. Issue #9905 remains unmet. `isTuiIdleS… Make fresh first-party non-done status veto all positive idle evidence, including explicit idle titles and ready prompts. Add regression tests for a fresh first-party status combined with each positive evidence path.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 14 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The evidence-ranking logic, first-party status tracking, live-record polling, runtime integration, and regression tests directly implement issues #6011 and #9905. No unrelated change is established by…
Title check ✅ Passed The title clearly identifies the primary fix: preventing a name-only agent title from incorrectly satisfying tui-idle.
Description check ✅ Passed The description is detailed and directly addresses the linked issue, behavior changes, evidence ranking, testing, performance, residual risk, and compatibility considerations. It does not reproduce se…
Full details: Linked Issues check

Explanation

Issue #6011 is addressed. Name-only titles require quiescence for agents such as Codex, live leaf records are re-read, and explicit idle titles remain immediate. Issue #9905 remains unmet. isTuiIdleSatisfied returns true for explicit idle-title or ready-prompt evidence before it checks hasFreshWorkingFirstPartyStatus. A fresh first-party working, blocked, or waiting status can therefore coexist with a Grok prompt or explicit idle title and satisfy tui-idle while background work remains active.

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

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

❤️ Share

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

@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

  • Name-only idle provenance — detectAgentStatusFromTitle now emits a parallel detectAgentTitleIdleEvidence that tags each idle verdict as explicit or name-only, without changing the verdict itself (sidebar, worktree ps, and mobile spinner-clearing semantics are preserved).
  • Write-time evidence stamp — a new optional lastAgentIdleEvidence field is stamped on pty/leaf records in applyTrackedPtyTitle, the headless-seed path (applySeededAgentStatus), and the done-hook exit recovery; stored-agent-idle-evidence.ts is the only reader.
  • Settlement gating — all four terminal wait --for tui-idle satisfaction sites (the immediate paths in runtime-terminal-wait.ts and the sweep ticks in runtime-terminal-idle-polls.ts) now require positive evidence, parking name-only idles on a quiescence + live-foreground corroboration poll.
  • Scoped demotion — nameOnlyIdleNeedsCorroboration gates demotion on getSyntheticAgentTerminalTitle(agent, 'done'), so churning name-only agents (Grok) keep their prior immediate-settle behavior instead of losing tui-idle to a perpetual timeout.
  • Tests — poll-lane unit coverage, an OSC-title-pipeline E2E test, a demotion-scope test, and a real-PTY integration test driving a genuine node-pty fixture that emits real \033]0;…\007 control bytes.

The core reasoning is sound and the fix is tight: the detector keeps its display meaning while the settlement decision moves to a provenance stamp that only the wait path reads. I traced the transition edge (explicitIdle && !prevExplicitIdle), the exit-recovery provenance (confirmedStatus === 'idle' ? 'explicit' : …), the headless-seed stamp, and all resolve*TuiIdleWaiters call sites — the evidence gate is consistently applied and the unstamped-reads-positive fallback is safe because RuntimeSyncedLeaf never carried lastAgentStatus, so no new wire surface and no mirroring hazard. The Grok/OpenCode "no explicit idle channel" carve-outs match the enumerated provider table, and the residual risk (repainting TUIs with synthetic titles still depend on their hook) is explicitly documented rather than papered over.

Pullfrog  | View workflow run | Using DeepSeek Pro (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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e9bfdfb6-a257-4ddb-9979-23aa191d5a44

📥 Commits

Reviewing files that changed from the base of the PR and between f7238ce and c3b1161.

📒 Files selected for processing (13)
  • src/main/runtime/orca-runtime-apply-tracked-pty-title.ts
  • src/main/runtime/orca-runtime-on-pty-data.ts
  • src/main/runtime/orca-runtime-resolve-exit-waiters.ts
  • src/main/runtime/orca-runtime-runtime-id.ts
  • src/main/runtime/runtime-terminal-idle-polls.test.ts
  • src/main/runtime/runtime-terminal-idle-polls.ts
  • src/main/runtime/runtime-terminal-state-records.ts
  • src/main/runtime/runtime-terminal-wait.ts
  • src/main/runtime/terminal-wait-name-only-idle.test.ts
  • src/main/runtime/tui-idle-agent-fixture.mjs
  • src/main/runtime/tui-idle-evidence.ts
  • src/main/runtime/tui-idle-name-only-real-pty.integration.test.ts
  • src/shared/pane-agent-identity-inventory.test.ts

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

Comment thread src/main/runtime/tui-idle-evidence.ts Resolved

@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

Two issues in the new evidence-ranking code: the first-party veto is ordered after the tier-1 positive return, so it can never veto an explicit idle title despite the documented contract; and the new lastExplicitAgentStatus field is never cleared when a PTY id is reused, so a stale non-done status suppresses tui-idle for up to 30 minutes after a daemon respawn.

Reviewed changes

  • Read-time evidence ranking — replaced the prior write-time provenance stamp with src/main/runtime/tui-idle-evidence.ts, deriving the rank from lastOscTitle/lastOutputAt so a syncWindowGraph leaf rebuild cannot drop it and re-open #6011.
  • First-party OSC 9999 veto — added lastExplicitAgentStatus to RuntimePtyWorktreeRecord and hasFreshWorkingFirstPartyStatus, intended to let the agent's own status stream override inferred idle.
  • Tier-3 corroboration — hasSustainedTitleIdle demands TUI_IDLE_QUIESCENCE_MS of quiet for agents that announce rest explicitly, and quietForegroundProcessProvesTuiIdle restricts the quiet-foreground lane to panes Orca did not launch a known agent on (#9976).
  • Live leaf re-read — the idle poll re-reads the current leaf every tick instead of the registration-time capture, fixing the frozen lastOutputAt false settle.
  • Unified settlement sites — ptySatisfied/leafSatisfied and the resolve-exit-waiters re-rank guards route every wait site through isTuiIdleSatisfied; the idle transition guard relaxed to prevStatus !== 'permission'.
  • Tests — new terminal-wait-name-only-idle.test.ts, a real-node-pty integration test with a control-byte fixture, and poll-lane/identity-inventory updates.

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

Comment thread src/main/runtime/tui-idle-evidence.ts Outdated

/** The one place the three tiers are combined; every satisfaction site routes here. */
export function isTuiIdleSatisfied(input: TuiIdleSatisfactionInput): boolean {
if (input.positiveBodyEvidence || hasExplicitIdleTitle(input.record, input.rendererTitle)) {

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.

The tier-2 veto can never veto tier 1: this returns true on an explicit idle title (or ready-prompt body) before hasFreshWorkingFirstPartyStatus is consulted, yet the doc directly above says the agent's own OSC 9999 status "outranks anything inferred" and the PR body says a fresh working/blocked/waiting status "vetoes — never idle". For synthesizeWorkingTitle: false agents (codex/pi/omp) a new turn's hook status does not repaint the lingering Codex ready/Pi ready title, so a pure OSC 9999 working chunk leaves both signals present and terminal wait --for tui-idle settles immediately.

Technical details
# Tier-1 positive short-circuits before the first-party veto

## Affected sites
- `src/main/runtime/tui-idle-evidence.ts:121-128` — `isTuiIdleSatisfied` returns at the `positiveBodyEvidence || hasExplicitIdleTitle` check before `hasFreshWorkingFirstPartyStatus`.
- `src/main/runtime/terminal-wait-name-only-idle.test.ts:146-183` — the only veto case uses a name-only title; no case pairs an explicit idle title with a fresh `working` first-party status.

## Required outcome
- A fresh non-`done` first-party status must be able to prevent settlement when an explicit idle title is present, per the documented contract — or the contract must be corrected.

## Open questions for the human
- Is the intended precedence "explicit title wins" or "first-party status wins"? The file comment and PR body say the latter; the code implements the former.

if (latestAgentStatus) {
const ptyRecord = this.ptysById.get(ptyId)
if (ptyRecord) {
ptyRecord.lastExplicitAgentStatus = {

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.

lastExplicitAgentStatus is written here but never cleared. resetTrackedTerminalStateForProviderGeneration nulls lastOscTitle, lastAgentStatus and the other sibling fields precisely because prior-process state must not bleed into a reused PTY id, and onPtyExit likewise leaves it — so a stale working/blocked/waiting value survives a same-id respawn and vetoes tier 3 for AGENT_STATUS_STALE_AFTER_MS (30 min).

Technical details
# New PTY-record field survives provider-generation reset / exit

## Affected sites
- `src/main/runtime/orca-runtime-on-pty-data.ts:221-229` — sole write of `lastExplicitAgentStatus`.
- `src/main/runtime/orca-runtime-apply-tracked-pty-title.ts:147-184` — `resetTrackedTerminalStateForProviderGeneration` clears `lastOscTitle`/`lastAgentStatus`/`lastAgentStatusObservedLive` but not the new field.
- `src/main/runtime/orca-runtime-on-pty-exit.ts:218` — exit path resets `lastAgentStatusObservedLive` but not the new field.
- `src/main/runtime/tui-idle-evidence.ts:57-59` — `isFreshNonDoneAgentStatus` treats any non-`done` state as fresh for 30 min.

## Required outcome
- A reused PTY id must not inherit a prior process's first-party status, so a name-only idle can still settle at `TUI_IDLE_QUIESCENCE_MS` after respawn.

## Suggested approach
- Null `pty.lastExplicitAgentStatus` in `resetTrackedTerminalStateForProviderGeneration` alongside `lastAgentStatus`, and on PTY exit; add a reset-then-settle regression test.

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 69b2414a-ca8c-4974-92a2-72b3f7e6078b

📥 Commits

Reviewing files that changed from the base of the PR and between 4090c4f and 81a4206627d691f4318ff2f88536086d70cd0dc0.

📒 Files selected for processing (3)
  • src/main/runtime/terminal-wait-name-only-idle.test.ts
  • src/main/runtime/tui-idle-name-only-real-pty.integration.test.ts
  • src/main/runtime/tui-idle-wait-test-harness.ts

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

@nwparker
nwparker force-pushed the fix/tui-idle-wait branch 2 times, most recently from b7525f9 to 23b38f6 Compare September 13, 2026 05:42

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 47857ebb-cc65-409c-be35-0cf1603d1f5a

📥 Commits

Reviewing files that changed from the base of the PR and between 81a4206627d691f4318ff2f88536086d70cd0dc0 and b7525f979cfebe9b2a1b81aafafee9530e80c6f9.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime-apply-tracked-pty-title.ts
  • src/main/runtime/orca-runtime-resolve-exit-waiters.ts
  • src/main/runtime/runtime-terminal-idle-polls.ts
  • src/main/runtime/runtime-terminal-wait.ts
  • src/main/runtime/tui-idle-evidence.ts

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

Comment on lines 172 to 180
pty.lastOscTitleAt = null
pty.lastOscTitleEpochMs = null
pty.lastAgentStatus = null
// Why: the prior process's first-party status would otherwise veto idle for its
// replacement — a stale `working` keeps tui-idle unresolved on the new generation.
pty.lastExplicitAgentStatus = null
// Why: the prior process's live frames say nothing about the replacement,
// so the seed a same-id restore applies must not inherit its authority.
pty.lastAgentStatusObservedLive = false

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear stale first-party status on every provider-generation replacement.

When postSpawnSequence > 0, the replacement path skips resetTrackedTerminalStateForProviderGeneration. The prior process's fresh working, blocked, or waiting status remains available to tui-idle evaluation and can keep the replacement unresolved.

Clear lastExplicitAgentStatus on this replacement path, while preserving the current-generation snapshot state required by the snapshot-preference path.

Comment on lines +140 to +147
const live = this.deps.getLiveLeaf(entry.leaf)
if (
foreground &&
!isShellProcess(foreground) &&
(leaf.lastOutputAt ? Date.now() - leaf.lastOutputAt : 0) >= this.deps.quiescenceMs
(live.lastOutputAt ? Date.now() - live.lastOutputAt : 0) >= this.deps.quiescenceMs
) {
this.stop(entry)
this.deps.resolve(waiter, buildTerminalWaitResult(waiter.handle, 'tui-idle', leaf))
this.deps.resolve(waiter, buildTerminalWaitResult(waiter.handle, 'tui-idle', live))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Re-apply the active-state veto after getForegroundProcess resolves.

Both continuations capture active-state evidence before the await. They then check only the foreground process and output age. A pane can gain an agent identity or a fresh non-done first-party status while the read is pending, so the continuation can resolve tui-idle for a busy TUI. Re-check this.entries.has(entry), lastAgentStatus, getPaneAgent(...), and the fresh first-party status before resolving.

The title callbacks re-rank current evidence, but RuntimeTerminalWaiterRegistry.remove only removes the poll entry. It does not cancel the suspended continuation.

This is a functional-correctness failure because callers can treat a busy TUI as ready and send work at the wrong time.

Comment on lines +113 to +138
export type TuiIdleSatisfactionInput = {
record: TuiIdleEvidenceRecord
/** Renderer-synced pane/tab title, when one exists. */
rendererTitle?: string | null
/** Tier 1 body evidence: a known ready prompt, or an adopted pane's explicit title.
* A thunk because producing it means building the pane's wait text and lowercasing it
* (~11us and a multi-KB string on a full tail); the title check below usually answers
* first, and then none of that has to happen at all. */
readPositiveBodyEvidence: () => boolean
agent: TuiAgent | null | undefined
firstPartyStatus: FirstPartyAgentStatus
quiescenceMs: number
}

/** The one place the three tiers are combined; every satisfaction site routes here. */
export function isTuiIdleSatisfied(input: TuiIdleSatisfactionInput): boolean {
// Why the title before the body: both are tier 1, so either settles, but the title is a
// memoized lookup and the body is a fresh multi-KB scan. Same verdict, cheaper order.
if (hasExplicitIdleTitle(input.record, input.rendererTitle) || input.readPositiveBodyEvidence()) {
return true
}
if (hasFreshWorkingFirstPartyStatus(input.firstPartyStatus)) {
return false
}
return hasSustainedTitleIdle(input.record, input.agent, input.quiescenceMs)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Evaluate fresh first-party status before positive idle evidence.

isTuiIdleSatisfied returns true for an explicit idle title or known ready-prompt body before it calls hasFreshWorkingFirstPartyStatus. The runtime stores the latest OSC 9999 working or blocked state and passes it to this helper. A visible prompt or idle title can therefore resolve tui-idle during active or blocked work, violating the #9905 contract. Evaluate the first-party status veto before the title/body checks.

@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 critical issues — one minor coverage suggestion inline.

Reviewed changes

  • Cleared lastExplicitAgentStatus on provider-generation reset, so a replaced daemon session cannot inherit the prior process's first-party status.
  • Gated the idle re-rank on both PTY and leaf title application to skip unchanged idle repaints; waiters stay covered by the poll, which re-checks each tick.
  • Held tier-3 corroboration for agents that announce rest explicitly when the pane has no local output clock (lastOutputAt === null now refuses instead of settling).
  • Made tier-1 body evidence lazy (readPositiveBodyEvidence thunk) and checked the title first — same verdict, cheaper.

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

// no local output clock, so for an agent that WILL announce rest explicitly there is no
// corroboration available at all. Settling here let a busy Codex/Devin satisfy the wait
// from a name-only title (#6011); hold out for tier 1/2 or the caller's timeout instead.
if (record.lastOutputAt === null) {

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.

lastOutputAt === null is the new guard that stops an adopted/daemon-backed pane from settling on a name-only title (#6011), but nothing pins it: makeTuiIdlePty/makeTuiIdleLeaf default lastOutputAt to Date.now(), and the lastOutputAt: null fixtures in runtime-terminal-idle-polls.test.ts pass agent: null, so they exit through nameOnlyIdleNeedsCorroboration before reaching this line. A case with agent: 'codex', lastAgentStatus: 'idle', lastOscTitle: 'Codex', lastOutputAt: null that asserts a timeout would lock the fix in.

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

Caution

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

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime-on-pty-data.ts (1)

225-228: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear lastExplicitAgentStatus when recordPtyWorktree replaces an incarnation.

An SSH reattach can omit providerSequence, so provider-generation reset does not run. recordPtyWorktree then updates incarnationId but retains the previous status. resolveExitWaiters passes that status to isTuiIdleSatisfied, where a fresh working status can block name-only idle evidence.

Clear the status in the existing-record incarnation-change branch in src/main/runtime/orca-runtime-record-pty-worktree.ts. This is the lifecycle boundary shared by SSH registration and controller inventory.

       pty.agentSessionOwners = []
+      pty.lastExplicitAgentStatus = null

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f8486ab8-75cb-4cd7-88ec-96bd70c74a70

📥 Commits

Reviewing files that changed from the base of the PR and between b7525f979cfebe9b2a1b81aafafee9530e80c6f9 and 23b38f6b6a5bf1572e0f7da1d2b3fb4a8b216b0c.

📒 Files selected for processing (1)
  • src/main/runtime/tui-idle-name-only-real-pty.integration.test.ts

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

…ilence

`terminal wait --for tui-idle` returned satisfied in ~0s while an agent was
mid-turn. The shared title detector defaults a name-only agent title to `idle`
so the sidebar can clear a stale spinner, and the wait accepted that stored
value as completion.

Rank the evidence instead. An explicit idle marker in the agent's own title or
a known ready prompt settles the wait; a fresh first-party OSC 9999 status
saying working/blocked/waiting vetoes it; a name-only title is a last resort
that settles only once the stream has also gone quiet. The rank is derived at
read time from `lastOscTitle` rather than stamped onto the record, because
`syncWindowGraph` rebuilds leaves from an explicit field list and would drop a
bespoke provenance field on any renderer publish.

Two things the ranking alone gets wrong are handled here too. A quiet non-shell
foreground process no longer proves idle on a pane where Orca launched a known
agent — that is an agent still booting, and resolving on it is what let
`dispatch --inject` lose the prompt (#9976). And the idle poll re-reads the live
leaf each tick, because a record captured at registration stops advancing and
its frozen `lastOutputAt` makes the quiescence gate pass while the pane streams.

The demotion is scoped to agents that go on to announce rest explicitly. Grok,
Copilot, Aider, Mimo, agy and OpenCode emit their name and nothing more at rest:
a real idle Grok pane repaints its banner about four times a second forever, so
demanding quiescence from it left no settle signal at all and the wait ran to
timeout.

The design is Brennan Benson's, from #14642, which won a cross-review against
#6012, #6555 and this branch's earlier approach; it is ported here only because
that branch shares no git history with main and cannot be merged. Neil's #6555
first drew the explicit-vs-ambiguous line the ranking rests on, and Revofusion's
#6012 first identified that a single title sample cannot prove completion.

Fixes #6011

Co-authored-by: Brennan Benson <[email protected]>
Co-authored-by: Neil <[email protected]>
Co-authored-by: Revofusion <[email protected]>
@nwparker
nwparker merged commit e9065dd into main Sep 13, 2026
28 checks passed
Fartown pushed a commit to Fartown/orca that referenced this pull request Sep 13, 2026
D-007's two predicted ratchet conflicts landed exactly as described and were
recomputed per its recipe. Upstream stablyai#20155 tightened tui-idle ranking without
changing the wait reply shape, so the delivery needs no change — but the
readiness timings measured on device came from the old semantics and should be
re-measured.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ddyy32VYir3LAeFDHv71UT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant