Skip to content

fix(runtime): apply the tui-idle evidence ranking to mailbox delivery - #20578

Merged
nwparker merged 5 commits into
mainfrom
fix/tui-idle-followups
Sep 14, 2026
Merged

nwparker merged 5 commits into
mainfrom
fix/tui-idle-followups

Conversation

@nwparker

@nwparker nwparker commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​192 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​192
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​119 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​114

Refs #6011

Two follow-ons to #20155. The evidence ranking that fixed the wait path did not reach two other consumers of the same signal. Both verified against origin/main before fixing, and both pinned by tests that fail on the parent commit.

Defect 1 — mailbox delivery types into a working pane

deliverPendingMessagesForLeaf was gated on a raw lastAgentStatus === 'idle'. A busy Codex/Devin pane repaints its OSC title to the bare product name mid-turn; that reads as idle for display (the sidebar needs it to clear a stale spinner, #1437), so delivery fired and wrote the pointer plus Enter into a running turn.

This is the same mis-settlement as #6011, in a path with a worse failure mode: a bad tui-idle makes a script race ahead, whereas this injects keystrokes into the user's agent session.

Confirmed on main before fixing:

deliverPendingMessagesForLeaf calls after a working title:     0
...after a NAME-ONLY idle title arrives mid-turn:              1

It was not one consumer — it was five. All shared the lastAgentStatus === 'idle' shape, and three are independent entry points that can each fire during the same busy-pane situation:

Site Trigger
orca-runtime-apply-tracked-pty-title.ts title transition (the reported one)
orca-runtime-sync-window-graph.ts renderer graph-sync sweep
orchestration/mailbox-pointer-delivery.ts (entry) mailbox notification
orca-runtime-deliver-pending-messages.ts post-probe re-read
orchestration/mailbox-pointer-delivery.ts (post-probe) post-probe re-read

All five now route through one predicate, isAgentSettledForDelivery, which is the wait path's own ranking. Liveness (lastAgentStatusObservedLive) stays a separate requirement at each caller — this adds evidence, it does not replace the existing gate.

Deliberately left alone: orchestration/mailbox-pointer-submit.ts accepts idle or working. It asks "is this pane in a known state, safe to queue against", not "is it safe to type now" — a different question, and tightening it would stall queuing rather than prevent an injection.

Behaviour change. Only the ambiguous case is withheld. Agents that announce rest explicitly (Codex ready, Claude ✳, Gemini ◇) deliver exactly as before. Agents whose name is their only rest signal (Grok, Copilot, Aider, Mimo, agy, OpenCode) are not demoted at all, so they also deliver as before. The single newly-withheld case is a corroboration-required agent showing nothing but its name — which is the bug.

Defect 2 — a pane that never produced output could never settle

runtime-terminal-idle-polls.ts computed quiescence as (x ? Date.now() - x : 0) >= quiescenceMs. A null lastOutputAt collapsed to 0, and 0 >= 3000 is false forever — the least quiet value, for a record that has in fact been silent since it was created. A pane with a live non-shell foreground process and no output ever could not settle at any timeout.

Now extracted to isQuietForQuiescence, where null means quiet.

A correction to the reported diagnosis, since it changes what is and is not fixed here. The report attributed a restored lastAgentStatus='idle' + name-only pane to this expression. That is not the mechanism — such a pane is refused by hasSustainedTitleIdle, which deliberately returns false when a corroboration-required agent has no output clock, because there is then no corroboration available at all. That behaviour is intentional (#20155 review) and is left as is; settling there would be #6011 with zero evidence. Measured on main:

restored codex, name-only title : status=idle  lastOutputAt=null -> refused (hasSustainedTitleIdle, intended)
restored codex, explicit title  : status=idle  lastOutputAt=null -> SATISFIED at 0ms
restored grok,  name-only title : status=idle  lastOutputAt=null -> SATISFIED at 0ms
no status, no launchAgent       : status=null  lastOutputAt=null -> refused  <- this expression, fixed here

Corrections to the original report

Recording these so the history reads accurately; both were raised in review and are reflected in the fix above.

The mechanism of defect 1 is not a stored field. The report attributed it to a lastAgentIdleEvidence stamp being ignored. That field does not exist on main — it belonged to an earlier approach on #20155 and was removed when that PR was ported to the read-time ranking. The defect is real, but the mechanism is "this consumer never consults isTuiIdleSatisfied", not "it ignores a stored field". Nothing about the fix changes; the framing does.

"A restored pane can never satisfy tui-idle" was too broad. Explicit-title and name-only-only agents both settle at 0ms from a restored record (see the measurement table above). The (x ? Date.now() - x : 0) expression is genuinely broken for a record silent since creation, and that is what is fixed here — but a restored Codex pane showing a name-only title is refused by hasSustainedTitleIdle deliberately, and that behaviour is left as is.

Why delivery also needs a retry

Review (thanks @fable-fixes-review) caught that the gate above, on its own, is the over-tightening case — and it was right. Verified independently before acting on it.

The wait path polls; delivery does not. runtime-terminal-idle-polls.ts re-checks on a timer, so tier-3 evidence that only becomes valid with the passage of time (a pane going quiet) eventually satisfies it. Delivery is edge-driven with no poll behind it:

Trigger Kind
orca-runtime-apply-tracked-pty-title.ts title transition edge
orca-runtime-sync-window-graph.ts renderer graph sync edge (recurs, but only where a renderer is publishing)
orchestration/mailbox-pointer-delivery.ts mailbox notification edge
orca-runtime-serialize-agent-prompt-submission.ts foreground-probe recovery edge
redrive / parked redelivery microtask off a state change, not a timer

There is no timer anywhere in the delivery path; the existing code says so itself, in the catch at mailbox-pointer-delivery.ts: "Durable mail remains available to explicit check or a later idle edge."

So a refusal at an edge was final. Measured on the previous head of this PR:

at the name-only edge (mid-turn):     deliveries=0  <- correct
5s later, pane quiet past quiescence: deliveries=0
  -> STRANDED: the pane is idle, the message is queued, nothing will ever fire again

The concrete case: a hookless corroboration-required agent (Codex, Devin, Cursor, Pi, OMP, Droid, Hermes). It never emits an explicit X ready, so the only evidence that can lift the refusal is quiescence — which is the passage of time, and no edge fires on that. On a daemon-hosted pane with no renderer publishing graph syncs, nothing re-fires at all. That trades a visible mis-delivery for an invisible lost message, which is the worse failure.

Fix: a refusal arms a one-shot retry for that leaf, timed to just after the quiescence window could have elapsed. One timer per refused leaf, unref'd, cleared as soon as any path delivers. The retry re-runs the same gate before delivering — the delivery sites gate at the call rather than inside deliverPendingMessagesForLeaf, so firing straight into it would hand the retry the very injection the gate exists to prevent. A pane that went busy again re-arms from its own fresher timestamp instead of spinning.

The invariant now holds in both directions: no queued message is lost, and no message is typed into a busy pane.

Where bytes actually reach a pane

Review found ungated paths twice, at five then eight. The count was never the point: delivery is implemented twice, and each implementation writes bytes itself. Every "consumer" is routing that ends at one of four sites.

Subsystem Writes pointer text Writes Enter
Runtime orca-runtime-deliver-pending-messages.ts:140 :174
Orchestration orchestration/mailbox-pointer-stage.ts:97 orchestration/mailbox-pointer-submit.ts:118

Gating callers can never be exhaustive — a new caller silently bypasses the check, which is what happened twice. Gating the point at which each implementation commits to typing is exhaustive by construction. The orchestration gate now sits inside deliver, covering its four callers — deliverForHandle, redeliverAfterProbe, settle, and the notification coordinator's deliverForLeaf — and a fifth cannot bypass it. Refusal parks for redelivery rather than dropping.

Closed as a side effect, with no call-site change needed: mailbox-pointer-delivery.ts:254 (settle) and mailbox-notification-coordinator.ts:44. Gated separately because it is on the runtime trunk: orca-runtime-serialize-agent-prompt-submission.ts.

observeAgentIdle is not a bypass — refuted

Flagged by two reviewers as a seventh bypass that presses Enter on a raw name-only idle. It isn't, and gating it would cause harm. The chain:

observeAgentIdle -> state.takeDeferredEnter(ptyId)?.()
takeDeferredEnter returns null unless flight.deferredUntilIdle AND flight.submitEnter
flight.submitEnter is assigned at mailbox-pointer-stage.ts:183
  -- which is AFTER the pointer text write at mailbox-pointer-stage.ts:97

So the deferred Enter can only ever complete a flight whose text is already in the pane. It injects nothing on its own. Refusing it would orphan typed pointer text in the user's input line with no way to submit or clear it — worse than the hazard it was meant to prevent.

The observation behind the report was real (Enter can reach a pane under a name-only title); the diagnosis was not. What makes that Enter safe is gating the stage, because the text is what arrives first. Recorded here so it is not re-found.

A required gate can ship inert

Moving the gate broke three cases in mailbox-pointer-stage.test.ts: its dependency object is built untyped, so the new required dep was simply missing and this.deps.isAgentSettledForDelivery is not a function only surfaced when the suite ran. Typecheck did not catch it.

The fixture is fixed rather than the dep given a default, deliberately — a defaulted gate would silently disable itself, which is the same class of failure as this PR's own bug: a check that exists, is called, and decides nothing. Worth knowing more generally: any untyped partial-deps fixture can drop a required dependency without the compiler noticing, which is how a gate ships inert.

Tests

Six cases in tui-idle-delivery-and-quiescence.test.ts. Each spies on the delivery entry point, never on the gate under test — the gate runs for real and decides whether the entry point is reached.

Eight cases. Three assert delivery does happen once the evidence the edge was missing finally arrives — the assertion class the earlier tests skipped, since they only pinned the early negative.

Differential across the three states of this PR:

vs origin/main (no gate):              6 failed | 2 passed
vs b9c2403 (strict gate, no retry):    3 failed | 5 passed   <- the three stranding cases
vs c1048482 (retry, no idle->idle):    1 failed | 7 passed   <- late ready title only

Each step fixes exactly what it claims and nothing more. The three stranding cases, measured on the current head:

CASE A (hookless codex):         at edge=0        after 4.5s quiet=1
CASE B (hooked codex, mainline): at name-only=0   at ready title=1   <- prompt, not 3s late
CASE C (9999 veto race):         at idle title=0  at done=0          after 4.5s=1

Case B is the mainline path: a hooked Codex emits a name-only frame before the hook's Codex ready, consuming the working->idle transition and leaving the ready title as an idle->idle step delivery was never offered. Delivery now re-offers on a title change, as the waiter branch already did.

Case C still resolves via the quiescence retry rather than promptly on the done payload. Correct but not prompt; re-offering at on-pty-data.ts:225 would tighten it and is left as a follow-up rather than widening this change further.

The two that pass on main are deliberate regression guards, not filler: "delivers once the agent states it is done" and "still delivers for an agent whose name is its only rest signal" prove the new gate does not over-tighten. They must pass both before and after.

Verification

  • src/main/runtime/ src/shared/ — 16,150 passed, 148 skipped, 0 failed
  • changed-code quality gate, oxlint, type-aware gate, oxfmt --check, typecheck: all clean

The ranking that fixed #6011 reached the wait path but not two other consumers
of the same signal.

Mailbox delivery gated on a raw `lastAgentStatus === 'idle'`, so a busy
Codex/Devin pane repainting its title to the bare product name was treated as
finished and had the pointer plus Enter typed into it mid-turn. That is the same
mis-settlement, in a path that writes to the user's terminal rather than one that
returns a wrong answer to a script. Five delivery sites shared the shape: the
title-transition path, the graph-sync sweep, the post-probe re-read, and both
mailbox pointer-delivery gates. All now route through one predicate, which is the
wait path's own ranking; liveness stays a separate requirement at each caller.

The idle poll's quiescence gate read a null `lastOutputAt` as `0ms since output`
via `(x ? Date.now() - x : 0)`, so `0 >= quiescenceMs` was false forever and a
pane that had never produced output could not settle no matter how long the
caller waited. A record with no output timestamp has been quiet since it was
created, which is the quietest a pane can be.

Both cases are pinned by tests that fail against the parent commit.

Refs #6011
@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6356cd52-3e1d-4a22-8674-2f7ad798a493

📥 Commits

Reviewing files that changed from the base of the PR and between 4a347d0 and ad47705.

📒 Files selected for processing (1)
  • src/main/runtime/tui-idle-delivery-and-quiescence.test.ts

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


📝 Walkthrough

Walkthrough

Pending-message and mailbox-pointer delivery now require settled live TUI idle evidence. The runtime centralizes this check for pointer commits and schedules one retry after the quiescence interval when delivery is refused. Delivery paths use the check for title changes, restored idle status, window synchronization, and probe redelivery. Quiescence polling treats a missing output timestamp as quiet for leaves and PTYs. Tests cover title evidence, retries, continuous output, agent status changes, and null timestamps.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to ad477

Pending mailbox input can be injected after live agent evidence has been cleared, including while a pane may be busy. Preserve the idle and live-observation guards on parked and timer-driven delivery before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed change rationale, defect analysis, issue reference, tests, and verification results. However, it omits several required template sections, including Visual Proof or a… Add the required template sections and complete them. Include Fixes #6011``, provide before/after visual proof or write N/A with a reason, complete the Testing checkboxes, address AI Disclosure, Review, Agent skill upstream boundary, Note…
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the main change: applying TUI-idle evidence ranking to mailbox delivery.
Full details: Description check

Explanation

The description provides detailed change rationale, defect analysis, issue reference, tests, and verification results. However, it omits several required template sections, including Visual Proof or an explicit N/A explanation, the checklist, Agent skill upstream boundary, Notes, Review, and AI Disclosure. It also uses Refs #6011`` instead of the required Fixes # format.

Resolution

Add the required template sections and complete them. Include Fixes #6011``, provide before/after visual proof or write N/A with a reason, complete the Testing checkboxes, address AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

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

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
src/main/runtime/orchestration/mailbox-pointer-delivery.ts (1)

254-254: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Recheck delivery safety before draining parked deliveries.

Line 254 calls deliver without checking lastAgentStatus, lastAgentStatusObservedLive, or isAgentSettledForDelivery.

If a second delivery is parked during a pointer flight and the pane becomes working before that flight settles, this path can stage another pointer plus Enter into the busy pane. Apply the same gate to currentLeaf; otherwise retain the delivery for a later idle edge.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: fdb55413-9785-4762-8a0e-626c41cd5226

📥 Commits

Reviewing files that changed from the base of the PR and between 0c81284 and b9c2403.

📒 Files selected for processing (9)
  • src/main/runtime/orca-runtime-apply-tracked-pty-title.ts
  • src/main/runtime/orca-runtime-deliver-pending-messages.ts
  • src/main/runtime/orca-runtime-resolve-exit-waiters.ts
  • src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
  • src/main/runtime/orca-runtime-sync-window-graph.ts
  • src/main/runtime/orchestration/mailbox-pointer-delivery-contract.ts
  • src/main/runtime/orchestration/mailbox-pointer-delivery.ts
  • src/main/runtime/runtime-terminal-idle-polls.ts
  • src/main/runtime/tui-idle-delivery-and-quiescence.test.ts

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new gate is enforced at call sites rather than at the single delivery funnel, and one idle-authorized caller of the same method was missed — it can still type the pointer plus Enter into a pane whose idle is only a name-only title from a transient frame.

Reviewed changes

  • Mailbox delivery ranking — new isAgentSettledForDelivery on OrcaRuntimeWithResolveExitWaiters delegates to the wait path's isTuiIdleSatisfiedForLeaf, and is wired into the apply-tracked-pty-title idle transition, the sync-window-graph sweep, the deliver-pending-messages post-probe re-read, and both mailbox-pointer-delivery sites. Liveness stays a separate per-caller requirement.
  • Quiescence null semantics — isQuietForQuiescence extracted in runtime-terminal-idle-polls.ts; a null lastOutputAt now counts as quiet in both the leaf and PTY foreground lanes.
  • Tests — tui-idle-delivery-and-quiescence.test.ts adds four cases that spy on the delivery entry point (the gate runs for real), two of which fail on the parent commit and two of which guard against over-tightening.

⚠️ A sixth idle-authorized delivery path bypasses the new gate

deliverPendingMessagesForLeaf has three callers (plus its definition at orca-runtime-get-pty-record-for-pane-key.ts:338). This PR gates two of them; orca-runtime-serialize-agent-prompt-submission.ts:142 still delivers on a bare restoredStatus === 'idle'. Its sibling call one line above (resolveTuiIdleWaiters(leaf)) does re-rank, so this is exactly the asymmetry the PR removes at the other sites. restoreLastExit can hand back a name-only idle — agent-title-status.ts:99-102 stashes the previous non-working status when the title clears to neutral, and a bare Codex title classifies as idle (tui-idle-evidence.ts:13-17) — while a recognized foreground agent is still running (orchestra-runtime-serialize-agent-prompt-submission.ts:116-120). That is the reported mid-turn injection, reachable through the one caller the enumeration missed.

Technical details
# Route the restore-idle delivery through the same gate

## Affected sites
- `src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts:140-143` — `deliverPendingMessagesForLeaf(leaf)` fires on `restoredStatus === 'idle'` with no `isAgentSettledForDelivery` check, next to a `resolveTuiIdleWaiters` that does re-rank.
- `src/main/runtime/orchestration/mailbox-pointer-delivery.ts:254` — `settle()` re-enters `deliver()` for parked mail with no status check at all (lower confidence: the mail was gated when parked, but the pane may have started working inside the 500ms flight window).
- `src/main/runtime/orchestration/mailbox-pointer-delivery.ts:58` — `deliver()` is the shared funnel and contains no gate, which is why each new caller is a fresh opportunity to bypass it.

## Required outcome
- The restore-idle delivery must not type into a pane whose idle is not corroborated, matching the other `deliverPendingMessagesForLeaf` call sites.

## Suggested approach (optional)
Gate at the funnel (`deliver()`, or `OrchestrationMailboxNotificationCoordinator.deliverForLeaf`) so no caller can bypass it, or at minimum add `this.isAgentSettledForDelivery(leaf)` at `:142`. Note `restoreLastExit`'s `confirmedStatus === 'idle'` variant already requires a fresh explicit idle hook (`:105-111`), so only the `restorableExitStatus` path needs re-ranking.

## Open questions for the human (optional)
Is the restore-idle caller deliberately exempt because the stashed status is tracker-authoritative, or was it simply outside the five-site enumeration?

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

* emitted could not settle no matter how long the caller waited.
*/
function isQuietForQuiescence(lastOutputAt: number | null, quiescenceMs: number): boolean {
return lastOutputAt === null ? true : Date.now() - lastOutputAt >= quiescenceMs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

null is not a reliable "never produced output" signal: applyRestoredTerminalTailSeed (terminal-tail-restore-seed.ts:44-59) installs real tailBuffer/preview content while deliberately leaving lastOutputAt null, and daemon-backed panes have no local output clock at all. The same null is read the opposite way in hasSustainedTitleIdle (tui-idle-evidence.ts:97), which refuses to settle a corroboration-required agent with no clock. So this settles restored/no-clock records on the first 2s sweep with zero elapsed evidence, which is the input #9976 was about.

Technical details
# Distinguish an absent clock from an empty record

## Affected sites
- `src/main/runtime/runtime-terminal-idle-polls.ts:27-28` — `isQuietForQuiescence` collapses `null` and `0ms elapsed` into `true`.
- `src/main/runtime/runtime-terminal-idle-polls.ts:154` and `:219` — both foreground lanes now settle a null clock on the first tick.
- `src/main/runtime/terminal-tail-restore-seed.ts:35-42` — `restoredTerminalTailSeedAllowed` requires `lastOutputAt === null` but also empty preview/tail; after seeding, content is present and the clock stays null.
- `src/main/runtime/tui-idle-evidence.ts:97` — the title lane treats the same null as "no corroboration available".

## Required outcome
- A record whose clock is absent but which has output content (preview/tail non-empty) must not read as quiet, or the settle must be bounded rather than instantaneous.

## Suggested approach (optional)
Treat null as quiet only when the record is genuinely empty (`preview`/`tailBuffer`/`tailPartialLine` all empty, the same predicate `restoredTerminalTailSeedAllowed` uses), or keep waiting for a clock and let the caller's timeout decide.

The gate added in the previous commit is correct for a POLLED consumer and wrong
for an edge-driven one. The wait path polls, so tier-3 evidence that only becomes
valid with the passage of time — a pane going quiet — eventually satisfies it.
Delivery has no poll behind it: it fires on a title transition, a graph sync, or a
new message, and a refusal at one of those edges is final unless another edge
happens to arrive.

A hookless Codex pane never emits an explicit `X ready`, so once it fell quiet
nothing re-fired and the queued message stranded permanently. That trades a
visible mis-delivery for an invisible lost one, which is the worse failure.

Refusing now arms a one-shot retry for that leaf, timed to just after the
quiescence window could have elapsed. The retry re-runs the same gate before
delivering — the delivery sites gate at the call rather than inside
deliverPendingMessagesForLeaf, so firing straight into it would hand the retry
the very injection the gate exists to prevent — and a pane that went busy again
simply re-arms from its own fresher timestamp.

Refs #6011
Review found three more ungated paths after the last commit, which is the second
time a new caller turned up. The cause was the shape of the fix: gating callers
of a delivery entry point means every future caller silently bypasses the check.

There are two delivery implementations, each writing bytes itself — the runtime
path (orca-runtime-deliver-pending-messages) and the orchestration pointer path
(mailbox-pointer-stage / -submit). The orchestration gate now sits inside
`deliver`, the single point at which that subsystem commits to typing into the
pane, so its four callers — handle delivery, post-probe redelivery, flight
settle, and the notification coordinator's per-leaf path — are all covered and a
fifth cannot bypass it. Refusal parks for redelivery rather than dropping.

The neutral-title foreground restoration path is gated too.

A name-only frame routinely lands before the hook's `X ready`, consuming the
working→idle transition and leaving the ready title as an idle→idle step that
delivery was never offered — so the strongest evidence a hooked Codex emits never
reached it. Delivery now re-offers on a title change, as the waiter branch
already did.

`observeAgentIdle` is deliberately NOT gated: its deferred Enter only resolves a
flight whose pointer text was already written, so refusing it would orphan that
text in the pane with no way to submit or clear it. Gating the commit point is
what makes that Enter safe.

Refs #6011

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1e702254-442b-42cf-812d-d63730568e0a

📥 Commits

Reviewing files that changed from the base of the PR and between b9c2403 and c104848.

📒 Files selected for processing (7)
  • src/main/runtime/orca-runtime-apply-tracked-pty-title.ts
  • src/main/runtime/orca-runtime-deliver-pending-messages.ts
  • src/main/runtime/orca-runtime-resolve-exit-waiters.ts
  • src/main/runtime/orca-runtime-runtime-id.ts
  • src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
  • src/main/runtime/orca-runtime-sync-window-graph.ts
  • src/main/runtime/tui-idle-delivery-and-quiescence.test.ts

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

// Why the gate again here: delivery sites gate at the CALL, not inside
// deliverPendingMessagesForLeaf, so firing straight into it would hand the retry the
// very injection the gate exists to prevent. A pane that went busy again re-arms.
if (this.checkDeliverySettledAndArmRecheck(current)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve the liveness gate in the retry callback.

isAgentSettledForDelivery does not enforce lastAgentStatusObservedLive. The retry can survive a provider-generation reset, which clears that field. The callback can then deliver from title-based settlement without a current live idle observation.

Require the same lastAgentStatus === 'idle' and lastAgentStatusObservedLive checks that direct delivery paths use before calling deliverPendingMessagesForLeaf.

Proposed fix
-      if (this.checkDeliverySettledAndArmRecheck(current)) {
+      if (
+        current.lastAgentStatus === 'idle' &&
+        current.lastAgentStatusObservedLive &&
+        this.checkDeliverySettledAndArmRecheck(current)
+      ) {
         this.deliverPendingMessagesForLeaf(current)
       }
📝 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
if (this.checkDeliverySettledAndArmRecheck(current)) {
if (
current.lastAgentStatus === 'idle' &&
current.lastAgentStatusObservedLive &&
this.checkDeliverySettledAndArmRecheck(current)
) {

Each case asserts delivery DOES happen once the evidence the edge was missing
arrives: quiescence elapsing, a ready title after a name-only frame, and a done
status after a vetoed idle title. Positive-after-the-edge is the assertion the
earlier tests skipped — they only pinned the early negative.

Refs #6011
The retry fires on a real 3s quiescence window, and asserting around it with
wall-clock sleeps left ~1.5s of margin and a 250ms interval that a loaded CI
runner is not obliged to schedule on time — the busy-pane case could see a gap
past the window and legitimately deliver. The clock is the thing under test, so
it has to be the deterministic part.

Refs #6011

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The retry added in c104848 can collapse into a 20 Hz timer loop when the gate refuses for a reason that time cannot lift — reproduced on this head at 20 re-checks/second.

Reviewed changes

  • The delivery gate became self-arming — checkDeliverySettledAndArmRecheck wraps isAgentSettledForDelivery and arms a per-leaf retry timer on refusal; all five delivery sites and the pointer-delivery dependency were switched from the pure predicate to it.
  • Retry timer lifecycle — clearDeliveryRecheck/armDeliveryRecheck on OrcaRuntimeWithResolveExitWaiters, backed by deliveryRecheckTimersByLeafKey on the runtime; the timer re-runs the full gate before delivering, and re-arms when the pane went busy again.
  • Tests — two cases added (a refused delivery delivers once the pane falls quiet; no retry while output continues), on top of the four delivery/quiescence cases from the previous commit.

The null-quiescence inline note and the sixth idle-authorized delivery caller from the prior review are unchanged by this commit and remain open as tracked.

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

Comment on lines +157 to +158
const elapsed = live?.lastOutputAt ? Date.now() - live.lastOutputAt : 0
const delay = Math.max(TUI_IDLE_QUIESCENCE_MS - elapsed, 0) + 50

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.

delay collapses to 50ms as soon as elapsed >= TUI_IDLE_QUIESCENCE_MS, but a refusal is only time-liftable when tier 3 is waiting on quiescence. A tier-2 veto (a fresh first-party working/blocked status) does not clear with time, so the retry re-arms every 50ms. Reproduced on this head with the shared harness: 20 gate re-checks in one second after the first window, for up to the 30-minute AGENT_STATUS_STALE_AFTER_MS window.

Technical details
# Floor the retry interval so a non-time-liftable refusal cannot spin

## Affected sites
- `src/main/runtime/orca-runtime-resolve-exit-waiters.ts:157-158` — `elapsed` keeps growing while the gate still refuses, so `delay = max(0, 0) + 50`.
- `src/main/runtime/orca-runtime-resolve-exit-waiters.ts:168` — the retry re-runs `checkDeliverySettledAndArmRecheck`; on refusal it re-arms with the same collapsed delay.
- `src/main/runtime/tui-idle-evidence.ts:57-59` (`hasFreshWorkingFirstPartyStatus`) + `src/shared/agent-status-freshness.ts:7` — the tier-2 veto stays "fresh" for `AGENT_STATUS_STALE_AFTER_MS` = 30 minutes.

## Why it is reachable
`firstPartyStatus` is read from the PTY record's `lastExplicitAgentStatus` (OSC 9999), independent of the title-derived `lastAgentStatus`. A name-only idle title plus a fresh OSC 9999 `working` status is exactly the busy Codex/Devin pane this PR targets: tier 1 finds nothing, tier 2 vetoes, and tier 3 is never reached. Once PTY output stops for more than `quiescenceMs` (agent thinking or blocked), every retry re-arms at 50ms. The retry is only armed after an idle+live edge, so those preconditions held at arm time.

Measured on `c1048482` with `makeTuiIdleRuntime`: `onPtyData(osc('⠋ Codex') + OSC9999 working)` then `onPtyData(osc('Codex'))`, then count `checkDeliverySettledAndArmRecheck` calls in the 1s following the first ~3s window -> 20.

## Required outcome
A persistent refusal must not schedule itself faster than the window it is waiting on. Any re-arm delay needs a floor (quiescence window, or backoff). A refusal that tier-3 quiescence could lift would already have passed once `elapsed >= quiescenceMs`; anything still refused at that point is non-time-liftable, so waking sooner than the window buys nothing.

## Suggested approach (optional)
Floor the delay at the quiescence window — e.g. `Math.max(TUI_IDLE_QUIESCENCE_MS, TUI_IDLE_QUIESCENCE_MS - elapsed) + 50` (simply `TUI_IDLE_QUIESCENCE_MS + 50`), or add an attempt counter with backoff and stop re-arming when the first-party status is the veto.

## Coverage note
Neither new test exercises a refusal that time cannot lift; both go busy via raw output, which resets `lastOutputAt` and keeps the delay at ~quiescence.

## Open question for the human (optional)
The retry re-runs only the ranking, not the `lastAgentStatus === 'idle' && lastAgentStatusObservedLive` preconditions each call site applied. Tier 3 re-derives idle, but tier 1 can pass on title/body evidence alone — is dropping the liveness recheck deliberate?

@nwparker
nwparker merged commit 49fba59 into main Sep 14, 2026
27 checks passed
nwparker added a commit that referenced this pull request Sep 19, 2026
* fix: gate startup agent recovery on host inventory

* fix: defer recovery while a live agent lacks conversation ownership

* fix(mobile): two known main bugs the RPC migration preserved (#20563)

* fix(mobile): two known main bugs the RPC migration preserved

A malformed host `error` and a null settings result both reach a property read that throws.
Both are deliberate behaviour changes; the goldens move in the follow-up commit.

`hostReplyErrorTextOrFallback` passed a truthy non-string through under a `string` annotation.
Its one caller is the in-band `git.commit` failure, and every consumer of that text is display or
prompt copy: `use-mobile-create-pr-runner` and `PrSidebarCreateEmptyState` record it as a commit
failure, `use-mobile-commit-failure-recovery` hands it to `summarizeCommitFailure`, which starts
with `raw.slice(...).replace(...)`. So no consumer needs the value, and the decision is the
fallback rather than `String(value)` — the relay handler declares
`commit(): Promise<{ success: boolean; error?: string }>`, so a non-string is a malformed reply,
and `generatedCommitMessageReader` in the same domain already reads a non-string host error as
absent. The parameter stays `unknown`, which it honestly is, and the `SAFETY` cast is gone.

`useNewWorkspaceRuntimeContext` read settings through `settingsRead`, whose reader preserves
main's `boxed!.settings` throw, so a `null` or absent result threw a TypeError out of the effect —
losing the trusted-hooks publish and the available-provider computation that follow it, not just
the settings. It now uses `optionalSettingsRead`, the operation that already reads a null or
absent result as absent settings, so the reply degrades exactly the way a reply with no `settings`
member does. Reply-side only: same method, same params, same barrier, no wire change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens the two bug fixes move

Baseline bumped to 3f71999237. Two goldens move an observation; the other 151 move only
`baseline` and `recorderSha256`, which `pilot-scenarios.json` is still digested into.

Observation moves, one claim each:

- `matrix-hostedreview.create-intent-git.commit-1`, partition `inner-false-object-error`:
  `settlements.run.value.error` and `state.outcome.error` go from `{"message":"inner refused"}` to
  `"Commit failed"`. A non-string in-band `git.commit` error is a malformed reply and now reads as
  the screen's copy, converging with `result-absent`, `result-null` and `outer-refused-no-message`,
  which already reported the fallback. The other ten partitions at this site are unchanged.
- `matrix-settings.workspace-context-settings.get-1`, partitions `result-null` and `result-absent`:
  the `unhandled-rejection` TypeError effect (`reading 'settings'`) is gone and `state.providers`
  goes from `[]` to `["github"]`. The effect no longer aborts the rest of the hook, so the
  provider computation runs; `state.settings` stays null because nothing was published, which is
  how a reply with no `settings` member already degraded. The other nine partitions are unchanged.

Header-only moves:

- 9 goldens of the `settings.workspace-context` family rename `namedDeltas` from
  `new-workspace-runtime-context-null-settings-typeerror` — the name now lies, the TypeError is
  fixed — to `new-workspace-runtime-context-null-settings-degrades-to-absent`.
- All 153 move `baseline` and `recorderSha256`. The digest covers `pilot-scenarios.json`, so the
  baseline bump and the rename re-digest every file.

No sender recording moved: both fixes are reply-side, and no golden's `sender` or `payloads` field
differs. The README paragraph that claimed the settings TypeError was preserved is updated, and
now records that the `ui.get` leg of the same hook still is.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): degrade a null ui.get result the way the settings leg now does

One host answers both legs of useNewWorkspaceRuntimeContext, so fixing only
settings.get left the likelier failure in place: a null or absent ui.get result
still threw `reading 'ui'` out of the effect, skipping the provider commit.

Review follow-ups on the same files: reply() returns the literal uncast and the
stub client is FakeSession, dropping two assertions and their SAFETY disables;
the degradation cases now assert absolute state instead of comparing mounts.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens the ui.get leg fix moves

Observational move, 1 golden:

- matrix-settings.workspace-context-ui.get-1: the `result-absent` and
  `result-null` partitions drop their `reading 'ui'` unhandled-rejection effect
  and their state commits `providers: ["github"]` instead of `[]`, because the
  effect no longer throws before the provider commit.

Header-only moves, 153 goldens: `baseline` to the fix commit and `recorderSha256`,
which covers `pilot-scenarios.json` and so re-digests on the delta rename.

The delta is renamed `new-workspace-runtime-context-null-settings-degrades-to-absent`
-> `new-workspace-runtime-context-null-results-degrade-to-absent` (9 goldens): it
now covers both reads, not just settings. README updated to match.

No sender recording moved: resolving the value pool across all 153 goldens shows
`sender` and `payloads` byte-identical everywhere.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): name the ui.get result shape so the changed cast carries a rationale

The inline union wrapped over four lines and tripped the changed-code casting gate
as a new assertion; a named alias keeps the cast on one line under a SAFETY note.
No behaviour change.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): repin the golden baseline to the cast-rationale commit

Header-only: `baseline` on all 153 goldens. The re-record is inert — no golden
moves observationally and no field other than `baseline` changes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin the ui.get trust blank, and correct two stale acceptance comments

The goldens cannot catch a regression to `if (uiResult?.result)`: the scenario's
success reply is `{"ui":{}}`, so every partition of
matrix-settings.workspace-context-ui.get-1 records the same `trust:{}` state. The
new case answers once with real trust and again with a null result on a fresh
client, which is the only shape where skipping the blank is observable —
trustedOrcaHooks gates the setup-hook approval prompt in
use-new-workspace-create-submit.ts, so a stale value would skip it.

settingsRead's comment still claimed workspace context, which this branch moved to
optionalSettingsRead; both comments now name their real callers.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): repin the golden baseline to the trust-blank commit

The record fence rejected the previous pin ("Product sources or lockfile differ
from the pinned main baseline"), so the branch was no longer re-recordable.

Header-only: `baseline` and `recorderSha256` on all 153 goldens — the digest
covers pilot-scenarios.json, whose only edit is that baseline. The re-record is
inert: 0 goldens move observationally and no other field changes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): name the right operation per refuse-after-data probe

Three of the five probes read through optionalSettingsRead, not settingsRead:
repo metadata and resume metadata already did, and workspace context does as of
this branch. The sentence now splits them and states why the split does not move
what the probes record.

Markdown is excluded from recorderSha256, so no re-record.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin the recorder's unhandled-rejection capture

This branch removed the last two goldens that recorded an unhandled-rejection
effect, so nothing exercised unhandled-recording.ts any more: gutting the emit to
`void captureError(error)` leaves all 153 goldens comparing clean. The unit test
drives a detached rejection through the window and asserts both the effect and
the listener restore. README says so where it describes the capture.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-digest the goldens for the new recorder test

Header-only: `recorderSha256` on all 153 goldens, which covers every non-markdown
file under rpc-recording/ and so moves for the added test file. The re-record is
inert: 0 goldens move observationally and no other field changes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin each RPC golden to its own scenario input, not the whole manifest (#20562)

* refactor(mobile): pin each golden to its own scenario input, not the whole manifest

`recorderSha256` covered the recorder directory plus `pilot-scenarios.json`, so every golden's
header was a function of every other family's scenarios. Adding a family for one domain re-digested
all 153 goldens and put a conflict on that line in every domain branch in flight, which serialized
the step-4 fan-out.

Split the two things it conflated. `recorderSha256` now covers the recorder directory only, with
unchanged semantics: a recorder edit still forces a full, deliberate re-record. A new
`scenarioSha256` pins the scenario input that golden was recorded from — every scenario
`runRecording` consumed for it, in order — canonicalised through `captureValue` so an
explicit-undefined param stays distinct from an absent one. `goldenRecording` takes that list
instead of just its first member.

The variants are hashed rather than the base they expand from because they are what was recorded: a
matrix site, its replayed normal result and its partition replies are all visible in them without
the derivation having to be restated. `derived-goldens.ts` is that derivation, extracted from
`family-recordings.test.ts` so the digest and the recording agree by construction — a property test
that restated how a matrix or schedule expands could agree with itself and with nothing else. It
reproduces exactly the 153 golden ids on disk, and the census the suite already ran (every family
matrixed, no stale normal-result inventory entry) now reads off its output.

`golden-header-digest.test.ts` pins the four properties:

- a new family in the manifest moves zero existing goldens' headers, and derives two of its own
- editing one field of `b1` moves exactly `b1` and its family's four matrix goldens — not the two
  other `legacy-inventory` scenarios, and not the goldens that expand from `inventory-lifecycle`
- editing a recorder file still moves every golden's `recorderSha256`, and no `scenarioSha256`
- `recorderSha256` is unchanged by the manifest's contents, and no longer reads the file at all

`GOLDEN_FORMAT_VERSION` goes to 4: a version-3 header has no `scenarioSha256`, and `compareGolden`
walks the expected header's keys, so a reader that accepted one would compare that golden's own
scenarios as though they were unpinned.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the 153 RPC goldens for the split digest

Recorder edit, so every golden needs rewriting. Recorded from the pinned baseline
`16d1ab81d3` with this branch's recorder overlaid, per the README's procedure: main has
moved past the baseline, so recording in place would have failed the product-source fence.

Three header fields moved and nothing else did:

- `recorderSha256` 6a12160a87… -> 2fda557f58…, one value across all 153 files
- `scenarioSha256` added, 153 distinct values
- `goldenFormatVersion` 3 -> 4

No observation, checkpoint, value-pool entry, `baseline`, `lockfileSha256` or `platform` changed:

    git diff -U0 -- mobile/rpc-foundation | grep -E '^[+-]' | grep -vE '^(\+\+\+|---)' \
      | grep -vcE 'recorderSha256|scenarioSha256|goldenFormatVersion'
    0

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): certify the pilot goldens from the derivation that digests them

`pilot-recordings.test.ts` restated `[scenario]` instead of consuming `pilotGoldens`, so the claim
that a golden's `scenarioSha256` is a function of the same derivation that records the file held
only for the 75 family goldens: dropping a scenario from `pilotGoldens` left the whole suite green
and put that golden outside the header oracle. The pilot suite now iterates `pilotGoldens`, and a
census fails if the derivation and the goldens directory disagree in either direction — which also
closes the pre-existing orphan-golden gap.

Also from review: pin the cross-sibling replay that hashing the generated variants buys (a matrix
golden's `normal` partition replays a sibling's recorded reply, so editing that sibling must move
it); state the real reason for the format bump, which is the diagnosis a version check gives rather
than a rejection the byte compare already made; drop the fourth property test, which re-proved what
tests 1 and 2 and `recording-runner`'s digest test already fail on; and drop a guard in
`scenarioSha256` that its only caller reaches after an identical one.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the 153 RPC goldens for the review edits

Recorder files changed, so `recorderSha256` moved. Recorded from the pinned baseline with this
branch's recorder laid over it, per the README's migration-branch procedure. That one header field
is the only line that moved in all 153 files: `scenarioSha256` and `goldenFormatVersion` are
unchanged, and no observation moved.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): correct the recording suite's test count

Round-2 review: the README said 200 tests; the suite is 209 after the five
added here. Markdown is outside recorderSha256, so no golden moves.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the 153 goldens on the merged baseline

Four header fields moved and nothing else. Proven against origin/main: every
changed line in all 153 files is one of these, and the file set is unchanged.

- `recorderSha256` 70aa6f59e0 -> 58a461dbc9: this branch's recorder, and it now
  digests only the recorder directory, not the scenario manifest.
- `scenarioSha256` added, 153 distinct values over 153 goldens.
- `goldenFormatVersion` 3 -> 4 for that added field.
- `baseline` 5ec0b2698f -> e53f1557e1, the merge's repoint onto the real main
  commit. #20563's value was a branch commit the squash left unreachable, so the
  record fence's `git diff <baseline>` could not resolve it.

No checkpoint, value pool, effect or settlement byte moved, so main's recorded
behaviour is carried over intact.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile): account for main's added recorder test in the suite count

The merge brought in `unhandled-recording.test.ts`, one test, so the recording
suite is 210 rather than the 209 this branch documented. Markdown is excluded
from `recorderSha256`, so no golden moves.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(native-chat): stop a bounded tail read from moving the chat cursor past unapplied rows (#20581)

* fix(native-chat): stop a bounded tail read from moving the chat cursor past unapplied rows

A structured chat pane could latch "Working for N" forever after the agent had
finished, showing the send arrow rather than Stop, while the sidebar and
`worktree ps` correctly read idle.

The client replica has one position (`state.cursor`) and one body. Two
operations keep those consistent: replace (both from one host snapshot) and
append (rows contiguous with the cursor). The `tail-page` branch was a third
thing: it took the cursor from the journal head, the items from a bounded page
(200 items, byte-capped), then merged retained client submissions over the
page's. Under continuous journal writes the client is always slightly behind,
so the branch ran on every window focus and on every pane re-activation. When
more than a page of rows had landed since a send, that send's user item fell
off the page, its submission was not carried, the retained `pending` survived,
and the cursor jumped past the dispatch-acceptance row. Nothing re-sends it: a
batch carries only touched items and that submission is never touched again.

Delete the third operation rather than guard it. A live subscription is now the
only thing that moves the cursor, and `subscribe({ cursor })` already replays
exactly the missed rows.

- remove the window `focus` listener and the owner/transport `refresh` contract
- skip warm hydration: a retained owner subscribes at its applied cursor
- cold hydration keeps its history read, applied as the existing `snapshot`
  (replace) event rather than `tail-page`
- delete the `tail-page` action and its reducer branch
- delete `resumeCursor` and `shouldAdvanceStructuredResumeCursor`; two cursors
  with two advancement rules were how position and body drifted apart

`older-page`/`loadOlder`, the unattached-refusal grace, generation guards and
the coalescer are unchanged. No host, wire or schema change.

Also fixes a second cost of the same branch: focus during a busy turn discarded
paged-in older items, shrinking the transcript to one bounded page mid-turn.

* fix(native-chat): preserve unavailable mixed-version session fences

* refactor(mobile): send the task workspace-creation domain through typed RpcOperations (#20568)

* test(mobile): record main's task workspace-creation RPC behaviour before migrating it

28 scenarios over nine task senders, recorded from main so the step-4 migration of
the workspace-creation half of src/tasks/ has a frozen answer to compare against.
Four senders mount as plain exported functions; three are model-chained hooks
mounted the way the settings adapters mount theirs.

The 153 existing goldens change header-only (`baseline`, `recorderSha256`): any new
scenario re-digests the recorder, and the pinned baseline had drifted from main
because the source-control migration landed. Content is byte-identical on all 153 —
verified field-by-field against HEAD.

`operation-module-loader.ts` now shares src/transport/rpc-delivery-ambiguity.ts with
mounted modules instead of evaluating a second copy. The mark is a WeakSet keyed on
the rejection object, so the copy the loader built had an empty registry and every
delivery-unknown rejection read as a definite failure inside the operation under
test — worktree.create's whole replay path was unreachable. With one registry,
`tw-create-retry-ambiguous-after-drop` records the create still pending at the
reconnect wait and abandoning at exactly 20000 ms, while the unstamped-create
scenario records the same rejection surfacing at 0 ms. No existing golden moves:
no other mounted module consumes the mark.

`task-preferences-optimistic` is re-anchored above the send rather than across it,
so migrating this file does not have to move the anchor. It still kills, and for
the same reason: the preset the screen shows no longer follows the tap.

Scenarios deliberately pin the empty-message refusals (`*-refused-empty-message`,
`*-empty-message`), because a refusal with no message falls back to the screen's
copy while a transport error with no message does not, and the two paths are easy
to collapse when a call site moves behind an acceptance policy.

Goldens: 153 -> 201, 2.9M -> 3.7M.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): format the recording manifest and re-digest the goldens

`oxfmt --check` from mobile/ collapses a one-element `sites` array in each new
scenario. The JSON value is unchanged — verified by comparing both files parsed
and key-sorted — but the manifest is inside `recorderSha256`, so all 201 goldens
carry a new digest. Every other field, header and observation alike, is
byte-identical.

Re-recorded in a separate worktree at the previous commit so the goldens stay
attributable to main's product source rather than to the migration that follows.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): separate the goldens from the migration, and re-digest

The previous commit accidentally carried the product migration alongside the
manifest format, which both broke the commit that is supposed to prove parity and
left the suite red: the digest was recorded without a comment move that a lint fix
had made inside the adapter, so all 201 goldens failed their `recorderSha256`
header.

This backs the product half straight out again — the next commit re-applies it
byte-for-byte — and re-records from the pinned baseline in a separate worktree
carrying this branch's recorder, per the procedure in the recording README. Every
field except `recorderSha256` is byte-identical to the previous commit's goldens on
all 201 files, so no observation moved in either direction. The suite is green here
with main's product source, which is what makes the next commit's "no golden
changed" claim mean something.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): send the task workspace-creation domain through typed RpcOperations

12 of src/tasks/'s 37 raw-port files now send through a declared operation instead of
the raw request port: 36 references to 0, leaving 25 files and 73 references for the
provider item/detail/mutation half. No golden moved — `git show --stat` on this commit
touches nothing under mobile/rpc-foundation/, which is the parity claim.

Twenty-two operations over twenty methods, in four modules named for what they send:
workspace create (create, PR/MR base resolution, create-time capabilities), workspace
source (SSH connect/state, agent detection, repo hooks, sparse presets, ref search),
task runtime (status, ui.get/ui.set, preflight, Linear status, settings.update) and the
Smart picker's provider reads.

Two methods carry two policies each, and both pairs are named. `status.get`: the Tasks
screen cannot hydrate without it and surfaces the host's message, while create-time
capability probing degrades to "no capabilities" and creates anyway — so one throws on
refusal and one skips. `ui.set`: two sites await it, one is fire-and-forget and never
interprets the reply at all. Both pairs share one reader, so no method has two readers.
No new acceptance policy.

worktree.create keeps its delivery-unknown contract. `request` returns the transport
promise itself, so the retry loop catches the object the transport marked; two new tests
assert `toBe(marked)` in one direction and that an unmarked rejection stays unmarked in
the other, because a mark added on the way out would replay a create the host never
received. `tw-create-retry-ambiguous-after-drop` records the create still pending at the
reconnect wait and abandoning at exactly 20000 ms.

Three sites still read the raw refusal envelope before interpreting, because the code or
the message decides the route and no acceptance policy carries either through: the create
retry needs the message for `isRetryableWorktreeCreateConflict`, and the paste lookup
needs `method_not_found` to retire the slug probe host-wide. Both are documented at the
site.

The hydration barrier keeps raw requests inside its `Promise.all`. main's group rejects as
soon as one leg rejects; `startRpcOperation` + `interpretAtRpcBarrier` would wait for the
slowest peer and let a later policy surface a different error. Interpretation stays after
the `stale` guard, where it was.

`WorkspaceCreateParams` is now `RpcSendParams<'worktree.create'>` rather than
`Record<string, unknown>`, which types the builder and the operation together; every field
the three builders already sent typechecks against the host schema unchanged.
`RpcSendArguments` now also makes params optional for a method whose params type has no
required field, because `preflight.check` is such a method and main sent it none —
requiring `{}` would have put a new object on the wire.

The Mobile Tasks source-parity hashes move for the same reason bound settings requests
moved them: the method string and the envelope read leave the screen. The signature diff
is evidence rather than a re-pin — `semantics` is a pure deletion of 22 `rpc:` call
signatures and 22 method literals with nothing added, statement/declaration/render/style
counts are unchanged, and render tokens, styles and declarations are byte-identical.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): split the task workspace adapters at the sender/hook seam

The single adapter file reached 344 lines against mobile's 300-line limit. CI lints
every file, so this is red there even though the changed-code gate does not report it.
Split along the seam the recording README already draws: exported async senders that
take a client and need no React host, and the drawer's three model-chained hooks.
No adapter body changed.

Both files are inside `recorderSha256`, so all 201 goldens carry a new digest. Every
other field is byte-identical, verified file by file. Re-recorded from the pinned
baseline in a separate worktree carrying this branch's recorder, so the goldens stay
attributable to main's product source.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile): give the one-key unchecked reader a name

Four readers were the same three lines: read one property off the reply, wrap
it unchecked. `rpcUncheckedMemberReader` is the one-key sibling of the existing
`rpcUncheckedPayloadReader`, so the annotation and the closure go away at each
site. The pilot's `commitCompareEntriesReader` is converted too, so the helper
has no longhand twin left to copy from.

No behaviour change: the helper composes the same `rpcReadUnchecked` over
`rpcPayloadMember`, including the property-read exception on a null result.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): record the local arm of workspace agent detection

`preflight.detectAgents` was the one migrated operation with no recorded
coverage: the ssh adapter hardcoded `connectionId: 'ssh-1'`, so the detection
effect's ternary only ever took the remote arm and the local call site could be
repointed at another method without a golden noticing.

The adapter now takes the connectionId as a parameter and registers twice;
`tasks.workspace-ssh-local` mounts the same hook with no connection, which is
the only difference the effect branches on. Recorded at the pinned baseline
with this branch's recorder laid over it, so the new golden is main's
behaviour and the migrated code has to reproduce it — it does.

Goldens: two added (`tw-workspace-ssh-local-agents` and its reply matrix). The
other 201 changed on `recorderSha256` only, because the adapter edit moves the
recorder digest every golden pins.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): drive workspace create and the Linear list to a recorded wire

