Skip to content

fix(orchestration): wake coordinators with mail pointers - #12988

Merged
Jinwoo-H merged 3 commits into
mainfrom
fix-12953-orchestration-mail-pointer
Aug 7, 2026
Merged

Jinwoo-H merged 3 commits into
mainfrom
fix-12953-orchestration-mail-pointer

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • push a short orca orchestration check pointer instead of orchestration message payloads
  • resolve run:<id> mail through the modern Run's coordinator terminal
  • keep mail pending until check consumes it and suppress duplicate pointers with an in-memory sequence watermark
  • preserve waiter/live-idle gates, delayed Enter behavior, and Cursor's manual-submit carve-out
  • restore PTY/leaf idle state when foreground-process evidence disproves Codex's neutral-title exit candidate, then retry pending delivery

Part of #12953 (Phase 1).

Verification

  • pnpm exec vitest run src/main/runtime/orca-runtime.test.ts src/main/runtime/orchestration/formatter.test.ts — 1093 passed, 1 skipped
  • pnpm run typecheck:node
  • pnpm run lint
  • pnpm exec electron-vite build --mode e2e
  • SKIP_BUILD=1 npx playwright test tests/e2e/orchestration-idle-mail-delivery.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 — 8 passed (1.1m)
  • SKIP_BUILD=1 npx playwright test tests/e2e/orchestration-idle-mail-restore.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 — 1 passed (12.6s)

The Electron suite exercises a real pane/PTY path with a scriptable agent process, OSC status transitions, delayed Enter, and an stdin ledger.

A final API-backed Codex-to-Codex smoke test also passed. A real Codex worker sent worker_done with subject fixed real-agent smoke complete; an already-idle real Codex coordinator received the pointer without a forced second turn, ran orca orchestration check, and verified the body named package orca. The delivery was acknowledged and the worker released.

Mutation checks

  • singular formatter test failed when the production formatter always pluralized messages
  • plural formatter test failed when the production formatter always used singular message
  • Run-mailbox unit test failed when the old terminal-only early return was restored
  • reported-bug e2e failed with an empty stdin ledger when that terminal-only early return was restored
  • Codex neutral-title regression failed with zero PTY writes when foreground confirmation restored only the title tracker instead of PTY/leaf runtime state

Screenshots

No visual change.

Security audit

No new external input, privilege boundary, persistence format, or wire protocol. The change reuses existing local PTY status and foreground-process evidence.

Notes

No RPC or remote-wire schema changes. The behavior applies to local, SSH, and folder-workspace PTYs through the existing runtime abstractions.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8573f375-f184-4358-a241-37a0f5e2d937

📥 Commits

Reviewing files that changed from the base of the PR and between 8bc659f and 6b4bc00.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.ts

📝 Walkthrough

Walkthrough

The runtime now routes orchestration messages from run: addresses to coordinator panes. It injects count-based pointers instead of private message bodies, suppresses duplicate pointers, preserves mailbox delivery markers, and delays Enter submission for supported agents. Delivery coordinates live idle status, waiter reservations, parked triggers, restored exits, and Cursor behavior. Formatter, runtime, unit, and end-to-end tests cover these flows.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: waking coordinators with orchestration mail pointers.
Description check ✅ Passed The description covers the change, screenshots, verification, security, and notes, but omits the required AI Review Report and explicit cross-platform review confirmation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 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.

Actionable comments posted: 2

🧹 Nitpick comments (6)
tests/e2e/orchestration-idle-mail-delivery.spec.ts (2)

244-248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace the expect.poll(...).toBe('pending') wrappers with direct assertions.

expect.poll returns on the first matching read. The row is already pending at this point, so the poll settles immediately and adds no waiting. The file states this exact caveat at lines 209-213. The preceding expectPointed and expectSubmitted calls already supply the time barrier. The same pattern appears at lines 269-273 and 361-365.

♻️ Proposed change
-    await expect
-      .poll(() => mailDisposition(readMailRow(userDataDir, messageId)), {
-        timeout: DELIVERY_TIMEOUT_MS
-      })
-      .toBe('pending')
+    expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending')

347-355: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

The 1s settle can make this test pass for the wrong reason.

If the worker_done waiter is not registered before line 358 sends the message, the push happens because no waiter existed at all, not because the waiter filtered the type out. The test still passes. The sibling test at line 300 fails loudly in the same situation, so only this one is affected. If the runtime exposes waiter state, poll for the registration instead of the fixed wait.

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

