Skip to content

fix(runtime): rank tui-idle evidence instead of inferring idle from silence - #14642

Closed
brennanb2025 wants to merge 6 commits into
mainfrom
brennanb2025/tui-idle-quiescence-6011
Closed

brennanb2025 wants to merge 6 commits into
mainfrom
brennanb2025/tui-idle-quiescence-6011

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​541 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​541
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​162 $\color{#cf222e}{\Huge{\mathbf{−}}}$​77 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​85

ELI5

Orca has a command that means "tell me when the agent is done": orca terminal wait --for tui-idle. Orchestration and automation use it to decide a worker finished so the next step can start.

Today it answers "done!" instantly while the agent is still working. The way it decided was, roughly, "I don't currently see proof it's busy, so it must be finished." That's the bug in one sentence — a thinking agent and a finished agent look identical if all you're measuring is quiet.

This PR changes the question from "is it quiet?" to "who actually said it was done, and how good is that evidence?" Orca already receives a real "I'm working / I'm done" report from the agents themselves — it just wasn't being read here. Now it is.

What Changed

waitForTerminal(..., 'tui-idle') now ranks its evidence at every satisfaction site instead of accepting the first idle-looking sample:

  1. Positive — an explicit idle OSC title, or a known ready-prompt body (the composer is literally on screen). Resolves immediately, exactly as before.
  2. First-party veto — a fresh structured status from the agent's own stream saying working / blocked / waiting. This outranks anything Orca infers from titles or bytes.
  3. Absence — a name-only agent title, or a quiet non-shell foreground process. Last resort only, and only once sustained.

Concretely:

  • Added RuntimePtyWorktreeRecord.lastExplicitAgentStatus, stamped from the OSC 9999 payloads that onPtyData already parses. It lives on the PTY record rather than the existing paneKey-keyed snapshot map because a background CLI-created PTY may never have a paneKey, and the ptyId is the only identity the wait path is guaranteed to hold. Cleared on provider-generation reset so a dead process's turn can't veto its replacement.
  • The eight scattered lastAgentStatus === 'idle' / title / preview checks collapse into two evaluators, isPtyTuiIdleSatisfied and isLeafTuiIdleSatisfied, used by the sync fast paths, the in-promise registration checks, both fallback polls, and both working→idle transition resolvers. Net −75 lines of duplicated branching.
  • A title-derived idle now requires TUI_IDLE_QUIESCENCE_MS of quiet before it counts (the constant already existed but was only reachable from the foreground-process branch).
  • The quiet-foreground fallback no longer fires when Orca launched a known agent on that PTY (pty.launchAgent).

Two incidental consistency fixes fell out: the leaf fallback poll now checks blocked-prompt state before idle evidence (every other site already did, so the poll could disagree with its own fast path), and the transition resolvers re-rank rather than resolving on the raw transition.

Why

The KEY QUESTION: is "sustained quiescence" the right fix?

No — not as the primary fix. Silence is not a signal. A TUI that is thinking emits nothing; a TUI that is idle also emits nothing. A longer window only buys the agent more time to be slow before we mislabel it; it converts a fast false positive into a slower false positive and taxes every honest wait to do it. The four open PRs are all variations on tuning that window or pattern-matching a specific agent's HUD chrome.

The correct fix is (c): consume the structured agent-status signal that already exists. The evidence is in this repo, not in theory:

  • src/shared/agent-status-types.ts:250 — the file's own header: "status comes from hooks (Claude, Codex, etc.) — never inferred from terminal titles." A canonical working|blocked|waiting|done enum is defined at :16.
  • src/shared/agent-status-osc.ts — a stateful OSC 9999 parser that runs on every PTY chunk, at orca-runtime.ts:9830, before any title handling.
  • getTerminalAgentStatus() (orca-runtime.ts:17001) already resolves that structured status via getFreshExplicitAgentStatusForHandle() and gives it authority over title heuristics.
  • waitForTerminal() — the same class, the same handle — had zero references to it. It read only lastAgentStatus, which applyTrackedPtyTitle() (:10589) assigns from detectAgentStatusFromTitle(rawTitle) and nothing else.

So the two APIs were self-inconsistent by construction: terminal agent-status could report working from a hook at the same instant terminal wait --for tui-idle reported satisfied from a name-only title. That is the defect, and it's the same family as #14610 (re-armed staleness from a replayed signal) and #14626 (a gate that only spoke one provider's vocabulary): lifecycle inferred from the wrong signal.

Making both APIs read the same status under the same freshness rule is the fix. Reusing the existing isFreshNonDoneAgentStatus predicate rather than inventing a new window is deliberate — if a status is fresh enough for terminal agent-status to report working, it is fresh enough for tui-idle to refuse to claim idle.

Why (a) survives as tier 3, and (b) is not needed

