From 02abcb40514d5dfdb4183381f4c2c7f6a7e4d7b7 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Mon, 27 Apr 2026 19:17:21 -0400 Subject: [PATCH] fix(orchestration): daemon PTY reads, inject auto-submit, and check --wait - Forward daemon-hosted terminal PTY data to runtime so terminal.read returns actual content instead of empty buffers - Split text and control characters into separate PTY writes with 500ms delay so Claude Code processes paste events before receiving Enter - Add orchestration check --wait to block until a message arrives, replacing sleep+poll loops in coordinator flows - Add message waiter infrastructure (waitForMessage/notifyMessageArrived) mirroring the TerminalWaiter pattern - Add orca-dev CLI wrapper and rebuild:electron script for dev workflow Co-authored-by: Orca --- bin/orca-dev | 28 +++ config/scripts/install-dev-cli.mjs | 50 ++++ package.json | 6 +- scripts/rebuild-native-deps.mjs | 15 ++ src/cli/handlers/orchestration.ts | 4 +- src/cli/specs/orchestration.ts | 4 +- src/main/ipc/pty.ts | 22 ++ src/main/runtime/orca-runtime.test.ts | 40 ++- src/main/runtime/orca-runtime.ts | 228 +++++++++++++++++- .../runtime/rpc/methods/orchestration.test.ts | 16 ++ src/main/runtime/rpc/methods/orchestration.ts | 60 ++++- src/main/runtime/runtime-rpc.test.ts | 5 +- src/renderer/src/lib/tui-agent-startup.ts | 15 +- .../src/runtime/sync-runtime-graph.ts | 4 +- src/shared/agent-detection.ts | 20 ++ src/shared/runtime-types.ts | 1 + 16 files changed, 464 insertions(+), 54 deletions(-) create mode 100755 bin/orca-dev create mode 100644 config/scripts/install-dev-cli.mjs diff --git a/bin/orca-dev b/bin/orca-dev new file mode 100755 index 000000000..97acbf9f1 --- /dev/null +++ b/bin/orca-dev @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Dev CLI wrapper — uses a separate userData path to avoid clobbering production Orca data. +set -euo pipefail + +# Resolve through symlinks so this works when called via /usr/local/bin/orca-dev +SOURCE="$0" +while [ -L "$SOURCE" ]; do + DIR="$(cd "$(dirname "$SOURCE")" && pwd)" + SOURCE="$(readlink "$SOURCE")" + [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" +done +SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +CLI_ENTRY="$REPO_ROOT/out/cli/index.js" + +if [ ! -f "$CLI_ENTRY" ]; then + echo "orca-dev: CLI not built yet. Run 'pnpm run build:cli' first." >&2 + exit 1 +fi + +case "$(uname -s)" in + Darwin) default_data="$HOME/Library/Application Support/orca-dev" ;; + MINGW*|MSYS*) default_data="${APPDATA:-$HOME/AppData/Roaming}/orca-dev" ;; + *) default_data="${XDG_CONFIG_HOME:-$HOME/.config}/orca-dev" ;; +esac + +export ORCA_USER_DATA_PATH="${ORCA_DEV_USER_DATA_PATH:-$default_data}" +exec node "$CLI_ENTRY" "$@" diff --git a/config/scripts/install-dev-cli.mjs b/config/scripts/install-dev-cli.mjs new file mode 100644 index 000000000..dd5c8b101 --- /dev/null +++ b/config/scripts/install-dev-cli.mjs @@ -0,0 +1,50 @@ +#!/usr/bin/env node +// Symlinks the orca-dev wrapper into /usr/local/bin so the dev CLI is +// available globally after `pnpm run build:cli`. +import { existsSync, lstatSync, readlinkSync } from 'node:fs' +import { execFileSync } from 'node:child_process' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') +const source = path.join(repoRoot, 'bin', 'orca-dev') + +const commandPath = + process.platform === 'darwin' || process.platform === 'linux' + ? '/usr/local/bin/orca-dev' + : null + +if (!commandPath) { + console.log('[orca-dev] Skipping global symlink (unsupported platform).') + process.exit(0) +} + +function isOwnedByUs(target) { + try { + if (!lstatSync(target).isSymbolicLink()) return false + return readlinkSync(target) === source + } catch { + return false + } +} + +if (existsSync(commandPath)) { + if (isOwnedByUs(commandPath)) { + console.log(`[orca-dev] ${commandPath} already points to dev CLI.`) + process.exit(0) + } + console.error( + `[orca-dev] ${commandPath} exists but is not our symlink. Remove it manually if you want the dev CLI installed globally.` + ) + process.exit(0) +} + +try { + execFileSync('ln', ['-s', source, commandPath], { stdio: 'inherit' }) + console.log(`[orca-dev] Symlinked ${commandPath} → ${source}`) +} catch { + console.log( + `[orca-dev] Could not create ${commandPath} (permission denied). Run once with:\n` + + ` sudo ln -s ${source} ${commandPath}` + ) +} diff --git a/package.json b/package.json index 51a39996b..47be3686c 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "homepage": "https://github.com/stablyai/orca", "author": "stablyai", "bin": { - "orca": "./out/cli/index.js" + "orca": "./out/cli/index.js", + "orca-dev": "./bin/orca-dev" }, "main": "./out/main/index.js", "scripts": { @@ -24,11 +25,12 @@ "start": "electron-vite preview", "dev": "node config/scripts/run-electron-vite-dev.mjs", "build:relay": "node scripts/build-relay.mjs", - "build:cli": "tsc -p config/tsconfig.cli.json --outDir out --composite false --incremental false", + "build:cli": "tsc -p config/tsconfig.cli.json --outDir out --composite false --incremental false && node config/scripts/install-dev-cli.mjs", "build:electron-vite": "node config/scripts/run-electron-vite-build.mjs", "build": "pnpm run typecheck && pnpm run build:relay && pnpm run build:electron-vite && pnpm run build:cli", "build:release": "pnpm run build:relay && pnpm run build:electron-vite && pnpm run build:cli", "postinstall": "pnpm rebuild electron && node scripts/rebuild-native-deps.mjs", + "rebuild:electron": "node scripts/rebuild-native-deps.mjs", "build:unpack": "pnpm run build && electron-builder --config config/electron-builder.config.cjs --dir", "build:win": "pnpm run build && electron-builder --config config/electron-builder.config.cjs --win", "build:icons": "bash resources/icon-source/generate.sh", diff --git a/scripts/rebuild-native-deps.mjs b/scripts/rebuild-native-deps.mjs index 6fdb6b7b3..2e9893789 100644 --- a/scripts/rebuild-native-deps.mjs +++ b/scripts/rebuild-native-deps.mjs @@ -20,6 +20,7 @@ */ import { rebuild } from '@electron/rebuild' +import { execSync } from 'node:child_process' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' @@ -34,11 +35,25 @@ if (ignoreModules.length > 0) { console.log(`[rebuild] Skipping modules on Windows: ${ignoreModules.join(', ')}`) } +// Why: @electron/rebuild's default module walker doesn't reliably find native +// modules inside pnpm's .pnpm/ store. Passing an explicit list of modules to +// rebuild via `onlyModules` ensures they're recompiled against Electron's Node +// ABI regardless of the package manager's store layout. +const NATIVE_MODULES = ['better-sqlite3', 'node-pty', 'cpu-features'] +const onlyModules = NATIVE_MODULES.filter((m) => !ignoreModules.includes(m)) + try { await rebuild({ buildPath: projectDir, electronVersion, ignoreModules, + onlyModules, + // Why: without force, @electron/rebuild skips modules it considers + // "already built" — even when they were compiled for the wrong ABI + // (e.g., system Node instead of Electron's embedded Node). This is + // common after pnpm install, which compiles native modules for system + // Node before postinstall runs this script. + force: true, }) } catch (/** @type {any} */ err) { console.error('[rebuild] Native module rebuild failed:', err?.message ?? err) diff --git a/src/cli/handlers/orchestration.ts b/src/cli/handlers/orchestration.ts index 281c336cc..be807c28a 100644 --- a/src/cli/handlers/orchestration.ts +++ b/src/cli/handlers/orchestration.ts @@ -70,7 +70,9 @@ export const ORCHESTRATION_HANDLERS: Record = { terminal, unread: flags.has('unread') ? true : undefined, types: getOptionalStringFlag(flags, 'types'), - inject: flags.has('inject') ? true : undefined + inject: flags.has('inject') ? true : undefined, + wait: flags.has('wait') ? true : undefined, + timeoutMs: flags.has('timeout-ms') ? Number(flags.get('timeout-ms')) : undefined }) printResult(result, json, (r) => { if (r.formatted) { diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 02a32836e..e527fe8b9 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -23,8 +23,8 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'check'], summary: 'Check messages for a terminal', usage: - 'orca orchestration check [--terminal ] [--unread] [--types ] [--inject] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'terminal', 'unread', 'types', 'inject'] + 'orca orchestration check [--terminal ] [--unread] [--types ] [--inject] [--wait] [--timeout-ms ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'terminal', 'unread', 'types', 'inject', 'wait', 'timeout-ms'] }, { path: ['orchestration', 'reply'], diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index a5506a120..70627c21b 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -395,6 +395,12 @@ export function registerPtyHandlers( pendingData.clear() } + // Why: LocalPtyProvider routes data to the runtime via configure().onData, + // but daemon-backed providers don't have configure(). Without this, daemon + // PTY data never reaches the runtime's tail buffer, so terminal.read returns + // empty and agent-detection from raw data never fires. + const isLocalProvider = localProvider instanceof LocalPtyProvider + localDataUnsub = localProvider.onData((payload) => { if (mainWindow.isDestroyed()) { // Why: clear the pending flush timer so it doesn't fire after the window @@ -407,6 +413,9 @@ export function registerPtyHandlers( pendingData.clear() return } + if (!isLocalProvider) { + runtime?.onPtyData(payload.id, payload.data, Date.now()) + } const existing = pendingData.get(payload.id) pendingData.set(payload.id, existing ? existing + payload.data : payload.data) if (!flushTimer) { @@ -414,6 +423,12 @@ export function registerPtyHandlers( } }) localExitUnsub = localProvider.onExit((payload) => { + if (!isLocalProvider) { + clearProviderPtyState(payload.id) + ptyOwnership.delete(payload.id) + markClaudePtyExited(payload.id) + runtime?.onPtyExit(payload.id, payload.code) + } if (!mainWindow.isDestroyed()) { // Why: flush any batched data for this PTY before sending the exit event, // otherwise the last ≤8ms of output is silently lost because the renderer @@ -471,6 +486,13 @@ export function registerPtyHandlers( markClaudePtyExited(ptyId) runtime?.onPtyExit(ptyId, -1) return true + }, + getForegroundProcess: async (ptyId) => { + try { + return await getProviderForPty(ptyId).getForegroundProcess(ptyId) + } catch { + return null + } } }) diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index ec5749a43..2edcd0956 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -97,7 +97,8 @@ function syncSinglePty(runtime: OrcaRuntimeService, ptyId: string | null = 'pty- worktreeId: TEST_WORKTREE_ID, leafId: 'pane:1', paneRuntimeId: 1, - ptyId + ptyId, + paneTitle: null } ] }) @@ -325,7 +326,8 @@ describe('OrcaRuntimeService', () => { writes.push(data) return true }, - kill: () => true + kill: () => true, + getForegroundProcess: async () => null }) runtime.attachWindow(1) @@ -369,7 +371,7 @@ describe('OrcaRuntimeService', () => { handle: terminal.handle, accepted: true }) - expect(writes).toEqual(['continue\r']) + expect(writes).toEqual(['continue', '\r']) }) it('waits for terminal exit and resolves with the exit status', async () => { @@ -470,7 +472,8 @@ describe('OrcaRuntimeService', () => { runtime.setOrchestrationDb(db) runtime.setPtyController({ write, - kill: vi.fn() + kill: vi.fn(), + getForegroundProcess: async () => null }) syncSinglePty(runtime) @@ -551,7 +554,8 @@ describe('OrcaRuntimeService', () => { runtime.setOrchestrationDb(db) runtime.setPtyController({ write, - kill: vi.fn() + kill: vi.fn(), + getForegroundProcess: async () => null }) syncSinglePty(runtime) @@ -567,6 +571,24 @@ describe('OrcaRuntimeService', () => { db.close() }) + it('resolves message waiters when notifyMessageArrived is called', async () => { + const runtime = new OrcaRuntimeService(store) + + const waitPromise = runtime.waitForMessage('term_abc', { timeoutMs: 5000 }) + runtime.notifyMessageArrived('term_abc') + await waitPromise + }) + + it('resolves message waiters on timeout when no message arrives', async () => { + const runtime = new OrcaRuntimeService(store) + + const start = Date.now() + await runtime.waitForMessage('term_abc', { timeoutMs: 100 }) + const elapsed = Date.now() - start + expect(elapsed).toBeGreaterThanOrEqual(90) + expect(elapsed).toBeLessThan(500) + }) + it('fails terminal waits closed when the handle goes stale during reload', async () => { const runtime = new OrcaRuntimeService(store) @@ -610,7 +632,7 @@ describe('OrcaRuntimeService', () => { { tabId: 'tab-1', worktreeId: 'repo-1::/tmp/worktree-a', - title: 'Claude', + title: 'Terminal 1', activeLeafId: 'pane:1', layout: null } @@ -740,7 +762,8 @@ describe('OrcaRuntimeService', () => { kill: () => { killed = true return true - } + }, + getForegroundProcess: async () => null }) runtime.attachWindow(1) @@ -820,7 +843,8 @@ describe('OrcaRuntimeService', () => { kill: () => { killed = true return true - } + }, + getForegroundProcess: async () => null }) runtime.attachWindow(1) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index e5b9e0ffc..f3872ddfb 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1,7 +1,11 @@ /* eslint-disable max-lines -- Why: the Orca runtime is the authoritative live control plane for the CLI, so handle validation, selector resolution, wait state, and summaries are kept together to avoid split-brain behavior. */ /* eslint-disable unicorn/no-useless-spread -- Why: waiter sets and handle keys are cloned intentionally before mutation so resolution and rejection can safely remove entries while iterating. */ /* eslint-disable no-control-regex -- Why: terminal normalization must strip ANSI and OSC control sequences from PTY output before returning bounded text to agents. */ -import { extractLastOscTitle, detectAgentStatusFromTitle } from '../../shared/agent-detection' +import { + extractLastOscTitle, + detectAgentStatusFromTitle, + isShellProcess +} from '../../shared/agent-detection' import type { AgentStatus } from '../../shared/agent-detection' import { gitExecFileAsync, gitExecFileSync } from '../git/runner' import { isWslPath, parseWslPath, getWslHome } from '../wsl' @@ -137,6 +141,7 @@ type RuntimeLeafRecord = RuntimeSyncedLeaf & { type RuntimePtyController = { write(ptyId: string, data: string): boolean kill(ptyId: string): boolean + getForegroundProcess(ptyId: string): Promise } type RuntimeNotifier = { @@ -171,6 +176,14 @@ type TerminalWaiter = { resolve: (result: RuntimeTerminalWait) => void reject: (error: Error) => void timeout: NodeJS.Timeout | null + pollInterval: NodeJS.Timeout | null +} + +type MessageWaiter = { + handle: string + typeFilter: string[] | undefined + resolve: (result: void) => void + timeout: NodeJS.Timeout | null } type ResolvedWorktree = { @@ -226,6 +239,7 @@ export class OrcaRuntimeService { private resolvedWorktreeCache: ResolvedWorktreeCache | null = null private agentDetector: AgentDetector | null = null private _orchestrationDb: OrchestrationDb | null = null + private messageWaitersByHandle = new Map>() constructor(store: RuntimeStore | null = null, stats?: StatsCollector) { this.store = store @@ -452,11 +466,13 @@ export class OrcaRuntimeService { if (agentStatus !== null) { const prevStatus = leaf.lastAgentStatus leaf.lastAgentStatus = agentStatus - // Why: resolve tui-idle waiters only on working→idle, not working→permission. - // Permission means the agent is blocked on user approval (e.g. Gemini's - // "y/n" prompt) — it hasn't finished its task. Resolving tui-idle here - // would cause the CLI consumer to proceed while the agent is still waiting. - if (prevStatus === 'working' && agentStatus === 'idle') { + // Why: resolve tui-idle on any transition TO idle (not just working→idle). + // Claude Code may skip "working" entirely on fast tasks, going null→idle, + // and the coordinator's tui-idle waiter would hang forever waiting for a + // working→idle transition that never comes. Permission→idle is excluded: + // it means the agent was blocked on user approval and the user said no, + // which isn't a task-completion signal. + if (agentStatus === 'idle' && prevStatus !== 'idle') { this.resolveTuiIdleWaiters(leaf) this.deliverPendingMessages(leaf) } @@ -655,10 +671,33 @@ export class OrcaRuntimeService { if (payload === null) { throw new Error('invalid_terminal_send') } - const wrote = this.ptyController?.write(leaf.ptyId, payload) ?? false - if (!wrote) { - throw new Error('terminal_not_writable') + + // Why: TUI apps (Claude Code, etc.) treat a single large write as a paste + // event. If \r is included in the same write as multi-line text, the TUI + // interprets it as part of the paste rather than a discrete Enter keypress. + // Splitting the text and the trailing control characters into separate + // writes with a small delay ensures the TUI processes the paste first, + // then receives Enter as a distinct input event. + const hasText = typeof action.text === 'string' && action.text.length > 0 + const hasSuffix = action.enter || action.interrupt + if (hasText && hasSuffix) { + const textWrote = this.ptyController?.write(leaf.ptyId, action.text!) ?? false + if (!textWrote) { + throw new Error('terminal_not_writable') + } + const suffix = (action.enter ? '\r' : '') + (action.interrupt ? '\x03' : '') + await new Promise((resolve) => setTimeout(resolve, 500)) + const suffixWrote = this.ptyController?.write(leaf.ptyId, suffix) ?? false + if (!suffixWrote) { + throw new Error('terminal_not_writable') + } + } else { + const wrote = this.ptyController?.write(leaf.ptyId, payload) ?? false + if (!wrote) { + throw new Error('terminal_not_writable') + } } + return { handle, accepted: true, @@ -705,7 +744,8 @@ export class OrcaRuntimeService { condition, resolve, reject, - timeout: null + timeout: null, + pollInterval: null } if (effectiveTimeoutMs > 0) { @@ -730,8 +770,21 @@ export class OrcaRuntimeService { if (getTerminalState(live.leaf) === 'exited') { this.resolveWaiter(waiter, buildTerminalWaitResult(handle, condition, live.leaf)) } else if (condition === 'tui-idle' && live.leaf.lastAgentStatus === 'idle') { - live.leaf.lastAgentStatus = null + // Why: don't clear lastAgentStatus here. It's a factual record of the + // last detected OSC state, not a one-shot signal. Clearing it causes + // subsequent tui-idle waiters to hang even though the agent is idle — + // the first waiter consumes the status and all later ones see null. this.resolveWaiter(waiter, buildTerminalWaitResult(handle, condition, live.leaf)) + } else if (condition === 'tui-idle' && live.leaf.lastAgentStatus === null) { + // Why: for daemon-hosted terminals, lastAgentStatus stays null because + // PTY data doesn't flow through onPtyData. Check the renderer-synced + // title as a fast path before falling back to polling. + const fastPathTitle = live.leaf.paneTitle ?? this.tabs.get(live.leaf.tabId)?.title + if (fastPathTitle && detectAgentStatusFromTitle(fastPathTitle) === 'idle') { + this.resolveWaiter(waiter, buildTerminalWaitResult(handle, condition, live.leaf)) + } else { + this.startTuiIdleFallbackPoll(waiter, live.leaf) + } } } catch (error) { this.removeWaiter(waiter) @@ -1546,6 +1599,40 @@ export class OrcaRuntimeService { } } + // Why: OSC title detection via onPtyData is the tightest signal for agent + // presence, but the runtime may not see PTY data for daemon-hosted terminals + // (the daemon adapter stubs getForegroundProcess). This checks three signals + // in order: (1) lastAgentStatus from PTY data OSC titles, (2) the renderer- + // synced tab title (which reflects OSC titles from the xterm instance), and + // (3) the PTY foreground process. Returns true if any signal indicates a + // non-shell agent is running. + async isTerminalRunningAgent(handle: string): Promise { + try { + const { leaf } = this.getLiveLeafForHandle(handle) + if (leaf.lastAgentStatus !== null) { + return true + } + // Why: check both the leaf-level pane title (synced from the renderer's + // runtimePaneTitlesByTabId) and the tab-level title. The tab title already + // includes OSC-enriched agent indicators (e.g. ✳ prefix) synced from the + // renderer's xterm instance. + const titleToCheck = leaf.paneTitle ?? this.tabs.get(leaf.tabId)?.title + if (titleToCheck && detectAgentStatusFromTitle(titleToCheck) !== null) { + return true + } + if (!leaf.ptyId || !this.ptyController) { + return false + } + const fg = await this.ptyController.getForegroundProcess(leaf.ptyId) + if (!fg) { + return false + } + return !isShellProcess(fg) + } catch { + return false + } + } + deliverPendingMessagesForHandle(handle: string): void { try { const { leaf } = this.getLiveLeafForHandle(handle) @@ -1558,6 +1645,66 @@ export class OrcaRuntimeService { } } + // Why: after a message is inserted for a recipient, any blocking + // orchestration.check --wait calls watching that handle must be woken + // so they can return the new message immediately instead of polling. + notifyMessageArrived(handle: string): void { + const waiters = this.messageWaitersByHandle.get(handle) + if (!waiters || waiters.size === 0) { + return + } + for (const waiter of [...waiters]) { + this.resolveMessageWaiter(waiter) + } + } + + waitForMessage( + handle: string, + options?: { typeFilter?: string[]; timeoutMs?: number } + ): Promise { + return new Promise((resolve) => { + const timeoutMs = options?.timeoutMs ?? MESSAGE_WAIT_DEFAULT_TIMEOUT_MS + + const waiter: MessageWaiter = { + handle, + typeFilter: options?.typeFilter, + resolve, + timeout: null + } + + waiter.timeout = setTimeout(() => { + this.removeMessageWaiter(waiter) + resolve() + }, timeoutMs) + + let waiters = this.messageWaitersByHandle.get(handle) + if (!waiters) { + waiters = new Set() + this.messageWaitersByHandle.set(handle, waiters) + } + waiters.add(waiter) + }) + } + + private resolveMessageWaiter(waiter: MessageWaiter): void { + this.removeMessageWaiter(waiter) + waiter.resolve() + } + + private removeMessageWaiter(waiter: MessageWaiter): void { + if (waiter.timeout) { + clearTimeout(waiter.timeout) + waiter.timeout = null + } + const waiters = this.messageWaitersByHandle.get(waiter.handle) + if (waiters) { + waiters.delete(waiter) + if (waiters.size === 0) { + this.messageWaitersByHandle.delete(waiter.handle) + } + } + } + private getLiveLeafForHandle(handle: string): { record: TerminalHandleRecord leaf: RuntimeLeafRecord @@ -1698,6 +1845,59 @@ export class OrcaRuntimeService { } } + // Why: OSC title detection via onPtyData is the primary signal for tui-idle, + // but daemon-hosted terminals don't flow PTY data through the runtime, and + // some agents don't emit recognized titles on startup. This fallback polls + // two signals: (1) the renderer-synced tab title (reflects xterm's OSC title + // handler, works even for daemon terminals), and (2) the PTY foreground process + // + output quiescence. The poll self-cancels when the primary OSC path fires. + private startTuiIdleFallbackPoll(waiter: TerminalWaiter, leaf: RuntimeLeafRecord): void { + waiter.pollInterval = setInterval(async () => { + try { + // If OSC detection via onPtyData kicked in, stop — the primary path + // will handle (or has already handled) resolution. + if (leaf.lastAgentStatus !== null) { + if (waiter.pollInterval) { + clearInterval(waiter.pollInterval) + waiter.pollInterval = null + } + return + } + // Why: check the renderer-synced title. For daemon-hosted terminals, + // this is the only path where OSC titles are visible to the runtime. + const pollTitle = leaf.paneTitle ?? this.tabs.get(leaf.tabId)?.title + if (pollTitle) { + const titleStatus = detectAgentStatusFromTitle(pollTitle) + if (titleStatus === 'idle') { + if (waiter.pollInterval) { + clearInterval(waiter.pollInterval) + waiter.pollInterval = null + } + this.resolveWaiter(waiter, buildTerminalWaitResult(waiter.handle, 'tui-idle', leaf)) + return + } + } + // Foreground process fallback: if the daemon/local provider can report + // the process and it's a non-shell with quiet output, treat as idle. + if (leaf.ptyId && this.ptyController) { + const fg = await this.ptyController.getForegroundProcess(leaf.ptyId) + if (fg && !isShellProcess(fg)) { + const quietMs = leaf.lastOutputAt ? Date.now() - leaf.lastOutputAt : 0 + if (quietMs >= TUI_IDLE_QUIESCENCE_MS) { + if (waiter.pollInterval) { + clearInterval(waiter.pollInterval) + waiter.pollInterval = null + } + this.resolveWaiter(waiter, buildTerminalWaitResult(waiter.handle, 'tui-idle', leaf)) + } + } + } + } catch { + // Swallow transient PTY inspection errors and keep polling. + } + }, TUI_IDLE_POLL_INTERVAL_MS) + } + // Why: push-on-idle delivery — when an agent transitions working→idle, check // for unread orchestration messages addressed to that terminal and inject them // into the PTY. This is event-driven (no polling) because the runtime owns @@ -1754,6 +1954,9 @@ export class OrcaRuntimeService { if (waiter.timeout) { clearTimeout(waiter.timeout) } + if (waiter.pollInterval) { + clearInterval(waiter.pollInterval) + } const waiters = this.waitersByHandle.get(waiter.handle) if (!waiters) { return @@ -2930,6 +3133,9 @@ function buildSendPayload(action: { // will ever fire. A 5-minute ceiling prevents indefinite hangs while still // giving real agent tasks plenty of time to complete. const TUI_IDLE_DEFAULT_TIMEOUT_MS = 5 * 60 * 1000 +const TUI_IDLE_POLL_INTERVAL_MS = 2000 +const TUI_IDLE_QUIESCENCE_MS = 3000 +const MESSAGE_WAIT_DEFAULT_TIMEOUT_MS = 2 * 60 * 1000 function buildTerminalWaitResult( handle: string, diff --git a/src/main/runtime/rpc/methods/orchestration.test.ts b/src/main/runtime/rpc/methods/orchestration.test.ts index e554c745f..64a2507d0 100644 --- a/src/main/runtime/rpc/methods/orchestration.test.ts +++ b/src/main/runtime/rpc/methods/orchestration.test.ts @@ -437,6 +437,7 @@ describe('orchestration RPC methods', () => { it('rolls back active dispatch when injection fails', async () => { setup() const task = db.createTask({ spec: 'work' }) + vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) vi.spyOn(runtime, 'sendTerminal').mockRejectedValue(new Error('terminal_not_writable')) await expect( @@ -454,6 +455,7 @@ describe('orchestration RPC methods', () => { it('uses caller-provided dev mode for injected preamble', async () => { setup() const task = db.createTask({ spec: 'work' }) + vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(true) const send = vi.spyOn(runtime, 'sendTerminal').mockResolvedValue({ handle: 'term_a', accepted: true, @@ -470,6 +472,20 @@ describe('orchestration RPC methods', () => { expect(send.mock.calls[0]?.[1].text).toContain('orca-dev orchestration send') }) + it('rejects inject to terminal without recognized agent', async () => { + setup() + const task = db.createTask({ spec: 'work' }) + vi.spyOn(runtime, 'isTerminalRunningAgent').mockResolvedValue(false) + + await expect( + call('orchestration.dispatch', { + task: task.id, + to: 'term_a', + inject: true + }) + ).rejects.toThrow('no recognized agent detected') + }) + it('rejects dispatch to occupied terminal', async () => { setup() const t1 = db.createTask({ spec: 'first' }) diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index dc0a7379a..5c467e369 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -53,7 +53,9 @@ const CheckParams = z.object({ terminal: OptionalString, unread: OptionalBoolean, types: OptionalString, - inject: OptionalBoolean + inject: OptionalBoolean, + wait: OptionalBoolean, + timeoutMs: OptionalFiniteNumber }) const ReplyParams = z.object({ @@ -134,6 +136,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ payload: params.payload }) runtime.deliverPendingMessagesForHandle(params.to) + runtime.notifyMessageArrived(params.to) return { message: msg } } @@ -164,6 +167,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ ) for (const handle of handles) { runtime.deliverPendingMessagesForHandle(handle) + runtime.notifyMessageArrived(handle) } return { messages, recipients: handles.length } @@ -173,7 +177,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ defineMethod({ name: 'orchestration.check', params: CheckParams, - handler: (params, { runtime }) => { + handler: async (params, { runtime }) => { const db = runtime.getOrchestrationDb() const handle = params.terminal ?? 'unknown' const typeFilter = params.types @@ -188,22 +192,36 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ } const showUnread = params.unread !== false - const messages = showUnread - ? db.getUnreadMessages(handle, typeFilter) - : db.getAllMessages(handle) - // Why: mark retrieved unread messages as read so the next check call - // only surfaces genuinely new messages (Section 4.4). - if (showUnread && messages.length > 0) { - db.markAsRead(messages.map((m) => m.id)) + const readAndReturn = () => { + const messages = showUnread + ? db.getUnreadMessages(handle, typeFilter) + : db.getAllMessages(handle) + + if (showUnread && messages.length > 0) { + db.markAsRead(messages.map((m) => m.id)) + } + + if (params.inject) { + const formatted = messages.map(formatMessageBanner).join('\n\n') + return { messages, formatted, count: messages.length } + } + + return { messages, count: messages.length } } - if (params.inject) { - const formatted = messages.map(formatMessageBanner).join('\n\n') - return { messages, formatted, count: messages.length } + const result = readAndReturn() + if (result.count > 0 || !params.wait) { + return result } - return { messages, count: messages.length } + // Why: blocking wait lets coordinators replace sleep+poll loops with a + // single call that resolves when a message arrives or the timeout expires. + await runtime.waitForMessage(handle, { + typeFilter: typeFilter as string[] | undefined, + timeoutMs: params.timeoutMs ?? undefined + }) + return readAndReturn() } }), @@ -227,6 +245,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ threadId: original.thread_id ?? original.id }) + runtime.notifyMessageArrived(original.from_handle) return { message: reply } } }), @@ -306,6 +325,21 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [ throw new Error(`Task ${params.task} is ${task.status}; only ready tasks can be dispatched`) } + // Why: dispatching with --inject to a bare shell (zsh/bash) dumps the + // preamble as shell commands, producing gibberish. Check both OSC title + // status and foreground process — Claude Code doesn't emit recognized OSC + // titles on startup, so title-only detection misses freshly spawned agents. + if (params.inject) { + const hasAgent = await runtime.isTerminalRunningAgent(params.to) + if (!hasAgent) { + throw new Error( + `Cannot dispatch --inject to terminal ${params.to}: no recognized agent detected. ` + + 'Start an agent CLI (e.g. claude, codex, gemini) in the terminal first, ' + + 'or dispatch without --inject and send the prompt manually.' + ) + } + } + const ctx = db.createDispatchContext(params.task, params.to) let injected = false diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index 594a0161b..58fff491f 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -247,7 +247,8 @@ describe('OrcaRuntimeRpcServer', () => { writes.push(data) return true }, - kill: () => true + kill: () => true, + getForegroundProcess: async () => null }) const server = new OrcaRuntimeRpcServer({ runtime, userDataPath }) @@ -341,7 +342,7 @@ describe('OrcaRuntimeRpcServer', () => { id: 'req_send', ok: true }) - expect(writes).toEqual(['continue\r']) + expect(writes).toEqual(['continue', '\r']) const waitPromise = sendRequest(metadata!.transport!.endpoint, { id: 'req_wait', diff --git a/src/renderer/src/lib/tui-agent-startup.ts b/src/renderer/src/lib/tui-agent-startup.ts index 1ba2e70ba..59c64c0f0 100644 --- a/src/renderer/src/lib/tui-agent-startup.ts +++ b/src/renderer/src/lib/tui-agent-startup.ts @@ -83,17 +83,4 @@ export function buildAgentStartupPlan(args: { } } -export function isShellProcess(processName: string): boolean { - const normalized = processName.trim().toLowerCase() - return ( - normalized === '' || - normalized === 'bash' || - normalized === 'zsh' || - normalized === 'sh' || - normalized === 'fish' || - normalized === 'cmd.exe' || - normalized === 'powershell.exe' || - normalized === 'pwsh.exe' || - normalized === 'nu' - ) -} +export { isShellProcess } from '../../../shared/agent-detection' diff --git a/src/renderer/src/runtime/sync-runtime-graph.ts b/src/renderer/src/runtime/sync-runtime-graph.ts index 3ebe8fb08..f7502bdeb 100644 --- a/src/renderer/src/runtime/sync-runtime-graph.ts +++ b/src/renderer/src/runtime/sync-runtime-graph.ts @@ -98,12 +98,14 @@ async function syncRuntimeGraph(): Promise { ptyId: savedPtyId }) } + const paneTitles = state.runtimePaneTitlesByTabId[tabId] ?? {} graph.leaves.push({ tabId, worktreeId: registeredTab.worktreeId, leafId, paneRuntimeId: pane.id, - ptyId + ptyId, + paneTitle: paneTitles[pane.id] ?? null }) } } diff --git a/src/shared/agent-detection.ts b/src/shared/agent-detection.ts index a3f4416d5..caba0ead3 100644 --- a/src/shared/agent-detection.ts +++ b/src/shared/agent-detection.ts @@ -434,3 +434,23 @@ export function detectAgentStatusFromTitle(title: string): AgentStatus | null { return null } + +// Why: shared between the runtime (dispatch guard, tui-idle fallback) and the +// renderer (agent-ready-wait, new-workspace). A bare shell is the only process +// type that garbles injected preambles, so this is the negative signal for +// "is an agent running". +const SHELL_NAMES = new Set([ + '', + 'bash', + 'zsh', + 'sh', + 'fish', + 'cmd.exe', + 'powershell.exe', + 'pwsh.exe', + 'nu' +]) + +export function isShellProcess(processName: string): boolean { + return SHELL_NAMES.has(processName.trim().toLowerCase()) +} diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index 1d0835c80..adba1447e 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -49,6 +49,7 @@ export type RuntimeSyncedLeaf = { leafId: string paneRuntimeId: number ptyId: string | null + paneTitle?: string | null } export type RuntimeSyncWindowGraph = {