From d503ff9f1601dc7a5a5aa2f2daf8f3fd92283da3 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:13:34 +0000 Subject: [PATCH] fix(terminal): hold a phone send until a new Claude tab's composer is up (#36494) * fix(terminal): hold a phone send until a new Claude tab's composer is up * fix(terminal): replace a reused PTY's launch-composer watch --- src/main/ipc/pty/ipc/spawn-commit.ts | 5 +- src/main/ipc/pty/runtime/spawn-commit.ts | 3 +- src/main/ipc/pty/spawn-commit-assembly.ts | 3 + .../construction/runtime-service-state.ts | 3 + src/main/runtime/launch-composer-watch.ts | 98 +++++++++++ .../methods/terminal/terminal-send-method.ts | 1 + .../rpc/terminal-send-launch-composer.test.ts | 154 ++++++++++++++++++ src/main/runtime/rpc/terminal-send.test.ts | 7 +- .../runtime-agent-launch-resolution.ts | 16 ++ src/main/runtime/runtime-terminal-writer.ts | 2 + .../terminal/input/terminal-input-dispatch.ts | 24 +++ .../terminal/launch/terminal-create.ts | 9 +- .../terminal/launch/terminal-launch-result.ts | 31 ++-- .../terminal/launch/terminal-split-surface.ts | 1 + .../lifecycle/floating-session-liveness.ts | 1 + .../terminal/lifecycle/pty-exit-lifecycle.ts | 1 + .../terminal/lifecycle/pty-registration.ts | 5 + .../workspaces/workspace-activation.ts | 55 +++---- 18 files changed, 371 insertions(+), 48 deletions(-) create mode 100644 src/main/runtime/launch-composer-watch.ts create mode 100644 src/main/runtime/rpc/terminal-send-launch-composer.test.ts diff --git a/src/main/ipc/pty/ipc/spawn-commit.ts b/src/main/ipc/pty/ipc/spawn-commit.ts index f5bdc0b4631..948d5e5a7c5 100644 --- a/src/main/ipc/pty/ipc/spawn-commit.ts +++ b/src/main/ipc/pty/ipc/spawn-commit.ts @@ -1,5 +1,6 @@ import { provenSpawnResponse, type PtySpawnOutcome } from '../spawn-outcome' import { admitRendererAgentLaunchAuthority } from '../pane/launch-authority' +import { resolveLaunchedAgent } from '../../../runtime/runtime-agent-launch-resolution' import type { PtyIpcSpawnState } from './spawn-state' import { startupCwdFallbackOutcome } from '../spawn-startup-target' import { commitPtySpawn } from '../spawn-commit-assembly' @@ -20,6 +21,7 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise() + // A fresh launch's pending composer watch; submits await it, and it is dropped once settled. + protected launchComposerReadyByPtyId = new Map>() + protected setupCompletionTokenByPtyId = new Map() } diff --git a/src/main/runtime/launch-composer-watch.ts b/src/main/runtime/launch-composer-watch.ts new file mode 100644 index 00000000000..62492d157c1 --- /dev/null +++ b/src/main/runtime/launch-composer-watch.ts @@ -0,0 +1,98 @@ +import type { TuiAgent } from '../../shared/tui-agent' +import { resolveDraftPasteReadyTimeoutMs } from '../../shared/draft-paste-ready-timeout' +import type { LaunchedAgentForeground } from './launched-agent-foreground' +import { readFreshComposerHold } from './launched-agent-composer-readiness' +import type { RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' +import { buildTerminalWaitText } from './terminal-wait-tail-state' +import { + waitForWorktreeStartupDraft, + type WorktreeStartupReadinessHost +} from './runtime-worktree-startup-readiness' + +// Why: a paste that lands before Claude's composer mounts stays in its input, but its Enter is lost (#34580). +const SUBMIT_WAITS_FOR_LAUNCH_COMPOSER: ReadonlySet = new Set([ + 'claude', + 'claude-agent-teams' +]) + +/** A startup dialog or hold anchor on the pane's tail or screen vetoes a ready signal. */ +export function readPtyFreshComposerHold( + pty: Pick | undefined, + screenLines: readonly string[] | null +): 'dialog' | 'starting' | null { + return pty + ? readFreshComposerHold( + buildTerminalWaitText(pty.tailBuffer, pty.tailPartialLine, pty.preview), + screenLines + ) + : null +} + +export type FreshComposerPtyHost = { + readiness: WorktreeStartupReadinessHost + readHold: (ptyId: string) => 'dialog' | 'starting' | null + readForeground: (ptyId: string, agent: TuiAgent) => Promise +} + +/** An agent ready signal on one PTY with no startup dialog and no shell in front; null on timeout or stop. */ +export function waitForFreshComposerOnPty( + host: FreshComposerPtyHost, + ptyId: string | null, + agent: TuiAgent, + timeoutMs: number, + options: { requireComposerMarker: boolean; stopOnDialog: boolean; stop: AbortController } +): Promise { + const { stop } = options + return waitForWorktreeStartupDraft( + { ...host.readiness, getPtyId: () => ptyId }, + ptyId ?? '', + agent, + { + timeoutMs, + requireComposerMarker: options.requireComposerMarker, + // Every caller pastes and then presses Enter: a worker brief, a launch prompt or a send. + submit: true, + signal: stop.signal, + isShellInFront: async (ownerPtyId) => + (await host.readForeground(ownerPtyId, agent)) === 'shell', + accept: (readyPtyId) => { + const hold = host.readHold(readyPtyId) + if (hold === 'dialog' && options.stopOnDialog) { + stop.abort() + } + return hold === null + } + } + ) +} + +/** Watched from launch: the replay buffer loses the startup marker on a busy pane, so a send cannot check it later. */ +export function watchLaunchComposer( + watches: Map>, + host: FreshComposerPtyHost, + ptyId: string, + agent: TuiAgent | null +): void { + // A new launch on a reused PTY id replaces its predecessor's watch. + if (!agent || !SUBMIT_WAITS_FOR_LAUNCH_COMPOSER.has(agent)) { + return + } + const stop = new AbortController() + const ready = waitForFreshComposerOnPty( + host, + ptyId, + agent, + resolveDraftPasteReadyTimeoutMs(agent), + { requireComposerMarker: false, stopOnDialog: true, stop } + ).then( + // A startup dialog stops the watch: it takes the next input, so sends reach it as before. + (readyPtyId) => readyPtyId !== null || stop.signal.aborted, + () => false + ) + watches.set(ptyId, ready) + void ready.then(() => { + if (watches.get(ptyId) === ready) { + watches.delete(ptyId) + } + }) +} diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts index 4bd10a5a31f..f4c304ddf91 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts @@ -226,6 +226,7 @@ export const TERMINAL_SEND_METHODS = [ // Why: a wire write carries no provenance beyond a client's own query reply. inputKind: params.inputKind === 'query-reply' ? 'query-reply' : 'driving', ...(params.requireWriteSettlement ? { requireWriteSettlement: true as const } : {}), + ...(params.enter === true ? { waitForLaunchComposer: true as const } : {}), ...(reserveWrite ? { reserveWrite } : {}), ...(params.inputKind !== 'query-reply' && mobileFloorClientId ? { afterWrite: () => commitMobileInputFloorClaim(mobileFloorClaim) } diff --git a/src/main/runtime/rpc/terminal-send-launch-composer.test.ts b/src/main/runtime/rpc/terminal-send-launch-composer.test.ts new file mode 100644 index 00000000000..9313fd7ad5d --- /dev/null +++ b/src/main/runtime/rpc/terminal-send-launch-composer.test.ts @@ -0,0 +1,154 @@ +import './unused-default-rpc-methods.test-fixture' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../orca-runtime' +import { makeStore } from '../runtime-rpc-worktree-store-fixtures' +import { AGENT_PROMPT_TEST_WORKTREE_PATH } from '../agent-prompt-submission-runtime-test-fixture' +import { RpcDispatcher } from './dispatcher' +import { TERMINAL_METHODS } from './methods/terminal' + +vi.mock('../../git/worktree', () => ({ + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/launch-composer', + isBare: false, + isMainWorktree: false + } + ]), + listWorktreesStrict: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/launch-composer', + isBare: false, + isMainWorktree: false + } + ]) +})) + +// Claude's palette-report anchor, then its composer prompt row (draft-paste-ready-scanner.ts). +const CLAUDE_COMPOSER_READY_OUTPUT = '\x1b[?2031h\x1b[?2004h❯\u00a0' +const PTY_ID = 'pty-claude' +// Claude 2.1.314's first-launch trust menu, captured from a real PTY. +const CLAUDE_TRUST_DIALOG_OUTPUT = + '\x1b[?2004h Accessing workspace:\r\n\r\n /private/tmp/repro\r\n\r\n' + + ' Quick safety check: Is this a project you created or one you trust?\r\n\r\n' + + ' ❯ No, exit\r\n Yes, I trust this folder\r\n\r\n Enter to confirm · Esc to cancel\r\n' + +async function launchClaude(command: string | undefined) { + const runtime = new OrcaRuntimeService( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: partial store double; terminal create and send read only its repo and worktree members. + makeStore() as never + ) + const writes: string[] = [] + runtime.setPtyController({ + spawn: async () => ({ id: PTY_ID }), + write: (_ptyId, data) => { + writes.push(data) + return true + }, + kill: () => true, + getForegroundProcess: async () => 'claude' + }) + const { handle } = await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, { + launchAgent: 'claude', + ...(command ? { command } : {}) + }) + vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent') + const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) + const send = (text: string, signal?: AbortSignal) => + dispatcher.dispatch( + { + id: 'rpc-send', + authToken: 'token', + method: 'terminal.send', + params: { terminal: handle, text, enter: true } + }, + signal ? { signal } : undefined + ) + return { runtime, writes, send } +} + +const PASTE = '\x1b[200~/review\nthis\x1b[201~' + +describe('terminal.send into a freshly launched Claude', () => { + afterEach(() => vi.useRealTimers()) + + // A command override keeps the planned agent, so its launch is held too. + it.each(['claude', 'my-claude'])( + 'holds the submit until the composer is drawn (#34580, %s)', + async (command) => { + vi.useFakeTimers() + const { runtime, writes, send } = await launchClaude(command) + + const sending = send(PASTE) + await vi.advanceTimersByTimeAsync(3_000) + expect(writes).toEqual([]) + + runtime.onPtyData(PTY_ID, CLAUDE_COMPOSER_READY_OUTPUT, Date.now()) + await vi.runAllTimersAsync() + + await expect(sending).resolves.toMatchObject({ + ok: true, + result: { send: { accepted: true } } + }) + expect(writes).toEqual([PASTE, '\r']) + } + ) + + it('refuses the send, writing nothing, when the composer never comes up', async () => { + vi.useFakeTimers() + const { writes, send } = await launchClaude('claude') + + const sending = send(PASTE) + await vi.runAllTimersAsync() + + await expect(sending).resolves.toMatchObject({ + ok: true, + result: { send: { accepted: false, bytesWritten: 0 } } + }) + expect(writes).toEqual([]) + }) + + it('lets an answer reach a startup dialog shown before the composer', async () => { + vi.useFakeTimers() + const { runtime, writes, send } = await launchClaude('claude') + + const sending = send('1') + runtime.onPtyData(PTY_ID, CLAUDE_TRUST_DIALOG_OUTPUT, Date.now()) + await vi.advanceTimersByTimeAsync(3_000) + + await expect(sending).resolves.toMatchObject({ ok: true, result: { send: { accepted: true } } }) + expect(writes).toEqual(['1', '\r']) + }) + + it('writes nothing for a held send whose request was cancelled', async () => { + vi.useFakeTimers() + const { runtime, writes, send } = await launchClaude('claude') + const request = new AbortController() + + const sending = send(PASTE, request.signal) + await vi.advanceTimersByTimeAsync(1_000) + request.abort() + runtime.onPtyData(PTY_ID, CLAUDE_COMPOSER_READY_OUTPUT, Date.now()) + await vi.runAllTimersAsync() + + await sending + expect(writes).toEqual([]) + }) + + // A resume tab types its own `claude --resume`; a headless `--print` run never draws a composer. + it.each([undefined, 'claude --print task'])( + 'does not hold sends to a shell tagged for Claude that starts no composer (%s)', + async (command) => { + const { writes, send } = await launchClaude(command) + + await expect(send('claude --resume abc')).resolves.toMatchObject({ + ok: true, + result: { send: { accepted: true } } + }) + expect(writes).toEqual(['claude --resume abc', '\r']) + } + ) +}) diff --git a/src/main/runtime/rpc/terminal-send.test.ts b/src/main/runtime/rpc/terminal-send.test.ts index 83b3dd632b4..7253e911b5b 100644 --- a/src/main/runtime/rpc/terminal-send.test.ts +++ b/src/main/runtime/rpc/terminal-send.test.ts @@ -700,7 +700,12 @@ describe('terminal send RPC', () => { enter: true, interrupt: false }, - { inputKind: 'driving', inputSource: 'programmatic', beforeWrite: expect.any(Function) } + { + inputKind: 'driving', + inputSource: 'programmatic', + beforeWrite: expect.any(Function), + waitForLaunchComposer: true + } ) }) diff --git a/src/main/runtime/runtime-agent-launch-resolution.ts b/src/main/runtime/runtime-agent-launch-resolution.ts index f41f364d083..792e38975d0 100644 --- a/src/main/runtime/runtime-agent-launch-resolution.ts +++ b/src/main/runtime/runtime-agent-launch-resolution.ts @@ -97,6 +97,22 @@ export function resolveLaunchCommandPaneAgent(command: string | null | undefined return recognized && isTuiAgent(recognized.agent) ? recognized.agent : null } +/** The agent a fresh launch's command starts; a command override keeps the planned agent. No command starts none. */ +export function resolveLaunchedAgent( + command: string | null | undefined, + plannedAgent: unknown +): TuiAgent | null { + if (!command) { + return null + } + const recognized = resolveLaunchCommandPaneAgent(command) + // A known agent run headless (`claude --print`) has no composer; only an unrecognized override keeps the plan. + if (recognized || recognizeAgentLaunchCommand(command, { includeHeadlessOneShot: true })) { + return recognized + } + return isTuiAgent(plannedAgent) ? plannedAgent : null +} + export function inferCapturedClaudeAgentTeamsMode( launchConfig: SleepingAgentLaunchConfig | undefined, command: string | undefined, diff --git a/src/main/runtime/runtime-terminal-writer.ts b/src/main/runtime/runtime-terminal-writer.ts index e0eddf02522..0c5715d1ec9 100644 --- a/src/main/runtime/runtime-terminal-writer.ts +++ b/src/main/runtime/runtime-terminal-writer.ts @@ -19,6 +19,8 @@ export type RuntimeTerminalWriteOptions = { afterWrite?: (ptyId: string) => void | Promise suffixFailureError?: string requireWriteSettlement?: true + /** Hold an Enter until a fresh launch's composer is up, refusing the send if it never comes (#34580). */ + waitForLaunchComposer?: true } export class RuntimeTerminalWriter { diff --git a/src/main/runtime/terminal/input/terminal-input-dispatch.ts b/src/main/runtime/terminal/input/terminal-input-dispatch.ts index d4059d16030..e7c0a455bfd 100644 --- a/src/main/runtime/terminal/input/terminal-input-dispatch.ts +++ b/src/main/runtime/terminal/input/terminal-input-dispatch.ts @@ -154,6 +154,9 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim throw new Error('invalid_terminal_send') } await assertTerminalInputWithinLimitWithYield(action.text) + if (!(await this.launchComposerAdmitsSubmit(pty.pty.ptyId, action, options))) { + return { handle, accepted: false, bytesWritten: 0 } + } const writeSettlement = await this.writeTerminalAction( pty.pty.ptyId, action, @@ -184,6 +187,9 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim if (await this.isLeafPtyProvenAbsent(leaf.ptyId)) { throw new Error('terminal_not_writable') } + if (!(await this.launchComposerAdmitsSubmit(leaf.ptyId, action, options))) { + return { handle, accepted: false, bytesWritten: 0 } + } const writeSettlement = await this.writeTerminalAction(leaf.ptyId, action, payload, options) @@ -198,6 +204,24 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim } } + private async launchComposerAdmitsSubmit( + ptyId: string, + action: { enter?: boolean }, + options: RuntimeTerminalWriteOptions + ): Promise { + if (!(options.waitForLaunchComposer && action.enter)) { + return true + } + const generation = this.getPtyLifecycleGeneration(ptyId) + return ( + // No pending watch: not a fresh launch, or its watch already settled. + ((await this.launchComposerReadyByPtyId.get(ptyId)) ?? true) && + // A held send must not land in a replacement process or outlive its cancelled request. + this.getPtyLifecycleGeneration(ptyId) === generation && + options.signal?.aborted !== true + ) + } + async sendTerminalAgentPrompt( handle: string, prompt: string, diff --git a/src/main/runtime/terminal/launch/terminal-create.ts b/src/main/runtime/terminal/launch/terminal-create.ts index 3c82a8b4ac9..c3770fbacea 100644 --- a/src/main/runtime/terminal/launch/terminal-create.ts +++ b/src/main/runtime/terminal/launch/terminal-create.ts @@ -15,7 +15,6 @@ import { agentLaunchTokenFor, withAgentLaunchToken } from '../../../agent-launch import { seedPtyLaunchTitle } from './pty-launch-title' import { migratedPaneRestoreHint } from '../../migrated-pane-restore-cwd' import { paneSize, resolvePtyFirstSize } from '../../../ipc/pty/pty-first-size' -import { resolveLaunchCommandPaneAgent } from '../../runtime-agent-launch-resolution' export abstract class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTerminalCreateDeduplication { protected abstract paneStartStatusArgs: dependencies.PaneStartArgsOf @@ -243,11 +242,11 @@ export abstract class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTermi this.setPtyManagementTitleFromObservedTitle(pty, title, at) ) } - recordTerminalLaunchMetadata(pty, result, launch) + this.watchLaunchComposer( + result.id, + recordTerminalLaunchMetadata(pty, result, launch, launchOpts.command) + ) if (!launch.adoptedStablePane) { - pty.launchCommandAgent = result.agentResumeRefused - ? null - : resolveLaunchCommandPaneAgent(launchOpts.command) this.rememberSavedTerminalLaunchResult(result.id, result) } recordPtySurface(pty, tabId, paneKey, spawnSurfaceClaimSequence(this.graphSequence)) diff --git a/src/main/runtime/terminal/launch/terminal-launch-result.ts b/src/main/runtime/terminal/launch/terminal-launch-result.ts index 05a293f4d8a..752eec8bfa6 100644 --- a/src/main/runtime/terminal/launch/terminal-launch-result.ts +++ b/src/main/runtime/terminal/launch/terminal-launch-result.ts @@ -3,7 +3,12 @@ import { admitStablePaneAdoption } from '../../runtime-terminal-pane-identity' import type { RuntimePtyController } from '../../runtime-pty-controller-contract' import type { TerminalCreateOptions } from '../../runtime-terminal-contracts' import type { RuntimePtyWorktreeRecord } from '../../runtime-terminal-state-records' -import { copySleepingAgentLaunchConfig } from '../../runtime-agent-launch-resolution' +import type { TuiAgent } from '../../../../shared/tui-agent' +import { + copySleepingAgentLaunchConfig, + resolveLaunchCommandPaneAgent, + resolveLaunchedAgent +} from '../../runtime-agent-launch-resolution' type TerminalSpawnResult = Awaited>> @@ -41,11 +46,13 @@ export function resolveTerminalLaunchResult( } } +/** Returns the agent a fresh launch's command starts; null for an adopted pane, whose process was already running. */ export function recordTerminalLaunchMetadata( pty: RuntimePtyWorktreeRecord, result: TerminalSpawnResult, - launch: ReturnType -): void { + launch: ReturnType, + command: string | undefined +): TuiAgent | null { if (launch.adoptedStablePane) { // A lower owner can supply facts before this runtime has a launch record. if (!pty.launchConfig && result.launchConfig) { @@ -56,14 +63,18 @@ export function recordTerminalLaunchMetadata( if (pty.launchToken && !pty.launchIncarnationId) { pty.launchIncarnationId = pty.incarnationId } - } else { - pty.launchConfig = launch.launchConfig - ? copySleepingAgentLaunchConfig(launch.launchConfig) - : null - pty.launchToken = launch.launchToken ?? null - pty.launchIncarnationId = launch.launchToken ? pty.incarnationId : null - pty.launchAgent = launch.launchAgent ?? null + return null } + pty.launchConfig = launch.launchConfig ? copySleepingAgentLaunchConfig(launch.launchConfig) : null + pty.launchToken = launch.launchToken ?? null + pty.launchIncarnationId = launch.launchToken ? pty.incarnationId : null + pty.launchAgent = launch.launchAgent ?? null + if (result.agentResumeRefused) { + pty.launchCommandAgent = null + return null + } + pty.launchCommandAgent = resolveLaunchCommandPaneAgent(command) + return resolveLaunchedAgent(command, pty.launchAgent) } export function terminalLaunchPublicFacts( diff --git a/src/main/runtime/terminal/launch/terminal-split-surface.ts b/src/main/runtime/terminal/launch/terminal-split-surface.ts index be9e6dc9753..c8e30b90102 100644 --- a/src/main/runtime/terminal/launch/terminal-split-surface.ts +++ b/src/main/runtime/terminal/launch/terminal-split-surface.ts @@ -122,6 +122,7 @@ export abstract class OrcaRuntimeWithSplitPtyBackedTerminal extends OrcaRuntimeW ) createdPty.runtimeSessionOwned = pty.runtimeSessionOwned createdPty.launchCommandAgent = resolveLaunchCommandPaneAgent(opts.command) + this.watchLaunchComposer(result.id, createdPty.launchCommandAgent) this.setPairedRendererSessionOwnership( createdPty.ptyId, this.pairedRendererSessionOwnedPtyIds.has(pty.ptyId) diff --git a/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts b/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts index 7a657376bc0..8d4a4b195a9 100644 --- a/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts +++ b/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts @@ -117,6 +117,7 @@ export abstract class OrcaRuntimeWithRefreshFloatingWorkspacePtyLiveness extends this.ptysById.delete(ptyId) this.pendingPtyHandleReplacementFences.delete(ptyId) this.recentPtyOutputById.delete(ptyId) + this.launchComposerReadyByPtyId.delete(ptyId) this.setupCompletionTokenByPtyId.delete(ptyId) this.clearWaitBlockedCheckState(ptyId) this.trustDialogStatus.forget(ptyId) diff --git a/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts b/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts index 1ebe8857583..ac792e0b3a7 100644 --- a/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts +++ b/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts @@ -166,6 +166,7 @@ export abstract class OrcaRuntimeWithOnPtyExit extends OrcaRuntimeWithOnClientDi this.resizeListeners.delete(ptyId) this.lastRendererSizes.delete(ptyId) this.recentPtyOutputById.delete(ptyId) + this.launchComposerReadyByPtyId.delete(ptyId) this.setupCompletionTokenByPtyId.delete(ptyId) this.clearWaitBlockedCheckState(ptyId) this.ptyOutputSequenceById.delete(ptyId) diff --git a/src/main/runtime/terminal/lifecycle/pty-registration.ts b/src/main/runtime/terminal/lifecycle/pty-registration.ts index 78b33b71a52..04c17768fb2 100644 --- a/src/main/runtime/terminal/lifecycle/pty-registration.ts +++ b/src/main/runtime/terminal/lifecycle/pty-registration.ts @@ -30,6 +30,8 @@ export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalida pty: RuntimePtyWorktreeRecord ): OrchestrationCompatibilityTerminalAuthority['hostScope'] | null + protected abstract watchLaunchComposer(ptyId: string, agent: TuiAgent | null): void + registerPty( ptyId: string, worktreeId: string, @@ -41,6 +43,8 @@ export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalida /** Handle allocated for the replacement incarnation, when one is known. */ terminalHandle?: string agentLaunchAuthority?: { launchToken: string; launchAgent: TuiAgent } + /** The agent a fresh spawn's launch command starts, whose submits wait for its composer. */ + launchedAgent?: TuiAgent providerReattachLaunchIdentity?: { incarnationId: PtyIncarnationId launchAgent: TuiAgent @@ -150,6 +154,7 @@ export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalida pty.launchIncarnationId = binding.incarnationId pty.launchAgent = agentLaunchAuthority.launchAgent } + this.watchLaunchComposer(ptyId, binding?.launchedAgent ?? null) const providerReattachLaunchIdentity = binding?.providerReattachLaunchIdentity if ( providerReattachLaunchIdentity && diff --git a/src/main/runtime/workspaces/workspace-activation.ts b/src/main/runtime/workspaces/workspace-activation.ts index 6014cf7e963..f2df1ae529b 100644 --- a/src/main/runtime/workspaces/workspace-activation.ts +++ b/src/main/runtime/workspaces/workspace-activation.ts @@ -32,7 +32,6 @@ import { recordCreatedWorktreeLineage as recordCreatedWorktreeLineageState } fro import { deliverStartupFollowupPrompt, pasteWorktreeStartupDraftWhenReady, - waitForWorktreeStartupDraft, type StartupFollowupPromptOptions, type WorktreeStartupReadinessHost } from '../runtime-worktree-startup-readiness' @@ -41,9 +40,7 @@ import { provisionWorktreeTerminals, type WorktreeTerminalProvisioningHost } from '../runtime-worktree-terminal-provisioning' -import { readFreshComposerHold } from '../launched-agent-composer-readiness' import { waitForTerminalComposer } from '../terminal/wait/terminal-composer-lifetime' -import { buildTerminalWaitText } from '../terminal-wait-tail-state' import { describeLaunchedAgentHost, readLaunchedAgentForeground, @@ -51,6 +48,12 @@ import { type LaunchedAgentHost } from '../launched-agent-foreground' import { worktreeRowTarget } from '../../persistence/host-qualified-worktree-meta' +import { + readPtyFreshComposerHold, + waitForFreshComposerOnPty, + watchLaunchComposer, + type FreshComposerPtyHost +} from '../launch-composer-watch' export abstract class OrcaRuntimeWithActivateManagedWorktree extends OrcaRuntimeWithListManagedWorktrees { protected abstract toAgentSessionOptions( @@ -232,36 +235,28 @@ export abstract class OrcaRuntimeWithActivateManagedWorktree extends OrcaRuntime signal }, (target, stop) => - waitForWorktreeStartupDraft( - { ...this.getWorktreeStartupReadinessHost(), getPtyId: () => target.ptyId }, - handle, - agent, - { - timeoutMs, - requireComposerMarker, - // Every caller pastes and then presses Enter: a worker brief or a launch prompt. - submit: true, - signal: stop.signal, - isShellInFront: async (ownerPtyId) => - (await this.readLaunchedAgentForeground(ownerPtyId, agent)) === 'shell', - accept: (readyPtyId) => { - const pty = this.ptysById.get(readyPtyId) - const hold = pty - ? readFreshComposerHold( - buildTerminalWaitText(pty.tailBuffer, pty.tailPartialLine, pty.preview), - this.readLiveTerminalScreenLines(readyPtyId) - ) - : null - if (hold === 'dialog' && stopOnDialog) { - stop.abort() - } - return hold === null - } - } - ) + waitForFreshComposerOnPty(this.freshComposerPtyHost(), target.ptyId, agent, timeoutMs, { + requireComposerMarker, + stopOnDialog, + stop + }) ) } + /** Hold submits to a fresh launch of `agent` until its composer is up (launch-composer-watch.ts). */ + watchLaunchComposer(ptyId: string, agent: TuiAgent | null): void { + watchLaunchComposer(this.launchComposerReadyByPtyId, this.freshComposerPtyHost(), ptyId, agent) + } + + private freshComposerPtyHost(): FreshComposerPtyHost { + return { + readiness: this.getWorktreeStartupReadinessHost(), + readForeground: (ptyId, agent) => this.readLaunchedAgentForeground(ptyId, agent), + readHold: (ptyId) => + readPtyFreshComposerHold(this.ptysById.get(ptyId), this.readLiveTerminalScreenLines(ptyId)) + } + } + /** What holds the terminal a launch started its agent in, read fresh from the execution host. */ readLaunchedAgentForeground(ptyId: string, agent: TuiAgent): Promise { const host = this.launchedAgentHost(ptyId)