Two operations passed a policy swap unnoticed, both because no golden reached
their acceptance branch.

`worktree.create`: the create hook's fixture resolved setup to a prompt, so all
three settings.task-workspace scenarios stopped before the request and the only
consumer that hands a refusal to interpret was never recorded. The adapter now
takes the setup resolution as a parameter and registers a second family that
resolves it, so createWorkspace runs to the wire. Two scenarios: a Linear item
that creates directly, and a GitHub pull request that resolves its base first,
which also puts this hook's built params — start point, generated display name,
agent launch fields — in a golden for the first time. The existing prompt
family is untouched, so its recordings still pin that branch.

`linear.listIssues`: it appeared only in a non-base scenario, and the matrix
reads the family base, so the family had no partition for it. The base now
lists assigned issues after searching.

Goldens: five added. Five moved beyond the digest, all derived from the
smart-search base that gained the list leg. The other 198 changed on
`recorderSha256` only. Recorded at the pinned baseline with this branch's
recorder laid over it, so every new golden is main's behaviour.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): drop the unreachable unmount branches from the task adapters

Nothing dispatches `unmount` to these three adapters: the only producer is
`lifecycleSchedules`, driven from a hardcoded five-id list that names no
task-workspace family, and it pushes a `remount` right after, which these
adapters would throw on. The branch read as lifecycle coverage that was never
wired up. `dispose: hook.unmount` already tears the mount down.

