Skip to content

fix(orchestration): wake a restored idle pane that never speaks again - #13203

Open
Jinwoo-H wants to merge 2 commits into
mainfrom
fix-orchestration-restored-idle-mail
Open

Jinwoo-H wants to merge 2 commits into
mainfrom
fix-orchestration-restored-idle-mail

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

The report

A coordinator was left idle overnight. Eight worker messages arrived and none reached it. When the user came back and sent an unrelated prompt, all eight surfaced at once — making it look like delivery is triggered by the human rather than by the mail.

Why it happens

Push-on-idle only fires on a live agent-status observation. That gate is correct in intent: a seeded status is a memory, and typing a pointer plus Enter into an agent that went busy across a relaunch would corrupt a real turn.

But the gate has no way to ever resolve, because an idle agent TUI is silent. Pulled from the reporter's own pane history — 232 title frames:

WORKING (braille spinner) : 226
IDLE ('✳ …')              :   6

The ✳ idle title is painted once, on the working→idle edge. After that the agent emits nothing until it is given work. So a pane restored while its agent sits at the prompt never produces the frame the gate is waiting for, and its mail strands indefinitely. The existing unit test even encodes the dead end — it releases the row with onPtyData('\x1b]0;Codex done\x07'), a frame the real world never supplies.

The fix

Probe instead of waiting. Quiescence across a window plus a recognized foreground agent establishes the same fact the missing title would have carried:

  • a byte inside the window means a spinner repaint, tool output, or a human mid-keystroke — none safe to submit into;
  • a foreground that is not a recognized agent (a bare shell, or node as a mere wrapper name) means there is nothing there to wake.

The condition covers unknown status as well as a seeded idle. A cold relaunch returns its restore payload before the renderer publishes the graph, so the seed lands on a pty with no leaves and the pane comes back carrying no status at all — that, not the seeded idle, is the shape the restart e2e reproduces. working and permission are positive evidence of not-idle and never probe. One window per pane per burst, so a busy Run does not open a foreground read per message.

Verification

Every test was shown to fail against its own reverted change.

Test Mutation that kills it
restored idle pane, agent never emits another title whole fix reverted → 0 writes after 10 simulated min
restored pane with no agent status at all narrow condition back to === 'idle'
does not push when output lands inside the window quiescence comparison → false
does not push when foreground is not an agent foreground check → false
one quiescence window for a burst single-flight guard removed → 1 call becomes 5

The burst test initially did not discriminate — fake timers let each probe settle before the next fired, so the guard was never exercised. Rewritten to hold every probe in flight, it now fails 1-vs-5 without the guard.

E2E (--workers=1, real PTYs, two Electron launches, no mocking):

  • delivers mail after a restart to a quiet pane whose agent never speaks again — new, and verified to fail on main before the fix. The agent is launched through a link named codex so the pane presents a recognized foreground; no title is emitted anywhere after the restart, so the pointer arriving is the assertion.
  • keeps mail pending across a restart and delivers it when the agent reports live — unchanged and still passing. Its agent runs under bare node, a wrapper rather than a recognized agent, so the probe refuses it and only a live frame releases the row. The two tests split precisely on the probe.
  • All 8 orchestration-idle-mail-delivery specs pass.

orca-runtime.test.ts 1078 passed · orchestration suites 320 passed · typecheck:node, lint, and check:code-quality:changed clean.

Trade-off worth a reviewer's eye

This widens push delivery to panes whose status is unknown, gated on quiescence plus a recognized agent. An agent that works silently for longer than the window — no spinner, no output — would receive the pointer and an Enter. Agent TUIs repaint several times a second, so the window has an order of magnitude of headroom, and the payload is a short pointer rather than message content. I judged that acceptable against mail stranding indefinitely, but it is a deliberate choice rather than a free win.

Not in scope

The same investigation surfaced a second, independent defect: check on a run-bound pane replays an unacknowledged delivery forever, so the pointer count and what check returns describe different sets (the reporter saw "8 messages" while check kept handing back the same 2, same delivery ID). That is a separate fix and is not touched here.