Quiescence is kept only for agents that publish no structured status at all, layered under a positive content signal (a recognized agent title) — a confirmation guard on a match, not "N ms of nothing ⇒ done." Screen-snapshot semantics (#14561) would improve tier 1's content inspection, but it is still inference over bytes; it doesn't change that tier 2 should outrank it. I did survey how comparable tools solve this before choosing; the ordering here matches the direction that work has converged on, including the specific rule that a live first-party lifecycle report suppresses screen-derived detection.

Why the veto does not strand waits

A stuck working (agent misses its completion hook) cannot hang a wait indefinitely, because tier 1 outranks the veto: an explicit idle title or a visible ready prompt still resolves immediately. That carve-out is pinned by a test. Where no evidence at all exists, the wait times out — which is the honest answer, and the right failure mode: a timeout is loud, a false satisfied: true silently drops dispatched work (#9976).

Superseded PRs

Not bundled: #8113 (nwparker, perf — skipping full wait scans for ordinary PTY output). It is a pure hot-path optimization with its own benchmark and should land or not land on its own merits.

Root cause, limits, and what this does not fix

The actual root cause of #6011

detectAgentStatusFromTitle falls through to 'idle' for any title carrying a known
agent name with no spinner and no working keyword (src/shared/agent-title-status.ts:224 is
a bare return 'idle'). So a single frame of the plain task title classifies as idle — no
special glyph required. Claude Code's transient ✳ frame (CLAUDE_IDLE at
agent-title-core.ts:14) is one instance of this, not the whole of it.

Every satisfaction site that trusted the title therefore reported a finished turn from a
classifier fall-through. A pre-fix measurement resolved at t=7.1s through the transition
resolver
, which only fires on a transition to idle — direct evidence that an
idle-classifying title genuinely arrives mid-turn.

That is why four previous PRs kept reaching for longer quiescence windows: they were treating
a classifier fall-through as a timing problem. No window fixes it, because the title is
wrong rather than early. Ranking removes the misread instead.

Tier 2 only helps agents that publish OSC 9999

The claim "a longer window trades one failure for the other, ranking should not" holds for
Claude and Codex, which publish first-party status. For an agent that emits no OSC 9999 at
all, there is no veto to apply and the ranking collapses to exactly a plain quiescence
window at TUI_IDLE_QUIESCENCE_MS (3s) — the same mechanism the superseded PRs proposed,
just gated behind a positive title match. grok is in that group today. This change does not
make those agents more correct; it makes them no worse, and it makes the agents that do
publish status strictly correct.

The grok HUD case works for an incidental reason

grok's background-task HUD animates ◎/○/◉ continuously, so lastOutputAt keeps moving and
quiet never reaches 3s — which is why tier 3 does not fire during background work. That is
luck, not design. If that HUD ever stops repainting for more than 3s while a task is still
running, tier 3 reports idle, which is the same fragility #9929 conceded, minus the regex.
A durable fix for grok needs structured status from grok itself, not a longer window here.

The PTY poll does not share the defect

The leaf poll and the PTY poll close over the same kind of reference, so the fix was applied
to both. Forcing the real cycle then disproved the premise for the PTY side, and the negative
result is worth recording:

  • this.ptysById has exactly one set site (orca-runtime.ts:30068), guarded by
    if (!pty). Records are create-once and mutated in place — never swapped.
  • The only path that mints a fresh object under an existing id is
    dropDisconnectedPtyRecord (:30509), and it calls invalidatePtyIncarnationHandle,
    which rejects that handle's waiters (terminal_handle_stale) on its way through.

So no PTY waiter can survive long enough to observe a replaced record. A test that appeared to
cover this passed its mutation check only because the fixture reached into ptysById and
manufactured a state production cannot reach; it has been removed rather than left as false
coverage.

The general rule, because this is easy to get wrong: "fails without the fix" is necessary
but not sufficient for a poll test. The state it pins also has to be one production can reach.
A fixture that reaches into internal state to manufacture an impossible condition passes its
mutation check and still proves nothing. Check reachability, not just redness.

getLivePtyRecord stays as an inert guard — one Map.get per 2s tick — so the two parallel
polls cannot drift apart: one that re-resolves beside one that does not is the shape a future
refactor trips over. Its comment names the two mechanisms that keep it inert (the single
if (!pty)-guarded set site, and rejectWaitersForHandle on the drop path) so whoever
changes either knows precisely what they have made live.

this.leaves, by contrast, is rebuilt wholesale by syncWindowGraph
(nextLeaves.set(leafKey, {...leaf}) at :5728, swapped at :5827). That asymmetry is the
entire bug: the leaf capture dies within milliseconds, the PTY capture stays live.

Timing budget

TUI_IDLE_POLL_INTERVAL_MS is 2s and TUI_IDLE_QUIESCENCE_MS is 3s, so the worst case from
readiness to resolution is one quiescence window plus one tick — about 5s, against the 60s
orchestration.workerStart allows. Tier 1 and tier 2 evidence resolve on the next tick
without waiting out the window at all.

Severity: did this break orchestration dispatch?

Yes, for a specific and common shape. startWorker
(src/main/runtime/rpc/methods/orchestration-workers.ts:197) gates agent_readiness on
waitForTerminal(..., 'tui-idle') against a freshly launched agent, so the
pre-registration fast path can never be satisfied — it always registers a waiter and falls
through to the fallback poll. On a desktop app with a renderer attached, that handle is
leaf-backed, and every renderer publish replaced the record the poll had closed over
(creating the worker pane is itself such a publish).

Whether a given wait survived depended on how its agent announces readiness:

  • Rescued — agents whose readiness arrives as an explicit idle OSC title. The transition
    resolver re-reads the leaf live, so it resolved them despite the dead poll record.
  • Stranded — agents whose readiness is only visible in the terminal body. Codex is
    the clear case: findCodexReadyPromptIndex matches its banner, and Codex YOLO is
    explicitly not treated as a readiness title. No title transition fires, so the poll was
    the only path, and it was checking a frozen snapshot. Those dispatches failed
    agent_readiness with Agent did not become ready (timeout).

That shape is pinned by a test (resolves a leaf tui-idle waiter from a ready prompt that lands after a resync), which hangs for its full timeout with the live-record read reverted.

Headless (orca serve, no renderer) was unaffected: with no graph publishes the handle
stays PTY-backed and those records are mutated in place.

Linked Issue

Fixes #6011

Related: #9976, #9905 / STA-2331, #14561

Visual Proof

N/A — this is a main-process CLI/RPC behavior change in waitForTerminal; it renders nothing and touches no renderer code, so there is no before/after surface to capture.

Testing

Nine tests in src/main/runtime/orca-runtime.test.ts — the original five, plus four added
after a mutation matrix showed four of the eight production hunks were undetectable by
the suite as it stood, including both transition-resolver re-rankings.

Every test below was mutation-checked: its own hunk was reverted in isolation and the
test was re-run. All of them fail without their hunk.

Hunk Test With hunk reverted
live leaf record in the fallback poll polls the live leaf record after a graph resync replaces it hangs to timeout
live leaf record (worker-readiness shape) resolves a leaf tui-idle waiter from a ready prompt that lands after a resync hangs to timeout
resolveTuiIdleWaiters re-ranking does not resolve a leaf tui-idle waiter on a title transition the stream vetoes expected true to be false
resolvePtyTuiIdleWaiters re-ranking does not resolve a pty tui-idle waiter on a title transition the stream vetoes expected true to be false
veto guard on quiet-foreground does not report tui-idle from quiet foreground while the stream reports working expected true to be false
clear retained status on generation reset drops the retained working veto when the provider generation resets hangs to timeout
veto (original) does not report tui-idle while the agent status stream still reports working fails
sustained quiescence (original) does not report tui-idle while a name-only agent title keeps streaming output fails
launchAgent cold-start guard (original) does not report tui-idle from quiet foreground alone for a launched agent fails

Two originals are regression guards that pass both ways by design, and are labelled as such:
resolves tui-idle from a ready prompt even while a working status is retained (tier 1
outranks the veto) and still reports tui-idle from quiet foreground for an unlaunched non-shell TUI.

Checking this branch out locally: the rebase brings in @xterm/addon-serialize, which is
in package.json but was not present in an older worktree's node_modules. Run
pnpm install --frozen-lockfile first or the runtime suite fails to collect with
Cannot find package '@xterm/addon-serialize'. CI installs fresh, so it only bites humans.

Rebased onto origin/main (142 commits) and re-run on the materialized tree, not merged
speculatively — orca-runtime.ts had drifted enough that a clean merge-tree was not
sufficient evidence on its own.

  • vitest run src/main/runtime/orca-runtime.test.ts → 1174 passed, 1 skipped
  • tsc --noEmit -p config/tsconfig.node.json --composite false → clean
  • oxlint + oxfmt --check on both changed files → clean
  • check-changed-code-quality.mjs → 0 new findings (native, type-aware, React Doctor)

Platforms: macOS.

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

Honest gap: I did not re-run the live agent repro. The original hang was reproduced live
4/5 times on fresh panes before this fix, and the mechanism is now reproduced deterministically
at the unit level against the real OrcaRuntimeService — real syncWindowGraph publishes,
real onPtyData byte sequences — with every assertion mutation-checked. A live confirmation
run would still be worth doing before merge.

AI Disclosure

Review

  • Security — no new IPC surface, command execution, path handling, or network access. Only already-parsed in-band status and existing PTY records are read.
  • Cross-platform — no platform branches, paths, shell commands, or accelerators touched. isShellProcess / getForegroundProcess behavior is unchanged; only whether its result is trusted changed.
  • Remote SSH — no wire change. lastExplicitAgentStatus is main-process-local state derived from bytes the host already parses; nothing new crosses the RPC boundary, no new stream opcode, no new RPC param. Per docs/reference/remote-wire-compatibility.md this is not a mixed-version concern.
  • Mobile — untouched. The retained paneKey-keyed snapshots that feed mobile worktree.ps are written exactly as before; the new field is additive and read only by the wait path.
  • Backwards compatibility — tui-idle gets stricter, so a wait that used to lie now either resolves later or times out. Callers already pass --timeout-ms. The three paths that resolved immediately before (explicit idle title, ready prompt, adopted/daemon handles with no PTY stream of their own) still resolve immediately.
  • Performance — the veto is a Map.get plus two comparisons. buildTerminalWaitText in the two transition resolvers runs only when that handle actually has waiters (guarded by an existing early return) and only on a transition to idle, so it is off the per-chunk hot path.

What this PR's own mistakes taught

Two checks written for this PR could not have observed what they claimed to. A
vitest -t "tui-idle" filter silently skipped the two tests whose names lacked that
substring and reported them green. A latency rig stopped sampling the moment the wait
resolved, so a mid-turn resolve was invisible to it by construction. Both produced
confident, right-looking, wrong answers — more dangerous than an obviously wrong one.
A third test pinned a state production cannot reach: dropDisconnectedPtyRecord
rejects a handle's waiters on the way through, so no PTY waiter survives to observe a
replaced record, and the test was removed rather than kept as false assurance.

Two rules came out of that, and they are more durable than this fix:

a test must pin a state production can actually reach; and a measurement must be able
to observe its own failure case.

Root cause, measured rather than assumed

Driving a real claude through a pty and timestamping every OSC title frame shows the
classifier fall-through is not a rare transient. In one 4.8s turn, ✳ Claude Code — an
idle-classifying title — was emitted ten times, interleaved with spinner frames at
roughly 100ms cadence, the first 30ms after submit. CLAUDE_IDLE = '✳'
(agent-title-core.ts:14) makes detectAgentStatusFromTitle return idle for those,
and separately the function falls through to 'idle' for any title carrying a known
agent name with no spinner (agent-title-status.ts:199-224) — so the glyph is not even
required. That is why four previous PRs reached for longer timers: they were treating a
classifier fall-through as a timing problem.

Scope honestly stated: this clustering at turn opening is well-supported for ~5s turns
and not established for long ones. A 1s-sampled trace of a longer turn showed an
idle-classifying title about 4.5s before output ceased, which is evidence against
generalising it.

A known gap this PR does not close

Tier 2 reads lastExplicitAgentStatus, which is written only from the OSC 9999 stream.
None of the bundled hooks in ~/.orca/agent-hooks/ emit OSC 9999 — all twelve POST to
the hook server keyed by ORCA_PANE_KEY — so for Claude and Codex the veto is inert and
the ranking runs on tiers 1 and 3 alone. Pointing the veto at the paneKey-keyed map was
built and measured: the veto then fires (18/22 samples, up from none), but it makes
observable behaviour worse, because tier 1 outranks the veto by design and its title
branch has no quiescence gate, so resolution simply moves to tier 1 and fires mid-turn.
That change is deliberately not included here — it is a real fix to a real defect
that should not ship alone, recorded so it is not rediscovered as new.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)
    Scoped equivalents run locally and listed above; full typecheck / build left to CI by instruction (OOM risk).