Goldens re-recorded at the pinned baseline because the recorder digest moved;
`recorderSha256` is the only line that changed in all 208.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens at main's post-squash baseline

Recorded from a detached checkout of e53f1557e1 (main's unmigrated
product code) with this branch's recorder laid over it, so the parity
claim stays non-circular.

- `baseline` repinned to e53f1557e1 on all 208 goldens; main pinned
  5ec0b2698f, a pre-squash branch commit not reachable from main.
- `recorderSha256` moved on all 208 because this branch's adapters are
  in the whole-manifest digest.
- 55 task-workspace goldens re-recorded at the new baseline.
- No other line in any of main's 153 goldens changed.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): re-record the goldens under #20562's per-scenario digest

Baseline repinned to 50e752fc66 and all 208 goldens recorded from that
commit's unmigrated product tree with this branch's recorder laid over it.
recorderSha256 moves on every golden because the task-workspace adapters
live in the recorder directory. scenarioSha256 does not move on any of
main's 153: the manifest only adds 31 scenarios and edits none, which is
the property #20562 was built to give.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(ai-vault-search): construct the session search indexer in the scanner service behind a setting (#20516)

* feat(ai-vault-search): persist agent-session search consent and retention

Two booleans and nothing else: `enabled` and `historyDays`, off by default
because building the index reads every transcript on the machine. No `paused` --
the PR 3 indexer is immutable, so every change is close-and-construct.