Push-on-idle only fires on a live agent-status observation. That gate is
right in intent — a seeded status is a memory, and typing plus Enter into
an agent that went busy across a relaunch corrupts a real turn — but it
has no way to ever resolve, because an idle agent TUI is silent. Claude
paints its title on the working→idle edge and emits nothing afterwards,
so a pane restored while its agent sits at the prompt never produces the
frame the gate waits for. Mail addressed to it strands until a human
gives the agent something unrelated to do, which is what makes it look
like delivery is triggered by the user rather than by the mail.

Probe instead of waiting. Quiescence across a window plus a recognized
foreground agent establishes the same fact the missing title would have
carried: a byte in the window means a spinner repaint, tool output, or a
human mid-keystroke, and a foreground that is not a known agent means
there is nothing there to wake. Neither is safe to submit into, and both
are cheap to observe.

The condition covers unknown status as well as a seeded idle. A cold
relaunch returns its restore payload before the renderer publishes the
graph, so the seed lands on a pty with no leaves and the pane comes back
carrying no status at all — that, not the seeded idle, is the shape the
restart e2e reproduces. 'working' and 'permission' are positive evidence
of not-idle and never probe.
@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The runtime delays delivery to restored panes until a bounded quiet period completes. It rechecks pane state, detects output or replacement, verifies a recognized foreground agent, deduplicates probes per terminal handle, and delivers pending messages. Tests cover timing, safety, missing status, delayed leaf binding, non-agent processes, stale reads, bounded polling, and bursts. End-to-end tests cover restored codex delivery and configurable process names.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the defect, fix, tests, trade-off, and scope, but omits the required AI Review Report, Security Audit, Screenshots statement, and testing checklist. Add the missing template sections, including cross-platform review confirmation, security audit findings, a Screenshots statement, and checked testing items.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: waking restored idle panes that emit no further status frames.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
tests/e2e/helpers/orchestration-mail-pane-agent.ts (1)

122-128: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce the test commentary.

Keep one short comment for each test-specific invariant. Remove implementation details that the code already shows.

  • tests/e2e/helpers/orchestration-mail-pane-agent.ts#L122-L128: Keep the recognized-process purpose. Remove kernel execution details.
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts#L288-L291: State that bare node requires a live status frame.
  • tests/e2e/orchestration-idle-mail-restore.spec.ts#L11-L27: Replace the long scenario description with a short statement of the restart invariant.

As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line; do not explain obvious code or describe how it works.”

Source: Coding guidelines

src/main/runtime/orca-runtime.test.ts (2)

33639-33639: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the exact two-second quiescence boundary.

These tests can pass if the delay changes to any value between one and 2.5 seconds. Assert no write or probe at 1,999 ms, then assert the expected action after one additional millisecond.

  • src/main/runtime/orca-runtime.test.ts#L33639-L33639: replace the 10-minute advance with boundary assertions for restored idle delivery.
  • src/main/runtime/orca-runtime.test.ts#L33682-L33682: add the same boundary assertions for missing-status delivery.
  • src/main/runtime/orca-runtime.test.ts#L33889-L33889: assert that the single probe starts at the two-second boundary for a message burst.

33614-33616: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce expanded test comments.

Keep only concise rationale that the test cannot express. Remove comments that restate setup, actions, or assertions.

As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ecd57520-6433-4334-8910-f1a6bca8a346

📥 Commits

Reviewing files that changed from the base of the PR and between 54a9b58 and c9216df.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • tests/e2e/helpers/orchestration-mail-pane-agent.ts
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts
  • tests/e2e/orchestration-idle-mail-restore.spec.ts