Author

  • X / Twitter: @BrennanKB5

@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The runtime records the latest explicit OSC 9999 agent status for each PTY and clears it when the PTY process resets. TUI-idle waiters now share ranked evidence checks for registration, transitions, and fallback polling. Ready prompts and explicit idle titles can resolve waits, while fresh active status and launched-agent cold starts prevent quiet-process inference. Fallback polling rereads live records after graph resynchronization. New tests cover active work, repeated output, readiness, cold starts, resets, and compatibility.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed The description covers all required sections, links issue #6011, documents testing, and discloses the remaining live-test and full-build gaps.
Linked Issues check ✅ Passed The description links the primary issue with “Fixes #6011” and identifies related issues relevant to the change.
Out of Scope Changes check ✅ Passed The changes are limited to tui-idle runtime behavior and regression tests, including closely related polling and transition consistency fixes.
Title check ✅ Passed The title clearly and concisely describes the main runtime change: ranking tui-idle evidence instead of inferring idleness from silence.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)

15987-15990: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the test rationale comments.

Replace each multi-line Why comment with one short statement of non-obvious behavior. Remove it when the test name already states the behavior.

  • src/main/runtime/orca-runtime.test.ts#L15987-L15990: reduce the status-stream rationale to one line.
  • src/main/runtime/orca-runtime.test.ts#L16045-L16046: reduce the streaming-output rationale to one line.
  • src/main/runtime/orca-runtime.test.ts#L16092-L16094: reduce the ready-prompt priority rationale to one line.
  • src/main/runtime/orca-runtime.test.ts#L16134-L16136: reduce the launched-agent cold-start rationale to one line.
  • src/main/runtime/orca-runtime.test.ts#L16167-L16168: reduce the unlaunched-TUI compatibility rationale to one line.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fc721b28-4450-49da-b99f-41abd9ccccdc