The settings IPC normalizes a write like every other field and hands the change
to the index; there is no UI for it until PR 8.

* feat(ai-vault-search): hold one indexer and engine pair per host

The object that owns a host's live index and the three recipes that change it.
The indexer is immutable, so a settings change is close-and-construct, disabling
is close with no replacement, and clearing is close, remove the database,
construct. The new instance's first sweep purges a narrowed window and admits a
widened one, so neither needs a code path.

The database sits beside the scanner's parse cache, one file per host. A runtime
with no node:sqlite can hold no index at all, which the Node 18 floor on orcad
and the relay makes a real case rather than a hypothetical one.

* feat(ai-vault): let the scanner child own the session search index

The transcript reader runs in that child, so the index consumer has to as well:
one read serves both the session list and the index. Three request operations
(search, status, reconcile) and one fire-and-forget settings message carry
everything a parent needs; main never opens the database file.

The init frame becomes a factory because it is read at every spawn, so a
respawned child sees current consent rather than the first frame's. A child
holding a running index is never idle from the parent's side, so idle retirement
is suppressed while the index is on -- retiring it would stop the reconcile loop
until some later scan happened to respawn one.

Both files this lands in were already at the max-lines ceiling, so three
collaborators move to where they belong rather than being disabled around: the
invalidation deadline into the class that owns invalidations, call cancellation
and the start requeue into the call-state module, and orcad's flag parsing into
its own file.