Comment thread src/main/runtime/orca-runtime.ts Outdated
Comment on lines +31385 to +31440
const ptyId = leaf.ptyId
if (!ptyId || !this.ptyController || this.restoredIdleProbePtyIds.has(ptyId)) {
return
}
const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId)
const outputAtBeforeWindow = leaf.lastOutputAt
this.restoredIdleProbePtyIds.add(ptyId)
setTimeout(() => {
void (async () => {
try {
// Why re-read rather than trust the captured leaf: a graph resync
// replaces leaf objects, and a live frame during the window already
// delivered on real evidence.
const settled = this.leaves.get(leafKey)
if (
!settled ||
settled.ptyId !== ptyId ||
(settled.lastAgentStatus !== 'idle' && settled.lastAgentStatus !== null) ||
settled.lastAgentStatusObservedLive ||
settled.lastOutputAt !== outputAtBeforeWindow
) {
return
}
const foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
if (
!foregroundProcess ||
!(await this.isRecognizedForegroundAgentProcess(ptyId, foregroundProcess))
) {
return
}
// Why re-check after the await: the foreground read is itself slow
// enough for the pane to start working underneath it.
const confirmed = this.leaves.get(leafKey)
if (
!confirmed ||
confirmed.ptyId !== ptyId ||
(confirmed.lastAgentStatus !== 'idle' && confirmed.lastAgentStatus !== null) ||
confirmed.lastOutputAt !== outputAtBeforeWindow
) {
return
}
// The probe IS the live observation, so later mail for this pane
// delivers immediately instead of paying the window again.
confirmed.lastAgentStatusObservedLive = true
// Why no reservedTypes: that snapshot guards a sub-millisecond race
// with a check resolving in the same drain, which this window has
// long outlived. Replaying it here could suppress a type forever;
// deliverPendingMessages re-reads the waiters that are still live.
this.deliverPendingMessages(confirmed, { mailboxHandle })
} finally {
this.restoredIdleProbePtyIds.delete(ptyId)
}
})()
}, RESTORED_IDLE_QUIESCENCE_MS)
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add a catch clause to the quiescence probe and check connected before probing.

The async IIFE in confirmRestoredIdleThenDeliver has a try/finally block but no catch. getForegroundProcess and isRecognizedForegroundAgentProcess run inside the try. Every other call site of getForegroundProcess in this file wraps the call in a try/catch or .catch() (for example terminalHasShellForegroundProcess and readPtyForegroundProcessFromController), which confirms the call can throw or reject. Because this async function is invoked with void (async () => {...})() and never awaited by the caller, an exception here becomes an unhandled promise rejection.

This gap is reachable: onPtyExit sets leaf.connected = false on exit but does not clear leaf.ptyId, leaf.lastAgentStatus, or leaf.lastOutputAt. If the PTY exits during the 2-second quiescence window, both guard checks (settled and confirmed) still pass, because neither checks connected. The probe then calls getForegroundProcess on an exited PTY.

Add a catch clause, and check connected in both guard checks so the probe stops as soon as the terminal exits instead of relying on the error path.

🛡️ Proposed fix: add exit check and error handling to the quiescence probe
     this.restoredIdleProbePtyIds.add(ptyId)
     setTimeout(() => {
       void (async () => {
         try {
           // Why re-read rather than trust the captured leaf: a graph resync
           // replaces leaf objects, and a live frame during the window already
           // delivered on real evidence.
           const settled = this.leaves.get(leafKey)
           if (
             !settled ||
             settled.ptyId !== ptyId ||
+            !settled.connected ||
             (settled.lastAgentStatus !== 'idle' && settled.lastAgentStatus !== null) ||
             settled.lastAgentStatusObservedLive ||
             settled.lastOutputAt !== outputAtBeforeWindow
           ) {
             return
           }
           const foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
           if (
             !foregroundProcess ||
             !(await this.isRecognizedForegroundAgentProcess(ptyId, foregroundProcess))
           ) {
             return
           }
           // Why re-check after the await: the foreground read is itself slow
           // enough for the pane to start working underneath it.
           const confirmed = this.leaves.get(leafKey)
           if (
             !confirmed ||
             confirmed.ptyId !== ptyId ||
+            !confirmed.connected ||
             (confirmed.lastAgentStatus !== 'idle' && confirmed.lastAgentStatus !== null) ||
             confirmed.lastOutputAt !== outputAtBeforeWindow
           ) {
             return
           }
           // The probe IS the live observation, so later mail for this pane
           // delivers immediately instead of paying the window again.
           confirmed.lastAgentStatusObservedLive = true
           // Why no reservedTypes: that snapshot guards a sub-millisecond race
           // with a check resolving in the same drain, which this window has
           // long outlived. Replaying it here could suppress a type forever;
           // deliverPendingMessages re-reads the waiters that are still live.
           this.deliverPendingMessages(confirmed, { mailboxHandle })
+        } catch (error) {
+          console.warn('[runtime] restored-idle quiescence probe failed', { ptyId, error })
         } finally {
           this.restoredIdleProbePtyIds.delete(ptyId)
         }
       })()
     }, RESTORED_IDLE_QUIESCENCE_MS)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const ptyId = leaf.ptyId