📥 Commits

Reviewing files that changed from the base of the PR and between c0f9dcc and da6e079.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

…ilence

`terminal wait --for tui-idle` concluded a turn had ended from the absence of
evidence: a name-only agent OSC title (which detectAgentStatusFromTitle DEFAULTS
to 'idle'), or a quiet non-shell foreground process. A thinking TUI and a
finished TUI are both silent, so neither can prove completion.

Orca already parses an authoritative first-party status stream on every PTY
(OSC 9999 -> working|blocked|waiting|done) and getTerminalAgentStatus already
trusts it over titles. waitForTerminal never consulted it, so the two APIs could
disagree about the same handle at the same instant.

Rank the evidence at every tui-idle satisfaction site:
  1. positive  - explicit idle OSC title, or a known ready-prompt body
  2. veto      - a fresh OSC 9999 non-done status outranks anything inferred
  3. absence   - name-only idle title / quiet foreground, and only once sustained

Also stop treating a quiet non-shell process as readiness when Orca launched a
known agent on that PTY: a cold-starting agent is quiet by definition, which is
how a dispatch inject could be written into a TUI that had not attached its
reader yet and be silently lost.

Fixes #6011
syncWindowGraph rebuilds this.leaves with fresh objects on every renderer publish,
so the record a tui-idle waiter closed over froze at its registration values. The
fallback poll then re-checked a dead snapshot forever: tier 1 could not see the
live title and tier 3 could not see lastAgentStatus reach idle, so the waiter was
unsatisfiable and the wait burned its whole timeout.

The stale capture predates this branch, but ranking makes it fatal — the transition
resolver used to rescue these waiters by resolving on any title transition, and it
now correctly declines at the transition instant, leaving the poll as the only path.

Re-read the record per tick in both polls. The PTY one is fixed symmetrically: its
records are mutated in place today, but a drop and re-register under the same id
mints a new object and would strand it the same way.

Tests cover the two transition-resolver re-rankings that no test could previously
detect, plus the orchestration worker-readiness shape (Codex announces readiness in
its body banner, so no title transition fires and only the poll can resolve it).
A mutation matrix found half the ranking change invisible to the suite: both
transition-resolver re-rankings, the veto guard on the quiet-foreground branches,
and clearing the retained status on a provider-generation reset. Each test here
fails with its own hunk reverted.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/tui-idle-quiescence-6011 branch from da6e079 to b876ff8 Compare August 17, 2026 09:04
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fallback-poll hang fixed, coverage gap closed, rebased onto main

Pushed as b876ff8 (force-update from da6e079 — rebased, so history was rewritten).

The hang

Both tui-idle fallback polls closed over the record they were handed at registration. syncWindowGraph rebuilds this.leaves with fresh object literals on every renderer publish:

nextLeaves.set(leafKey, { ...leaf, ptyId, ptyGeneration, /* … */ })
…
this.leaves = nextLeaves

so the captured leaf froze at its registration values within milliseconds. isLeafTuiIdleSatisfied then read leaf.paneTitle and leaf.lastAgentStatus off a dead object — tier 1 could never see the live title, tier 3 could never see lastAgentStatus reach idle, and the waiter was unsatisfiable by construction. The wait burned its whole timeout.

The stale capture predates this branch. What makes it fatal here is that resolveTuiIdleWaiters used to resolve unconditionally on any title transition and rescued these waiters; ranking makes it correctly decline at the transition instant (quiet ≈ 0), leaving the broken poll as the only path.

Both polls now re-read per tick. The PTY one is fixed symmetrically — its records are mutated in place today, so it is not stale by the same mechanism, but a drop and re-register under the same id (restore, reconnect, dropDisconnectedPtyRecord prune) mints a new object and would strand it identically.

Coverage gap

The mutation matrix found four of eight hunks undetectable. All four are now covered, and every test was checked by reverting its own hunk in isolation:

Hunk With it reverted
live leaf record in the poll hangs to timeout (3 tests)
live pty record in the poll hangs to timeout
resolveTuiIdleWaiters re-ranking expected true to be false
resolvePtyTuiIdleWaiters re-ranking expected true to be false
veto guard on quiet-foreground expected true to be false
clear retained status on generation reset hangs to timeout