* feat(ai-vault-search): register a search service on every host that answers

Without a registered service a host answers no-service, which means "this host
does not have the feature" rather than "the index is off". All three hosts now
answer the second thing.

The desktop forwards to the scanner child. orcad and the SSH relay daemon have
no such child -- orcad ships only the watcher and daemon entries, and the relay's
AI Vault sidecar runs the remote scanner, which publishes nothing to the
transcript channel -- so on those two the index lives in the process that would
drive its reads, gated on a runtime that has node:sqlite at all.

The relay registers with consent off and no way to turn it on: nothing carries a
setting to a remote host yet. That is the honest state, and it is still worth
registering, because it is what tells a client the difference between off and
too old.

* test(ai-vault-search): price a warm pass over five thousand transcripts

The number the reconcile interval will be revisited against, measured rather
than argued: a warm sweep stats every file under every root, a warm cycle stats
the newest N per agent, and neither reads what the index already holds. It does
not tune the interval.

* fix(ai-vault-search): answer the casting gate without assertions

main's new type-assertion rule reaches every file this branch touches. All nine
sites drop the cast rather than carry a SAFETY: rationale: the operation guard
narrows with `in`, the sqlite probe narrows the builtin it loads, the child test
keeps the discriminated reply instead of widening it, and the settings resolver
takes `unknown` -- which is what it really reads, since a persisted profile can
hold a value no version of this code wrote.

