From c5058f3316fcc7a536515c0940a4358a1ec8ae38 Mon Sep 17 00:00:00 2001 From: Julian Gonzalez <32027782+juli-gonzalez@users.noreply.github.com> Date: Sun, 13 Sep 2026 02:00:42 -0300 Subject: [PATCH 1/2] fix(orchestration): wait for opencode's composer marker before worker-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 Claude-Session: https://claude.ai/code/session_01XQqgVMU8gMxcA5fqgMPyAd --- ...get-worktree-terminal-provisioning-host.ts | 22 ++++- .../worker/local-worker-start.ts | 14 +++ ...orker-start-opencode-composer-wait.test.ts | 86 +++++++++++++++++++ 3 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts diff --git a/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts b/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts index d9d6b2acfb93..6329d0957ba2 100644 --- a/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts +++ b/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts @@ -5,10 +5,14 @@ import type { WorktreeTerminalProvisioningHost } from './runtime-worktree-terminal-provisioning' import type { TerminalCreateOptions } from './runtime-terminal-contracts' -import type { WorktreeStartupReadinessHost } from './runtime-worktree-startup-readiness' +import { + waitForWorktreeStartupDraft, + type WorktreeStartupReadinessHost +} from './runtime-worktree-startup-readiness' import { prefetchWorktreeCreateBase } from '../worktree-create-base-prefetch' import { prepareWorktreeCreateForRepo } from '../worktree-create-preparation' import { getWorktreeCreatePrefetchGitOptions } from '../project-runtime-git-options' +import type { TuiAgent } from '../../shared/tui-agent' export class OrcaRuntimeWithGetWorktreeTerminalProvisioningHost extends OrcaRuntimeWithActivateManagedWorktree { protected getWorktreeTerminalProvisioningHost(): WorktreeTerminalProvisioningHost { @@ -40,6 +44,22 @@ export class OrcaRuntimeWithGetWorktreeTerminalProvisioningHost extends OrcaRunt } } + /** + * 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. + * Resolves `false` on the agent's own hard timeout — callers should treat that as "proceed + * anyway" (best effort), the same way the draft-paste path does, not as a hard failure. + */ + async waitForAgentComposerReady(handle: string, agent: TuiAgent): Promise { + const ptyId = await waitForWorktreeStartupDraft( + this.getWorktreeStartupReadinessHost(), + handle, + agent + ) + return ptyId !== null + } + async prefetchManagedWorktreeCreateBase(args: { repoSelector: string baseBranch?: string diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index f8cd1033c97c..3db872e93027 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -1,5 +1,6 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' import { describeTerminalWaitBlockedReason } from '../../../../../../shared/terminal-wait-blocked-reason-legacy-alias' +import { TUI_AGENT_CONFIG } from '../../../../../../shared/tui-agent-config' import type { OrchestrationDb } from '../../../../orchestration/db' import type { RunRow, TaskRow } from '../../../../orchestration/types' import { resolveDispatchCreator } from '../runs/dispatch-creator' @@ -194,6 +195,19 @@ export async function startLocalWorker(args: { ) } } + // tui-idle fires on the generic OSC-title idle edge. Agents that enable bracketed paste + // before their composer actually mounts (opencode, mimo-code) can hit that edge while still + // on the boot splash, so the preamble below lands on a screen with no composer to catch it + // and is silently dropped. Wait for the agent's own composer-mount marker on top of + // tui-idle for just those agents — Codex has its own composer-wait fix in flight upstream, + // and structured/other agents are unaffected. + if ( + !structuredSession && + agent && + TUI_AGENT_CONFIG[agent].draftPasteReadySignal === 'render-cursor-after-bracketed-paste' + ) { + await runtime.waitForAgentComposerReady(terminalHandle, agent) + } const terminalAuthority = requireWorkerAuthority(runtime, terminalHandle) const capability = db.prepareStartingWorkerAuthority({ dispatchId: started.dispatch.id, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts new file mode 100644 index 000000000000..875c6d1ac93b --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' + +// tui-idle fires on the generic OSC-title idle edge. opencode (and mimo-code, which shares its +// config) enable bracketed paste before their composer actually mounts, so tui-idle can resolve +// on their boot splash: worker-start then pastes the dispatch preamble into a screen with no +// composer to catch it, and the preamble is silently dropped even though the receipt reports +// `input_accepted` / `ready`. This asserts worker-start waits for opencode's own composer-mount +// marker (`waitForAgentComposerReady`, reusing the existing render-cursor-after-bracketed-paste +// detector) before writing the preamble, and that unrelated agents are unaffected. +describe('worker-start composer readiness for opencode', () => { + const harness = createOrchestrationWorkerReleaseHarness() + beforeEach(() => harness.setup()) + afterEach(() => harness.cleanup()) + + 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() + }) +}) From 3963cedbdd5bd440d219d4d7756420a5e38114c1 Mon Sep 17 00:00:00 2001 From: Julian Gonzalez <32027782+juli-gonzalez@users.noreply.github.com> Date: Sun, 13 Sep 2026 02:31:13 -0300 Subject: [PATCH 2/2] fix(orchestration): make the composer wait honor timeoutMs and never 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, ) 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 Claude-Session: https://claude.ai/code/session_01XQqgVMU8gMxcA5fqgMPyAd --- ...get-worktree-terminal-provisioning-host.ts | 32 +++++++++++++------ .../worker/local-worker-start.ts | 11 ++++++- ...orker-start-opencode-composer-wait.test.ts | 28 +++++++++++++++- .../runtime-worktree-startup-readiness.ts | 8 +++-- 4 files changed, 66 insertions(+), 13 deletions(-) diff --git a/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts b/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts index 6329d0957ba2..10438e4d2efa 100644 --- a/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts +++ b/src/main/runtime/orca-runtime-get-worktree-terminal-provisioning-host.ts @@ -48,16 +48,30 @@ export class OrcaRuntimeWithGetWorktreeTerminalProvisioningHost extends OrcaRunt * 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. - * Resolves `false` on the agent's own hard timeout — callers should treat that as "proceed - * anyway" (best effort), the same way the draft-paste path does, not as a hard failure. + * `timeoutMs`, when given, caps the agent's own hard timeout (never extends it) so a caller + * with a short overall budget isn't blocked past it by this wait alone. + * + * Always resolves — including on a `getWorktreeStartupReadinessHost` failure (e.g. the PTY + * tore down between placement and this call) — the same "proceed anyway" contract + * `pasteWorktreeStartupDraftWhenReady` already relies on `.catch` for. Resolves `false` on + * any of those non-ready outcomes; callers should treat that as best effort, not a failure. */ - async waitForAgentComposerReady(handle: string, agent: TuiAgent): Promise { - const ptyId = await waitForWorktreeStartupDraft( - this.getWorktreeStartupReadinessHost(), - handle, - agent - ) - return ptyId !== null + async waitForAgentComposerReady( + handle: string, + agent: TuiAgent, + timeoutMs?: number + ): Promise { + try { + const ptyId = await waitForWorktreeStartupDraft( + this.getWorktreeStartupReadinessHost(), + handle, + agent, + timeoutMs + ) + return ptyId !== null + } catch { + return false + } } async prefetchManagedWorktreeCreateBase(args: { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index 3db872e93027..c025aa19767c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -1,6 +1,7 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' import { describeTerminalWaitBlockedReason } from '../../../../../../shared/terminal-wait-blocked-reason-legacy-alias' import { TUI_AGENT_CONFIG } from '../../../../../../shared/tui-agent-config' +import { resolveDraftPasteReadyTimeoutMs } from '../../../../../../shared/draft-paste-ready-timeout' import type { OrchestrationDb } from '../../../../orchestration/db' import type { RunRow, TaskRow } from '../../../../orchestration/types' import { resolveDispatchCreator } from '../runs/dispatch-creator' @@ -206,7 +207,15 @@ export async function startLocalWorker(args: { agent && TUI_AGENT_CONFIG[agent].draftPasteReadySignal === 'render-cursor-after-bracketed-paste' ) { - await runtime.waitForAgentComposerReady(terminalHandle, agent) + // Cap by (never extend past) the caller's own budget, so an explicit short + // --timeout-ms still bounds total dispatch latency the way it does for every other + // wait above. waitForAgentComposerReady never throws — a failure here is "proceed + // anyway", the same best-effort contract the pre-existing draft-paste caller relies on. + await runtime.waitForAgentComposerReady( + terminalHandle, + agent, + Math.min(params.timeoutMs ?? 60_000, resolveDraftPasteReadyTimeoutMs(agent)) + ) } const terminalAuthority = requireWorkerAuthority(runtime, terminalHandle) const capability = db.prepareStartingWorkerAuthority({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts index 875c6d1ac93b..d82eef65c024 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-opencode-composer-wait.test.ts @@ -1,5 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' +import { resolveDraftPasteReadyTimeoutMs } from '../../../../../../shared/draft-paste-ready-timeout' + +const OPENCODE_DEFAULT_COMPOSER_TIMEOUT_MS = resolveDraftPasteReadyTimeoutMs('opencode') // tui-idle fires on the generic OSC-title idle edge. opencode (and mimo-code, which shares its // config) enable bracketed paste before their composer actually mounts, so tui-idle can resolve @@ -38,10 +41,33 @@ describe('worker-start composer readiness for opencode', () => { })) as { state: string } expect(result.state).toBe('ready') - expect(composerWait).toHaveBeenCalledWith('term_worker', 'opencode') + expect(composerWait).toHaveBeenCalledWith( + 'term_worker', + 'opencode', + OPENCODE_DEFAULT_COMPOSER_TIMEOUT_MS + ) expect(sends).toEqual(['waitForAgentComposerReady', 'sendTerminalAgentPrompt']) }) + it('caps the composer wait at an explicit --timeout-ms shorter than the default', async () => { + const composerWait = vi + .spyOn(harness.runtime, 'waitForAgentComposerReady') + .mockResolvedValue(true) + + const task = harness.db.createTask({ + spec: 'opencode short timeout fixture', + runId: harness.activeRunId + }) + await harness.call('orchestration.workerStart', { + task: task.id, + from: 'term_coord', + agent: 'opencode', + timeoutMs: 2_000 + }) + + expect(composerWait).toHaveBeenCalledWith('term_worker', 'opencode', 2_000) + }) + it('proceeds anyway when the opencode composer marker times out', async () => { vi.spyOn(harness.runtime, 'waitForAgentComposerReady').mockResolvedValue(false) diff --git a/src/main/runtime/runtime-worktree-startup-readiness.ts b/src/main/runtime/runtime-worktree-startup-readiness.ts index 77b4e1315db7..a4d18adec29a 100644 --- a/src/main/runtime/runtime-worktree-startup-readiness.ts +++ b/src/main/runtime/runtime-worktree-startup-readiness.ts @@ -89,7 +89,8 @@ export async function waitForWorktreeStartupFollowup( export function waitForWorktreeStartupDraft( host: WorktreeStartupReadinessHost, handle: string, - agent: TuiAgent + agent: TuiAgent, + timeoutOverrideMs?: number ): Promise { const ptyId = host.getPtyId(handle) if (!ptyId) { @@ -134,6 +135,9 @@ export function waitForWorktreeStartupDraft( if (replay) { observe(replay) } - hardTimer = setTimeout(() => finish(null), resolveDraftPasteReadyTimeoutMs(agent)) + hardTimer = setTimeout( + () => finish(null), + resolveDraftPasteReadyTimeoutMs(agent, timeoutOverrideMs) + ) }) }