Skip to content

fix(orchestration): deliver pending mail to already-idle agents - #12584

Merged
Jinwoo-H merged 12 commits into
stablyai:mainfrom
bbingz:fix/12536-orchestration-idle-mail-delivery
Aug 7, 2026
Merged

Jinwoo-H merged 12 commits into
stablyai:mainfrom
bbingz:fix/12536-orchestration-idle-mail-delivery

Conversation

@bbingz

@bbingz bbingz commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Mail sent to an agent that was already idle stayed undelivered. Push-on-idle only ran on a status transition to idle, so with no further transition the message sat pending until the recipient happened to go busy and idle again.

notifyMessageArrived now delivers pending mail directly — but only when no mailbox waiter is registered for that handle. If a blocked orchestration.check --wait is live, the pull wins and the push stays pending for a later notify: deliverPendingMessages stamps delivered_at without marking read, so pushing alongside a waiter would deliver the same message twice (once to the waiter, once typed into the pane).

Safety for synthetic handles: deliverPendingMessagesForHandle (src/main/runtime/orca-runtime.ts:31049 on main) no-ops unless the leaf is idle and wraps getLiveLeafForHandle in try/catch, so the dispatch:<id> callers in orchestration-worker-control.ts, orchestration-worker-stop.ts, orchestration-worker-release-completion.ts and orchestration-federation-relay.ts, plus run:<id> in orchestration.ts, cannot throw through.

Mid-Enter concurrency continues to use main's existing messageDeliveryFlights single-flight/park path — no separate settle barrier is introduced here.

Fixes #12536

Screenshots

No visual change.

Testing

  • Unit tests: already-idle notify, working no-op, re-notify, mid-flight park/settle
  • Campaign review APPROVE_WITH_NITS (body was the only nit)

Regression coverage in orca-runtime.test.ts: already-idle notify injects the message and the delayed Enter; a still-working recipient gets no write and keeps delivered_at null so a later idle can still push it; a registered waiter resolves with no PTY write and no delivered_at stamp; a repeat notify during the Enter delay does not re-inject; and a second message parked mid-flight is delivered exactly once when the flight timer settles, with no further status output required.

Notes

Main-process orchestration only.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The runtime now tracks live agent status and requires a live-observed idle state before injecting pending messages. Message notifications coordinate with active and filtered waiters through reserved message types and deferred delivery. Delivery rechecks terminal liveness after PTY probing and handles process replacement, duplicate notifications, graph republishing, and Enter-delay settling. New E2E helpers and scenarios validate PTY delivery, mailbox disposition, waiter arbitration, agent-specific submission, and restored-terminal behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change, visual impact, testing, and notes, but it omits the required AI Review Report and Security Audit sections. Add the AI Review Report and Security Audit sections, including cross-platform compatibility checks and the required lint, typecheck, test, and build results.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: delivering pending orchestration mail to agents that are already idle.
Linked Issues check ✅ Passed The changes address issue #12536 by delivering mail to already-idle agents while preserving waiter precedence, busy-agent safety, coordinator behavior, and synthetic-handle safety.
Out of Scope Changes check ✅ Passed The runtime changes and supporting unit, integration, and E2E tests are directly related to the linked issue and stated orchestration objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

32345-32350: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Keep the busy-recipient message pending.

The test verifies that no PTY write occurs. It does not verify that the message remains undelivered. If the busy path sets delivered_at without a write, this test passes and later delivery is suppressed.

Proposed test update
-    db.insertMessage({ from: 'sender', to: terminal.handle, subject: 'while working' })
+    const message = db.insertMessage({
+      from: 'sender',
+      to: terminal.handle,
+      subject: 'while working'
+    })
     write.mockClear()

     runtime.notifyMessageArrived(terminal.handle, 'status')

     expect(write).not.toHaveBeenCalled()
+    expect(message.delivered_at).toBeNull()

32391-32440: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test the three-second settling deadline.