* fix(ai-vault-search): let a refreshed scan root reach the live index

The parent re-resolves scan roots before every policy push, precisely so a
WSL distro or extra Codex home that appeared since the child spawned enters
the window. The child forwarded only the settings to a live instance and used
the roots solely in its `??=` initializer, so those roots were dropped for the
child's lifetime.

The indexer stays immutable: a structurally different root set closes the pair
and constructs a new one, the same way a changed databasePath already does.
Compare via `sameSessionSearchRoots` rather than a plain JSON compare, because
nothing fixes the key order two producers write; lists are sorted too, since
the indexer walks every root and a re-enumeration that reorders is not a
change. An unchanged set still never restarts a running index.

The orcad and relay in-process hosts resolve roots once at install and never
re-apply, so they have no such seam.

* fix(ai-vault): restart the scanner child the index is holding

Three review items.

The hold keeps a child alive for the index, but only a queued call ever
started one: `pump()` skipped a hold with an empty queue, so an idle indexing
child that crashed, or an `ensureChild()` that failed at start, left indexing
stopped until an unrelated request happened to arrive. `pump()` now starts the
child the hold requires, which is also the restart callback the fault policy
already schedules, so the existing delay and circuit bound the retry exactly as
they bound a queued call's start. `updateSessionSearch` goes through the same
seam instead of its own `ensureChild` call.

A search registers no AbortController, so a cancel sent for a search id was
added to the `cancelled` set and never consumed. Nothing can reach that today
-- no caller passes a signal and the child answers in milliseconds -- so this
is only a leak of ids: consume it when the search settles.

The orcad argument doc claimed a `--`-prefixed value stays a flag. The parser
takes the next token regardless, and orcad-launch-contract.test.ts pins that,
so the doc is what was wrong. Behaviour is unchanged.

* fix(ai-vault): recover search indexing and refresh scan roots

* fix(ai-vault): defer search refresh policy reads

* fix(session-search): stabilize paging and host enablement

* fix(session-search): refresh host roots within full sweeps

* docs(session-search): clarify initial root fallback