if (!ptyId || !this.ptyController || this.restoredIdleProbePtyIds.has(ptyId)) {
return
}
const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId)
const outputAtBeforeWindow = leaf.lastOutputAt
this.restoredIdleProbePtyIds.add(ptyId)
setTimeout(() => {
void (async () => {
try {
// Why re-read rather than trust the captured leaf: a graph resync
// replaces leaf objects, and a live frame during the window already
// delivered on real evidence.
const settled = this.leaves.get(leafKey)
if (
!settled ||
settled.ptyId !== ptyId ||
(settled.lastAgentStatus !== 'idle' && settled.lastAgentStatus !== null) ||
settled.lastAgentStatusObservedLive ||
settled.lastOutputAt !== outputAtBeforeWindow
) {
return
}
const foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
if (
!foregroundProcess ||
!(await this.isRecognizedForegroundAgentProcess(ptyId, foregroundProcess))
) {
return
}
// Why re-check after the await: the foreground read is itself slow
// enough for the pane to start working underneath it.
const confirmed = this.leaves.get(leafKey)
if (
!confirmed ||
confirmed.ptyId !== ptyId ||
(confirmed.lastAgentStatus !== 'idle' && confirmed.lastAgentStatus !== null) ||
confirmed.lastOutputAt !== outputAtBeforeWindow
) {
return
}
// The probe IS the live observation, so later mail for this pane
// delivers immediately instead of paying the window again.
confirmed.lastAgentStatusObservedLive = true
// Why no reservedTypes: that snapshot guards a sub-millisecond race
// with a check resolving in the same drain, which this window has
// long outlived. Replaying it here could suppress a type forever;
// deliverPendingMessages re-reads the waiters that are still live.
this.deliverPendingMessages(confirmed, { mailboxHandle })
} finally {
this.restoredIdleProbePtyIds.delete(ptyId)
}
})()
}, RESTORED_IDLE_QUIESCENCE_MS)
}
const ptyId = leaf.ptyId
if (!ptyId || !this.ptyController || this.restoredIdleProbePtyIds.has(ptyId)) {
return
}
const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId)
const outputAtBeforeWindow = leaf.lastOutputAt
this.restoredIdleProbePtyIds.add(ptyId)
setTimeout(() => {
void (async () => {
try {
// Why re-read rather than trust the captured leaf: a graph resync
// replaces leaf objects, and a live frame during the window already
// delivered on real evidence.
const settled = this.leaves.get(leafKey)
if (
!settled ||
settled.ptyId !== ptyId ||
!settled.connected ||
(settled.lastAgentStatus !== 'idle' && settled.lastAgentStatus !== null) ||
settled.lastAgentStatusObservedLive ||
settled.lastOutputAt !== outputAtBeforeWindow
) {
return
}
const foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
if (
!foregroundProcess ||
!(await this.isRecognizedForegroundAgentProcess(ptyId, foregroundProcess))
) {
return
}
// Why re-check after the await: the foreground read is itself slow
// enough for the pane to start working underneath it.
const confirmed = this.leaves.get(leafKey)
if (
!confirmed ||
confirmed.ptyId !== ptyId ||
!confirmed.connected ||
(confirmed.lastAgentStatus !== 'idle' && confirmed.lastAgentStatus !== null) ||
confirmed.lastOutputAt !== outputAtBeforeWindow
) {
return
}
// The probe IS the live observation, so later mail for this pane
// delivers immediately instead of paying the window again.
confirmed.lastAgentStatusObservedLive = true
// Why no reservedTypes: that snapshot guards a sub-millisecond race
// with a check resolving in the same drain, which this window has
// long outlived. Replaying it here could suppress a type forever;
// deliverPendingMessages re-reads the waiters that are still live.
this.deliverPendingMessages(confirmed, { mailboxHandle })
} catch (error) {
console.warn('[runtime] restored-idle quiescence probe failed', { ptyId, error })
} finally {
this.restoredIdleProbePtyIds.delete(ptyId)
}
})()
}, RESTORED_IDLE_QUIESCENCE_MS)
}