Both previously-silent items you offered to let me excuse turned out to be reachable, so nothing is excused: the quiet-foreground veto is exercised by emitting OSC 9999 with no OSC 0 title (keeping lastAgentStatus null so the branch stays live), and the generation reset via synchronizePtyOutputSequenceFromProvider with generation: 'reset'.

Severity: yes, it broke dispatch — for body-announced agents

startWorker gates agent_readiness on a tui-idle wait against a freshly launched agent, so the fast path can never satisfy it: it always registers, always falls to the poll. On a desktop app with a renderer attached the handle is leaf-backed, and creating the worker pane is itself a graph publish.

  • Rescued — agents whose readiness is an explicit idle OSC title. The transition resolver re-reads the leaf live, so it resolved them despite the dead poll record.
  • Stranded — agents whose readiness only appears in the terminal body. Codex is the clear case: its banner is matched by findCodexReadyPromptIndex, while Codex YOLO is explicitly not a readiness title. No transition fires, so the poll was the only path. Those dispatches failed with Agent did not become ready (timeout).

Headless (orca serve) was unaffected — no graph publishes, so the handle stays PTY-backed.

That shape is now a test, and it hangs for its full timeout with the fix reverted.

Rebase

142 commits, rebased and re-run on the materialized tree rather than trusting merge-tree — orca-runtime.ts had drifted from ~32.9k to ~34.6k lines, so I re-checked that every hunk is still wired rather than sitting in dead code. Full runtime suite: 1175 passed, 1 skipped. tsc node project clean, oxlint + oxfmt --check clean, changed-code quality gate 0 new findings.

Still open

I did not re-run the live agent repro. The mechanism is now reproduced deterministically against the real OrcaRuntimeService with real graph publishes and real OSC byte sequences, and every assertion is mutation-checked — but a live confirmation before merge would still be worth having. The PR body says so rather than implying it was done.

… honest

Forcing the real drop-and-re-register cycle disproved the premise: the only path
that mints a fresh PTY record under an existing id is dropDisconnectedPtyRecord,
and that rejects the handle's waiters on its way through. So a PTY poll can never
observe a replaced record, and the test that claimed to cover it was pinning a
state the production code cannot reach — it only failed pre-fix because the
fixture manufactured it.

Remove that test rather than keep false coverage. getLivePtyRecord stays as a
no-op guard against the two polls drifting apart, and now says so.
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Correction: the PTY poll does not share the defect

Pushed ccf6f8c. The challenge to the PTY test was right to make, and forcing the real cycle produced a stronger answer than expected — the scenario is unreachable, so the test is gone rather than fixed.

What the real cycle showed

The prediction was that polls the live pty record after it is replaced under the same id would be vacuous unless it forced a genuine drop-and-re-register. So I forced it, via dropDisconnectedPtyRecord rather than a hand-built map entry. The test then hung with the fix in place — and the probe explains why:

PROBE after drop: handleAlive= []

dropDisconnectedPtyRecord (:30509) calls invalidatePtyIncarnationHandle, which ends in rejectWaitersForHandle(retained.handle, 'terminal_handle_stale'). The drop rejects that handle's waiters on its way through. So no PTY waiter can survive to observe a replaced record: by the time a fresh object exists under the id, the waiter it would have served is already rejected.

That makes the earlier version of the test worse than useless. It passed its mutation check — hung pre-fix, resolved post-fix — but only because the fixture reached into ptysById and manufactured a state production cannot produce. A test that fails without the fix is not automatically load-bearing; it also has to pin a state the system can actually reach. This one didn't, so it's removed rather than left as false coverage.

getLivePtyRecord stays, as a no-op guard — one Map.get per 2s tick — so a future second set site on ptysById cannot silently reintroduce the leaf hang on the PTY side. Its comment now states plainly that it is unreachable today and why, so no reader mistakes it for a live fix. Happy to drop it entirely if you'd rather not carry a deliberate no-op.

The asymmetry that remains is the whole bug: this.leaves is rebuilt wholesale by syncWindowGraph (nextLeaves.set(leafKey, {...leaf}) at :5728, swapped at :5827), so the leaf capture dies within milliseconds, while ptysById records are create-once and mutated in place.

Root cause corrected — it is wider than ✳

The PR body previously pinned #6011 on Claude's transient ✳ frame. That is one instance, not the cause. detectAgentStatusFromTitle ends in a bare return 'idle' (src/shared/agent-title-status.ts:224) for any title carrying a known agent name with no spinner and no working keyword. A single frame of the plain task title classifies as idle; no special glyph needed. The pre-fix arm resolving at t=7.1s through the transition resolver — which only fires on a transition to idle — is direct evidence that an idle-classifying title arrives mid-turn.

That is why four previous PRs kept reaching for longer windows: they were treating a classifier fall-through as a timing problem. No window fixes it, because the title is wrong rather than early.

Timing budget

TUI_IDLE_POLL_INTERVAL_MS = 2s, TUI_IDLE_QUIESCENCE_MS = 3s, so worst case from readiness to resolution is one window plus one tick, ~5s against the 60s orchestration.workerStart allows. Tier 1 and tier 2 evidence resolve on the next tick without waiting out the window at all. That is arithmetic, not a measurement — the end-to-end number on a real turn is still worth having.

State

Nine tests, each mutation-checked against its own hunk. Full runtime suite 1174 passed, 1 skipped, on the rebased tree. tsc node clean, oxlint + oxfmt clean, changed-code quality 0 new findings. One note for anyone else in this worktree: the rebase pulled in @xterm/addon-serialize, which was not installed here — pnpm install --frozen-lockfile was needed before the suite would even collect.

"Unreachable today" tells a future reader nothing actionable. Name both conditions
instead — the single if (!pty)-guarded set site, and rejectWaitersForHandle on the
drop path — so whoever changes either knows what they have just made live.

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