48-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Both specs copy the same runtime-polling helpers. The shared root cause is that no module holds the runtime title and worktree polling used by both new specs, so each spec redefines them. The two copies can drift as the runtime contract changes.

  • tests/e2e/orchestration-idle-mail-restore.spec.ts#L48-L74: move waitForRegisteredWorktree and waitForObservedTitle into a shared module, for example tests/e2e/helpers/orchestration-mail-runtime-wait.ts, and import them here along with POINTER_COMMAND and DELIVERY_TIMEOUT_MS.
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts#L139-L154: delete the local waitForObservedTitle and the inline worktree poll at lines 104-112, and import the shared versions instead.
tests/e2e/helpers/orchestration-mail-store.ts (1)

23-30: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Open read paths read-only and set a busy timeout.

withMailDb opens orchestration.db read-write without a timeout while the main process can write it. SyncDatabase supports readonly and timeout; use { readonly: true, timeout: 5000 } for readMailRow/readMailbox, and only make the write path from startCoordinatorRun use { readonly: false, timeout: 5000 }.

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

33465-33476: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assert an exact leaf count before indexing.

The test reads [...leaves.values()][0] but only checks size > 0. If the map ever contains more than the republished leaf, the assertions target an arbitrary record and the fence regression is not detected. Pin the count.

♻️ Proposed tightening
-      expect(leaves.size).toBeGreaterThan(0)
+      expect(leaves.size).toBe(1)
       const rebuilt = [...leaves.values()][0]
src/main/runtime/rpc/methods/orchestration.test.ts (1)

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

Assert the delivered handle, not just the call.

toHaveBeenCalled() passes for any argument. The routing contract this PR changes is which mailbox send notifies. If the handler ever passed the sender handle instead of the recipient handle, this assertion would still pass. Pin the argument to the recipient handle used in this test's setup.

expect(runtime.deliverPendingMessagesForHandle).toHaveBeenCalledWith(<recipient handle>)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7bdbbd78-88b7-4e3e-9b32-d349a2dbd2a5

📥 Commits

Reviewing files that changed from the base of the PR and between 7e60b33 and 460424a94b8699bf4557eaf139eb5f39171feebc.

📒 Files selected for processing (10)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts
  • 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 +177 to +185
} finally {
if (firstApp) {
await session.close(firstApp)
}
if (secondApp) {
await session.close(secondApp)
}
await session.dispose()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

A failing close skips the remaining cleanup.

If session.close(firstApp) rejects, lines 181-184 never run. session.dispose() is then skipped, and per tests/e2e/helpers/orca-restart.ts that call performs cleanupE2EDaemons and removes the profile directory. Leftover daemons and temp profiles can affect later specs in this worker. Isolate each close so dispose() always runs.

🛡️ Proposed fix
   } finally {
-    if (firstApp) {
-      await session.close(firstApp)
-    }
-    if (secondApp) {
-      await session.close(secondApp)
-    }
-    await session.dispose()
+    for (const app of [firstApp, secondApp]) {
+      if (!app) continue
+      try {
+        await session.close(app)
+      } catch (error) {
+        console.warn('[e2e] failed to close Electron app', error)
+      }
+    }
+    await session.dispose()
   }
📝 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
} finally {
if (firstApp) {
await session.close(firstApp)
}
if (secondApp) {
await session.close(secondApp)
}
await session.dispose()
}
} finally {
for (const app of [firstApp, secondApp]) {
if (!app) continue
try {
await session.close(app)
} catch (error) {
console.warn('[e2e] failed to close Electron app', error)
}
}
await session.dispose()
}

@Jinwoo-H

Jinwoo-H commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up from the requested real Codex smoke test:

The smoke test exposed a genuine runtime bug, not a reproduction-only failure. After synthetic Codex ready, Codex replaced the title with a neutral session title. Orca's foreground probe correctly proved codex was still running, but only restored the title tracker's status; pty.lastAgentStatus and leaf.lastAgentStatus remained null, so already-idle Run mail could not inject its pointer until a later idle transition.

Commit d21b68675b restores the PTY/leaf status from the foreground-confirmed tracker result and immediately retries pending mail when that status is idle. Its regression fails with zero PTY writes under the old tracker-only behavior.

Post-fix verification:

  • runtime + formatter unit tests: 1083 passed, 1 skipped
  • typecheck and lint: passed
  • rebuilt with pnpm exec electron-vite build --mode e2e
  • delivery e2e at --workers=1: 8 passed (1.1m)
  • restore e2e at --workers=1: 1 passed (12.6s)
  • real Codex worker → idle Codex coordinator: pointer delivered, check returned fixed real-agent smoke complete, body named orca, delivery acknowledged

@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: Pro Plus

Run ID: 1974953d-bd07-4f9f-bb92-74e1d9edc0ee

📥 Commits

Reviewing files that changed from the base of the PR and between 460424a94b8699bf4557eaf139eb5f39171feebc and d21b68675b356acd248df804e972077d64f9c0a7.

📒 Files selected for processing (4)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/agent-title-status.ts
  • src/shared/terminal-output-side-effects.ts

Comment on lines +16795 to +16810
const restoredStatus = this.ptyTitleTrackersByPtyId
.get(ptyId)
?.tracker.restoreLastAgentExit()
if (restoredStatus !== null && restoredStatus !== undefined) {
current.lastAgentStatus = restoredStatus
for (const leaf of this.getLeavesForPty(ptyId)) {
if (leaf.lastAgentStatus !== null) {
continue
}
// Why: the foreground agent disproved the neutral title's exit signal; keep runtime delivery state aligned with the restored tracker.
leaf.lastAgentStatus = restoredStatus
if (restoredStatus === 'idle') {
this.deliverPendingMessagesForLeaf(leaf)
}
}
}

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

Restore path skips resolving tui-idle waiters.

When restoredStatus is 'idle', this branch restores leaf.lastAgentStatus from null to 'idle' and delivers pending mail via deliverPendingMessagesForLeaf. Elsewhere, an equivalent null→idle transition (applyTrackedPtyTitle, around line 10313) also calls this.resolveTuiIdleWaiters(leaf) (and resolvePtyTuiIdleWaiters for the PTY record). This restore branch does not.

A caller blocked on terminal.wait --for tui-idle for this pane stays blocked even though the agent's idle status is confirmed here, until an unrelated future title change happens to trigger the resolution path.

🐛 Proposed fix to resolve tui-idle waiters on restore
         if (restoredStatus !== null && restoredStatus !== undefined) {
           current.lastAgentStatus = restoredStatus
+          if (restoredStatus === 'idle') {
+            this.resolvePtyTuiIdleWaiters(current, ptyId)
+          }
           for (const leaf of this.getLeavesForPty(ptyId)) {
             if (leaf.lastAgentStatus !== null) {
               continue
             }
             // Why: the foreground agent disproved the neutral title's exit signal; keep runtime delivery state aligned with the restored tracker.
             leaf.lastAgentStatus = restoredStatus
             if (restoredStatus === 'idle') {
+              this.resolveTuiIdleWaiters(leaf)
               this.deliverPendingMessagesForLeaf(leaf)
             }
           }
         }
📝 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 restoredStatus = this.ptyTitleTrackersByPtyId
.get(ptyId)
?.tracker.restoreLastAgentExit()
if (restoredStatus !== null && restoredStatus !== undefined) {
current.lastAgentStatus = restoredStatus
for (const leaf of this.getLeavesForPty(ptyId)) {
if (leaf.lastAgentStatus !== null) {
continue
}
// Why: the foreground agent disproved the neutral title's exit signal; keep runtime delivery state aligned with the restored tracker.
leaf.lastAgentStatus = restoredStatus
if (restoredStatus === 'idle') {
this.deliverPendingMessagesForLeaf(leaf)
}
}
}
const restoredStatus = this.ptyTitleTrackersByPtyId
.get(ptyId)
?.tracker.restoreLastAgentExit()
if (restoredStatus !== null && restoredStatus !== undefined) {
current.lastAgentStatus = restoredStatus
if (restoredStatus === 'idle') {
this.resolvePtyTuiIdleWaiters(current, ptyId)
}
for (const leaf of this.getLeavesForPty(ptyId)) {
if (leaf.lastAgentStatus !== null) {
continue
}
// Why: the foreground agent disproved the neutral title's exit signal; keep runtime delivery state aligned with the restored tracker.
leaf.lastAgentStatus = restoredStatus
if (restoredStatus === 'idle') {
this.resolveTuiIdleWaiters(leaf)
this.deliverPendingMessagesForLeaf(leaf)
}
}
}

@Jinwoo-H
Jinwoo-H force-pushed the fix-12953-orchestration-mail-pointer branch from d21b686 to 8bc659f Compare August 7, 2026 05:02
@Jinwoo-H

Jinwoo-H commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Rebased cleanly onto current main after #12584 merged. git range-diff confirms both Phase 1 commits are patch-identical; the follow-up fix is now 8bc659f83e. Reverification on the rebased head: 1093 unit tests passed, 1 skipped; typecheck/lint passed; rebuilt e2e; delivery 8/8 and restore 1/1 at --workers=1.

@coderabbitai

coderabbitai Bot commented Aug 7, 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.

@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

♻️ Duplicate comments (1)
tests/e2e/orchestration-idle-mail-delivery.spec.ts (1)

179-188: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Poll for both pointer fields in one stdin snapshot.

Line 187 performs a second stdin read after the command poll succeeds. If PTY output splits between those reads, the count assertion can fail. This reintroduces the previously reported test flake.

Proposed fix
 async function expectPointed(pane: AgentPane, count = 1): Promise<void> {
+  const noun = count === 1 ? 'message' : 'messages'
+  const countPhrase = `${count} orchestration ${noun}`
   await expect
-    .poll(() => pane.agent.readStdin(), {
-      timeout: DELIVERY_TIMEOUT_MS,
-      message: 'mail pointer never reached the agent process'
-    })
-    .toContain(POINTER_COMMAND)
-  const noun = count === 1 ? 'message' : 'messages'
-  expect(pane.agent.readStdin()).toContain(`${count} orchestration ${noun}`)
+    .poll(() => {
+      const stdin = pane.agent.readStdin()
+      return stdin.includes(POINTER_COMMAND) && stdin.includes(countPhrase)
+    }, {
+      timeout: DELIVERY_TIMEOUT_MS,
+      message: 'mail pointer never reached the agent process'
+    })
+    .toBe(true)
 }
🧹 Nitpick comments (1)
tests/e2e/orchestration-idle-mail-delivery.spec.ts (1)

374-392: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Use separate worker and coordinator panes.

Line 380 and Line 391 both use pane.handle. Direct-recipient delivery and Run-coordinator routing therefore produce the same PTY result. Use a distinct worker pane and assert that only the coordinator pane receives and submits the pointer.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 804708d0-06ff-45ae-8da0-c097ff52a5de

📥 Commits

Reviewing files that changed from the base of the PR and between 7e60b33 and 8bc659f.

📒 Files selected for processing (10)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/shared/agent-title-status.ts
  • src/shared/terminal-output-side-effects.ts
  • 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
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/shared/terminal-output-side-effects.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/shared/agent-title-status.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • tests/e2e/orchestration-idle-mail-restore.spec.ts
  • tests/e2e/helpers/orchestration-mail-pane-agent.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

Comment on lines +439 to +445
const checked = await client.call<{ messages: { id: string; body: string }[] }>(
'orchestration.check',
{ terminal: pane.handle, run: run.result.run.id }
)
expect(checked.result.messages).toEqual([
expect.objectContaining({ id: sent.result.message.id, body })
])

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Assert that orchestration.check consumes the mailbox row.

After orchestration.check returns, assert that mailDisposition(readMailRow(...)) becomes pulled. The current test proves retrieval but does not prove the required transition from pending unread mail to consumed mail.

@Jinwoo-H

Jinwoo-H commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the red Node 24/26 shard in 6b4bc00625.

Root cause: terminal-send-stale-leaf-liveness.test.ts used a partial orchestration DB fake and still asserted pre-PR message-body injection / delivered_at semantics. Updating it to the pointer contract exposed one real lifecycle bug: when PTY exit retired a delayed Enter, the old per-handle sequence watermark survived, so a same-ID replacement could not receive a fresh pointer. The runtime now retires the exited pane's terminal and Run watermarks together with its delivery flight.

Verification:

  • exact failing CI shard command: 275 files passed, 2 skipped; 2997 tests passed, 6 skipped
  • runtime + formatter + liveness suites: 1112 passed, 1 skipped
  • typecheck and full lint: passed
  • rebuilt via pnpm exec electron-vite build --mode e2e
  • delivery e2e at --workers=1: 8 passed (1.1m); one prior attempt had a fixture setup failure (No active terminal tab found) before the test body, then the full rerun passed
  • restore e2e at --workers=1: 1 passed (12.5s)
  • mutation removing watermark cleanup: same-ID respawn failed with 1 pointer instead of 2, and cleanup retained 1 watermark instead of 0

@Jinwoo-H
Jinwoo-H merged commit 2b42de1 into main Aug 7, 2026
46 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
)

Wake idle Run coordinators with durable orchestration mail pointers while keeping message payloads in the store until check consumes them. Preserve waiter, Cursor, restart, real Codex title, and PTY replacement behavior.\n\nPart of stablyai#12953.
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