This test verifies release after a status transition only. If timeout release or its rerun is broken, held mail can remain pending and this test still passes. Advance fake time by three seconds without status output, then assert delivery of second.

The PR objective specifies a three-second release path.

src/main/runtime/rpc/methods/orchestration.test.ts (1)

313-313: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert the notified recipient handle.

toHaveBeenCalled() passes if delivery runs for another handle. Assert that deliverPendingMessagesForHandle receives the target recipient handle. Assert one call if this test performs one send.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5cfbeb7a-a559-4be5-82c5-f7cadc3b687f

📥 Commits

Reviewing files that changed from the base of the PR and between 9ee3595 and 85214d6c28dc55cd7c36cff87583ad07aae2ef89.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts

@bbingz
bbingz force-pushed the fix/12536-orchestration-idle-mail-delivery branch from 85214d6 to 18fe6dd Compare August 5, 2026 00:39
@electro56435

Copy link
Copy Markdown

<----From here on agentslop if helpful.---->

Ordering question on the new call.

The new call runs before the waiter loop, so it interacts with orchestration.check --wait.

deliverPendingMessages writes the payload to the PTY and stamps delivered_at after the Enter. It does not stamp read. orchestration.check re-reads with getUnreadMessages after its waiter resolves. For a recipient that is idle and has a blocked waiter, both paths return the same message. The check call returns it, and the pane also receives it with Enter.

Worker mail is not affected. It addresses dispatch:<id>, where getLiveLeafForHandle throws and the injection stops. The case needs a terminal handle as the recipient.

Question: is that combination reachable in practice? A coordinator that blocks in check --wait usually reads as working, so the injection stops at the status test. That protection depends on the terminal title, which is the coupling #12536 reports as fragile.

The three new tests cover idle without a waiter. A test for idle with a waiter settles it.

@bbingz

bbingz commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Reachable, and worth closing off instead of leaning on the status gate.

Confirmed in the diff: notifyMessageArrived calls deliverPendingMessagesForHandle(handle) immediately before const waiters = this.messageWaitersByHandle.get(handle) in src/main/runtime/orca-runtime.ts. Since deliverPendingMessages stamps delivered_at but not read, and orchestration.check re-reads through getUnreadMessages after its waiter resolves, an idle leaf with a blocked waiter does surface the message on both paths.

You're also right about the guard. Today the only thing preventing it is the idle test inside deliverPendingMessagesForHandle, and that status is title-derived — the exact coupling #12536 flags — so I don't want it to be the load-bearing protection here.

Change I'll push: skip the PTY injection when messageWaitersByHandle holds a live waiter for that handle. A blocked check --wait is an explicit pull, so the pull wins and the push stays pending; the pane gets it on the next notify if the waiter is gone. Plus the test you asked for — idle leaf with a registered waiter, asserting the waiter resolves with the message and write is never called.

Same pass picks up CodeRabbit's two test gaps: assert delivered_at stays null on the busy-recipient path (today the test only asserts no write, so a busy path that stamps without writing would pass), and advance fake time 3s with no status output to cover the settling-timeout release rather than only the status-transition release.