Follow-up to the probe on this branch, driven by an e2e that failed about
one run in three. Two single-attempt assumptions were wrong.

A pane comes back addressable before its leaf is bound, so
getLiveLeafForHandle throws while the handle already resolves. Delivery is
only ever attempted on message arrival, so that throw — swallowed by a
catch — stranded the row until unrelated mail happened to come in. The
probe now owns resolution and is keyed by handle rather than pty, so an
unbound leaf is a state to wait through rather than a dead end.

A restored pane also replays buffered output, and a single byte inside
the window failed the quiescence check with nothing to retry. The probe
now re-arms a bounded number of times, rebasing on the output it just
saw, so a pane that is genuinely working keeps failing the window until
it stops rather than being written to.

Two smaller changes fall out of measuring rather than assuming. The
quiescence window is now justified by sampled data — a working Claude
pane repaints every ~340ms, worst observed gap 451ms, while an idle one
emits nothing at all — leaving >4x headroom. And the foreground read uses
direct recognition instead of the review-note helper, which re-polls a
wrapper name every 150ms for 6.5s: ~45 process inspections for an answer
that cannot change on a pane already proven silent.

Also pins the post-await re-check, which no test had covered: the
foreground read is a round trip, long enough for the agent to start a
turn and make the window's verdict stale.
@Jinwoo-H

Jinwoo-H commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Update: two single-attempt bugs found and fixed

I pushed a second commit after an e2e started failing about one run in three. The flake was not the test — the implementation had two places where delivery got exactly one attempt and then gave up. Both are production defects.

1. A pane is addressable before its leaf is bound

getLiveLeafForHandle throws while the handle already resolves, and that throw was swallowed by a catch. Since delivery is only ever attempted on message arrival, the row stranded until unrelated mail happened to arrive — the same failure mode this PR exists to fix, one layer up. Captured from an instrumented failing run:

FORHANDLE term_1cbe086d-… known=true      ← handle resolves
(no GATE line)                            ← getLiveLeafForHandle threw

The probe now owns resolution and is keyed by handle rather than pty, so an unbound leaf is a state to wait through.

2. A restored pane replays buffered output

One byte inside the window failed the quiescence check with nothing to retry. The probe now re-arms a bounded number of times, rebasing on the output it just saw, so a genuinely working pane keeps failing the window until it stops.

Previously flaky e2e, after the fix: 8 runs, 8 passes.

Measured, not assumed

The 2s window was a guess. Sampled against live Claude panes:

state observed
working repaints every 340ms median, 451ms worst gap
idle zero bytes across 3s

So 2s carries >4x headroom over the worst measured gap, and the "idle agents are silent" premise is now directly confirmed rather than inferred from title counts.

Cheaper foreground read

Swapped isRecognizedForegroundAgentProcess for direct recognition. That helper re-polls a wrapper name (node, python) every 150ms for 6.5s waiting for it to exec into an agent — ~45 process inspections, repeated per message, for an answer that cannot change on a pane already proven silent for the whole window. A test pins the difference (5 reads, one per bounded attempt, vs 45).

Coverage gap closed

Mutation testing showed the post-await re-check had no test: disabling it alone left the suite green. The foreground read is a round trip — on a remote pane a network hop — long enough for the agent to start a turn and make the window's verdict stale. Now pinned by its own test.