🧹 Nitpick comments (4)
src/main/runtime/orca-runtime.test.ts (4)

16295-16302: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Advance fake timers or drop fake timers for this test.

This test awaits waitForTerminal directly with vi.useFakeTimers() active and never advances the clock. If the pre-registration fast path stops resolving, the internal 1,000 ms timeout timer never fires. The test then hangs until the Vitest test timeout instead of failing with a clear assertion.

Attach the assertion first, then advance the clock so a regression fails deterministically.

♻️ Proposed change
-      await expect(
-        runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 })
-      ).resolves.toMatchObject({
-        handle,
-        condition: 'tui-idle',
-        satisfied: true,
-        status: 'running'
-      })
+      const assertion = expect(
+        runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 })
+      ).resolves.toMatchObject({
+        handle,
+        condition: 'tui-idle',
+        satisfied: true,
+        status: 'running'
+      })
+      await vi.advanceTimersByTimeAsync(2_000)
+      await assertion

16186-16194: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the pending-state tracker into one test-local function.

The same nine-line settled block appears in six tests. A small named function removes about fifty lines and keeps the intent visible.

♻️ Proposed helper
function trackSettlement(promise: Promise<unknown>): { isSettled: () => boolean } {
  let settled = false
  const mark = (): void => {
    settled = true
  }
  void promise.then(mark, mark)
  return { isSettled: () => settled }
}

Then replace each block:

-      let settled = false
-      void waitPromise.then(
-        () => {
-          settled = true
-        },
-        () => {
-          settled = true
-        }
-      )
+      const waitState = trackSettlement(waitPromise)

and assert with expect(waitState.isSettled()).toBe(false).

Also applies to: 16238-16246, 16394-16402, 16498-16506, 16535-16543, 16596-16604


16161-16164: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the multi-line rationale comments.

Each of these // Why: blocks spans four lines. The issue references (#6011, #9976) and the ranked-evidence reason are worth keeping. Reduce each block to one or two lines and keep the issue number.

As per coding guidelines: "Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code."

Also applies to: 16373-16376, 16515-16518

Source: Coding guidelines


16474-16513: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a positive assertion after the veto clears.

This test proves only that the waiter stays pending while the stream reports working. It does not prove that the waiter can still resolve after the agent reports done. A mutation that vetoes quiet foreground forever would still pass.

Emit a done status and assert resolution, as test at Line 16165 does.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5d6a7704-da9b-48d9-ace5-1e44cf9c1358

📥 Commits

Reviewing files that changed from the base of the PR and between be07b43 and ccf6f8c.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.

The quiet-foreground fallback carries its own copy of the first-party veto
guard in each poll, and only the PTY copy was pinned: deleting the leaf one
left all 1176 tests green. A visible tab is what `orca terminal create`
produces, so the leaf branch is the one real dispatches take.

Verified red-first against the full file, not a -t filter — with the leaf
guard removed this is the only failure.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live-validation status — one open design decision, deliberately not made here

Pushed here: test(runtime): pin the leaf quiet-foreground veto guard only. Production
code is untouched by that commit. It closes the last of four production hunks that no
test could detect (verified red-first against the full file — with the leaf guard removed
it is the only failure).

Everything below was built and measured but deliberately not shipped, because it is a
design decision rather than a fix.

Headline caveat, and it does not depend on sample size

The ranking has a structural hole that the currently-inert tier 2 conceals:
tier 1 outranks the first-party veto, and tier 1's title branch has no quiescence gate.
So during a long silent thinking gap with an idle-classifying title on screen, tier 1 can
fire and the veto — even once it works — cannot stop it.

That is a statement about the ordering, not about any measurement. Two candidate changes
were measured against it:

as-merged (a) veto repaired (a)+(b) title branch gated
runs with post-resolve output 2/7 9/10 0/10
any negative latency none one (−0.19s) none
latency after true idle 3.22–4.56s 0.04–1.52s 3.55–4.68s

0/10 is evidence, not proof. The as-merged column produced its one sustained false
idle (23.5s of further output after satisfied: true) once in seven runs, so ten clean
runs are entirely consistent with a low-rate residual surviving under (a)+(b).

The two candidates

  • (a) Repair the veto. lastExplicitAgentStatus is written only from OSC 9999, and no
    bundled hook emits OSC 9999 — all twelve in ~/.orca/agent-hooks/ POST to the hook
    server keyed by ORCA_PANE_KEY. Pointing the veto at the paneKey-keyed source (with the
    ptyId stamp kept as fallback, since a background CLI-created PTY has no paneKey) makes it
    fire: 18/22 samples, up from none. On its own it makes behaviour worse — with tier 3
    correctly suppressed, resolution moves up to the ungated tier 1 and fires mid-turn.
  • (b) Gate tier 1's title branch behind sustained quiet, leave the body branch
    ungated.
    These are not the same test: the body branch is positive content evidence
    (a rendered composer / Codex banner) with no title involved, so this does not collapse the
    ranking into a plain window. Measured on top of (a): the table above.

The ordering that would actually close the residual — not built

body (ungated) → veto → title + sustained quiet → tier 3

This lets the repaired veto block the silent-gap case while body evidence still rescues a
pane whose agent missed its completion hook. It is a third design decision and belongs to
whoever owns the call.

How to put a rate on the residual

The failure needs a >3s silent gap mid-turn, which short prompts do not produce. Use a
prompt tuned to make the agent think in long silent stretches, register one
terminal wait --for tui-idle while it works, and — this part matters — keep sampling
lastOutputAt for ~25s after the wait returns.
A rig that stops sampling at resolve
cannot observe a mid-turn resolve at all; it will report a healthy positive latency for a
run that actually failed. Count runs where output arrives after satisfied: true, and
report the span of that output, since a single trailing render at +1s is not the same
finding as sustained work at +23s.

Measurement caveat on the body-only number