* fix(native-chat): hide activity while awaiting input (#20496)

* fix(native-chat): hide activity while awaiting input

* fix(native-chat): keep approval turns cancellable

* test(native-chat): satisfy split PR quality gate

* fix(native-chat): catalog approval cancellation label

* fix(native-chat): include approval cancellation runtime label

* fix(codex): settle prompts when cancelled turns complete

* fix(codex): settle prompt registry fallbacks

* test(native-chat): cover pending interaction fallbacks

* test(native-chat): split prompt state coverage

* test(native-chat): keep prompt state isolated

* fix(native-chat): bound prompt turn backfill

* refactor(codex): centralize prompt registry bounds

---------

Co-authored-by: Merge Sim <sim@local>

* Update README downloads badge

* Bump mobile app.json to 0.0.50 (#20661)

* fix(native-chat): bound a dispatch reason before it reaches the journal row (#20654)

`AgentJournalSubmission.reason` was the only unbounded field written by
Orca's own code. `dispatchSafely` sets it from the adapter's raw
`error.message` and `journalDispatchRowBuilder` stored it verbatim, so a
provider error carrying a multi-megabyte body -- a stringified HTTP error
payload, say -- reached the row at whatever length the provider sent, and
stayed on disk at that size for the life of the journal.

It now goes through `boundInlineText` with the journal's existing inline
limit, the same idiom already applied to arbitrary text on the Claude and
Codex translation paths.

The bound must stay head-preserving. `dispatchRejectionWasTransportWriteFailure`
prefix-matches the value, and `dispatchRejectionReasonIsInternal` builds on
it, so a bound that kept the tail instead would stop classifying a clipped
transport failure and render raw provider text to the user as an ordinary
rejection notice. A test pins that, and clipping stays marked rather than
silent so a truncated reason is never presented as the provider's complete
explanation.

Rows written before this keep their full text, so readers can still meet an
unbounded reason.

* fix(native-chat): keep a resumed transcript pinned to its end (#20651)

* fix(native-chat): keep a resumed transcript pinned to its end

Follow state was recomputed from distance on every scroll event, and a pin writes scrollTop itself, so the browser reports that write back as a scroll event a frame later. Once a resumed session's later history pages and settling row heights had moved the end away from it, that echoed event read as the reader leaving and the pin was dropped for good, stranding them mid-transcript. Measured in Chromium: a pin followed by same-task growth delivers a scroll event reading 2000px from the bottom, indistinguishable from a reader scrolling up.

Pins now go through the virtualizer instead of writing scrollTop directly, so both parties resolve the end through the same maximum rather than holding rival definitions of it. Whether the reader left is now a question of provenance rather than distance: an offset this transcript wrote is never a departure. The end test reads live geometry, because the virtualizer's own isAtEnd subtracts a cached offset from a live maximum and this handler runs before that cache is refreshed. overflow-anchor:none stops the engine moving scrollTop under a settling row, which would otherwise look like the reader.

This does not make ownership singular. The virtualizer still writes autonomously from several paths and those writes stay unattributed; what this removes is the rival definition of the end, not the second writer.

* fix(native-chat): cancel stale end reconciliation

* fix(native-chat): attribute scroll ownership centrally

* Surface stage, unstage and discard failures with retry capability (#20423)

* fix(source-control): surface stage, unstage and discard failures

* fix(source-control): use single slot for entry failure toasts

- Consolidate entry failures to one stable slot instead of per-worktree
- Handle stale retries inline at click time rather than via a cleanup hook
- Remove retry button from discard failures to prevent destructive accidents

* test: improve type safety and mock patterns in source-control tests

- Add proper type definitions for toast options and test data instead of using `as never`
- Replace `mock.calls.at(-1)` with safer `mock.lastCall` pattern
- Create `entry()` helper to construct typed test entries
- Add explicit type annotations to mocked functions for better IDE support

* test: extract shared toast options type for source control tests

Consolidate duplicate `ToastOptions` type definitions across three test files into a single `SourceControlToastTestOptions` type, reducing duplication and improving consistency.

* fix(source-control): separate refresh failures from mutation failures

Post-mutation refresh failures are logged separately, not surfaced as toasts
(mutation already succeeded). Use preventDefault() on retry to prevent sonner's
auto-dismiss from swallowing re-raised failures. Consolidate stage/unstage into
a shared handler to reduce duplication.

* fix(source-control): only dismiss entry failures from the owning worktre

Track which worktree owns the shared entry-failure toast slot. When a mutation
completes, only dismiss the slot if the completing worktree is the one that
raised the failure — a slow retry in one worktree should not erase a failure
another worktree has since raised into the slot.

* Remove entry mutation status refresh helper

Inlined into the caller during consolidation of failure handling and
tracking in the source-control entry mutations flow.

* Simplify entry mutation refresh without wrapper

Call refreshActiveGitStatusAfterMutation directly instead of through the
refreshEntryMutationStatus helper. This ensures refresh failures propagate
directly from the callback without being caught as mutation failures.
Remove tests that validated the wrapper's error handling.

* Add copy button to code blocks (#20357)

* feat(native-chat): add copy button to code blocks

Enable users to copy code snippets directly from chat messages via a dedicated copy button on fenced code blocks. Supports language detection and integrates with markdown rendering via a `renderCodeBlock` prop.

* i18n: add English copy code button label

* refactor: use React.isValidElement type parameters for type narrowing

- Specify props types as type parameters to React.isValidElement instead
  of casting after the fact
- Allows TypeScript to narrow element.props type automatically
- Eliminates manual type assertions in extractCodeText and extractCodeFenceLanguage

* fix(source-control): prevent text wrapping in section headers and action buttons (#20046)

* fix(source-control): prevent text wrapping in section headers and action

Use flex layout constraints (flex-1, shrink-0) and text truncation instead of
wrapping to keep section labels and action buttons on a single line in the
right sidebar.

* test(source-control): add section action button alignment tests

Ensure View all button stays on single line with icon actions in
crowded section headers. Pin layout constraints (shrink-0, flex-wrap,
whitespace-nowrap) to prevent regression.

* Rely on Button base styles for action label wrapping

Remove redundant shrink-0 and whitespace-nowrap utilities from
section action buttons. These should be supplied by the Button
component's base variant, not duplicated at each usage site.

* fix(store): stop two no-op writes from re-running every selector in the app (#20641)

* fix(store): stop two no-op writes from re-running every selector in the app

zustand bails out of a `set` only when `Object.is(next, state)`. Two updaters that
mean "nothing changed" hand it a fresh reference instead:

- `setWorkspacePortScanRefreshing` wrote unconditionally — the one action in its
  file that did; its four siblings all early-return `state`.
- `applyGitHubPRRefreshEvent` ended its no-op branch with `: {}`, and
  `Object.assign({}, state, {})` reproduces every field unchanged while still
  notifying. ~20 sibling sites in the same store already use `return state`.

Both rebuild the root and wake every subscribed selector (~2.2k per the listener
census). Renders are unaffected — the selection is unchanged — so the cost is
wasted selector evaluation, not commit pressure. The resulting state looks
identical either way, which is why it goes unnoticed; both tests therefore count
subscriber notifications rather than asserting state.

* test(store): use checked initial state in notification regression

---------

Co-authored-by: m4air <[email protected]>
Co-authored-by: Neil <[email protected]>

* fix(ai-vault): bound streamed remote JSONL records (#20700)

* fix(ci): stop hourly versions dropping below a tagged or already-shipped build (#20699)

* fix(ci): stop hourly versions dropping below a tagged or already-shipped build

Hourly/daily/adhoc based their X.Y.Z on GitHub releases, not git tags. When
v1.4.202 was tagged and then its GitHub release vanished, the next hourlies
shipped as 1.4.202-hourly — below both stable 1.4.202 and the 1.4.203-hourly
builds already installed, so electron-updater stopped offering updates.

Read main's v* tags and already-published channel tags instead.

* docs(ci): record that 1.4.202's release was unpublished for a bug

The leftover tag is what hourly must still honor; this was not a failed cut.

* fix(store): preserve state identity for no-op updater branches (#20703)

* fix(codex): settle a structured send on admission, and stop minting a colliding identity (#20138)

* fix(codex): settle a structured send on admission, and stop minting a colliding identity

Two sends could be written into the journal under one durable identity.

Codex coalesces a mid-turn `turn/start` into the running turn rather than
refusing it -- measured against real `codex app-server` builds 0.147.0,
0.150.1 and 0.153.4, none of which refuse and none of which fire a second
`turn/started`. The dispatch path read the turn id from the turn/start
response and stamped every accepted send `ordinal: 0`. Since a coalesced
send gets the running turn's id back, two submissions persisted the same
`providerItemId`. That string is durable, and it is the key a restore uses
to match a submission against provider history, so the second message's real
history row matched nothing and rendered as an extra bubble on replay.

On 0.147.0 it is worse than a collision: the coalesced response returns a
turn id that never starts and never completes, so the persisted key named a
turn absent from history and NEITHER message could match.

Identity is now minted from the echoed user message at `identityFor` -- the
single point that mints the journal row's own identity -- so the settled key
is by construction the one replay computes, rather than a parallel
calculation that can drift.

Dispatch returns `admitted` when the transport write completes; identity
settles on the echo through a channel that did not previously exist for
Codex. Waiters are keyed by client message id instead of being shifted off
the front of an array by arrival order, and they are cleared on session
close and child exit -- previously a timeout was the only thing that ever
ended one.

`TURN_ID_WAIT_MS` is deleted. It was never reachable on any build measured:
`readCodexTurnId` returns non-null on all three, so the 10s wait never
fired. The comment justifying it claimed older builds acknowledge before the
id exists, which no tested build does.

Three comments asserting Codex answers a mid-turn send with `turn already
running` are corrected. Their only backing was a test fixture inventing that
error string. The correction is factual only -- every changed line in
`src/main/runtime/orchestration/` is a comment, and mid-turn delivery is
still refused for both providers. Whether that policy is right is a separate
question; it was resting on a false premise.

Known gap, stated rather than implied: this prevents new collisions and does
not repair journals already written with a colliding or phantom key. Those
conversations keep duplicating on restore. Repairing them means re-matching
persisted submissions against provider history and rewriting
`providerItemId` -- which is what `journal-submission-reconciler.ts` is
written for, and it still has no production caller.

* test(codex): drop the synchronous-accept contract and the colliding `:0` from the integration fakes

Three tests in the structured-session integration suites encoded the dispatch
contract this branch replaces, and two of them pinned the defect it fixes.

They asserted `agentSession.send` answers `dispatchState: 'accepted'` carrying
`providerItemId: codex:<thread>:<turn>:0` at send time. That ordinal was never
observed; it was stamped on every accepted send, which is exactly the collision
this branch removes -- a send coalesced into a running turn is answered with the
running turn's id, so two submissions persisted one durable key.

The visible failure was a 30s timeout rather than a failed assertion. The fake
client advertised no `agent-session.pending-send-result.v1`, and without it the
host holds the reply until the send settles: a shim for clients too old to
render a pending bubble. The fake provider then echoed the user message with no
`clientId`, so nothing could correlate that echo back to the submission, and the
wait ran to its own 30s ceiling. Real Codex sends `clientId` on that echo, and
the fake now does too, which is what makes it a model of the provider rather
than a sketch of one.

The identity assertion is kept rather than dropped. Each send now asserts
`pending` with no identity at admission, then asserts the submission settles
`accepted` at `codex:<thread>:<turn>:0` once the echo lands. Same ordinal, but
earned from `identityFor` on the echo -- the key a replay recomputes -- instead
of guessed from the turn/start response. Ablated: removing `clientId` from the
two echoes leaves both submissions `pending` and fails both assertions, so the
assertion is load-bearing and not satisfied by something incidental.

Both suites' client fixtures now advertise the capability set the desktop
renderer sends in `src/main/ipc/runtime.ts`, which is what these suites mean by
a client. The older-client settlement wait keeps its own coverage in
`src/main/runtime/rpc/methods/structured-agent-session.test.ts`.

`structured-agent-session-runtime-exit.test.ts` asserts `pending` for the same
reason; it drives the host directly, so it never took the compatibility path,
and what proves delivery there is still the turn the reacquired provider starts.

The replay suite's "without dispatching it twice" property is untouched: one
`turn/start` call, one replayed ledger row.

* fix(codex): preserve unsettled dispatch correlations

* test(codex): type the dispatch fixtures instead of asserting over them

main's new casting gate (#20367 base) flags type assertions on changed
lines. Replace them with checked types: the recording sink already
satisfies its interface, both CodexSession fixtures are now annotated and
carry real collaborators, the settlement assertion compares whole
identities, and the integration helper reads submissions through the
host's public journalSnapshot instead of its private session map.

* fix(test): merge the duplicate doubt-reasons import the merge left behind

Both sides added an import from journal-dispatch-doubt-reasons and the
merge kept both statements, which the whole-repo native plugin gate
refuses under --deny-warnings.

* test(codex): a Fast mode turn is admitted, not accepted

#20506 landed its Fast mode tests against the dispatch contract this
branch replaces: a Codex send now returns admitted and settles its
identity on the provider echo. The tier assertions the test exists for
are untouched.

---------

Co-authored-by: Merge Sim <sim@local>

* test: add a verified OMP native-chat mock scenario (#20655)

Co-authored-by: plotarmordev <[email protected]>

* fix(omp): preserve status after terminal title owner rewrite (#20610)

Validated and independently reviewed OMP integration fix.

Co-authored-by: shahidbeig-a11y <[email protected]>

* fix(omp): preserve zsh startup with global aliases (#20621)

Validated and independently reviewed OMP integration fix.

* fix(git): avoid Windows tree kills after the command has exited (#20606)

Validated and independently reviewed OMP integration fix.

* fix(terminal): retain renames before renderer pane hydration (#20619)

* fix(terminal): retain renames before renderer pane hydration

* test(terminal): keep late renames from recreating closed tabs

* fix(agents): find OMP by its full project name (#20647)

* fix(agents): find OMP by its full project name

* test(agents): make picker baseline proof omit OMP aliases

* style(test): brace picker baseline condition

* feat(runtime): stream file uploads instead of buffering whole files (#16106)

* feat(runtime): stream file uploads instead of buffering whole files

Staging read each dropped file whole with readFile(), base64-encoded it
(a 4/3 expansion), and passed the string through IPC to the renderer,
which re-chunked it. Peak memory was ~2.3x the file size before a byte
moved, so a 25 MB per-file cap existed to protect the heap.

Staging now records identity only. The byte pump moves into main, where
the file handle and the runtime socket both live: 384 KiB slices (512 KiB
once base64-encoded, matching the chunk size the renderer used) appended
through the existing files.writeBase64Chunk RPC. Peak memory is one slice
regardless of file size, so the ceilings become user-safety limits on an
unattended transfer — 2 GB per file, 8 GB per drop — and over-limit errors
name both the size and the limit.

Because staging and streaming are separate calls, the staged entry carries
size, inode, device and mtime, and the streamer re-checks all four against
the pre-open lstat and against the handle it actually reads. A source
replaced or rewritten at the same size between the two calls is refused
rather than uploaded under the original name. The post-read check compares
mtime as well as size, so an in-place rewrite mid-transfer aborts before
commitUpload renames anything into place.

O_NOFOLLOW, realpath containment and stat identity are preserved, and the
pairing revision plus the runtime id ride every chunk, so a re-pair or a
replacement runtime aborts instead of appending the rest of the file to a
different host.

No wire change: files.writeBase64Chunk and its params are untouched, so
old and new hosts behave identically. The SSH import path is separate and
unchanged. The web client has no local filesystem to stream from and says
so instead of failing obscurely.

* fix(runtime): close the empty-upload and per-drop budget holes

Two gaps the first pass left open.

A zero-byte source returned before the post-transfer identity check, so a
file that gained content during the empty write's round trip committed as
an empty file at the user's chosen name. The empty chunk now falls through
to the same final check the slice loop uses.

Each staged source also started its own byte counter, so the 8 GB ceiling
capped one source rather than the drop: five 2 GB files staged cleanly at
10 GB total. The IPC handler now carries one budget across sourcePaths and
adds only what each source actually staged. The per-file ceiling is still
re-enforced where the bytes move; the drop total holds at staging because
identity enforcement means each file streams exactly the bytes measured.

* docs(runtime): name the invariants the upload helpers carry

* fix(runtime): name the source in errors and stop uploads with their window

Three problems an independent review turned up.

A dropped file's relative path is '', so the over-limit error read "'' is
3 GB, over the 2 GB per-file remote import limit" — the message this change
exists to fix, naming nothing. Errors now fall back to the file's own name;
the staged entry keeps '' so the destination path is unaffected. The
streamer had the same shape, falling back to the hidden .orca-upload-<nonce>
temp destination, a path the user never chose.

The byte loop used to live in the renderer and died with it. Moving it into
main meant closing or reloading the window left the rest of a multi-GB
transfer running, with the renderer's temp cleanup never reaching its
finally. An AbortSignal now rides the caller's lifetime and every chunk, is
re-checked per slice, and main sweeps the abandoned temp path itself when
the renderer is no longer there to do it.

Upload failures also reached the import result wrapped in Electron's
"Error invoking remote method '...'" prefix, because the throw crossed IPC
instead of happening in-renderer; extractIpcErrorMessage unwraps it.

An existing staging test asserted the empty-name message, so it encoded the
bug rather than catching it; it now asserts the file name.

* test(runtime): cover the containment check and the per-chunk host guards

The "escapes the dropped root" test only reached the lstat symlink guard,
so assertEntryInsideRoot had no coverage at all. The shape that actually
needs it is a regular file under a symlinked intermediate directory: lstat
sees a plain file, and realpath containment is the only thing that refuses
it. Disabling the guard now fails this test and nothing else.

Nothing asserted that the SSH target, connection generation and execution
host reach the writeBase64Chunk params either — the renderer tests stop at
the IPC boundary, so the streamer's half of that contract was untested.

* fix(runtime): survive a straggling append when sweeping an aborted upload

Aborting rejects the in-flight chunk locally, but the host may still apply
that append, and appends open with flag 'a' — which recreates the file the
sweep just deleted. The delete and the straggler also race: they are
separate calls on a queue that is not ordered between them.

Slices are strictly sequential, so at most one append can be outstanding.
A second pass after it has had time to land is therefore sufficient, not
merely a heuristic. The sweep moves out of filesystem-mutations.ts into its
own module so the behaviour is testable directly.

Found by an independent review pass, which also pointed out that the
"escapes the dropped root" test only reached the lstat symlink guard.

* fix(runtime): abort uploads only when the document commits, and honour manual disconnect per chunk

did-start-navigation fires before will-navigate blocks an external link or a
stray file drop, and the renderer survives those (verified against Electron 43
with a hidden window). Aborting there killed a healthy upload with a misleading
'window went away' error. did-navigate fires only once a new document has
replaced the caller.

The renderer's per-chunk calls used to go through the IPC handler that refuses
a manually disconnected environment; the loop in main made no such check, so a
disconnect mid-upload kept pushing the rest of the file. The handler now
resolves the selector to an environment id and the streamer checks it per slice.

Adds slice-boundary coverage against the real chunk schema and host write
flags, staging-to-stream on a real filesystem, and handler-level lifetime tests.

---------

Co-authored-by: Neil <[email protected]>

* fix(omp): preserve saved conversation names in session history (#20636)

Co-authored-by: Brennan Benson <[email protected]>

* fix(ui): contain idle caret paint so agent panes stop burning CPU (#10554)

An idle agent pane kept ~40% of a core busy just by being frontmost. The
xterm cursor and the native chat caret blink with no paint-containment
boundary, so Chromium treated each blink as damage to the whole pane
ancestry and re-rasterized it twice a second.

- `.xterm-container` and the native composer's input shell get
  `contain: paint`, bounding blink damage to the surface that blinks.
- The mention hint gains `z-20` to match the slash picker: a contained
  element becomes a stacking context and paints at z-index 0 in tree
  order, which would otherwise cover the hint's drop shadow.

Also records that DECSCUSR pins `decPrivateModes.cursorBlink`, which wins
over the option in `_updateCursorBlink` — so parking `cursorBlink` does not
reliably stop a hidden pane blinking. Pre-existing, documented only.

Co-authored-by: Wooseong Kim <[email protected]>

* feat(relay): expose preloaded PostgreSQL statement statistics (#20712)

* fix(runtime): apply the tui-idle evidence ranking to mailbox delivery (#20578)

fix(runtime): retry a delivery that the idle gate refused

Gates delivery at the two points where each implementation commits to typing into
the pane, rather than at each caller, and parks-and-re-offers a refusal so late
idle evidence cannot strand a queued message.

Refs #6011

* fix(agent-session): honour the backup-recovery fence floor on surface release (#20708)

* Fix surface release fence recovery floor

* fix(agents): advance backup recovery floor past lost mint

* fix(hooks): actually terminate a timed-out hook's process tree (#20576)

Repairs #20559, whose termination was a no-op: `detached` is a spawn-only option and `exec` ignored it, so the shell never became a group leader. Verified against real processes.

Refs #19334

* fix(worktrees): safely remove prunable git-file registrations (#20617)

Preserve checkout files and the named branch when removing a positively attested malformed Git-file registration. Reject file/symlink targets in deferred directory deletion.

Verified exact head with 75 focused tests including actual Git malformation, preserved marker/file bytes and branch HEAD. Independent review and complete product CI passed. WSL routing is covered by unit tests; direct SSH fails safely without local recovery.

Fixes #17316

* fix: keep OMP terminals when folder workspaces become Git repos (#20653)

Preserve the original folder locator through Git upgrade and subsequent listing, persistence, and removal decisions after proving it still names the same checkout.

Independently reviewed with 60 focused persistence/listing/removal tests and six native Windows real-Git/NTFS cases covering case/slashes, junction retention and retargeting, remote-host isolation and unrelated checkout preservation. Prior source-connected native OMP proof confirms process survival. Full PR CI passed; no rebuilt full-app after-proof claimed.

* fix(native-chat): cancel pending prompts precisely (#20601)

* fix(native-chat): hide activity while awaiting input

* fix(native-chat): keep approval turns cancellable

* test(native-chat): satisfy split PR quality gate

* fix(native-chat): catalog approval cancellation label

* fix(native-chat): include approval cancellation runtime label

* fix(codex): settle prompts when cancelled turns complete

* fix(codex): settle prompt registry fallbacks

* test(native-chat): cover pending interaction fallbacks

* test(native-chat): split prompt state coverage

* test(native-chat): keep prompt state isolated

* fix(native-chat): bound prompt turn backfill

* refactor(codex): centralize prompt registry bounds

* fix(native-chat): cancel pending prompts precisely

* fix(native-chat): consolidate capability imports

* fix(native-chat): harden precise prompt cancellation

* fix claude cancellation teardown races

* retry claude prompt lifecycle admission

* bound claude prompt cancellation retry work

* fix(codex): bound prompt turn identity on registration

* fix(native-chat): route rejected late dispatch settlements

* fix(codex): retain exact cancellable prompt turn ids

---------

Co-authored-by: Merge Sim <sim@local>

* fix(omp): resume independent child sessions from history (#20629)

Add Resume to eligible local OMP child history rows. Resolve lazy child targets from their own cwd and host, never an unrelated active workspace. Unresolved folder-only targets stay disabled; copy-command remains available.

Verified production map/resume resolver regression before/after; 50 focused tests and independent 40-test review, web types and code quality passed. Actual OMP storage/CLI smoke confirms distinct child/grandchild sessions. No native Windows or live SSH launch claim.

Addresses #12885 Scope 1.

* fix(ai-vault): expand nested OMP session history (#20663)

Expand saved OMP descendants lazily while preserving exact c…
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…stablyai#20578)

fix(runtime): retry a delivery that the idle gate refused

Gates delivery at the two points where each implementation commits to typing into
the pane, rather than at each caller, and parks-and-re-offers a refusal so late
idle evidence cannot strand a queued message.

Refs stablyai#6011
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