On the alternative from review discussion

I evaluated isKnownReadyPromptPreview as a possible replacement for the quiescence check and rejected it: it recognizes only Codex (via a startup banner that scrolls out of the tail), Antigravity, and Cursor. It has no Claude detection at all, so it cannot cover the reported bug. Worth noting its Cursor arm infers idle from braille-spinner absence — the same principle as the quiescence check, already trusted in production.

Full re-verification: 1081 unit tests, 31 orchestration suites (1401 tests), 10 e2e at --workers=1, typecheck / lint / changed-code gate all clean. Every test still shown to fail against its own reverted change.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

33716-33718: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce test-comment detail.

Keep only the non-obvious reason for each setup. Move measurements, E2E failure history, and review-note discussion to the PR description or issue.

Also applies to: 33753-33760, 33822-33824, 33842-33844, 33858-33860

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0cecadd9-e1ec-40f4-8d1c-cedfc7908e04

📥 Commits

Reviewing files that changed from the base of the PR and between c9216df and 88ebc2b.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts

Comment on lines +31401 to 31484
private confirmRestoredIdleThenDeliver(terminalHandle: string, mailboxHandle: string): void {
if (!this.ptyController || this.restoredIdleProbeHandles.has(terminalHandle)) {
return
}
this.restoredIdleProbeHandles.add(terminalHandle)

/** One window; resolves true once quiescence and the foreground both hold. */
const observeQuietWindow = async (baseline: number | null): Promise<boolean> => {
await new Promise((resolve) => setTimeout(resolve, RESTORED_IDLE_QUIESCENCE_MS))
// Why re-resolve every attempt: the pane may not have been bound when the
// mail landed, and a graph resync replaces leaf objects wholesale.
const settled = this.tryGetLiveLeafForHandle(terminalHandle)
if (
!settled ||
!settled.ptyId ||
(settled.lastAgentStatus !== 'idle' && settled.lastAgentStatus !== null) ||
settled.lastAgentStatusObservedLive
) {
return false
}
const ptyId = settled.ptyId
if (settled.lastOutputAt !== baseline) {
return false
}
// Why direct recognition and not isRecognizedForegroundAgentProcess: that
// helper re-polls a wrapper name (`node`, `python`) for seconds waiting
// for it to exec into the real agent. A pane silent for the whole window
// is not mid-launch, so the retry settles on the same answer after ~40
// more process inspections, once per message that arrives.
const foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
if (recognizeAgentProcess(foregroundProcess) === null) {
return false
}
// Why re-check after the await: the foreground read is itself slow enough
// for the pane to start working underneath it.
const confirmed = this.tryGetLiveLeafForHandle(terminalHandle)
if (
!confirmed ||
confirmed.ptyId !== ptyId ||
(confirmed.lastAgentStatus !== 'idle' && confirmed.lastAgentStatus !== null) ||
confirmed.lastOutputAt !== baseline
) {
return false
}
// The probe IS the live observation, so later mail for this pane delivers
// immediately instead of paying the window again.
confirmed.lastAgentStatusObservedLive = true
// Why no reservedTypes: that snapshot guards a sub-millisecond race with a
// check resolving in the same drain, which this window has long outlived.
// Replaying it here could suppress a type forever; deliverPendingMessages
// re-reads the waiters that are still live.
this.deliverPendingMessages(confirmed, { mailboxHandle })
return true
}

void (async () => {
try {
// Why re-arm instead of one attempt: a pane coming back replays buffered
// output, and a single byte landing mid-window would otherwise defer
// this row until unrelated mail happened to arrive. Each retry rebases
// on the output it just saw, so a pane that is genuinely working simply
// keeps failing the window until it stops.
for (let attempt = 0; attempt < RESTORED_IDLE_PROBE_ATTEMPTS; attempt += 1) {
const baseline = this.tryGetLiveLeafForHandle(terminalHandle)?.lastOutputAt ?? null
if (await observeQuietWindow(baseline)) {
return
}
const current = this.tryGetLiveLeafForHandle(terminalHandle)
// Keep waiting while the pane is still unbound — that is the state
// this retry exists for. Stop once it is visibly busy or a live frame
// took over the delivery path.
if (
current &&
(current.lastAgentStatusObservedLive ||
(current.lastAgentStatus !== 'idle' && current.lastAgentStatus !== null))
) {
return
}
}
} finally {
this.restoredIdleProbeHandles.delete(terminalHandle)
}
})()
}

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Add a connected check and a catch clause to the retry-based quiescence probe.

