Skip to content

fix(orchestration): wait for opencode's composer marker before worker-start's paste - #20451

Closed
juli-gonzalez wants to merge 2 commits into
stablyai:mainfrom
juli-gonzalez:fix/opencode-worker-start-composer-wait
Closed

juli-gonzalez wants to merge 2 commits into
stablyai:mainfrom
juli-gonzalez:fix/opencode-worker-start-composer-wait

Conversation

@juli-gonzalez

Copy link
Copy Markdown

What changed

worker-start gates injecting the dispatch preamble on the generic tui-idle
signal (runtime.waitForTerminal(handle, { condition: 'tui-idle' })), which
resolves on an OSC-title idle edge. opencode (and mimo-code, which shares its
config) enable bracketed paste almost immediately on launch but don't mount
their composer until roughly 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 PTY write
itself succeeded — Orca has no way to tell "written" from "landed in the
composer" with only tui-idle to 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-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, scanned by
createDraftPasteReadyScanner in src/shared/draft-paste-ready-scanner.ts) —
and is used by the "start workspace from issue" editable-draft-paste path
(waitForWorktreeStartupDraft in runtime-worktree-startup-readiness.ts), but
worker-start never called it.

Fix

  • src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts:
    add OrcaRuntimeService.waitForAgentComposerReady(handle, agent), a thin
    wrapper around the existing waitForWorktreeStartupDraft +
    getWorktreeStartupReadinessHost() — no new detection logic, it reuses the
    same 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 startLocalWorker right after the tui-idle wait succeeds,
    scoped to agents configured with the render-cursor-after-bracketed-paste
    signal (opencode, mimo-code). A timeout on the composer wait is
    best-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 that
    codex and a reused --terminal (no --agent) are unaffected.

Why this scope, not more

Evidence

  • Orca 1.4.200, opencode 1.18.25, macOS.
  • PTY-level repro: inject immediately after terminal creation → lost;
    inject after the composer shows "Ask anything..." → lands.
  • Stopgap verified before this fix landed: pre-warm the opencode terminal
    until the composer is on screen, then worker-start --terminal <handle>
    (no --agent, so the fix's new wait doesn't even engage) → state=ready
    and worker_done accepted 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.
  • Verified the new test fails on main (before this change) with
    The property "waitForAgentComposerReady" is not defined on the object.,
    by stashing the two source-file changes and re-running against the
    unmodified test.
  • Also ran the neighboring worker-start/readiness suites for regressions:
    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.
  • Limitation: I did not run the full test suite, pnpm run lint, or a
    production build — this is a ~930MB monorepo and a full run wasn't
    practical in the time available. lint-staged (oxlint + oxfmt) did run
    automatically via the repo's pre-commit hook and passed clean.

Related

…-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
@coderabbitai

coderabbitai Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The runtime now accepts an optional timeout for composer readiness. It forwards the timeout to worktree startup readiness and returns false when readiness fails or rejects. Local worker startup caps the wait by the caller timeout and the agent-specific draft-paste timeout. Tests cover the default and explicit timeout values.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 3963c

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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 Fixes # entry, Vis… Add all required template sections. Include an ELI5 summary, a separate Why section, a linked issue using Fixes #, Visual Proof with attachments or N/A and a reason, AI Disclosure details or the applicable internal-contributor omission,…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: waiting for opencode's composer marker before worker-start pastes the dispatch preamble.
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.
Full details: Description check

Explanation

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 Fixes # entry, Visual Proof or N/A justification, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the Checklist.

Resolution

Add all required template sections. Include an ELI5 summary, a separate Why section, a linked issue using Fixes #, Visual Proof with attachments or N/A and a reason, AI Disclosure details or the applicable internal-contributor omission, Review content, the Agent skill upstream boundary checkbox, Notes, and the completed Checklist.

  • Fix all pre-merge checks with AI

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6470f65b-1f9f-421b-beae-7115c4898af3

📥 Commits

Reviewing files that changed from the base of the PR and between e86cba8 and c5058f3.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts
  • src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts
  • src/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.

Comment on lines +16 to +85
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()
})

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

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The 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

  • waitForAgentComposerReady helper — orca-runtime-get-worktree-terminal-provisioning-host.ts wraps the existing waitForWorktreeStartupDraft scanner as Promise<boolean>; no new detection logic.
  • Local worker-start gate — local-worker-start.ts waits for the opencode/mimo-code composer marker after tui-idle and 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 --terminal handles 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?

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