bbingz added 2 commits August 6, 2026 09:15
Push-on-idle only ran on an agent-status transition to idle, so mail that
arrived while the recipient was already idle stayed undelivered until an
unrelated title flip (stablyai#12536). notifyMessageArrived now calls
deliverPendingMessagesForHandle, which still no-ops unless the leaf is idle.

Main already serializes delayed-Enter delivery via messageDeliveryFlights;
this rebase keeps that design and only wires the notify hook + covers the
already-idle, working no-op, re-notify, and mid-flight park paths in tests.
notifyMessageArrived was push-delivering before waking check --wait, so an
idle leaf with a blocked waiter saw the message twice (check return + pane
inject). Let the pull win; keep busy delivered_at null and timer-only flight
settle covered in tests.
@bbingz
bbingz force-pushed the fix/12536-orchestration-idle-mail-delivery branch from 18fe6dd to 3c304cd Compare August 6, 2026 01:21
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

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

@bbingz

bbingz commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Pushed as 3c304cd — notifyMessageArrived now skips the PTY push whenever messageWaitersByHandle holds a live waiter for the handle, so a blocked check --wait is the sole delivery path and the push stays pending for a later notify. Includes the test you asked for (idle leaf + registered waiter → waiter resolves with the message, write never called) plus CodeRabbit's two gaps: delivered_at asserted null on the busy path, and a timer-only settling release at +3s. 7 focused tests green.

Two holes in the notify-path push added by this PR.

deliverPendingMessagesForHandle read leaf.lastAgentStatus, which a cold
restore seeds from the title persisted at snapshot time. That field had no
production reader before this PR, so the documented seed invariant
(applySeededAgentStatus: "waiters must only react to LIVE transitions") held
by construction. Reading it here broke it: an agent that went busy across a
relaunch still reports idle until its first live frame, so the next send
typed a message plus Enter into a working agent and stamped it delivered.
Track lastAgentStatusObservedLive, set it only on a live OSC frame, and clear
it on provider-generation reset so a same-id restore cannot inherit the prior
process's authority.

notifyMessageArrived skipped the push whenever any waiter was registered, but
a waiter filtered to other types never returns the row -- check re-reads under
the same filter on timeout -- so a status message to a coordinator blocked on
`check --wait --types worker_done` was neither pushed nor pulled. That is the
stablyai#12536 symptom the PR set out to fix. Skip only when a waiter would actually
consume this message type.

Also skip the leaf lookup for handles the runtime does not own: federation
sync notifies `run:<id>` once per relayed item, and each one was building and
discarding a terminal_handle_stale Error.
… defer it past a resolved check

Round-1 review fixes for the stablyai#12536 push-on-notify path.

- onPtyExit clears lastAgentStatusObservedLive on the pty and its leaves. A
  same-id respawn makes the leaf writable again before any new title, so the
  dead process's live idle would otherwise type mail plus Enter into its
  replacement and stamp the row delivered. Both review lanes reproduced this.
- notifyMessageArrived defers the no-consumer push one microtask.
  resolveMessageWaiter drops the waiter synchronously but its check handler
  marks rows read a microtask later; two sends resuming off one shared
  in-flight promise put a no-waiter notify inside that window, where a
  synchronous push injects rows the resolved check is about to return.
- Pin the syncWindowGraph carry of the live flag, which no test covered.

terminal-send-stale-leaf-liveness now drives the replacement's own live idle
title before asserting its delivery, matching the tightened invariant.
Round-2 review fix. Push delivery is gated on LIVE idle, so its authorizing
edge is liveness as well as status — but the trigger stayed transition-only.
A restore seed, or the status kept across a same-id respawn, leaves a stale
'idle' on the leaf; an agent whose first live title is already idle (a resumed
Claude session sitting at its prompt emits exactly that) then shows no
transition, so the row that notify correctly declined to push never got a
second chance. That is the stablyai#12536 symptom in the corner the live-status gate
created.

Deliver on the idle transition OR on the first live observation of an idle
leaf. Waiter semantics stay transition-only. Both new tests drive the idle
title with no preceding working frame, which is what the earlier tests missed.
…batch

Round-3 review fix, found independently by both reviewers. The consumer
type-filter decided pull-vs-push per message type, but the push it authorized
reads EVERY pending row for the handle. So a `status` notify that no waiter
claimed pushed a `worker_done` row alongside it — and the waiter that reserved
worker_done still returned that row from its check. The coordinator processed
the same completion twice: typed into its pane with Enter, and as the check's
return value.

deliverPendingMessages now drops rows whose type a pull has claimed. Live
waiters cover the still-blocked case; notifyMessageArrived snapshots the
reservation before queueing the push, because a waiter resolved later in the
same microtask drain is already out of the map by the time the push runs —
which is the ordering both reviewers reproduced.
…be defers delivery

Round-4 review fixes.

The reservation snapshot exists for a waiter resolved inside one microtask
drain. The absence-probe continuation runs many macrotasks later, and the
probeDeferredDeliveryPtyIds dedup swallows every notify that arrives while the
probe is in flight — so carrying the snapshot in there skipped a row whose
waiter was long gone, with nothing left to retry it. On remote and
daemon-hosted panes that stranded a completion at delivered_at: null, which is
the stablyai#12536 symptom again. The continuation now re-reads unreserved; the
push-time live-waiter check still covers a genuinely blocked waiter.

Also pin that live-waiter check: deleting it was invisible to the whole suite.
The new test blocks a filtered check between the notify and the deferred push,
which only the push-time read can catch — the notify snapshot is empty there.
Round-5 review fix. A `remote:` pty answers probePtyLiveness with null before
its first await (src/main/ipc/pty.ts), so the absence-probe chain can settle
entirely in microtasks. The continuation then overtakes the resumption of a
check resolved in the meantime: that waiter is already out of
messageWaitersByHandle and its rows are not yet marked read, so the push
injected exactly what the check was about to return — the same worker_done
typed into the pane and returned by orchestration.check.

Deferring the continuation one macrotask lets every queued check mark its rows
read first. It re-reads rather than replaying the notify-time reservation,
which is what round 4 removed to stop an orphaned row from stranding.

The stub's getUndeliveredUnreadMessages now mirrors the real query's `read = 0`
clause; without it the regression test could not observe a check consuming a row.
Round-6 review fix, found independently by both reviewers. The gate that
authorizes a push runs before the absence probe defers, and the continuation
re-entered delivery on the closure-captured leaf checking only ptyId — which is
exactly what a same-id cold restore preserves. A session that exited and
respawned inside the probe window therefore took the payload plus a synthesized
Enter on the dead process's authority, and the row was stamped delivered, so a
restarting TUI that discards the paste loses it for good.

The continuation now re-reads the leaf and re-applies `idle && observedLive`,
the same current-state-not-the-closure rule the delayed-Enter callback already
follows. Nothing strands: a row skipped here is released by the replacement's
first live idle frame, or by the agent's next idle transition if it went busy
during the probe.
Round-7 review fix. Reverting `pty.lastAgentStatusObservedLive = false` in
onPtyExit left the whole suite green, so the line was load-bearing but
unpinned: a leaf rebuilt under a new leafId on the same pty takes its tail from
the PTY record, and without the clear it inherits live authority next to the
`idle` that exit deliberately keeps for `ps`.

An earlier attempt at this case was vacuous — the shared helper's `pane:1` leaf
id is not a UUID, so makeRuntimePaneKey falls back to `tabId:paneRuntimeId` and
the retirement fence's pty-candidate clause can never match, emptying the leaf
map and passing for the wrong reason. Using a UUID leaf id admits the
republish; the test asserts the map is non-empty and that the rebuilt leaf
carries the pty record's status before checking the flag.

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

Thanks for this — the diagnosis in #12536 was spot on, and the reasoning in your second commit (let the pull win, because deliverPendingMessages stamps delivered_at without marking read) is correct. I confirmed it: getUnreadMessages ignores delivered_at, so pushing alongside a live waiter really would have delivered twice.

I've pushed 8 commits on top. Two were defects I found in review, six came out of a follow-up hardening pass.

The two original findings

  1. Seeded agent status could authorize a PTY write. deliverPendingMessagesForHandle reads leaf.lastAgentStatus, which a cold restore seeds from the title persisted at snapshot time. That field had no production reader before this PR, so the documented seed invariant (applySeededAgentStatus: waiters "must only react to LIVE transitions") held by construction. Wiring it up broke it — an agent that went busy across a relaunch still reads idle until its first live frame, so the next send would type a message plus Enter into a working agent. Now gated on lastAgentStatusObservedLive, set only on a live OSC frame.

  2. A type-filtered waiter stranded the message. Skipping the push whenever any waiter existed was too broad: a waiter filtered to other types never returns the row (check re-reads under the same filter on timeout), so a status message to a coordinator blocked on check --wait --types worker_done was neither pushed nor pulled — the exact #12536 symptom. Now skipped only when a waiter would actually consume that message type.

From the hardening pass

  • lastAgentStatusObservedLive also has to clear on pty exit, or a same-id respawn inherits the dead process's authority.
  • The no-consumer push needs one microtask of deferral: resolveMessageWaiter drops the waiter synchronously but its check handler marks rows read a microtask later, and two sends resuming off one shared in-flight promise land inside that window.
  • Gating on live-idle created a new stranding corner: an agent whose first live title is already idle (a resumed session sitting at its prompt) shows no transition, so the row never got a second chance. Delivery now also fires on the first live observation of an idle leaf.
  • Rows a live pull has reserved are kept out of the pushed batch, and the waiter reservation is dropped when the liveness probe defers.

Validation

pnpm typecheck and pnpm lint clean; 6544 tests pass across src/main/runtime/ and src/main/ipc/. Each added test was verified to fail when its fix is reverted.

Also verified end-to-end in a dev build: with a recipient driven to a genuine live working -> idle transition and then left alone, a send now stamps delivered_at, injects the banner, and fires the delayed Enter — with no further title change. Worth noting src/main/ipc/pty.test.ts in the check list; it caught two partial runtime fakes that were silently swallowing failures.

Scope note, and one thing left unfixed

#12536 has a second half this PR does not fix: a pane bound as a run's coordinator_handle receives the text but no Enter, so it never acts on it. That's the deliberate user-owned-prompt carve-out. Worth knowing that lifecycle mail can't reach this path at all — worker_done/heartbeat are readdressed to run:<id>, which isn't a terminal handle, so it's pulled via check --wait and never pushed. The real fix belongs at the run: consumer layer.

I'd suggest not letting the merge auto-close #12536 as fully fixed. I'm filing a follow-up for the remainder, along with a related find: the guard that stops mail clobbering a half-typed prompt only ever covered the coordinator pane, and that guard is effectively unreachable from CLI-driven workflows — so a human typing into a worker pane still gets the banner plus a synthesized Enter today (#7337).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/main/runtime/terminal-send-stale-leaf-liveness.test.ts (2)

296-326: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider collecting probe resolvers instead of overwriting a single reference.

resolveProbe is reassigned on each probe arm. Line 324 assumes the second probe is already armed at that point. If the arm order changes, line 324 resolves the settled first promise and the second probe never settles, so the test fails for a reason unrelated to the gate. A resolver queue makes the intent explicit and removes the ordering assumption.

♻️ Optional: queue the resolvers
-    let resolveProbe!: (value: boolean | null) => void
+    const probeResolvers: Array<(value: boolean | null) => void> = []
     const { runtime, handle, write, stub } = await makeIdleLeafWithoutPtyRecord({
       probePtyLiveness: () =>
         new Promise<boolean | null>((resolve) => {
-          resolveProbe = resolve
+          probeResolvers.push(resolve)
         })
     })

Then resolve the newest pending resolver at each point, for example probeResolvers.shift()?.(null).


344-368: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assert the waiter resolution value to keep the test specific.

The .then() callback runs for any resolution, including 'cancelled' or 'timeout'. pulled would then still be filled by the row scan, so the assertion at line 368 can pass without the waiter actually consuming the arrival. Capture the resolution value and assert it.

♻️ Optional: assert the resolution
     const pulled: string[] = []
+    let waiterOutcome: unknown
     const checkResumed = runtime
       .waitForMessage(handle, { typeFilter: ['worker_done'], timeoutMs: 60_000 })
-      .then(() => {
+      .then((outcome) => {
+        waiterOutcome = outcome
         for (const row of stub.rows) {

Then assert waiterOutcome after await checkResumed.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 34e74d00-ab96-45e1-91a7-56387f534383

📥 Commits

Reviewing files that changed from the base of the PR and between 3c304cd and 5ae938a.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts

The fix and its seven follow-ups were unit-tested only. Nothing exercised a
real PTY, so the harness could not have caught that the runtime resolves
delivery through a renderer graph leaf an RPC-created pane does not have yet,
or that a cooked TTY rewrites the synthesized Enter before the agent sees it.

The recipient is a fake `codex` on PATH rather than a shell emitting titles:
push-on-idle both reads the status inferred from live OSC titles and writes
into the pane's foreground process, and only a process that records its stdin
can prove the banner and the Enter actually arrived. Titles come from a polled
file because orchestration owns stdin itself.

Four of the seven delivery cases fail on main. The rest are regression guards
and say so in place, as does the restore spec, which covers the restart path
but not the live-authority gate — the seed only reaches leaves that already
exist when pty:spawn answers, and a cold relaunch publishes its graph after
that. The gate, and the microtask/probe-window ordering fixes, stay in
orca-runtime.test.ts, which can stage those orderings directly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

85-101: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Key the title poll on mtime and content to remove a filesystem-granularity flake.

The poll skips the file whenever mtimeMs is unchanged. Filesystem timestamp granularity is not uniform across macOS, Linux, and Windows. If two setTitle calls land inside one timestamp tick, the second title is dropped. driveToLiveIdle writes CODEX_WORKING_TITLE and then CODEX_IDLE_TITLE back to back, so the dropped write would appear as a waitForObservedTitle timeout.

Comparing mtime plus content keeps the intentional re-emit of an identical title working, and also emits a changed title when mtime did not move.

♻️ Proposed change to the polled control-file check
-let lastStamp = null
+let lastKey = null
 setInterval(() => {
   if (!existsSync(controlPath)) return
   let title
   let stamp
   try {
     stamp = statSync(controlPath).mtimeMs
-    if (stamp === lastStamp) return
     title = readFileSync(controlPath, 'utf8').trim()
   } catch {
     return
   }
   if (!title) return
-  lastStamp = stamp
+  const key = stamp + '\\u0000' + title
+  if (key === lastKey) return
+  lastKey = key
   process.stdout.write('\\u001b]0;' + title + '\\u0007')
   log({ event: 'title', title })
 }, 50)

123-126: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Windows environments use Path, so a literal PATH key can be ignored after a merge.

If the fixture merges this record into process.env on Windows, the result can carry both Path (inherited) and PATH (this override). Which one the spawned process reads is then dependent on the merge order. Resolving the existing key name makes the override deterministic.

♻️ Proposed platform-safe key selection
-export const MAIL_AGENT_LAUNCH_ENV: Record<string, string> = {
-  PATH: `${fakeCliDir}${path.delimiter}${process.env.PATH ?? ''}`,
-  ORCA_E2E_MAIL_AGENT_DIR: agentStateDir
-}
+const pathKey =
+  Object.keys(process.env).find((key) => key.toUpperCase() === 'PATH') ?? 'PATH'
+
+export const MAIL_AGENT_LAUNCH_ENV: Record<string, string> = {
+  [pathKey]: `${fakeCliDir}${path.delimiter}${process.env[pathKey] ?? ''}`,
+  ORCA_E2E_MAIL_AGENT_DIR: agentStateDir
+}

132-134: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard the exit-time cleanup against a locked directory.

rmSync with force: true still throws on EPERM or EBUSY. On Windows a surviving PTY child can hold codex.cmd or fake-codex.js open at worker exit. A throw inside an exit handler fails the worker after the specs already passed.

♻️ Proposed cleanup guard
 process.once('exit', () => {
-  rmSync(fakeCliDir, { recursive: true, force: true })
+  try {
+    rmSync(fakeCliDir, { recursive: true, force: true })
+  } catch {
+    // A surviving PTY child can hold the shim open; leave it to the OS tmp sweep.
+  }
 })
tests/e2e/helpers/orchestration-mail-store.ts (1)

24-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the callback so the write path is not described as a read.

startCoordinatorRun passes a mutating callback into the parameter named read. Rename it to use to keep the name accurate for both callers.

♻️ Proposed rename
-function withMailDb<T>(userDataDir: string, read: (db: Database) => T): T {
+function withMailDb<T>(userDataDir: string, use: (db: Database) => T): T {
   const db = new Database(path.join(userDataDir, 'orchestration.db'))
   try {
-    return read(db)
+    return use(db)
   } finally {
     db.close()
   }
 }
tests/e2e/orchestration-idle-mail-delivery.spec.ts (2)

325-333: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Attach a rejection handler when the long-poll promise is created.

client.call('orchestration.check', ...) starts here but is awaited at line 338. If sendMail or an earlier assertion throws in between, this promise rejects with no handler attached. Playwright then reports an unrelated unhandled rejection instead of the real failure. The filtered-waiter test at line 357 already guards this with .catch.

♻️ Proposed guard
     const waiting = client.call<{ messages: { subject: string }[] }>('orchestration.check', {
       terminal: pane.handle,
       peek: true,
       wait: true,
       timeoutMs: 30_000
-    })
+    })
+    // Keep the rejection handled while the send and assertions below run.
+    waiting.catch(() => undefined)

346-377: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Bound the filtered waiter so its timeout cannot outlive the assertions.

The waiter uses timeoutMs: 8_000, and the delivery poll below allows up to 20s. The final await waiting therefore usually resolves immediately. That ordering is incidental. If DELIVERY_TIMEOUT_MS or the waiter timeout changes, the test can start waiting on a still-parked long-poll. Consider asserting that the filtered waiter returned no messages, which also pins the filter behavior this test claims to cover.

tests/e2e/orchestration-idle-mail-restore.spec.ts (1)

40-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shared observation logic is duplicated between the two specs. BANNER_PREFIX, DELIVERY_TIMEOUT_MS, waitForObservedTitle, and the fixed-window "stays pending" assertion exist in both spec files. The root cause is that these belong to the observation contract the helper modules already own. Two copies will drift, and a change to the delivery timing chain must then be applied twice.

  • tests/e2e/orchestration-idle-mail-restore.spec.ts#L40-L72: remove the local BANNER_PREFIX, DELIVERY_TIMEOUT_MS, and waitForObservedTitle, and import them from the helper modules instead.
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts#L150-L165: move BANNER_PREFIX, DELIVERY_TIMEOUT_MS, waitForObservedTitle, and the pending-window assertion into tests/e2e/helpers/orchestration-mail-pane-agent.ts and tests/e2e/helpers/orchestration-mail-store.ts, then import them here.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f5238e9d-e6e1-4cd1-bd44-848584663223

📥 Commits

Reviewing files that changed from the base of the PR and between 5ae938a and 6974539.

📒 Files selected for processing (4)
  • tests/e2e/helpers/orchestration-mail-pane-agent.ts
  • tests/e2e/helpers/orchestration-mail-store.ts
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts
  • tests/e2e/orchestration-idle-mail-restore.spec.ts

Comment on lines +336 to +343
const messageId = await sendMail(client, pane.handle, { subject })

const pulled = await waiting
expect(pulled.result.messages.map((message) => message.subject)).toContain(subject)
expect(pane.agent.readStdin()).not.toContain(BANNER_PREFIX)
// Pending, not pushed: the pull won, and the push stays available for a
// later notify rather than racing this one.
expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The pending assertion here can race the suppressed push.

Line 343 reads the row immediately after await waiting resolves. The push path is suppressed by the live waiter, so pending is the expected steady state. The assertion is still a point-in-time read taken microseconds after the send. If the suppression regressed, the push chain may not have stamped delivered_at yet, and this test would pass on a real duplicate-delivery bug.

Add the fixed settle window that expectStaysPending uses, so the assertion covers the whole push chain.

🐛 Proposed strengthening
     const pulled = await waiting
     expect(pulled.result.messages.map((message) => message.subject)).toContain(subject)
-    expect(pane.agent.readStdin()).not.toContain(BANNER_PREFIX)
     // Pending, not pushed: the pull won, and the push stays available for a
     // later notify rather than racing this one.
-    expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending')
+    await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS)
+    expect(pane.agent.readStdin()).not.toContain(BANNER_PREFIX)
+    expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending')
📝 Committable suggestion

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

Suggested change
const messageId = await sendMail(client, pane.handle, { subject })
const pulled = await waiting
expect(pulled.result.messages.map((message) => message.subject)).toContain(subject)
expect(pane.agent.readStdin()).not.toContain(BANNER_PREFIX)
// Pending, not pushed: the pull won, and the push stays available for a
// later notify rather than racing this one.
expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending')
const messageId = await sendMail(client, pane.handle, { subject })
const pulled = await waiting
expect(pulled.result.messages.map((message) => message.subject)).toContain(subject)
// Pending, not pushed: the pull won, and the push stays available for a
// later notify rather than racing this one.
await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS)
expect(pane.agent.readStdin()).not.toContain(BANNER_PREFIX)
expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending')

…y opened

All eight specs failed on Linux CI with 'Timed out waiting for terminal handle
after creation'. terminal.create waits up to 10s for a renderer graph sync to
bind the new tab's handle, and a headless CI renderer misses that deadline —
macOS was simply fast enough to hide it.

Nothing on the delivery path reads a pane's agent metadata: it resolves the
leaf, the OSC title, and PTY liveness. So the agent now runs as a foreground
process in the already-mounted fixture pane, which exercises the same code and
removes the startup race — and, since that pane is mounted, guarantees the leaf
that push delivery resolves its write target through. Its ledger and control
file move to argv, so nothing depends on the pane's exported handle either.

waitForPtyShellEcho gates the launch: keystrokes typed at a shell that has not
reached its prompt are dropped, which would surface as an agent that never
started for reasons unrelated to anything under test.

Re-verified the same four cases still fail against main after the rewrite.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

2-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the changed comments.

Keep the non-obvious reason for the CI race and live-title behavior. Reduce each comment to one concise statement. The current multi-paragraph comments duplicate implementation detail and obscure the test flow.

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

Also applies to: 67-69, 104-106

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e20b4b8b-129f-488d-a65d-8030f9812f03

📥 Commits

Reviewing files that changed from the base of the PR and between 6974539 and ae2b6b5.

📒 Files selected for processing (3)
  • tests/e2e/helpers/orchestration-mail-pane-agent.ts
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts
  • tests/e2e/orchestration-idle-mail-restore.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts

@Jinwoo-H
Jinwoo-H merged commit a025a71 into stablyai:main Aug 7, 2026
46 checks passed
@bbingz

bbingz commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@Jinwoo-H thank you for the thorough review and for landing the eight commits on top — especially the seeded-status / type-filtered-waiter findings. Those would have been easy to ship wrong from the outside.

Agree with the scope note: this PR correctly closes the already-idle push half of #12536, and the coordinator-no-Enter / run: consumer remainder belongs in #12953 (plus the worker half-typed clobber path you tied to #7337). Happy that auto-close of #12536 is paired with that follow-up rather than reading as fully fixed.

No further action from me on this PR.

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.

Pending orchestration mail is only delivered on an agent-status transition, so an already-idle recipient never receives it

5 participants