Real codex could not be exercised: it dies during MCP handshake on
HTTP 401 … "code": "token_revoked" (an expired OAuth token, unrelated to this change) and
never reaches its prompt. The 0.26s figure comes from driving the genuine Codex banner
bytes through the real isKnownReadyPromptPreview path with output still flowing
(quiet = 0.92s). That is a proxy for the byte pattern, not a live Codex run.

@nwparker

Copy link
Copy Markdown
Contributor

I've been working #6011 from a different angle (#20155) and cross-reviewed all five open PRs against it. Yours is the best design of the set, and reviewing it made me find two measured defects in my own PR. Recording that here, plus one gap and a patch for it.

What yours gets right that mine didn't

I verified these by running your branch, not by reading it:

  1. Evidence ranking derived at read time. Mine stamped provenance into a new lastAgentIdleEvidence field on the record. syncWindowGraph rebuilds every leaf with an explicit field list that doesn't copy unknown fields, so my stamp was silently dropped on any renderer publish — and since an unstamped record read as positive, terminal wait --for tui-idle returns satisfied:true in ~0s while an agent TUI is actively working #6011 came back in full: wait correctly refused before the sync, satisfied=true in 0ms after it. Your derivation off lastOscTitle is immune by construction, and I confirmed it on your branch — refused both before and after a graph sync.
  2. getLiveLeafRecord. I missed this entirely. My idle poll captured a leaf record at registration; after a graph sync it read a frozen lastOutputAt, so the quiescence gate passed while the pane was still streaming — measured: settled at 4005ms during 12s of uninterrupted output. Your re-read is exactly the fix, and your comment explaining why the PTY equivalent is inert-but-kept is the right call.
  3. The OSC 9999 first-party veto and quietForegroundProcessProvesTuiIdle. Neither is in mine. The second one matters a lot: my fix leans on a quiet non-shell foreground process as corroboration, which is precisely the [Bug]: slow Claude startup lets tui-idle false-positive and loses injected dispatch (v1.4.149) #9976 dispatch --inject prompt-loss case your guard prevents.

The one gap: Grok can never settle

Every #6011 approach in this set — yours, #6012, #6555 and mine — makes a name-only title wait for TUI_IDLE_QUIESCENCE_MS of output silence. I drove the real grok binary through a real PTY to check that holds up. It doesn't:

  • Grok emits a bare grok OSC title at rest — name-only, 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 the 3s threshold.
  • isKnownReadyPromptPreview doesn't match Grok's banner, and Grok has no synthetic idle title.

So a genuinely idle Grok pane has no path to tier 1 or 2 and can never clear tier 3. On my branch this was a measured 45s timeout against a real idle Grok pane where the parent commit returned in 1ms. I confirmed the same on yours: a repainting Grok pane stayed unsatisfied for the full 12s window.

The fix is to scope the demotion rather than apply it to every agent: a name-only title is weak evidence only for agents that go on to announce rest with an explicit title of their own (the hook-driven Codex ready / Devin ready). Grok, Copilot, Aider, Mimo, agy and OpenCode emit their name and nothing more, so for them that title is the only rest signal that will ever arrive.

Patch, against your branch

diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts
index ed645d6af08..a38be49bb34 100644
--- a/src/main/runtime/orca-runtime.ts
+++ b/src/main/runtime/orca-runtime.ts
@@ -23,6 +23,8 @@ import { isServerDriveListRequest, listWindowsDrives } from './windows-drive-lis
 import { extractLastOsc7Uri, extractOscScanTail } from '../daemon/osc7-uri-extraction'
 import { parseFileUriPathParts } from '../daemon/osc7-file-uri'
 import type { AgentStatus } from '../../shared/agent-detection'
+import { getSyntheticAgentTerminalTitle } from '../../shared/synthetic-agent-title'
+import { resolveExplicitTerminalTitleAgentType } from '../../shared/terminal-title-agent-type'
 import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges'
 import type { TerminalOscColorQueryReplyColors } from '../../shared/terminal-osc-color-reply'
 import type { TerminalOutputSourceRange } from '../../shared/terminal-output-source-range'