agent &&
TUI_AGENT_CONFIG[agent].draftPasteReadySignal === 'render-cursor-after-bracketed-paste'
) {
await runtime.waitForAgentComposerReady(terminalHandle, agent)

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.

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')

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.

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
@juli-gonzalez

juli-gonzalez commented Sep 13, 2026 •

Copy link
Copy Markdown
Author

Second pass: independent review + live validation with real OpenCode workers

Ran /code-review on this PR (commit c5058f33) and it found 2 real
findings, now fixed in 3963cedb:

  1. waitForAgentComposerReady was called with no try/catch. Its own
    JSDoc promises "proceed anyway" on failure, but a rejection (e.g. the
    PTY dying right between placeWorkerAgent and this call) would
    propagate and fail the whole dispatch — exactly what the best-effort
    wait was supposed to avoid. The sibling caller
    (pasteWorktreeStartupDraftWhenReady) already wraps the same call in
    .catch(...) for this reason. Fixed at the source: waitForAgentComposerReady
    now catches internally and always resolves, so the "never throws"
    contract its own doc already claimed is now actually guaranteed for any
    caller.
  2. 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).
    Every other wait in startLocalWorker respects
    params.timeoutMs ?? 60_000. Now passes
    min(params.timeoutMs ?? 60_000, <agent's own default>) as an override —
    caps but never extends the existing 8s default, so the common
    (unspecified --timeout-ms) case is unchanged.

A third finding (the tui-idle wait and the composer wait run sequentially
instead of in parallel, which in the worst case adds the full 8s timeout if
the composer happened to mount before tui-idle resolved) is left
intentionally unfixed: it's a latency concern, not a correctness one —
it never drops the prompt, it just adds up to 8s in a rare timing window —
and parallelizing it would touch the shared tui-idle path every agent
uses. Leaving it as a low-risk future improvement.

Live validation (not just unit tests)

On top of the static review, I dispatched 2 real workers with
orca orchestration worker-start --agent opencode against a worktree
checked out on this fix, each running its own /code-review and
/security-review over the diff:

  • First attempt for each worker, on the installed Orca 1.4.200 (fix not
    applied to the binary)
    : 2/2 injections were lost — the composer stayed
    on "Ask anything..." despite state=ready / stage=input_accepted.
    Reproduces exactly the bug reported 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.
  • Recovered with the documented stopgap (worker-abandon + retry via
    --terminal <handle> on the already "pre-warmed" terminal, composer
    visible): 2/2 delivered the full preamble and completed with a real
    worker_done.
  • Verdicts from the real workers (independent of my own review):
    • Security review (opencode, DeepSeek V4 Flash): APPROVED, no
      findings.
    • Code review (opencode, DeepSeek V4 Flash), run against c5058f33
      before the second commit: APPROVED, flagging the same 2 LOW
      findings my own /code-review caught — independent cross-confirmation
      that they were real but non-blocking. Already fixed in 3963cedb.

Extended worker-start-opencode-composer-wait.test.ts (now 5 cases) to
cover the new timeout argument and its capping; the 148/148 neighboring
test sweep is still green, and pnpm run typecheck is still 0.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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 timeoutMs via Math.min, and threaded an optional timeoutOverrideMs through waitForWorktreeStartupDraft / resolveDraftPasteReadyTimeoutMs.
  • Made waitForAgentComposerReady non-throwing: a host/PTY failure now resolves false (best effort) rather than failing the whole worker start.
  • Added a test pinning the explicit --timeout-ms cap and updated the default-timeout assertion to the new call shape.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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

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.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b398b7a9-11f8-420b-94c3-691c8f44e09e

📥 Commits

Reviewing files that changed from the base of the PR and between c5058f3 and 3963ced.

📒 Files selected for processing (4)
  • src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts
  • src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts
  • src/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))

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

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.

@juli-gonzalez

Copy link
Copy Markdown
Author

Independent adversarial review

Verdict: approve — no correctness bugs found, no fixes pushed.

I went in looking specifically for a TUI_AGENT_CONFIG[agent] crash, a double-wait against Codex, a regression for --terminal reuse, and a test that just echoes its own mock. None of those held up. Details below, each marked verified (traced the code/ran it) or assumed (inferred, not executed).

1. TUI_AGENT_CONFIG[agent] indexing safety — verified, not a bug

