Repository navigation
fix(runtime): rank tui-idle evidence instead of inferring idle from silence - #14642
brennanb2025 wants to merge 6 commits into
Conversation
📝 WalkthroughWalkthroughThe 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)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)
15987-15990: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the test rationale comments.
Replace each multi-line
Whycomment 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
📒 Files selected for processing (2)
src/main/runtime/orca-runtime.test.tssrc/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.
da6e079 to
b876ff8
Compare
Fallback-poll hang fixed, coverage gap closed, rebased onto mainPushed as The hangBoth tui-idle fallback polls closed over the record they were handed at registration. nextLeaves.set(leafKey, { ...leaf, ptyId, ptyGeneration, /* … */ })
…
this.leaves = nextLeavesso the captured leaf froze at its registration values within milliseconds. The stale capture predates this branch. What makes it fatal here is that 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, Coverage gapThe 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:
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 Severity: yes, it broke dispatch — for body-announced agents
Headless ( That shape is now a test, and it hangs for its full timeout with the fix reverted. Rebase142 commits, rebased and re-run on the materialized tree rather than trusting Still openI did not re-run the live agent repro. The mechanism is now reproduced deterministically against the real |
… 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.
|
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. |
Correction: the PTY poll does not share the defectPushed What the real cycle showedThe prediction was that
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
The asymmetry that remains is the whole bug: Root cause corrected — it is wider than
|
"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.
There was a problem hiding this comment.
🧹 Nitpick comments (4)
src/main/runtime/orca-runtime.test.ts (4)
16295-16302: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdvance fake timers or drop fake timers for this test.
This test awaits
waitForTerminaldirectly withvi.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 winExtract the pending-state tracker into one test-local function.
The same nine-line
settledblock 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 valueShorten 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 winAdd 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 reportsdone. A mutation that vetoes quiet foreground forever would still pass.Emit a
donestatus 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
📒 Files selected for processing (2)
src/main/runtime/orca-runtime.test.tssrc/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.
Live-validation status — one open design decision, deliberately not made herePushed here: Everything below was built and measured but deliberately not shipped, because it is a Headline caveat, and it does not depend on sample sizeThe ranking has a structural hole that the currently-inert tier 2 conceals: That is a statement about the ordering, not about any measurement. Two candidate changes
0/10 is evidence, not proof. The as-merged column produced its one sustained false The two candidates
The ordering that would actually close the residual — not built
This lets the repaired veto block the silent-gap case while body evidence still rescues a How to put a rate on the residualThe failure needs a >3s silent gap mid-turn, which short prompts do not produce. Use a Measurement caveat on the body-only numberReal |
|
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'tI verified these by running your branch, not by reading it:
The one gap: Grok can never settleEvery #6011 approach in this set — yours, #6012, #6555 and mine — makes a name-only title wait for
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 Patch, against your branchdiff --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): Your One small thing, unrelated to the aboveD vs E: an explicit Where this leaves thingsI'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 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. |
…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]>
…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]>
…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]>
|
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 Why it was ported rather than mergedPurely mechanical, and nothing to do with the quality of the work: this branch shares no git history with What is specifically yoursNamed individually so the merged commit does not obscure it:
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 addedOne gap: every #6011 approach in the set, yours included, demanded output quiescence before accepting a name-only title. Driving the real 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 If you would rather rebase this branch onto 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. |
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:working/blocked/waiting. This outranks anything Orca infers from titles or bytes.Concretely:
RuntimePtyWorktreeRecord.lastExplicitAgentStatus, stamped from the OSC 9999 payloads thatonPtyDataalready 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.lastAgentStatus === 'idle'/ title / preview checks collapse into two evaluators,isPtyTuiIdleSatisfiedandisLeafTuiIdleSatisfied, 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.idlenow requiresTUI_IDLE_QUIESCENCE_MSof quiet before it counts (the constant already existed but was only reachable from the foreground-process branch).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 canonicalworking|blocked|waiting|doneenum is defined at:16.src/shared/agent-status-osc.ts— a stateful OSC 9999 parser that runs on every PTY chunk, atorca-runtime.ts:9830, before any title handling.getTerminalAgentStatus()(orca-runtime.ts:17001) already resolves that structured status viagetFreshExplicitAgentStatusForHandle()and gives it authority over title heuristics.waitForTerminal()— the same class, the same handle — had zero references to it. It read onlylastAgentStatus, whichapplyTrackedPtyTitle()(:10589) assigns fromdetectAgentStatusFromTitle(rawTitle)and nothing else.So the two APIs were self-inconsistent by construction:
terminal agent-statuscould reportworkingfrom a hook at the same instantterminal wait --for tui-idlereported 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
isFreshNonDoneAgentStatuspredicate rather than inventing a new window is deliberate — if a status is fresh enough forterminal agent-statusto reportworking, it is fresh enough fortui-idleto 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 falsesatisfied: truesilently drops dispatched work (#9976).Superseded PRs
Tasks 1,watching · 1 command) with regexes. Superseded in approach: a per-agent screen-chrome regex is the tier-1 inference layer, and fix(runtime): do not treat Grok background tasks as tui-idle #9929's own body concedes it false-positives on any text containing those strings. If Grok publishes structured status during background tasks, tier 2 covers it with no patterns at all. I am not claiming terminal wait tui-idle reports success while Grok background task is still active #9905 is fixed — it is markedcannot_reproand I have no evidence about Grok's OSC 9999 behavior during background work. That needs a live measurement, not a regex.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
detectAgentStatusFromTitlefalls through to'idle'for any title carrying a knownagent name with no spinner and no working keyword (
src/shared/agent-title-status.ts:224isa bare
return 'idle'). So a single frame of the plain task title classifies as idle — nospecial glyph required. Claude Code's transient
✳frame (CLAUDE_IDLEatagent-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, solastOutputAtkeeps moving andquiet 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.ptysByIdhas exactly onesetsite (orca-runtime.ts:30068), guarded byif (!pty). Records are create-once and mutated in place — never swapped.dropDisconnectedPtyRecord(:30509), and it callsinvalidatePtyIncarnationHandle,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
ptysByIdandmanufactured 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.
getLivePtyRecordstays as an inert guard — oneMap.getper 2s tick — so the two parallelpolls 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)-guardedsetsite, andrejectWaitersForHandleon the drop path) so whoeverchanges either knows precisely what they have made live.
this.leaves, by contrast, is rebuilt wholesale bysyncWindowGraph(
nextLeaves.set(leafKey, {...leaf})at:5728, swapped at:5827). That asymmetry is theentire bug: the leaf capture dies within milliseconds, the PTY capture stays live.
Timing budget
TUI_IDLE_POLL_INTERVAL_MSis 2s andTUI_IDLE_QUIESCENCE_MSis 3s, so the worst case fromreadiness to resolution is one quiescence window plus one tick — about 5s, against the 60s
orchestration.workerStartallows. Tier 1 and tier 2 evidence resolve on the next tickwithout 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) gatesagent_readinessonwaitForTerminal(..., 'tui-idle')against a freshly launched agent, so thepre-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:
resolver re-reads the leaf live, so it resolved them despite the dead poll record.
the clear case:
findCodexReadyPromptIndexmatches its banner, andCodex YOLOisexplicitly 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_readinesswithAgent 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 handlestays 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 inwaitForTerminal; 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 addedafter 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.
resolveTuiIdleWaitersre-rankingexpected true to be falseresolvePtyTuiIdleWaitersre-rankingexpected true to be falseexpected true to be falseTwo 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 1outranks 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 isin
package.jsonbut was not present in an older worktree'snode_modules. Runpnpm install --frozen-lockfilefirst or the runtime suite fails to collect withCannot 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 mergedspeculatively —
orca-runtime.tshad drifted enough that a cleanmerge-treewas notsufficient evidence on its own.
vitest run src/main/runtime/orca-runtime.test.ts→ 1174 passed, 1 skippedtsc --noEmit -p config/tsconfig.node.json --composite false→ cleanoxlint+oxfmt --checkon both changed files → cleancheck-changed-code-quality.mjs→ 0 new findings (native, type-aware, React Doctor)Platforms: macOS.
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— realsyncWindowGraphpublishes,real
onPtyDatabyte sequences — with every assertion mutation-checked. A live confirmationrun would still be worth doing before merge.
AI Disclosure
Review
isShellProcess/getForegroundProcessbehavior is unchanged; only whether its result is trusted changed.lastExplicitAgentStatusis 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. Perdocs/reference/remote-wire-compatibility.mdthis is not a mixed-version concern.worktree.psare written exactly as before; the new field is additive and read only by the wait path.tui-idlegets 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.Map.getplus two comparisons.buildTerminalWaitTextin 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 thatsubstring 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:
dropDisconnectedPtyRecordrejects 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:
Root cause, measured rather than assumed
Driving a real
claudethrough a pty and timestamping every OSC title frame shows theclassifier fall-through is not a rare transient. In one 4.8s turn,
✳ Claude Code— anidle-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) makesdetectAgentStatusFromTitlereturnidlefor those,and separately the function falls through to
'idle'for any title carrying a knownagent name with no spinner (
agent-title-status.ts:199-224) — so the glyph is not evenrequired. 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 tothe hook server keyed by
ORCA_PANE_KEY— so for Claude and Codex the veto is inert andthe 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
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Scoped equivalents run locally and listed above; full
typecheck/buildleft to CI by instruction (OOM risk).Author