observeQuietWindow checks !settled.ptyId and settled.lastAgentStatus, but it never checks settled.connected (same for the post-await confirmed check). onPtyExit sets leaf.connected = false and leaf.lastAgentStatusObservedLive = false on exit, but it does not clear leaf.ptyId or leaf.lastAgentStatus. If the PTY exits during any of the up to RESTORED_IDLE_PROBE_ATTEMPTS windows, both guard checks still pass, and the probe calls getForegroundProcess on an exited PTY.

Every other call site of getForegroundProcess in this file wraps the call in a try/catch or .catch(), confirming the call can throw or reject. The outer void (async () => { ... })() at Line 31456 has a try/finally but no catch. If getForegroundProcess throws for the exited PTY, the rejection is unhandled, since the async IIFE result is never awaited by the caller.

Add connected checks to both guards, and wrap the getForegroundProcess call (or the whole loop body) in a try/catch so the probe stops as soon as the terminal exits, instead of relying on an unhandled-rejection path.

🛡️ Proposed fix: add exit check and error handling to the retry-based quiescence probe
     const observeQuietWindow = async (baseline: number | null): Promise<boolean> => {
       await new Promise((resolve) => setTimeout(resolve, RESTORED_IDLE_QUIESCENCE_MS))
       const settled = this.tryGetLiveLeafForHandle(terminalHandle)
       if (
         !settled ||
         !settled.ptyId ||
+        !settled.connected ||
         (settled.lastAgentStatus !== 'idle' && settled.lastAgentStatus !== null) ||
         settled.lastAgentStatusObservedLive
       ) {
         return false
       }
       const ptyId = settled.ptyId
       if (settled.lastOutputAt !== baseline) {
         return false
       }
-      const foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
+      let foregroundProcess: string | null | undefined
+      try {
+        foregroundProcess = await this.ptyController?.getForegroundProcess(ptyId)
+      } catch {
+        return false
+      }
       if (recognizeAgentProcess(foregroundProcess) === null) {
         return false
       }
       const confirmed = this.tryGetLiveLeafForHandle(terminalHandle)
       if (
         !confirmed ||
         confirmed.ptyId !== ptyId ||
+        !confirmed.connected ||
         (confirmed.lastAgentStatus !== 'idle' && confirmed.lastAgentStatus !== null) ||
         confirmed.lastOutputAt !== baseline
       ) {
         return false
       }
       confirmed.lastAgentStatusObservedLive = true
       this.deliverPendingMessages(confirmed, { mailboxHandle })
       return true
     }

     void (async () => {
       try {
         for (let attempt = 0; attempt < RESTORED_IDLE_PROBE_ATTEMPTS; attempt += 1) {
           const baseline = this.tryGetLiveLeafForHandle(terminalHandle)?.lastOutputAt ?? null
           if (await observeQuietWindow(baseline)) {
             return
           }
           const current = this.tryGetLiveLeafForHandle(terminalHandle)
           if (
             current &&
             (current.lastAgentStatusObservedLive ||
               (current.lastAgentStatus !== 'idle' && current.lastAgentStatus !== null))
           ) {
             return
           }
         }
+      } catch (error) {
+        console.warn('[runtime] restored-idle quiescence probe failed', { terminalHandle, error })
       } finally {
         this.restoredIdleProbeHandles.delete(terminalHandle)
       }
     })()

This concern was raised on an earlier commit for the single-attempt version of this probe and is still present after the rework into bounded retries.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant