Repository navigation
fix(orchestration): wait for opencode's composer marker before worker-start's paste - #20451
juli-gonzalez wants to merge 2 commits into
Conversation
…-start's paste
worker-start gates the dispatch preamble injection on the generic tui-idle
signal (runtime.waitForTerminal({ condition: 'tui-idle' })), which resolves
on an OSC-title idle edge. opencode (and mimo-code, which shares its config)
enable bracketed paste ~immediately on launch but don't mount their composer
until ~3.5s later; tui-idle can be satisfied during that quiet gap, so
worker-start pastes the preamble onto the boot splash instead of the
composer. The paste is silently dropped, but worker-start still reports
state=ready / stage=input_accepted because the write itself succeeded.
The dispatch capability token lives only inside the dropped preamble (the
DB stores just a hash), so a lost injection can't be recovered by
re-injecting -- the coordinator has to worker-abandon and retry the whole
dispatch.
opencode's own composer-mount marker already exists
(TUI_AGENT_CONFIG.opencode.draftPasteReadySignal ===
'render-cursor-after-bracketed-paste', added in #6798) and is used by the
"start workspace from issue" draft-paste path
(waitForWorktreeStartupDraft), but worker-start never called it.
Fix: add OrcaRuntimeService.waitForAgentComposerReady(handle, agent), a
thin wrapper around the existing waitForWorktreeStartupDraft +
getWorktreeStartupReadinessHost, and call it from startLocalWorker right
after the tui-idle wait succeeds, scoped to agents configured with the
render-cursor-after-bracketed-paste signal (opencode, mimo-code). Codex
already has its own composer-wait fix in flight upstream (#14888, #18019)
and is intentionally left untouched here to avoid duplicating that work;
structured sessions and a reused --terminal (no --agent) are unaffected.
A timeout on the composer wait is treated as best-effort (proceed anyway),
matching the existing draft-paste path's behavior.
Verified on Orca 1.4.200, opencode 1.18.25, macOS: PTY-level repro showed
inject-immediately-after-terminal-creation is lost while
inject-after-"Ask anything..."-is-visible lands; a stopgap harness that
pre-warms the terminal until the composer is on screen before calling
worker-start with --terminal confirms state=ready with a delivered prompt.
Adds a focused unit test (worker-start-opencode-composer-wait.test.ts)
that fails on main (no waitForAgentComposerReady exists) and passes with
this change; verified manually by stashing the fix and re-running the
test.
Refs #13911, #17741.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XQqgVMU8gMxcA5fqgMPyAd
📝 WalkthroughWalkthroughThe runtime now accepts an optional timeout for composer readiness. It forwards the timeout to worktree startup readiness and returns Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Worker startup can delay dispatch beyond its configured readiness timeout when terminal readiness is slow. Preserve the remaining budget before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the bug, fix, scope, evidence, related issues, and testing. However, it omits several required template sections, including ELI5, Why, Linked Issue with a Resolution Add all required template sections. Include an ELI5 summary, a separate Why section, a linked issue using
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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 6470f65b-1f9f-421b-beae-7115c4898af3
📒 Files selected for processing (3)
src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.tssrc/main/runtime/rpc/methods/orchestration/worker/local-worker-start.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| it('waits for the opencode composer marker before delivering the preamble', async () => { | ||
| const composerWait = vi | ||
| .spyOn(harness.runtime, 'waitForAgentComposerReady') | ||
| .mockResolvedValue(true) | ||
| const sends: string[] = [] | ||
| vi.spyOn(harness.runtime, 'sendTerminalAgentPrompt').mockImplementation(async () => { | ||
| sends.push('sendTerminalAgentPrompt') | ||
| return { handle: 'term_worker', accepted: true, bytesWritten: 1 } | ||
| }) | ||
| composerWait.mockImplementation(async () => { | ||
| sends.push('waitForAgentComposerReady') | ||
| return true | ||
| }) | ||
|
|
||
| const task = harness.db.createTask({ | ||
| spec: 'opencode composer fixture', | ||
| runId: harness.activeRunId | ||
| }) | ||
| const result = (await harness.call('orchestration.workerStart', { | ||
| task: task.id, | ||
| from: 'term_coord', | ||
| agent: 'opencode' | ||
| })) as { state: string } | ||
|
|
||
| expect(result.state).toBe('ready') | ||
| expect(composerWait).toHaveBeenCalledWith('term_worker', 'opencode') | ||
| expect(sends).toEqual(['waitForAgentComposerReady', 'sendTerminalAgentPrompt']) | ||
| }) | ||
|
|
||
| it('proceeds anyway when the opencode composer marker times out', async () => { | ||
| vi.spyOn(harness.runtime, 'waitForAgentComposerReady').mockResolvedValue(false) | ||
|
|
||
| const task = harness.db.createTask({ | ||
| spec: 'opencode timeout fixture', | ||
| runId: harness.activeRunId | ||
| }) | ||
| const result = (await harness.call('orchestration.workerStart', { | ||
| task: task.id, | ||
| from: 'term_coord', | ||
| agent: 'opencode' | ||
| })) as { state: string } | ||
|
|
||
| expect(result.state).toBe('ready') | ||
| }) | ||
|
|
||
| it('does not gate an unrelated agent (codex) on the opencode composer marker', async () => { | ||
| const composerWait = vi | ||
| .spyOn(harness.runtime, 'waitForAgentComposerReady') | ||
| .mockResolvedValue(true) | ||
|
|
||
| const task = harness.db.createTask({ spec: 'codex fixture', runId: harness.activeRunId }) | ||
| const result = (await harness.call('orchestration.workerStart', { | ||
| task: task.id, | ||
| from: 'term_coord', | ||
| agent: 'codex' | ||
| })) as { state: string } | ||
|
|
||
| expect(result.state).toBe('ready') | ||
| expect(composerWait).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('does not gate a reused --terminal (no --agent, e.g. a pre-warmed handle)', async () => { | ||
| const composerWait = vi | ||
| .spyOn(harness.runtime, 'waitForAgentComposerReady') | ||
| .mockResolvedValue(true) | ||
|
|
||
| await harness.startWorker({ terminal: 'term_worker' }) | ||
|
|
||
| expect(composerWait).not.toHaveBeenCalled() | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Add mimo-code coverage to the composer gate tests
opencode and mimo-code both use promptInjectionMode: 'flag-prompt' and draftPasteReadySignal: 'render-cursor-after-bracketed-paste', so both reach the production composer gate. The tests cover only opencode. Parameterize the ordering and timeout tests over opencode and mimo-code, including the expected waitForAgentComposerReady argument. Otherwise, a regression in the mimo-code path can pass these tests.
There was a problem hiding this comment.
Important
The fix targets only the local worker-start path. worker-start --on <server> still pastes the preamble on tui-idle alone, so a cold opencode terminal created on a remote host still drops it. Please either extend the guard to the federated attach handler or state that remote starts remain affected.
Reviewed changes
waitForAgentComposerReadyhelper —orca-runtime-get-worktree-terminal-provisioning-host.tswraps the existingwaitForWorktreeStartupDraftscanner asPromise<boolean>; no new detection logic.- Local worker-start gate —
local-worker-start.tswaits for the opencode/mimo-code composer marker aftertui-idleand before the preamble, with a best-effort timeout. - New test file — asserts the wait precedes the send for opencode, that a timeout still proceeds, and that codex and reused
--terminalhandles are not gated.
⚠️ Remote (--on) worker start still pastes on tui-idle alone
orchestration.workerStart routes params.on through startFederatedWorker to the remote orchestration.federationAttachStart handler, which cold-starts the agent terminal and then waits only on waitForTerminal(..., 'tui-idle') before pasting the dispatch preamble. The opencode boot gap this PR fixes is identical there, so a remote opencode/mimo-code worker still silently loses the preamble while the attachment reports ready. agent is already resolved in that handler, so the same guard is directly applicable.
Technical details
# Federated attach start lacks the composer gate
## Affected sites
- `src/main/runtime/rpc/methods/orchestration/federation/federation.ts:215` — `waitForTerminal(terminalHandle, { condition: 'tui-idle', ... })`, the only readiness gate before the paste.
- `src/main/runtime/rpc/methods/orchestration/federation/federation.ts:249` — `sendTerminalAgentPrompt(terminalHandle, buildDispatchPreamble(...))` pastes immediately after.
- `src/main/runtime/rpc/methods/orchestration/worker/workers.ts:56-67` — routes `params.on` to `startFederatedWorker`.
- `src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts:163` — calls the remote `orchestration.federationAttachStart`.
## Required outcome
- A remote (`--on`) worker start on opencode/mimo-code must wait for the same composer-mount marker before pasting the preamble, or the PR must explicitly document that remote starts remain affected.
## Suggested approach (optional)
- Apply the same `TUI_AGENT_CONFIG[agent].draftPasteReadySignal === 'render-cursor-after-bracketed-paste'` guard in `federationAttachStart` after its `tui-idle` wait, reusing `waitForAgentComposerReady` (`agent` is resolved at `federation.ts:54`).
## Open questions for the human (optional)
- Is the federated/SSH path intentionally out of scope for this fix (e.g. remote-host version skew), or was it missed?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| agent && | ||
| TUI_AGENT_CONFIG[agent].draftPasteReadySignal === 'render-cursor-after-bracketed-paste' | ||
| ) { | ||
| await runtime.waitForAgentComposerReady(terminalHandle, agent) |
There was a problem hiding this comment.
The returned boolean is dropped, so a composer timeout — which is exactly the opencode race this PR fixes — still leaves no trace beyond an ordinary state=ready receipt. Consider logging a warning (the draft-paste path does this in pasteWorktreeStartupDraftWhenReady) or folding the value into the receipt, so a timed-out paste is distinguishable from a landed one.
| agent: 'opencode' | ||
| })) as { state: string } | ||
|
|
||
| expect(result.state).toBe('ready') |
There was a problem hiding this comment.
This test only pins that a timeout doesn't block the start; it would still pass if the code skipped the preamble after waitForAgentComposerReady returned false, which is the "proceed anyway" behavior the wrapper JSDoc promises. Assert that sendTerminalAgentPrompt was still called — e.g. the sends ordering pattern from the first test — to actually cover best-effort delivery.
…throw Address two findings from an independent code-review pass on the previous commit: - waitForAgentComposerReady was awaited with no try/catch at its only call site. Its own doc comment promises "proceed anyway" (best effort) on failure, but a rejection from the underlying host (e.g. the PTY tearing down between placement and this call) would propagate straight into startLocalWorker's outer catch and fail the whole dispatch -- exactly the outcome the composer wait is supposed to avoid. The pre-existing sibling caller, pasteWorktreeStartupDraftWhenReady, already wraps the same underlying call in `.catch(...)` for this reason. Fixed at the source instead of the call site: waitForAgentComposerReady now catches internally and always resolves, so the "never throws" contract its own JSDoc already claimed is now actually guaranteed for every caller. - The composer wait ignored the caller's own `--timeout-ms` and always used the agent's fixed hard timeout (8s default for opencode/mimo-code, via resolveDraftPasteReadyTimeoutMs). Every other wait in startLocalWorker is bounded by `params.timeoutMs ?? 60_000`; this one wasn't, so an explicit short --timeout-ms no longer bounded total dispatch latency the way it does everywhere else in the same function. Threaded an optional timeoutOverrideMs through waitForAgentComposerReady -> waitForWorktreeStartupDraft -> resolveDraftPasteReadyTimeoutMs (already built to accept an override), and pass min(params.timeoutMs ?? 60_000, <agent's own default>) from startLocalWorker -- this caps but never extends the existing 8s default, so the common (unspecified --timeout-ms) case is unchanged. Extends worker-start-opencode-composer-wait.test.ts: the existing "waits for the marker" test now asserts the third (timeout) argument, and a new test asserts an explicit short --timeout-ms is forwarded uncapped-up (i.e. capped down) to the composer wait. Verified: the extended test file passes (5/5), the same 10-file/148-test neighboring sweep from the previous commit still passes with no regressions, and `pnpm run typecheck` exits 0. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XQqgVMU8gMxcA5fqgMPyAd
Second pass: independent review + live validation with real OpenCode workersRan
A third finding (the Live validation (not just unit tests)On top of the static review, I dispatched 2 real workers with
Extended |
There was a problem hiding this comment.
ℹ️ No critical issues — one minor contract nit inline.
Reviewed changes
Reviewed the delta since the prior pullfrog review (c5058f3 → 3963ced): the composer wait now respects the caller's timeout budget and can no longer throw.
- Capped the opencode/mimo-code composer wait at the caller's
timeoutMsviaMath.min, and threaded an optionaltimeoutOverrideMsthroughwaitForWorktreeStartupDraft/resolveDraftPasteReadyTimeoutMs. - Made
waitForAgentComposerReadynon-throwing: a host/PTY failure now resolvesfalse(best effort) rather than failing the whole worker start. - Added a test pinning the explicit
--timeout-mscap and updated the default-timeout assertion to the new call shape.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| * Waits for `agent`'s own composer-mount marker (the same PTY-output scanner that gates the | ||
| * editable "start workspace from issue" draft paste) instead of the generic tui-idle signal, | ||
| * which fires on OSC-title idle and can resolve while the TUI is still on its splash screen. | ||
| * `timeoutMs`, when given, caps the agent's own hard timeout (never extends it) so a caller |
There was a problem hiding this comment.
The JSDoc promises timeoutMs "caps the agent's own hard timeout (never extends it)", but the implementation passes it straight through as waitForWorktreeStartupDraft's timeoutOverrideMs, and resolveDraftPasteReadyTimeoutMs honors an override unconditionally — so a caller passing a value above the agent default extends the wait. The current call site is safe only because it pre-clamps with Math.min; clamping inside this wrapper (or naming the parameter timeoutOverrideMs and dropping the cap claim) keeps the contract honest for the follow-up callers this API invites.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b398b7a9-11f8-420b-94c3-691c8f44e09e
📒 Files selected for processing (4)
src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.tssrc/main/runtime/rpc/methods/orchestration/worker/local-worker-start.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.tssrc/main/runtime/runtime-worktree-startup-readiness.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| await runtime.waitForAgentComposerReady( | ||
| terminalHandle, | ||
| agent, | ||
| Math.min(params.timeoutMs ?? 60_000, resolveDraftPasteReadyTimeoutMs(agent)) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use the remaining readiness budget for the composer wait.
orchestration.workerStart passes params.timeoutMs as the readiness timeout. startLocalWorker can consume most of that timeout in waitForTerminal and then pass the same full timeout to waitForAgentComposerReady. The sequential waits can therefore delay preamble dispatch beyond the caller's overall budget. Record a deadline before the initial wait and pass Math.min(remainingMs, resolveDraftPasteReadyTimeoutMs(agent)). Add a test with delayed tui-idle readiness. The existing timeout test does not establish an intentional independent-budget exception.
Independent adversarial reviewVerdict: approve — no correctness bugs found, no fixes pushed. I went in looking specifically for a 1.
|

What changed
worker-startgates injecting the dispatch preamble on the generictui-idlesignal (
runtime.waitForTerminal(handle, { condition: 'tui-idle' })), whichresolves on an OSC-title idle edge. opencode (and
mimo-code, which shares itsconfig) enable bracketed paste almost immediately on launch but don't mount
their composer until roughly 3.5s later.
tui-idlecan be satisfied duringthat quiet gap, so
worker-startpastes the preamble onto the boot splashinstead of the composer. The paste is silently dropped, but
worker-startstill reports
state=ready/stage=input_accepted, because the PTY writeitself succeeded — Orca has no way to tell "written" from "landed in the
composer" with only
tui-idleto go on.The dispatch capability token lives only inside the dropped preamble (the DB
stores just a hash), so a lost injection can't be recovered by re-injecting —
the coordinator has to
worker-abandonand retry the whole dispatch.opencode's own composer-mount marker already exists —
TUI_AGENT_CONFIG.opencode.draftPasteReadySignal === 'render-cursor-after-bracketed-paste'(added in #6798, scanned bycreateDraftPasteReadyScannerinsrc/shared/draft-paste-ready-scanner.ts) —and is used by the "start workspace from issue" editable-draft-paste path
(
waitForWorktreeStartupDraftinruntime-worktree-startup-readiness.ts), butworker-startnever called it.Fix
src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts:add
OrcaRuntimeService.waitForAgentComposerReady(handle, agent), a thinwrapper around the existing
waitForWorktreeStartupDraft+getWorktreeStartupReadinessHost()— no new detection logic, it reuses thesame PTY-output scanner Reliably deliver the issue prompt into opencode's composer #6798 already ships.
src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts:call it from
startLocalWorkerright after thetui-idlewait succeeds,scoped to agents configured with the
render-cursor-after-bracketed-pastesignal (opencode,
mimo-code). A timeout on the composer wait isbest-effort (proceed anyway, matching the existing draft-paste path's
behavior) rather than a hard failure.
src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts(new): asserts the composer wait is called before the preamble is sent for
agent: 'opencode', that a timeout doesn't block the dispatch, and thatcodexand a reused--terminal(no--agent) are unaffected.Why this scope, not more
codex-composer-promptconfigured, but it's intentionallynot touched here — fix(orchestration): wait for Codex composer before paste #14888 and fix(terminal): stop treating the Codex boot header as tui-idle readiness #18019 are open PRs adding a more involved
composer-wait (with abort/generation handling) to Codex's write path
specifically, and gating Codex through this change too would conflict with
that work. Grok's
grok-composer-promptsignal is untouched for the same"don't expand scope beyond the reported bug" reason — nothing in [Bug]: Prompt Injection fails if there are delays with loading Opencode #13911 /
[Bug]: supervised worker-start: lost prompt injection reported as input_accepted, dispatch capability bound to wrong pane #17741 reports it, and I have no repro for it.
branch entirely (they resolve through
awaitStructuredWorkerSetupGateinstead), so they're unaffected.
worker-start --terminal <handle>reuse with no--agent(the documentedstopgap below) is also unaffected — Orca doesn't know the agent type there,
so it can't select a signal, and the existing
tui-idlewait is enough oncethe terminal is already warm.
Evidence
inject after the composer shows "Ask anything..." → lands.
until the composer is on screen, then
worker-start --terminal <handle>(no
--agent, so the fix's new wait doesn't even engage) →state=readyand
worker_doneaccepted end to end (task completed, worker succeeded).This confirms the delivery mechanism itself is sound once the composer is
actually up — the bug is purely about when Orca pastes.
Testing
pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts— 4/4 pass.main(before this change) withThe property "waitForAgentComposerReady" is not defined on the object.,by stashing the two source-file changes and re-running against the
unmodified test.
worker-start-terminal-target.test.ts,worker-start-prompt-contract.test.ts,worker-start-budgets.test.ts,worker-start-outcome-classification.test.ts,worker-start-prompt-budget.test.ts,composed-workers.test.ts,workers-new-worktree.test.ts,tui-agent-startup.test.ts,draft-paste-ready-scanner.test.ts— 147/147 pass across all 10 files.pnpm run typecheck(config/scripts/run-typecheck-projects-in-parallel.mjs,the repo's parallel per-project typecheck) — exits 0.
pnpm run lint, or aproduction build — this is a ~930MB monorepo and a full run wasn't
practical in the time available.
lint-staged(oxlint + oxfmt) did runautomatically via the repo's pre-commit hook and passed clean.
Related
loading Opencode": this is the same race, first reported against opencode.
input_accepted-but-lost defect thisPR fixes (there against Codex) and a second, unrelated defect (dispatch
capability bound to the wrong pane) that this PR does not address.
fix(terminal): stop treating the Codex boot header as tui-idle readiness #18019 ("stop treating the Codex boot header as tui-idle readiness") — both
are open, Codex-specific, and left untouched by this change.
draftPasteReadySignal/render-cursor-after-bracketed-pastedetectorthis PR reuses, for a different call site (editable draft paste, not
worker-start).