local-worker-start.ts:208 indexes TUI_AGENT_CONFIG[agent] only inside agent &&, and agent's only source is prepareLocalWorkerStart → resolveWorkerStartAgent (worker-start-validation.ts:134-160), which throws agent_unconfigured unless isTuiAgent(args.agent) passes when no --terminal is given. TUI_AGENT_CONFIG is declared Record<TuiAgent, TuiAgentConfig> (tui-agent-config.ts), a total map over the closed TuiAgent union, so once agent is narrowed to TuiAgent the index can never miss. There's exactly one call site into startLocalWorker (workers.ts:69), so there's no alternate path that could hand in an unvalidated string. Ran pnpm run typecheck:tsc:node — clean, confirming the narrowing also type-checks.

2. Ordering vs tui-idle and vs Codex PRs #14888 / #18019 — verified, no conflict

The new wait only fires when draftPasteReadySignal === 'render-cursor-after-bracketed-paste', which today only opencode/mimo-code have (tui-agent-config.ts, unmodified by this PR). Codex uses 'codex-composer-prompt', so the branch is a no-op for it regardless of what #14888/#18019 do. Checked file overlap explicitly (gh pr view 14888/18019 --json files): neither touches local-worker-start.ts, orca-runtime-get-worktree-terminal-provisioning-host.ts, or runtime-worktree-startup-readiness.ts — zero merge-conflict surface, zero double-wait risk.

3. --terminal reuse skipping the wait — verified intentional, residual gap is pre-existing (informational only)

--terminal + --agent are mutually exclusive (worker-start-validation.ts), so a reused terminal always has agent === undefined, short-circuiting agent && and skipping the new wait — confirmed by the harness test (does not gate a reused --terminal). This matches the PR description's documented stopgap (pre-warm until composer is visible, then reuse). One caveat, not introduced by this diff: if a coordinator reuses a freshly created, not pre-warmed opencode terminal via --terminal, the original lost-injection race is still there, because agent is never known on that path. That's a pre-existing structural gap in the --terminal reuse flow, not a regression from this change, and the PR author already calls it out under "Why this scope, not more" — flagging for visibility only, not requesting a fix here.

4. Timeout/failure handling — verified correct

waitForAgentComposerReady is try/catch-wrapped and always resolves (orca-runtime-get-worktree-terminal-provisioning-host.ts:37-53); its false/timeout result is intentionally ignored by the caller, matching the pre-existing pasteWorktreeStartupDraftWhenReady().catch() best-effort contract. The timeout math checks out: Math.min(params.timeoutMs ?? 60_000, resolveDraftPasteReadyTimeoutMs(agent)) for opencode/mimo-code (no per-agent override configured) resolves to the 8000ms default (draft-paste-ready-timeout.ts), and an explicit shorter --timeout-ms correctly overrides it — both paths are asserted in the new test and I confirmed the arithmetic by hand.
Latency note (pre-existing behavior, not new): for an already-ready composer, the wait resolves fast only if readRecentOutput's replay buffer still contains the bracketed-paste anchor + show-cursor marker; if that window has rolled off, this adds up to the full ~8s to every opencode/mimo-code worker-start. This is inherited from the already-shipped waitForWorktreeStartupDraft scanner (unchanged by this diff), so it's out of scope for this PR, but worth someone's attention if worker-start latency regresses in practice.

5. Test quality — verified, not a mock echo

worker-start-opencode-composer-wait.test.ts runs through createOrchestrationWorkerReleaseHarness, which instantiates a real OrcaRuntimeService and only mocks I/O-boundary methods (PTY/terminal calls); waitForAgentComposerReady itself is not pre-mocked in the harness setup, only spied per-test. So the assertions exercise the actual startLocalWorker control flow, not a fabricated substitute. It does more than echo the mock: it asserts call order (waitForAgentComposerReady before sendTerminalAgentPrompt), asserts scoping (codex: not called; reused --terminal: not called), and asserts the timeout-capping math end-to-end. Ran it directly: pnpm exec vitest run src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts → 5/5 passed.

6. mimo-code sharing the signal — verified pre-existing, intentional

tui-agent-config.ts (not touched by this diff) already mapped mimo-code to 'render-cursor-after-bracketed-paste' with an explicit comment ("mirrors opencode's cursor-gated signal by parity; mimo's startup stream isn't separately validated"). This PR just reuses that existing config; it isn't introducing or expanding the mimo-code assumption.

What I ran

  • gh pr diff 20451 --repo stablyai/orca (full diff review)
  • Shallow clone of juli-gonzalez:fix/opencode-worker-start-composer-wait, pnpm install
  • pnpm exec vitest run src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts → 5/5 passed
  • pnpm run typecheck:tsc:node → clean, no errors
  • gh pr view 14888/18019 --repo stablyai/orca --json files → confirmed no file overlap with this PR

No fixes were applied — nothing found rose to the level of a correctness bug.

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