@@ -34626,19 +34628,45 @@ export class OrcaRuntimeService {
    *  busy Codex/Devin/aider is routinely titled idle — that is #6011. Demand the
    *  stream also go quiet before acting on it. Handles with no PTY output of their
    *  own (adopted/daemon) have nothing to debounce, so their title still stands. */
-  private hasSustainedTitleIdle(target: {
-    lastAgentStatus: AgentStatus | null
-    lastOutputAt: number | null
-  }): boolean {
+  private hasSustainedTitleIdle(
+    target: {
+      lastAgentStatus: AgentStatus | null
+      lastOutputAt: number | null
+      lastOscTitle?: string | null
+    },
+    ptyId?: string | null
+  ): boolean {
     if (target.lastAgentStatus !== 'idle') {
       return false
     }
     if (target.lastOutputAt === null) {
       return true
     }
+    if (!this.nameOnlyIdleNeedsCorroboration(ptyId, target.lastOscTitle)) {
+      return true
+    }
     return Date.now() - target.lastOutputAt >= TUI_IDLE_QUIESCENCE_MS
   }
 
+  /** Whether a name-only title from this pane's agent may be held to the quiescence
+   *  demand above. Only for agents that go on to announce rest with an explicit title
+   *  of their own (the hook-driven `Codex ready` / `Devin ready`). Grok, Copilot, Aider,
+   *  Mimo, agy and OpenCode emit their NAME and nothing more at rest, so holding them to
+   *  it leaves no settle signal at all: a real idle Grok pane repaints its banner about
+   *  four times a second forever (max gap 891ms across a 22s observation), so the stream
+   *  never quiesces and the wait runs to timeout. */
+  private nameOnlyIdleNeedsCorroboration(
+    ptyId: string | null | undefined,
+    title?: string | null
+  ): boolean {
+    // Why the title fallback: an adopted pane carries no launch metadata, but its
+    // name-only title is exactly the thing that names the agent.
+    const agent =
+      (ptyId ? this.ptysById.get(ptyId)?.launchAgent : null) ??
+      (title ? resolveExplicitTerminalTitleAgentType(title) : null)
+    return getSyntheticAgentTerminalTitle(agent, 'done') !== null
+  }
+
   /** Tier 3, cold start: Orca launched a known agent on this PTY, so a quiet
    *  non-shell foreground process is an agent still booting, not one at its prompt.
    *  Resolving here is what let `dispatch --inject` write into a TUI that had not
@@ -34658,7 +34686,7 @@ export class OrcaRuntimeService {
     if (this.hasFreshWorkingAgentStatusForPty(pty.ptyId)) {
       return false
     }
-    return this.hasSustainedTitleIdle(pty)
+    return this.hasSustainedTitleIdle(pty, pty.ptyId)
   }
 
   /** Re-read the leaf the waiter registered against. `syncWindowGraph` rebuilds
@@ -34696,7 +34724,7 @@ export class OrcaRuntimeService {
     if (this.hasFreshWorkingAgentStatusForPty(leaf.ptyId)) {
       return false
     }
-    return this.hasSustainedTitleIdle(leaf)
+    return this.hasSustainedTitleIdle(leaf, leaf.ptyId)
   }
 
   private resolveTuiIdleWaiters(leaf: RuntimeLeafRecord): void {

Results on your branch with it applied (A/B unchanged, C fixed):

A  codex name-only, streaming:     refused (timeout) at 1504ms   <- #6011 still fixed
A2 same but NO launch metadata:    refused (timeout) at 1502ms   <- title fallback covers adopted panes
B  before graph sync:              refused (timeout) at 1501ms
B  after  graph sync:              refused (timeout) at 1503ms   <- your design holds where mine broke
C  grok, repaints forever:         SATISFIED=true at 0ms         <- was: never settles
D  codex explicit "ready" (8s):    SATISFIED=true at 4005ms
E  same, paneTitle published:      SATISFIED=true at 0ms

Your orca-runtime.test.ts passes with it: 1175 passed, 1 skipped. (The title fallback is load-bearing for your own does not report tui-idle while a name-only agent title keeps streaming output test, which uses a pane with no launch metadata — without it that test settles instantly.)

One small thing, unrelated to the above

D vs E: an explicit Codex ready OSC title settles immediately only once the renderer has published it as the pane title. Without a renderer (daemon-hosted or background pane) tier 1 reads paneTitle ?? tabs.get(tabId)?.title, misses it, and it falls through to the quiescence lane — ~4s instead of 0ms. Not a hang and not a blocker; having tier 1 also consult leaf.lastOscTitle would close it.

Where this leaves things

I'd rather your PR landed than mine — the design is better and the credit belongs on it. The blocker is environmental, not yours: this branch shares no git history with main (different root commit, git merge refuses unrelated histories), as do #6012, #6555 and #9929. So I couldn't merge-test it against current main, and I can't push this commit somewhere it would help. Flagging it for whoever can rebase the branch onto main.

Separately: #9929 is not a competitor here — it targets #9905, the opposite-direction Grok bug (title reads idle while background tasks still run), and composes with the scoping above rather than conflicting with it.

nwparker added a commit that referenced this pull request Sep 12, 2026
…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 added a commit that referenced this pull request Sep 13, 2026
…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 added a commit that referenced this pull request Sep 13, 2026
…ilence (#20155)

`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

Copy link
Copy Markdown
Contributor

Closing this, and I want to be precise about why, because this PR won the cross-review on merit and the design that just landed is yours.

#6011 is fixed on main as of e9065dd, and you are a co-author on that commit. It is your architecture, ported — not reimplemented, and not improved upon in any way that changes whose idea it was.

Why it was ported rather than merged

Purely mechanical, and nothing to do with the quality of the work: this branch shares no git history with main. Different root commit (224ab0b1 vs 200d8a57), no common ancestor, and git merge refuses with unrelated histories. The same is true of #6012, #6555 and #9929. Nobody can merge this branch as it stands — not you, not us. Porting was the only route to landing it.

What is specifically yours

Named individually so the merged commit does not obscure it:

  1. Rank the evidence, never infer idle from silence — the three-tier structure the fix is built on.
  2. Deriving the rank at read time from lastOscTitle rather than stamping provenance onto the record. This caught a real defect in our own 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, the wait correctly refused before a graph sync and returned satisfied=true in 0ms after it. Your derivation is immune by construction.
  3. getLiveLeafRecord — we missed this entirely. A record captured at waiter 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.
  4. The first-party OSC 9999 veto — the agent's own account of itself outranking anything inferred from titles or bytes.
  5. quietForegroundProcessProvesTuiIdle — a quiet non-shell foreground process must not prove idle on a pane where Orca launched a known agent. Our 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.

We ran your branch standalone before adopting it, rather than taking the design on faith. It passed: name-only title while streaming correctly refused, and the verdict held across a graph sync where ours broke.

What we added

One gap: every #6011 approach in the set, yours included, demanded output quiescence before accepting a name-only title. Driving the real grok binary through a real PTY shows that cannot work — Grok emits a bare grok title at rest and repaints a braille banner continuously (max gap 891ms across a 22s observation; tail-preview no better at 79 changes in 20 idle seconds, longest stable window 2.1s against a 3s threshold). A genuinely idle Grok pane therefore had no path to tier 1 or 2 and could never clear tier 3 — a measured 45s timeout where the parent returned in 1ms. So the demotion is now scoped to agents that go on to announce rest explicitly.

Plus one small thing we found while verifying yours: 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 (4005ms → 0ms).

If you would rather rebase this branch onto main and land it under your own name, say so and I will happily reopen and revert ours. That outcome would have been our first choice; the history problem is the only reason it was not.

Thank you — this was the best fix of the five, and finding two defects in our own approach by reading yours was the most useful thing to come out of the review.

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.

terminal wait --for tui-idle returns satisfied:true in ~0s while an agent TUI is actively working

2 participants