Repository navigation
fix(orchestration): deliver pending mail to already-idle agents - #12584
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/main/runtime/orca-runtime.test.ts (2)
32345-32350: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winKeep 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_atwithout 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 winTest 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 winAssert the notified recipient handle.
toHaveBeenCalled()passes if delivery runs for another handle. Assert thatdeliverPendingMessagesForHandlereceives 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.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/orchestration.test.ts
85214d6 to
18fe6dd
Compare
|
<----From here on agentslop if helpful.----> Ordering question on the new call. The new call runs before the waiter loop, so it interacts with
Worker mail is not affected. It addresses Question: is that combination reachable in practice? A coordinator that blocks in The three new tests cover idle without a waiter. A test for idle with a waiter settles it. |
|
Reachable, and worth closing off instead of leaning on the status gate. Confirmed in the diff: You're also right about the guard. Today the only thing preventing it is the idle test inside Change I'll push: skip the PTY injection when Same pass picks up CodeRabbit's two test gaps: assert |
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.
18fe6dd to
3c304cd
Compare
|
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. |
|
Pushed as 3c304cd — |
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
left a comment
There was a problem hiding this comment.
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
-
Seeded agent status could authorize a PTY write.
deliverPendingMessagesForHandlereadsleaf.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 readsidleuntil its first live frame, so the next send would type a message plus Enter into a working agent. Now gated onlastAgentStatusObservedLive, set only on a live OSC frame. -
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 (
checkre-reads under the same filter on timeout), so astatusmessage to a coordinator blocked oncheck --wait --types worker_donewas neither pushed nor pulled — the exact #12536 symptom. Now skipped only when a waiter would actually consume that message type.
From the hardening pass
lastAgentStatusObservedLivealso 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:
resolveMessageWaiterdrops the waiter synchronously but itscheckhandler 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).
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/main/runtime/terminal-send-stale-leaf-liveness.test.ts (2)
296-326: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider collecting probe resolvers instead of overwriting a single reference.
resolveProbeis 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 valueAssert the waiter resolution value to keep the test specific.
The
.then()callback runs for any resolution, including'cancelled'or'timeout'.pulledwould 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
waiterOutcomeafterawait checkResumed.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 34e74d00-ab96-45e1-91a7-56387f534383
📒 Files selected for processing (3)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/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.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (7)
tests/e2e/helpers/orchestration-mail-pane-agent.ts (3)
85-101: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winKey the title poll on mtime and content to remove a filesystem-granularity flake.
The poll skips the file whenever
mtimeMsis unchanged. Filesystem timestamp granularity is not uniform across macOS, Linux, and Windows. If twosetTitlecalls land inside one timestamp tick, the second title is dropped.driveToLiveIdlewritesCODEX_WORKING_TITLEand thenCODEX_IDLE_TITLEback to back, so the dropped write would appear as awaitForObservedTitletimeout.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 valueWindows environments use
Path, so a literalPATHkey can be ignored after a merge.If the fixture merges this record into
process.envon Windows, the result can carry bothPath(inherited) andPATH(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 winGuard the exit-time cleanup against a locked directory.
rmSyncwithforce: truestill throws onEPERMorEBUSY. On Windows a surviving PTY child can holdcodex.cmdorfake-codex.jsopen at worker exit. A throw inside anexithandler 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 valueRename the callback so the write path is not described as a read.
startCoordinatorRunpasses a mutating callback into the parameter namedread. Rename it touseto 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 winAttach a rejection handler when the long-poll promise is created.
client.call('orchestration.check', ...)starts here but is awaited at line 338. IfsendMailor 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 valueBound 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 finalawait waitingtherefore usually resolves immediately. That ordering is incidental. IfDELIVERY_TIMEOUT_MSor 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 winShared 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 localBANNER_PREFIX,DELIVERY_TIMEOUT_MS, andwaitForObservedTitle, and import them from the helper modules instead.tests/e2e/orchestration-idle-mail-delivery.spec.ts#L150-L165: moveBANNER_PREFIX,DELIVERY_TIMEOUT_MS,waitForObservedTitle, and the pending-window assertion intotests/e2e/helpers/orchestration-mail-pane-agent.tsandtests/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
📒 Files selected for processing (4)
tests/e2e/helpers/orchestration-mail-pane-agent.tstests/e2e/helpers/orchestration-mail-store.tstests/e2e/orchestration-idle-mail-delivery.spec.tstests/e2e/orchestration-idle-mail-restore.spec.ts
| 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') |
There was a problem hiding this comment.
🎯 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.
| 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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
tests/e2e/helpers/orchestration-mail-pane-agent.ts (1)
2-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCondense 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
📒 Files selected for processing (3)
tests/e2e/helpers/orchestration-mail-pane-agent.tstests/e2e/orchestration-idle-mail-delivery.spec.tstests/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 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 / No further action from me on this PR. |
…lyai#12584) Co-authored-by: Jinwoo-H <[email protected]>
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.
notifyMessageArrivednow delivers pending mail directly — but only when no mailbox waiter is registered for that handle. If a blockedorchestration.check --waitis live, the pull wins and the push stays pending for a later notify:deliverPendingMessagesstampsdelivered_atwithout 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:31049on main) no-ops unless the leaf is idle and wrapsgetLiveLeafForHandlein try/catch, so thedispatch:<id>callers inorchestration-worker-control.ts,orchestration-worker-stop.ts,orchestration-worker-release-completion.tsandorchestration-federation-relay.ts, plusrun:<id>inorchestration.ts, cannot throw through.Mid-Enter concurrency continues to use main's existing
messageDeliveryFlightssingle-flight/park path — no separate settle barrier is introduced here.Fixes #12536
Screenshots
No visual change.
Testing
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 keepsdelivered_atnull so a later idle can still push it; a registered waiter resolves with no PTY write and nodelivered_atstamp; 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.