From a6f9a5826e11119856370428a12fe90313daa96e Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 26 May 2026 14:45:34 -0700 Subject: [PATCH] Add Command Code agent status tracking Adds Command Code hook installation, status normalization, launch seeding, and terminal-output fallback detection for working/done sidebar status. Includes review hardening for long-running tool repaint cadence and prompt sanitization across split ANSI chunks. --- config/tsconfig.cli.json | 1 + .../managed-agent-hook-controls.ts | 4 + .../remote-hook-service-installers.test.ts | 25 +- .../remote-managed-hook-installers.ts | 2 + src/main/command-code/hook-service.test.ts | 174 +++++++++ src/main/command-code/hook-service.ts | 355 ++++++++++++++++++ src/main/daemon/pty-subprocess.test.ts | 34 ++ src/main/daemon/pty-subprocess.ts | 5 +- src/main/ipc/agent-hooks.test.ts | 17 + src/main/ipc/agent-hooks.ts | 15 + src/preload/api-types.ts | 1 + src/preload/index.ts | 2 + .../src/components/AgentStateDot.test.ts | 8 + .../sidebar/StatusIndicator.test.ts | 8 + .../command-code-output-status.test.ts | 216 +++++++++++ .../command-code-output-status.ts | 222 +++++++++++ .../terminal-pane/pty-connection-types.ts | 3 + .../terminal-pane/pty-connection.test.ts | 249 ++++++++++++ .../terminal-pane/pty-connection.ts | 95 +++++ ...rminal-agent-quick-command-presets.test.ts | 1 + src/renderer/src/hooks/useComposerState.ts | 17 + .../launch-agent-background-session.test.ts | 18 + .../lib/launch-agent-background-session.ts | 9 + .../src/lib/launch-agent-in-new-tab.test.ts | 124 ++++++ .../src/lib/launch-agent-in-new-tab.ts | 26 ++ .../src/lib/tui-agent-startup.test.ts | 6 +- src/renderer/src/lib/worktree-activation.ts | 16 +- src/renderer/src/store/slices/terminals.ts | 4 + src/renderer/src/web/web-preload-api.ts | 2 + src/shared/agent-hook-listener.test.ts | 75 ++++ src/shared/agent-hook-listener.ts | 155 ++++++++ src/shared/agent-hook-relay.ts | 1 + src/shared/agent-hook-types.ts | 1 + src/shared/tui-agent-config.ts | 8 +- src/shared/tui-agent-selection.test.ts | 1 + 35 files changed, 1890 insertions(+), 10 deletions(-) create mode 100644 src/main/command-code/hook-service.test.ts create mode 100644 src/main/command-code/hook-service.ts create mode 100644 src/renderer/src/components/terminal-pane/command-code-output-status.test.ts create mode 100644 src/renderer/src/components/terminal-pane/command-code-output-status.ts create mode 100644 src/renderer/src/lib/launch-agent-in-new-tab.test.ts diff --git a/config/tsconfig.cli.json b/config/tsconfig.cli.json index 7300cb749..111ac7a86 100644 --- a/config/tsconfig.cli.json +++ b/config/tsconfig.cli.json @@ -14,6 +14,7 @@ "../src/main/codex/config-toml-trust.ts", "../src/main/codex/hook-service.ts", "../src/main/codex-accounts/fs-utils.ts", + "../src/main/command-code/hook-service.ts", "../src/main/copilot/hook-service.ts", "../src/main/cursor/hook-service.ts", "../src/main/droid/hook-service.ts", diff --git a/src/main/agent-hooks/managed-agent-hook-controls.ts b/src/main/agent-hooks/managed-agent-hook-controls.ts index 3fabb160d..98df61b8a 100644 --- a/src/main/agent-hooks/managed-agent-hook-controls.ts +++ b/src/main/agent-hooks/managed-agent-hook-controls.ts @@ -7,6 +7,7 @@ import { codexHookService } from '../codex/hook-service' import { copilotHookService } from '../copilot/hook-service' import { cursorHookService } from '../cursor/hook-service' import { droidHookService } from '../droid/hook-service' +import { commandCodeHookService } from '../command-code/hook-service' import { geminiHookService } from '../gemini/hook-service' import { grokHookService } from '../grok/hook-service' import { hermesHookService } from '../hermes/hook-service' @@ -22,6 +23,7 @@ export const MANAGED_AGENT_HOOK_INSTALLERS: readonly ManagedAgentHookInstaller[] ['antigravity', () => antigravityHookService.install()], ['cursor', () => cursorHookService.install()], ['droid', () => droidHookService.install()], + ['command-code', () => commandCodeHookService.install()], ['grok', () => grokHookService.install()], ['copilot', () => copilotHookService.install()], ['hermes', () => hermesHookService.install()] @@ -34,6 +36,7 @@ const LOCAL_MANAGED_HOOK_REMOVERS: readonly ManagedHookRemover[] = [ ['antigravity', () => antigravityHookService.remove()], ['cursor', () => cursorHookService.remove()], ['droid', () => droidHookService.remove()], + ['command-code', () => commandCodeHookService.remove()], ['grok', () => grokHookService.remove()], ['copilot', () => copilotHookService.remove()], ['hermes', () => hermesHookService.remove()] @@ -46,6 +49,7 @@ const LOCAL_MANAGED_HOOK_STATUS_READERS: readonly ManagedHookStatusReader[] = [ ['antigravity', () => antigravityHookService.getStatus()], ['cursor', () => cursorHookService.getStatus()], ['droid', () => droidHookService.getStatus()], + ['command-code', () => commandCodeHookService.getStatus()], ['grok', () => grokHookService.getStatus()], ['copilot', () => copilotHookService.getStatus()], ['hermes', () => hermesHookService.getStatus()] diff --git a/src/main/agent-hooks/remote-hook-service-installers.test.ts b/src/main/agent-hooks/remote-hook-service-installers.test.ts index 48ad1f8fe..d87b93b58 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -10,6 +10,7 @@ vi.mock('electron', () => ({ import { CodexHookService } from '../codex/hook-service' import { CursorHookService } from '../cursor/hook-service' +import { CommandCodeHookService } from '../command-code/hook-service' import { GeminiHookService } from '../gemini/hook-service' import { AntigravityHookService } from '../antigravity/hook-service' import { ClaudeHookService } from '../claude/hook-service' @@ -138,6 +139,11 @@ describe('remote hook service installers', () => { path: '/home/dev/.orca/agent-hooks/cursor-hook.sh', install: (sftp: SFTPWrapper) => new CursorHookService().installRemote(sftp, '/home/dev') }, + { + path: '/home/dev/.orca/agent-hooks/command-code-hook.sh', + install: (sftp: SFTPWrapper) => + new CommandCodeHookService().installRemote(sftp, '/home/dev') + }, { path: '/home/dev/.orca/agent-hooks/grok-hook.sh', install: (sftp: SFTPWrapper) => new GrokHookService().installRemote(sftp, '/home/dev') @@ -206,15 +212,17 @@ describe('remote hook service installers', () => { expect(fs.files.get('/home/dev/.orca/agent-hooks/codex-hook.sh')).toContain('#!/bin/sh') }) - it('installs remote Gemini, Antigravity, Cursor, and Grok configs using their CLI-specific schemas', async () => { + it('installs remote Gemini, Antigravity, Cursor, Command Code, and Grok configs using their CLI-specific schemas', async () => { const gemini = createFakeSftp() const antigravity = createFakeSftp() const cursor = createFakeSftp() + const commandCode = createFakeSftp() const grok = createFakeSftp() await new GeminiHookService().installRemote(gemini.sftp, '/home/dev') await new AntigravityHookService().installRemote(antigravity.sftp, '/home/dev') await new CursorHookService().installRemote(cursor.sftp, '/home/dev') + await new CommandCodeHookService().installRemote(commandCode.sftp, '/home/dev') await new GrokHookService().installRemote(grok.sftp, '/home/dev') const geminiConfig = JSON.parse(gemini.fs.files.get('/home/dev/.gemini/settings.json')!) as { @@ -268,6 +276,21 @@ describe('remote hook service installers', () => { expect(definition?.hooks).toBeUndefined() } + const commandCodeConfig = JSON.parse( + commandCode.fs.files.get('/home/dev/.commandcode/settings.json')! + ) as { + hooks: Record + } + for (const eventName of ['PreToolUse', 'PostToolUse', 'Stop']) { + const definition = commandCodeConfig.hooks[eventName]?.[0] + const command = definition?.hooks?.[0]?.command + expect(command).toContain('/home/dev/.orca/agent-hooks/command-code-hook.sh') + expect(command).toMatch(/^if \[ -x /) + } + expect(commandCodeConfig.hooks.PreToolUse?.[0]?.matcher).toBe('.*') + expect(commandCodeConfig.hooks.PostToolUse?.[0]?.matcher).toBe('.*') + expect(commandCodeConfig.hooks.Stop?.[0]?.matcher).toBeUndefined() + const grokConfig = JSON.parse(grok.fs.files.get('/home/dev/.grok/hooks/orca-status.json')!) as { hooks: Record } diff --git a/src/main/agent-hooks/remote-managed-hook-installers.ts b/src/main/agent-hooks/remote-managed-hook-installers.ts index a8ef3d910..7100bec01 100644 --- a/src/main/agent-hooks/remote-managed-hook-installers.ts +++ b/src/main/agent-hooks/remote-managed-hook-installers.ts @@ -5,6 +5,7 @@ import { codexHookService } from '../codex/hook-service' import { geminiHookService } from '../gemini/hook-service' import { antigravityHookService } from '../antigravity/hook-service' import { cursorHookService } from '../cursor/hook-service' +import { commandCodeHookService } from '../command-code/hook-service' import { grokHookService } from '../grok/hook-service' import { hermesHookService } from '../hermes/hook-service' @@ -19,6 +20,7 @@ const REMOTE_MANAGED_HOOK_INSTALLERS: readonly RemoteManagedHookInstaller[] = [ ['gemini', (sftp, remoteHome) => geminiHookService.installRemote(sftp, remoteHome)], ['antigravity', (sftp, remoteHome) => antigravityHookService.installRemote(sftp, remoteHome)], ['cursor', (sftp, remoteHome) => cursorHookService.installRemote(sftp, remoteHome)], + ['command-code', (sftp, remoteHome) => commandCodeHookService.installRemote(sftp, remoteHome)], ['grok', (sftp, remoteHome) => grokHookService.installRemote(sftp, remoteHome)], ['hermes', (sftp, remoteHome) => hermesHookService.installRemote(sftp, remoteHome)] ] diff --git a/src/main/command-code/hook-service.test.ts b/src/main/command-code/hook-service.test.ts new file mode 100644 index 000000000..2fdd7826c --- /dev/null +++ b/src/main/command-code/hook-service.test.ts @@ -0,0 +1,174 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { spawn } from 'child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { createServer } from 'http' +import { tmpdir } from 'os' +import { dirname, join } from 'path' +import type { AddressInfo } from 'net' + +const { homedirMock } = vi.hoisted(() => ({ + homedirMock: vi.fn<() => string>() +})) + +vi.mock('os', async () => { + const actual = (await vi.importActual('os')) as Record + return { + ...actual, + homedir: homedirMock + } +}) + +import { CommandCodeHookService } from './hook-service' + +describe('CommandCodeHookService', () => { + let homeDir: string + + beforeEach(() => { + homeDir = mkdtempSync(join(tmpdir(), 'orca-command-code-home-')) + homedirMock.mockReturnValue(homeDir) + }) + + afterEach(() => { + vi.clearAllMocks() + rmSync(homeDir, { recursive: true, force: true }) + }) + + it('installs the managed command for Command Code status events', () => { + const status = new CommandCodeHookService().install() + + expect(status.state).toBe('installed') + expect(status.managedHooksPresent).toBe(true) + + const config = JSON.parse( + readFileSync(join(homeDir, '.commandcode', 'settings.json'), 'utf8') + ) as { + hooks: Record + } + expect(Object.keys(config.hooks).sort()).toEqual(['PostToolUse', 'PreToolUse', 'Stop'].sort()) + expect(config.hooks.PreToolUse[0].matcher).toBe('.*') + expect(config.hooks.PostToolUse[0].matcher).toBe('.*') + expect(config.hooks.Stop[0].matcher).toBeUndefined() + expect(config.hooks.PreToolUse[0].hooks[0].command).toContain('command-code-hook') + expect(config.hooks.PreToolUse[0].hooks[0].command).toContain(join(homeDir, '.orca')) + expect(config.hooks.PreToolUse[0].hooks[0].command).toMatch(/^if \[ -x /) + }) + + it('installs a hook script that can recover the endpoint when Command Code strips token env', () => { + new CommandCodeHookService().install() + + const scriptFileName = + process.platform === 'win32' ? 'command-code-hook.cmd' : 'command-code-hook.sh' + const script = readFileSync(join(homeDir, '.orca', 'agent-hooks', scriptFileName), 'utf8') + + if (process.platform === 'win32') { + expect(script).toContain('sourceEndpointByPort') + expect(script).toContain('orca-dev\\agent-hooks') + expect(script).toContain('set ORCA_AGENT_HOOK_PORT=') + } else { + expect(script).toContain('Command Code strips TOKEN-like env vars') + expect(script).toContain('Command Code sanitizes hook subprocess env') + expect(script).toContain('__orca_read_ancestor_var') + expect(script).toContain('__orca_fill_from_endpoint_file') + expect(script).toContain('[ "$__orca_endpoint_port" != "$ORCA_AGENT_HOOK_PORT" ]') + expect(script).toContain('ORCA_PANE_KEY') + expect(script).toContain('orca-dev/agent-hooks') + expect(script).toContain('endpoint_port=') + } + }) + + const itPosix = process.platform === 'win32' ? it.skip : it + + itPosix('does not let stale endpoint files clobber recovered connection fields', async () => { + new CommandCodeHookService().install() + + const staleEndpointPath = join(homeDir, 'stale-endpoint.env') + writeFileSync( + staleEndpointPath, + [ + 'ORCA_AGENT_HOOK_PORT=9', + 'ORCA_AGENT_HOOK_TOKEN=stale-token', + 'ORCA_AGENT_HOOK_ENV=development', + 'ORCA_AGENT_HOOK_VERSION=1', + '' + ].join('\n') + ) + + const requests: { body: string; token: string | string[] | undefined }[] = [] + const server = createServer((req, res) => { + let body = '' + req.setEncoding('utf8') + req.on('data', (chunk) => { + body += chunk + }) + req.on('end', () => { + requests.push({ body, token: req.headers['x-orca-agent-hook-token'] }) + res.statusCode = 204 + res.end() + }) + }) + + try { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() as AddressInfo + const scriptPath = join(homeDir, '.orca', 'agent-hooks', 'command-code-hook.sh') + const child = spawn('/bin/sh', [scriptPath], { + env: { + ...process.env, + HOME: homeDir, + ORCA_AGENT_HOOK_ENDPOINT: staleEndpointPath, + ORCA_AGENT_HOOK_PORT: String(address.port), + ORCA_AGENT_HOOK_TOKEN: 'current-token', + ORCA_PANE_KEY: 'tab:leaf', + ORCA_TAB_ID: 'tab', + ORCA_WORKTREE_ID: 'worktree', + ORCA_AGENT_HOOK_ENV: 'development', + ORCA_AGENT_HOOK_VERSION: '1' + }, + stdio: ['pipe', 'ignore', 'pipe'] + }) + child.stdin.end(JSON.stringify({ hook_event_name: 'Stop' })) + + const exitCode = await new Promise((resolve, reject) => { + let stderr = '' + child.stderr.setEncoding('utf8') + child.stderr.on('data', (chunk) => { + stderr += chunk + }) + child.on('error', reject) + child.on('exit', (code) => { + if (stderr.trim()) { + reject(new Error(stderr)) + } else { + resolve(code) + } + }) + }) + + expect(exitCode).toBe(0) + expect(requests).toHaveLength(1) + expect(requests[0].token).toBe('current-token') + expect(new URLSearchParams(requests[0].body).get('paneKey')).toBe('tab:leaf') + } finally { + await new Promise((resolve) => server.close(() => resolve())) + } + }) + + it('reports partial when one managed event is missing', () => { + const service = new CommandCodeHookService() + service.install() + + const configPath = join(homeDir, '.commandcode', 'settings.json') + const config = JSON.parse(readFileSync(configPath, 'utf8')) as { + hooks: Record + } + delete config.hooks.Stop + mkdirSync(dirname(configPath), { recursive: true }) + writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`) + + const status = service.getStatus() + + expect(status.state).toBe('partial') + expect(status.managedHooksPresent).toBe(true) + expect(status.detail).toBe('Managed hook missing for events: Stop') + }) +}) diff --git a/src/main/command-code/hook-service.ts b/src/main/command-code/hook-service.ts new file mode 100644 index 000000000..516d4c0ba --- /dev/null +++ b/src/main/command-code/hook-service.ts @@ -0,0 +1,355 @@ +/* eslint-disable max-lines */ +import { homedir } from 'os' +import { join } from 'path' +import type { SFTPWrapper } from 'ssh2' +import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' +import { + createManagedCommandMatcher, + buildWindowsAgentHookPostCommand, + getSharedManagedScriptPath, + readHooksJson, + removeManagedCommands, + wrapPosixHookCommand, + writeHooksJson, + writeManagedScript, + type HookDefinition +} from '../agent-hooks/installer-utils' +import { + readHooksJsonRemote, + writeHooksJsonRemote, + writeManagedScriptRemote +} from '../agent-hooks/installer-utils-remote' + +const COMMAND_CODE_EVENTS = [ + { + eventName: 'PreToolUse', + definition: { matcher: '.*', hooks: [{ type: 'command', command: '' }] } + }, + { + eventName: 'PostToolUse', + definition: { matcher: '.*', hooks: [{ type: 'command', command: '' }] } + }, + { eventName: 'Stop', definition: { hooks: [{ type: 'command', command: '' }] } } +] as const + +function getConfigPath(): string { + return join(homedir(), '.commandcode', 'settings.json') +} + +function getManagedScriptFileName(): string { + return process.platform === 'win32' ? 'command-code-hook.cmd' : 'command-code-hook.sh' +} + +function getManagedScriptPath(): string { + return getSharedManagedScriptPath(getManagedScriptFileName()) +} + +function getManagedCommand(scriptPath: string): string { + return process.platform === 'win32' ? scriptPath : wrapPosixHookCommand(scriptPath) +} + +function getManagedScript(target: 'local' | 'posix' = 'local'): string { + if (target === 'local' && process.platform === 'win32') { + return [ + '@echo off', + 'setlocal', + 'if "%ORCA_AGENT_HOOK_PORT%"=="" if defined ORCA_AGENT_HOOK_ENDPOINT if exist "%ORCA_AGENT_HOOK_ENDPOINT%" call "%ORCA_AGENT_HOOK_ENDPOINT%" 2>nul', + 'if "%ORCA_AGENT_HOOK_TOKEN%"=="" if not "%ORCA_AGENT_HOOK_PORT%"=="" call :sourceEndpointByPort', + 'if "%ORCA_AGENT_HOOK_PORT%"=="" exit /b 0', + 'if "%ORCA_AGENT_HOOK_TOKEN%"=="" exit /b 0', + 'if "%ORCA_PANE_KEY%"=="" exit /b 0', + buildWindowsAgentHookPostCommand('command-code'), + 'exit /b 0', + ':sourceEndpointByPort', + 'if not defined APPDATA exit /b 0', + 'if exist "%APPDATA%\\orca-dev\\agent-hooks" for /r "%APPDATA%\\orca-dev\\agent-hooks" %%F in (endpoint.cmd) do call :maybeSourceEndpoint "%%~fF"', + 'if "%ORCA_AGENT_HOOK_TOKEN%"=="" if exist "%APPDATA%\\orca\\agent-hooks" for /r "%APPDATA%\\orca\\agent-hooks" %%F in (endpoint.cmd) do call :maybeSourceEndpoint "%%~fF"', + 'exit /b 0', + ':maybeSourceEndpoint', + 'if not "%ORCA_AGENT_HOOK_TOKEN%"=="" exit /b 0', + 'for /f "tokens=2 delims==" %%P in (\'findstr /b /c:"set ORCA_AGENT_HOOK_PORT=" "%~1" 2^>nul\') do if "%%P"=="%ORCA_AGENT_HOOK_PORT%" call "%~1" 2>nul', + 'exit /b 0', + '' + ].join('\r\n') + } + + return [ + '#!/bin/sh', + '__orca_read_ancestor_var() {', + ' __orca_name="$1"', + ' __orca_pid="${PPID:-}"', + ' while [ -n "$__orca_pid" ] && [ "$__orca_pid" != "0" ] && [ "$__orca_pid" != "1" ]; do', + ' __orca_value=""', + ' if [ -r "/proc/$__orca_pid/environ" ]; then', + ' __orca_value=$(tr "\\000" "\\n" < "/proc/$__orca_pid/environ" 2>/dev/null | sed -n "s/^${__orca_name}=//p" | head -n 1)', + ' fi', + ' if [ -z "$__orca_value" ]; then', + ' __orca_value=$(ps eww -p "$__orca_pid" -o command= 2>/dev/null | tr " " "\\n" | sed -n "s/^${__orca_name}=//p" | head -n 1)', + ' fi', + ' if [ -n "$__orca_value" ]; then', + ' printf "%s\\n" "$__orca_value"', + ' return 0', + ' fi', + ' __orca_pid=$(ps -o ppid= -p "$__orca_pid" 2>/dev/null | tr -d " ")', + ' done', + ' return 1', + '}', + '__orca_fill_from_ancestor() {', + ' __orca_name="$1"', + ' case "$__orca_name" in', + ' ORCA_AGENT_HOOK_ENDPOINT) [ -z "${ORCA_AGENT_HOOK_ENDPOINT:-}" ] || return 0 ;;', + ' ORCA_AGENT_HOOK_PORT) [ -z "${ORCA_AGENT_HOOK_PORT:-}" ] || return 0 ;;', + ' ORCA_AGENT_HOOK_TOKEN) [ -z "${ORCA_AGENT_HOOK_TOKEN:-}" ] || return 0 ;;', + ' ORCA_AGENT_HOOK_ENV) [ -z "${ORCA_AGENT_HOOK_ENV:-}" ] || return 0 ;;', + ' ORCA_AGENT_HOOK_VERSION) [ -z "${ORCA_AGENT_HOOK_VERSION:-}" ] || return 0 ;;', + ' ORCA_PANE_KEY) [ -z "${ORCA_PANE_KEY:-}" ] || return 0 ;;', + ' ORCA_TAB_ID) [ -z "${ORCA_TAB_ID:-}" ] || return 0 ;;', + ' ORCA_WORKTREE_ID) [ -z "${ORCA_WORKTREE_ID:-}" ] || return 0 ;;', + ' *) return 0 ;;', + ' esac', + ' __orca_value=$(__orca_read_ancestor_var "$__orca_name") || return 0', + ' [ -n "$__orca_value" ] && export "$__orca_name=$__orca_value"', + '}', + '__orca_endpoint_value() {', + ' __orca_endpoint_name="$1"', + ' __orca_endpoint_path="$2"', + ' sed -n "s/^${__orca_endpoint_name}=//p" "$__orca_endpoint_path" 2>/dev/null | head -n 1', + '}', + '__orca_fill_from_endpoint_file() {', + ' __orca_endpoint_path="$1"', + ' [ -r "$__orca_endpoint_path" ] || return 0', + ' __orca_endpoint_port=$(__orca_endpoint_value ORCA_AGENT_HOOK_PORT "$__orca_endpoint_path")', + ' if [ -n "${ORCA_AGENT_HOOK_PORT:-}" ] && [ -n "$__orca_endpoint_port" ] && [ "$__orca_endpoint_port" != "$ORCA_AGENT_HOOK_PORT" ]; then', + ' return 0', + ' fi', + ' for __orca_endpoint_name in ORCA_AGENT_HOOK_PORT ORCA_AGENT_HOOK_TOKEN ORCA_AGENT_HOOK_ENV ORCA_AGENT_HOOK_VERSION; do', + ' eval "__orca_current=\\${$__orca_endpoint_name:-}"', + ' [ -z "$__orca_current" ] || continue', + ' __orca_endpoint_value=$(__orca_endpoint_value "$__orca_endpoint_name" "$__orca_endpoint_path")', + ' [ -n "$__orca_endpoint_value" ] && export "$__orca_endpoint_name=$__orca_endpoint_value"', + ' done', + '}', + '# Why: Command Code sanitizes hook subprocess env. The parent TUI process', + '# still has Orca pane/hook metadata, so recover it before posting.', + 'for __orca_name in ORCA_AGENT_HOOK_ENDPOINT ORCA_AGENT_HOOK_PORT ORCA_AGENT_HOOK_TOKEN ORCA_AGENT_HOOK_ENV ORCA_AGENT_HOOK_VERSION ORCA_PANE_KEY ORCA_TAB_ID ORCA_WORKTREE_ID; do', + ' __orca_fill_from_ancestor "$__orca_name"', + 'done', + 'if [ -n "$ORCA_AGENT_HOOK_ENDPOINT" ] && [ -r "$ORCA_AGENT_HOOK_ENDPOINT" ]; then', + ' __orca_fill_from_endpoint_file "$ORCA_AGENT_HOOK_ENDPOINT"', + 'fi', + '# Why: Command Code strips TOKEN-like env vars before invoking hooks. If', + '# ORCA_AGENT_HOOK_ENDPOINT was not exported into this PTY, recover the', + '# matching endpoint file by the unstripped loopback port.', + 'if [ -z "$ORCA_AGENT_HOOK_TOKEN" ] && [ -n "$ORCA_AGENT_HOOK_PORT" ]; then', + ' for endpoint in \\', + ' "$HOME/Library/Application Support/orca-dev/agent-hooks"/*/endpoint.env \\', + ' "$HOME/Library/Application Support/orca-dev/agent-hooks/endpoint.env" \\', + ' "${XDG_CONFIG_HOME:-$HOME/.config}/orca-dev/agent-hooks"/*/endpoint.env \\', + ' "${XDG_CONFIG_HOME:-$HOME/.config}/orca-dev/agent-hooks/endpoint.env" \\', + ' "$HOME/Library/Application Support/orca/agent-hooks/endpoint.env" \\', + ' "${XDG_CONFIG_HOME:-$HOME/.config}/orca/agent-hooks/endpoint.env"; do', + ' [ -r "$endpoint" ] || continue', + ' endpoint_port=$(sed -n "s/^ORCA_AGENT_HOOK_PORT=//p" "$endpoint" | head -n 1)', + ' if [ "$endpoint_port" = "$ORCA_AGENT_HOOK_PORT" ]; then', + ' __orca_fill_from_endpoint_file "$endpoint"', + ' break', + ' fi', + ' done', + 'fi', + 'if [ -z "$ORCA_AGENT_HOOK_PORT" ] || [ -z "$ORCA_AGENT_HOOK_TOKEN" ] || [ -z "$ORCA_PANE_KEY" ]; then', + ' exit 0', + 'fi', + 'payload=$(cat)', + 'if [ -z "$payload" ]; then', + ' exit 0', + 'fi', + 'curl -sS -X POST "http://127.0.0.1:${ORCA_AGENT_HOOK_PORT}/hook/command-code" \\', + ' -H "Content-Type: application/x-www-form-urlencoded" \\', + ' -H "X-Orca-Agent-Hook-Token: ${ORCA_AGENT_HOOK_TOKEN}" \\', + ' --data-urlencode "paneKey=${ORCA_PANE_KEY}" \\', + ' --data-urlencode "tabId=${ORCA_TAB_ID}" \\', + ' --data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" \\', + ' --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}" \\', + ' --data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}" \\', + ' --data-urlencode "payload=${payload}" >/dev/null 2>&1 || true', + 'exit 0', + '' + ].join('\n') +} + +function buildInstalledConfig( + config: NonNullable>, + command: string, + scriptFileName: string +): void { + const nextHooks = { ...config.hooks } + const isManagedCommand = createManagedCommandMatcher(scriptFileName) + const managedEvents = new Set(COMMAND_CODE_EVENTS.map((event) => event.eventName)) + + // Why: Orca owns only command-code-hook.* entries. Sweep retired managed + // events while preserving user-authored Command Code hooks. + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (managedEvents.has(eventName) || !Array.isArray(definitions)) { + continue + } + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + + for (const event of COMMAND_CODE_EVENTS) { + const current = Array.isArray(nextHooks[event.eventName]) ? nextHooks[event.eventName] : [] + const cleaned = removeManagedCommands(current, isManagedCommand) + const definition: HookDefinition = { + ...event.definition, + hooks: [{ type: 'command', command }] + } + nextHooks[event.eventName] = [...cleaned, definition] + } + + config.hooks = nextHooks +} + +export class CommandCodeHookService { + getStatus(): AgentHookInstallStatus { + const configPath = getConfigPath() + const scriptPath = getManagedScriptPath() + const config = readHooksJson(configPath) + if (!config) { + return { + agent: 'command-code', + state: 'error', + configPath, + managedHooksPresent: false, + detail: 'Could not parse Command Code settings.json' + } + } + + const command = getManagedCommand(scriptPath) + const missing: string[] = [] + let presentCount = 0 + for (const event of COMMAND_CODE_EVENTS) { + const definitions = Array.isArray(config.hooks?.[event.eventName]) + ? config.hooks![event.eventName]! + : [] + const hasCommand = definitions.some((definition) => + (definition.hooks ?? []).some((hook) => hook.command === command) + ) + if (hasCommand) { + presentCount += 1 + } else { + missing.push(event.eventName) + } + } + + const managedHooksPresent = presentCount > 0 + let state: AgentHookInstallState + let detail: string | null + if (missing.length === 0) { + state = 'installed' + detail = null + } else if (presentCount === 0) { + state = 'not_installed' + detail = null + } else { + state = 'partial' + detail = `Managed hook missing for events: ${missing.join(', ')}` + } + return { agent: 'command-code', state, configPath, managedHooksPresent, detail } + } + + install(): AgentHookInstallStatus { + const configPath = getConfigPath() + const scriptPath = getManagedScriptPath() + const config = readHooksJson(configPath) + if (!config) { + return { + agent: 'command-code', + state: 'error', + configPath, + managedHooksPresent: false, + detail: 'Could not parse Command Code settings.json' + } + } + + buildInstalledConfig(config, getManagedCommand(scriptPath), getManagedScriptFileName()) + writeManagedScript(scriptPath, getManagedScript()) + writeHooksJson(configPath, config) + return this.getStatus() + } + + async installRemote(sftp: SFTPWrapper, remoteHome: string): Promise { + const home = remoteHome.replace(/\/$/, '') + const remoteConfigPath = `${home}/.commandcode/settings.json` + const remoteScriptPath = `${home}/.orca/agent-hooks/command-code-hook.sh` + try { + const config = await readHooksJsonRemote(sftp, remoteConfigPath) + if (!config) { + return { + agent: 'command-code', + state: 'error', + configPath: remoteConfigPath, + managedHooksPresent: false, + detail: 'Could not parse remote Command Code settings.json' + } + } + + buildInstalledConfig(config, wrapPosixHookCommand(remoteScriptPath), 'command-code-hook.sh') + await writeManagedScriptRemote(sftp, remoteScriptPath, getManagedScript('posix')) + await writeHooksJsonRemote(sftp, remoteConfigPath, config) + + return { + agent: 'command-code', + state: 'installed', + configPath: remoteConfigPath, + managedHooksPresent: true, + detail: null + } + } catch (err) { + return { + agent: 'command-code', + state: 'error', + configPath: remoteConfigPath, + managedHooksPresent: false, + detail: err instanceof Error ? err.message : String(err) + } + } + } + + remove(): AgentHookInstallStatus { + const configPath = getConfigPath() + const config = readHooksJson(configPath) + if (!config) { + return { + agent: 'command-code', + state: 'error', + configPath, + managedHooksPresent: false, + detail: 'Could not parse Command Code settings.json' + } + } + + const nextHooks = { ...config.hooks } + const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName()) + for (const [eventName, definitions] of Object.entries(nextHooks)) { + if (!Array.isArray(definitions)) { + continue + } + const cleaned = removeManagedCommands(definitions, isManagedCommand) + if (cleaned.length === 0) { + delete nextHooks[eventName] + } else { + nextHooks[eventName] = cleaned + } + } + + config.hooks = nextHooks + writeHooksJson(configPath, config) + return this.getStatus() + } +} + +export const commandCodeHookService = new CommandCodeHookService() diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index e85f1d1d1..daed3cced 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -271,6 +271,40 @@ describe('createPtySubprocess', () => { expect(env.ORCA_AGENT_HOOK_TOKEN).toBe('token') }) + it('preserves explicit development agent hook endpoint files', () => { + const proc = mockPtyProcess() + spawnMock.mockReturnValue(proc) + const previousEndpoint = process.env.ORCA_AGENT_HOOK_ENDPOINT + process.env.ORCA_AGENT_HOOK_ENDPOINT = '/tmp/stale-endpoint.env' + + try { + createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24, + env: { + ORCA_AGENT_HOOK_ENV: 'development', + ORCA_AGENT_HOOK_PORT: '1234', + ORCA_AGENT_HOOK_TOKEN: 'token', + ORCA_AGENT_HOOK_VERSION: '1', + ORCA_AGENT_HOOK_ENDPOINT: '/tmp/fresh-endpoint.env' + } + }) + } finally { + if (previousEndpoint === undefined) { + delete process.env.ORCA_AGENT_HOOK_ENDPOINT + } else { + process.env.ORCA_AGENT_HOOK_ENDPOINT = previousEndpoint + } + } + + const env = spawnMock.mock.calls.at(-1)?.[2].env + expect(env.ORCA_AGENT_HOOK_ENDPOINT).toBe('/tmp/fresh-endpoint.env') + expect(env.ORCA_AGENT_HOOK_ENV).toBe('development') + expect(env.ORCA_AGENT_HOOK_PORT).toBe('1234') + expect(env.ORCA_AGENT_HOOK_TOKEN).toBe('token') + }) + it('forwards write calls', () => { const proc = mockPtyProcess() spawnMock.mockReturnValue(proc) diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts index e6535fcb9..c84f003f2 100644 --- a/src/main/daemon/pty-subprocess.ts +++ b/src/main/daemon/pty-subprocess.ts @@ -73,9 +73,10 @@ function removeInheritedDevAgentHookEndpoint( env: Record, explicitEnv: Record | undefined ): void { - if (explicitEnv?.ORCA_AGENT_HOOK_ENV === 'development') { + if (explicitEnv?.ORCA_AGENT_HOOK_ENV === 'development' && !explicitEnv.ORCA_AGENT_HOOK_ENDPOINT) { // Why: the daemon inherits the app process env before per-PTY env is - // merged, so dev terminals must explicitly drop a parent endpoint.env. + // merged. Strip only stale parent endpoints; a fresh explicit endpoint is + // needed by hooks whose runners scrub token-like env vars before exec. delete env.ORCA_AGENT_HOOK_ENDPOINT } } diff --git a/src/main/ipc/agent-hooks.test.ts b/src/main/ipc/agent-hooks.test.ts index 61c2cc073..679fe8d56 100644 --- a/src/main/ipc/agent-hooks.test.ts +++ b/src/main/ipc/agent-hooks.test.ts @@ -61,9 +61,15 @@ vi.mock('../cursor/hook-service', () => ({ vi.mock('../droid/hook-service', () => ({ droidHookService: { getStatus: vi.fn(() => ({ agent: 'droid', state: 'absent' })) } })) +vi.mock('../command-code/hook-service', () => ({ + commandCodeHookService: { getStatus: vi.fn(() => ({ agent: 'command-code', state: 'absent' })) } +})) vi.mock('../grok/hook-service', () => ({ grokHookService: { getStatus: vi.fn(() => ({ agent: 'grok', state: 'absent' })) } })) +vi.mock('../copilot/hook-service', () => ({ + copilotHookService: { getStatus: vi.fn(() => ({ agent: 'copilot', state: 'absent' })) } +})) vi.mock('../hermes/hook-service', () => ({ hermesHookService: { getStatus: vi.fn(() => ({ agent: 'hermes', state: 'absent' })) } })) @@ -115,6 +121,17 @@ describe('agentHooks:antigravityStatus IPC', () => { }) }) +describe('agentHooks:commandCodeStatus IPC', () => { + it('returns Command Code hook installation status', async () => { + const { registerAgentHookHandlers } = await import('./agent-hooks') + registerAgentHookHandlers() + + const handler = handleHandlers.get('agentHooks:commandCodeStatus') + expect(handler).toBeDefined() + expect(handler!({})).toEqual({ agent: 'command-code', state: 'absent' }) + }) +}) + describe('agentStatus:inferInterrupt IPC', () => { it('forwards valid inference requests to the hook server', async () => { inferInterrupt.mockReturnValue(true) diff --git a/src/main/ipc/agent-hooks.ts b/src/main/ipc/agent-hooks.ts index 79246f38b..11e05618e 100644 --- a/src/main/ipc/agent-hooks.ts +++ b/src/main/ipc/agent-hooks.ts @@ -16,6 +16,7 @@ import { geminiHookService } from '../gemini/hook-service' import { antigravityHookService } from '../antigravity/hook-service' import { cursorHookService } from '../cursor/hook-service' import { droidHookService } from '../droid/hook-service' +import { commandCodeHookService } from '../command-code/hook-service' import { grokHookService } from '../grok/hook-service' import { copilotHookService } from '../copilot/hook-service' import { hermesHookService } from '../hermes/hook-service' @@ -37,6 +38,7 @@ export function registerAgentHookHandlers(): void { ipcMain.removeHandler('agentHooks:antigravityStatus') ipcMain.removeHandler('agentHooks:cursorStatus') ipcMain.removeHandler('agentHooks:droidStatus') + ipcMain.removeHandler('agentHooks:commandCodeStatus') ipcMain.removeHandler('agentHooks:grokStatus') ipcMain.removeHandler('agentHooks:copilotStatus') ipcMain.removeHandler('agentHooks:hermesStatus') @@ -162,6 +164,19 @@ export function registerAgentHookHandlers(): void { } } }) + ipcMain.handle('agentHooks:commandCodeStatus', (): AgentHookInstallStatus => { + try { + return commandCodeHookService.getStatus() + } catch (err) { + return { + agent: 'command-code', + state: 'error', + configPath: '', + managedHooksPresent: false, + detail: err instanceof Error ? err.message : String(err) + } + } + }) ipcMain.handle('agentHooks:grokStatus', (): AgentHookInstallStatus => { try { return grokHookService.getStatus() diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index e85065213..c0afcffa2 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1303,6 +1303,7 @@ export type PreloadApi = { antigravityStatus: () => Promise cursorStatus: () => Promise droidStatus: () => Promise + commandCodeStatus: () => Promise grokStatus: () => Promise copilotStatus: () => Promise hermesStatus: () => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index cae4f791f..ed99e91e8 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1327,6 +1327,8 @@ const api = { ipcRenderer.invoke('agentHooks:cursorStatus'), droidStatus: (): Promise => ipcRenderer.invoke('agentHooks:droidStatus'), + commandCodeStatus: (): Promise => + ipcRenderer.invoke('agentHooks:commandCodeStatus'), grokStatus: (): Promise => ipcRenderer.invoke('agentHooks:grokStatus'), copilotStatus: (): Promise => ipcRenderer.invoke('agentHooks:copilotStatus'), diff --git a/src/renderer/src/components/AgentStateDot.test.ts b/src/renderer/src/components/AgentStateDot.test.ts index e5617c814..2a2aeff31 100644 --- a/src/renderer/src/components/AgentStateDot.test.ts +++ b/src/renderer/src/components/AgentStateDot.test.ts @@ -8,6 +8,14 @@ function renderMarkup(state: AgentDotState): string { } describe('AgentStateDot', () => { + it('renders working as a yellow spinner', () => { + const markup = renderMarkup('working') + + expect(markup).toContain('border-yellow-500') + expect(markup).toContain('border-t-transparent') + expect(markup).toContain('animate-spin') + }) + it('renders done as an emerald check icon', () => { const markup = renderMarkup('done') diff --git a/src/renderer/src/components/sidebar/StatusIndicator.test.ts b/src/renderer/src/components/sidebar/StatusIndicator.test.ts index 55253303c..aa198eb81 100644 --- a/src/renderer/src/components/sidebar/StatusIndicator.test.ts +++ b/src/renderer/src/components/sidebar/StatusIndicator.test.ts @@ -17,6 +17,14 @@ function renderDotClassNames(status: Status): string[] { } describe('StatusIndicator', () => { + it('renders working as a yellow spinner', () => { + const classNames = renderDotClassNames('working') + + expect(classNames).toContain('border-yellow-500') + expect(classNames).toContain('border-t-transparent') + expect(classNames).toContain('animate-spin') + }) + it('renders active as full emerald dot', () => { const classNames = renderDotClassNames('active') diff --git a/src/renderer/src/components/terminal-pane/command-code-output-status.test.ts b/src/renderer/src/components/terminal-pane/command-code-output-status.test.ts new file mode 100644 index 000000000..dc1027ae7 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/command-code-output-status.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, it, vi } from 'vitest' +import { createCommandCodeOutputStatusDetector } from './command-code-output-status' + +describe('createCommandCodeOutputStatusDetector', () => { + it('marks Command Code working with the submitted prompt when the TUI starts thinking', () => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe('❯ Fix the yellow spinner\r\n\x1b[35m✻ Thinking...\x1b[0m')).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner') + }) + + it('waits for the Command Code banner before trusting generic status text', () => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: null, + onWorking + }) + + expect(detector.observe('Thinking about unrelated shell output')).toBe(false) + expect(detector.observe('# Command Code v0.27.2')).toBe(false) + expect(detector.observe('⌘ Parsing...')).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('') + }) + + it.each([ + 'Pondering', + 'Contemplating', + 'Reasoning', + 'Reflecting', + 'Considering', + 'Deliberating', + 'Analyzing', + 'Evaluating', + 'Examining', + 'Inspecting', + 'Investigating', + 'Reviewing', + 'Researching', + 'Studying', + 'Exploring', + 'Mapping', + 'Tracing', + 'Parsing', + 'Processing', + 'Calculating', + 'Computing', + 'Synthesizing', + 'Planning', + 'Outlining', + 'Sketching', + 'Drafting', + 'Composing', + 'Crafting', + 'Building', + 'Assembling', + 'Constructing', + 'Designing', + 'Formulating', + 'Structuring', + 'Organizing', + 'Preparing', + 'Refining', + 'Polishing', + 'Honing', + 'Tuning', + 'Aligning', + 'Connecting', + 'Resolving', + 'Weaving', + 'Threading', + 'Sculpting', + 'Crystallizing', + 'Channeling', + 'Conjuring', + 'Brewing', + 'Working', + 'Cogitating', + 'Ruminating', + 'Hypothesizing', + 'Conceptualizing', + 'Philosophizing', + 'Deciphering', + 'Demystifying', + 'Articulating', + 'Illuminating', + 'Elaborating', + 'Orchestrating', + 'Choreographing', + 'Architecting', + 'Calibrating', + 'Materializing', + 'Visualizing', + 'Harmonizing', + 'Contemplificating', + 'Supercalifragilisting', + 'Bibbidibobbidibooing', + 'Abracadabraing', + 'Hocuspocusing', + 'Razzmatazzing' + ])('marks Command Code working when the TUI reports %s', (statusText) => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe(`❯ Fix the yellow spinner\r\n${statusText}...`)).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner') + }) + + it.each(['Executing: sleep 8 && echo done', '⎿ Running (1s | 0)'])( + 'marks Command Code working when the TUI reports %s', + (statusText) => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe(`❯ Fix the yellow spinner\r\n${statusText}`)).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner') + } + ) + + it('marks Command Code working when active status text is split across PTY chunks', () => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe('❯ Fix the yellow spinner\r\nExpl')).toBe(false) + expect(detector.observe('oring...')).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('Fix the yellow spinner') + }) + + it('does not capture a styled idle composer as the submitted prompt', () => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe('# Command Code v0.27.3\r\n❯ A\x1b')).toBe(false) + expect(detector.observe('[27msk your question...\r\n✻ Thinking...')).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('') + expect(onWorking).not.toHaveBeenCalledWith(expect.stringContaining('[27m')) + }) + + it('captures a submitted prompt when styling is split across PTY chunks', () => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe('❯ Fix the \x1b')).toBe(false) + expect(detector.observe('[38;2;99;109;131mstatus row\r\n✻ Thinking...')).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('Fix the status row') + }) + + it('marks Command Code done when a no-tool turn returns to the idle prompt', () => { + const onWorking = vi.fn() + const onDone = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking, + onDone + }) + + expect(detector.observe('❯ say hi\r\n✻ Thinking...')).toBe(true) + expect( + detector.observe( + '\r\n✻ Thought for 1 second\r\n:: Hi! How can I help you today?\r\n❯ Ask your question...' + ) + ).toBe(true) + + expect(onWorking).toHaveBeenCalledWith('say hi') + expect(onDone).toHaveBeenCalledWith('say hi') + }) + + it('does not mark the initial idle composer as done before a submitted prompt', () => { + const onDone = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking: vi.fn(), + onDone + }) + + expect(detector.observe('# Command Code v0.27.3\r\n❯ Ask your question...')).toBe(false) + + expect(onDone).not.toHaveBeenCalled() + }) + + it('does not treat completed thought text as a working status', () => { + const onWorking = vi.fn() + const detector = createCommandCodeOutputStatusDetector({ + startupCommand: 'command-code --trust', + onWorking + }) + + expect(detector.observe('❯ Fix the yellow spinner\r\nThought for 1 second')).toBe(false) + expect(onWorking).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/command-code-output-status.ts b/src/renderer/src/components/terminal-pane/command-code-output-status.ts new file mode 100644 index 000000000..8449f5f86 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/command-code-output-status.ts @@ -0,0 +1,222 @@ +type CommandCodeOutputStatusDetector = { + observe: (data: string) => boolean +} + +const ESC = String.fromCharCode(0x1b) +const BEL = String.fromCharCode(0x07) +const ANSI_ESCAPE_RE = new RegExp( + `${ESC}(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~]|\\][^${BEL}]*(?:${BEL}|${ESC}\\\\))`, + 'g' +) +const INCOMPLETE_ANSI_ESCAPE_RE = new RegExp( + `${ESC}(?:\\[[0-?]*[ -/]*|\\][^${BEL}${ESC}]*|\\S?)?$`, + 'g' +) +const ORPHAN_SGR_RE = /\[(?:\d{1,3}(?:;\d{1,3})*)?m/g +const RECENT_TEXT_LIMIT = 300 +const COMMAND_CODE_STATUS_GLYPH_RE_SOURCE = '[·○◇☆✧⌘✻⎿]' +// Why: Command Code 0.27.3 randomizes its in-flight LLM status from this +// package-local list, so checking only a few examples misses real active turns. +const COMMAND_CODE_LLM_STATUS_WORDS = [ + 'Thinking', + 'Pondering', + 'Contemplating', + 'Reasoning', + 'Reflecting', + 'Considering', + 'Deliberating', + 'Analyzing', + 'Evaluating', + 'Examining', + 'Inspecting', + 'Investigating', + 'Reviewing', + 'Researching', + 'Studying', + 'Exploring', + 'Mapping', + 'Tracing', + 'Parsing', + 'Processing', + 'Calculating', + 'Computing', + 'Synthesizing', + 'Planning', + 'Outlining', + 'Sketching', + 'Drafting', + 'Composing', + 'Crafting', + 'Building', + 'Assembling', + 'Constructing', + 'Designing', + 'Formulating', + 'Structuring', + 'Organizing', + 'Preparing', + 'Refining', + 'Polishing', + 'Honing', + 'Tuning', + 'Aligning', + 'Connecting', + 'Resolving', + 'Weaving', + 'Threading', + 'Sculpting', + 'Crystallizing', + 'Channeling', + 'Conjuring', + 'Brewing', + 'Working', + 'Cogitating', + 'Ruminating', + 'Hypothesizing', + 'Conceptualizing', + 'Philosophizing', + 'Deciphering', + 'Demystifying', + 'Articulating', + 'Illuminating', + 'Elaborating', + 'Orchestrating', + 'Choreographing', + 'Architecting', + 'Calibrating', + 'Materializing', + 'Visualizing', + 'Harmonizing', + 'Contemplificating', + 'Supercalifragilisting', + 'Bibbidibobbidibooing', + 'Abracadabraing', + 'Hocuspocusing', + 'Razzmatazzing' +] as const + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +const LLM_STATUS_WORDS_RE_SOURCE = COMMAND_CODE_LLM_STATUS_WORDS.map(escapeRegExp).join('|') +const ACTIVE_LLM_STATUS_RE = new RegExp( + `(?:^|[\\r\\n])\\s*(?:${COMMAND_CODE_STATUS_GLYPH_RE_SOURCE}\\s*)?(?:${LLM_STATUS_WORDS_RE_SOURCE})\\b(?:…|\\.\\.\\.)` +) +const ACTIVE_EXECUTION_STATUS_RE = new RegExp( + `(?:^|[\\r\\n])\\s*(?:${COMMAND_CODE_STATUS_GLYPH_RE_SOURCE}\\s*)?(?:Executing:\\s+\\S|Running\\s*\\()` +) +const IDLE_PROMPT_RE = /(?:^|[\r\n])\s*[❯>]\s+Ask your question\.\.\./ + +function stripTerminalControl(data: string): string { + const withoutAnsi = data.replace(ANSI_ESCAPE_RE, '').replace(INCOMPLETE_ANSI_ESCAPE_RE, '') + let output = '' + for (let index = 0; index < withoutAnsi.length; index += 1) { + const code = withoutAnsi.charCodeAt(index) + if ((code <= 0x1f && code !== 0x0a && code !== 0x0d) || (code >= 0x7f && code <= 0x9f)) { + continue + } + output += withoutAnsi[index] + } + return output +} + +function cleanPromptCandidate(value: string): string { + return stripTerminalControl(value).replace(/\s+/g, ' ').trim() +} + +function isIdlePromptCandidate(value: string): boolean { + return value.replace(ORPHAN_SGR_RE, '').replace(/\s+/g, '') === 'Askyourquestion...' +} + +function isCommandCodeLaunchCommand(command: string | null | undefined): boolean { + if (!command) { + return false + } + return /(?:^|[\s;&|])(?:command-code|commandcode|cmdc)(?:\s|$)/.test(command) +} + +function patternOverlapsCurrentRawText( + pattern: RegExp, + previousRawText: string, + currentRawText: string +): boolean { + const previousLength = stripTerminalControl(previousRawText).length + const combinedText = stripTerminalControl(previousRawText + currentRawText) + const re = new RegExp(pattern.source, 'g') + for (const match of combinedText.matchAll(re)) { + const start = match.index ?? 0 + if (start + match[0].length > previousLength) { + return true + } + } + return false +} + +function isActiveStatusText(currentRawText: string, previousRawText = ''): boolean { + return ( + patternOverlapsCurrentRawText(ACTIVE_LLM_STATUS_RE, previousRawText, currentRawText) || + patternOverlapsCurrentRawText(ACTIVE_EXECUTION_STATUS_RE, previousRawText, currentRawText) + ) +} + +function isIdlePromptText(currentRawText: string, previousRawText = ''): boolean { + return patternOverlapsCurrentRawText(IDLE_PROMPT_RE, previousRawText, currentRawText) +} + +export function createCommandCodeOutputStatusDetector(args: { + startupCommand?: string | null + onWorking: (prompt: string) => void + onDone?: (prompt: string) => void +}): CommandCodeOutputStatusDetector { + let hasSeenCommandCodeUi = isCommandCodeLaunchCommand(args.startupCommand) + let lastSubmittedPrompt = '' + let recentRawText = '' + + return { + observe(data: string): boolean { + const previousRawText = recentRawText + const scanText = stripTerminalControl(previousRawText + data) + const scanTextWithChunkBoundary = stripTerminalControl( + previousRawText ? `${previousRawText}\n${data}` : data + ) + recentRawText = (previousRawText + data).slice(-RECENT_TEXT_LIMIT) + if ( + !hasSeenCommandCodeUi && + (/\bCommand Code\b/.test(scanText) || /\bCommand Code\b/.test(scanTextWithChunkBoundary)) + ) { + hasSeenCommandCodeUi = true + } + if (!hasSeenCommandCodeUi) { + return false + } + for (const promptMatch of scanText.matchAll(/(?:^|[\r\n])\s*[❯>]\s+([^\r\n]+)(?=[\r\n])/g)) { + const prompt = cleanPromptCandidate(promptMatch[1] ?? '') + if (prompt && !isIdlePromptCandidate(prompt)) { + lastSubmittedPrompt = prompt + } + } + // Why: Command Code lacks a prompt-start hook. Its TUI prints these + // status words while a submitted prompt is actively running, including + // no-tool turns that would otherwise jump straight from idle to done. + if ( + isActiveStatusText(data, previousRawText) || + isActiveStatusText(data, `${previousRawText}\n`) + ) { + args.onWorking(lastSubmittedPrompt) + return true + } + // Why: Command Code does not reliably emit a Stop hook for no-tool turns. + // When a submitted prompt has returned to the idle composer, let the pane + // connection settle-check the current row and mark that turn done. + if ( + lastSubmittedPrompt && + (isIdlePromptText(data, previousRawText) || isIdlePromptText(data, `${previousRawText}\n`)) + ) { + args.onDone?.(lastSubmittedPrompt) + return true + } + return false + } + } +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection-types.ts b/src/renderer/src/components/terminal-pane/pty-connection-types.ts index 628f3b2ea..5d786487e 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-types.ts @@ -1,6 +1,7 @@ import type { PtyTransport } from './pty-transport' import type { ReplayingPanesRef } from './replay-guard' import type { EventProps } from '../../../../shared/telemetry-events' +import type { TuiAgent } from '../../../../shared/types' export type PtyConnectionDeps = { tabId: string @@ -15,6 +16,8 @@ export type PtyConnectionDeps = { /** Telemetry payload for `agent_started`. Forwarded to `pty:spawn` * so main fires the event only after the spawn succeeds. */ telemetry?: EventProps<'agent_started'> + /** Initial prompt-start status for agents that lack native prompt hooks. */ + initialAgentStatus?: { agent: TuiAgent; prompt: string } } | null restoredLeafId?: string | null restoredPtyIdByLeafId?: Record diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 143e6a491..bc5f0f95a 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -517,6 +517,255 @@ describe('connectPanePty', () => { ) }) + it('seeds a working status for Command Code startup prompts after spawn', async () => { + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport('pty-command-code') + transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] }, + repos: [{ id: 'repo1', connectionId: null }] + } + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + startup: { + command: "command-code --trust 'Fix the status'", + initialAgentStatus: { agent: 'command-code', prompt: 'Fix the status' } + } + }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as + | ((ptyId: string) => void) + | undefined + expect(onPtySpawn).toBeTypeOf('function') + onPtySpawn?.('pty-command-code') + + expect(mockStoreState.setAgentStatus).toHaveBeenCalledWith( + makePaneKey('tab-1', LEAF_1), + { + state: 'working', + prompt: 'Fix the status', + agentType: 'command-code' + }, + undefined + ) + }) + + it('seeds a working status from Command Code thinking output without a startup prompt', async () => { + const { connectPanePty } = await import('./pty-connection') + const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + capturedDataCallback.current = callbacks.onData ?? null + return 'pty-command-code' + }) + transportFactoryQueue.push(transport) + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + startup: { + command: 'command-code --trust' + } + }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + expect(capturedDataCallback.current).not.toBeNull() + + capturedDataCallback.current?.('# Command Code v0.27.2\r\n') + capturedDataCallback.current?.('❯ Fix the spinner\r\n\x1b[35m✻ Thinking...\x1b[0m') + + expect(mockStoreState.setAgentStatus).toHaveBeenCalledWith( + makePaneKey('tab-1', LEAF_1), + { + state: 'working', + prompt: 'Fix the spinner', + agentType: 'command-code' + }, + undefined + ) + }) + + it('marks a Command Code no-tool turn done after the idle prompt settles', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + capturedDataCallback.current = callbacks.onData ?? null + return 'pty-command-code' + }) + transportFactoryQueue.push(transport) + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + startup: { + command: 'command-code --trust' + } + }) + const paneKey = makePaneKey('tab-1', LEAF_1) + + connectPanePty(pane as never, manager as never, deps as never) + vi.runOnlyPendingTimers() + await flushAsyncTicks() + expect(capturedDataCallback.current).not.toBeNull() + + capturedDataCallback.current?.('❯ say hi\r\n✻ Thinking...') + expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ + state: 'working', + prompt: 'say hi', + agentType: 'command-code' + }) + + capturedDataCallback.current?.( + '\r\n✻ Thought for 1 second\r\n:: Hi! How can I help you today?\r\n❯ Ask your question...' + ) + vi.advanceTimersByTime(1499) + expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ + state: 'working', + prompt: 'say hi', + agentType: 'command-code' + }) + + vi.advanceTimersByTime(1) + expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ + state: 'done', + prompt: 'say hi', + agentType: 'command-code' + }) + }) + + it('keeps Command Code working when an active repaint follows the idle prompt before settle', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + capturedDataCallback.current = callbacks.onData ?? null + return 'pty-command-code' + }) + transportFactoryQueue.push(transport) + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + startup: { + command: 'command-code --trust' + } + }) + const paneKey = makePaneKey('tab-1', LEAF_1) + + connectPanePty(pane as never, manager as never, deps as never) + vi.runOnlyPendingTimers() + await flushAsyncTicks() + expect(capturedDataCallback.current).not.toBeNull() + + capturedDataCallback.current?.('❯ Run a slow command\r\n✻ Thinking...') + capturedDataCallback.current?.('\r\n❯ Ask your question...') + vi.advanceTimersByTime(1000) + capturedDataCallback.current?.('\r\n✧ Investigating... esc to interrupt') + vi.advanceTimersByTime(500) + + expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ + state: 'working', + prompt: 'Run a slow command', + agentType: 'command-code' + }) + }) + + it('does not downgrade a completed Command Code turn back to working from stale TUI output', async () => { + const { connectPanePty } = await import('./pty-connection') + const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + capturedDataCallback.current = callbacks.onData ?? null + return 'pty-command-code' + }) + transportFactoryQueue.push(transport) + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + startup: { + command: 'command-code --trust' + } + }) + const paneKey = makePaneKey('tab-1', LEAF_1) + mockStoreState.agentStatusByPaneKey[paneKey] = { + paneKey, + state: 'done', + prompt: 'Fix the spinner', + agentType: 'command-code', + updatedAt: Date.now(), + stateStartedAt: Date.now(), + stateHistory: [] + } + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + expect(capturedDataCallback.current).not.toBeNull() + + capturedDataCallback.current?.('# Command Code v0.27.2\r\n') + capturedDataCallback.current?.('❯ Fix the spinner\r\n\x1b[35m✻ Threading...\x1b[0m') + + expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled() + expect((mockStoreState.agentStatusByPaneKey[paneKey] as { state?: unknown })?.state).toBe( + 'done' + ) + }) + + it('starts a new Command Code turn after done when TUI output carries a different prompt', async () => { + const { connectPanePty } = await import('./pty-connection') + const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport() + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + capturedDataCallback.current = callbacks.onData ?? null + return 'pty-command-code' + }) + transportFactoryQueue.push(transport) + + const pane = createPane(1) + const manager = createManager(1) + const deps = createDeps({ + startup: { + command: 'command-code --trust' + } + }) + const paneKey = makePaneKey('tab-1', LEAF_1) + mockStoreState.agentStatusByPaneKey[paneKey] = { + paneKey, + state: 'done', + prompt: 'Fix the spinner', + agentType: 'command-code', + updatedAt: Date.now(), + stateStartedAt: Date.now(), + stateHistory: [] + } + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + expect(capturedDataCallback.current).not.toBeNull() + + capturedDataCallback.current?.('# Command Code v0.27.2\r\n') + capturedDataCallback.current?.('❯ Fix the green done state\r\n\x1b[35m✻ Threading...\x1b[0m') + + expect(mockStoreState.setAgentStatus).toHaveBeenCalledWith( + paneKey, + { + state: 'working', + prompt: 'Fix the green done state', + agentType: 'command-code' + }, + undefined + ) + }) + it('delivers terminal-paste startup commands through xterm before submitting', async () => { const pendingTimeouts: (() => void)[] = [] const originalSetTimeout = globalThis.setTimeout diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index d34743ec4..699f131af 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -52,6 +52,7 @@ import { observeTerminalBracketedPasteModeOutput, pasteTerminalText } from './terminal-bracketed-paste' +import { createCommandCodeOutputStatusDetector } from './command-code-output-status' const pendingSpawnByPaneKey = new Map>() const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED' @@ -60,6 +61,7 @@ const PTY_CONNECT_DIAG_LIMIT = 200 const AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS = 250 const AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS = 1000 const AGENT_TASK_COMPLETE_NOTIFICATION_DETAIL_MAX_AGE_MS = 10_000 +const COMMAND_CODE_OUTPUT_DONE_SETTLE_MS = 1500 let codexRestartNoticePresenceSource: Record< string, { previousAccountLabel: string; nextAccountLabel: string } @@ -561,11 +563,102 @@ export function connectPanePty( } } + const applyInitialAgentStatus = (terminalTitle?: string): void => { + const initialStatus = paneStartup?.initialAgentStatus + if (!initialStatus) { + return + } + useAppStore.getState().setAgentStatus( + cacheKey, + { + state: 'working', + prompt: initialStatus.prompt, + agentType: initialStatus.agent + }, + terminalTitle + ) + } + + const seedCommandCodeOutputWorkingStatus = (prompt: string): void => { + clearCommandCodeOutputDoneTimer() + const currentState = useAppStore.getState() + const currentEntry = currentState.agentStatusByPaneKey[cacheKey] + const currentTitle = currentState.runtimePaneTitlesByTabId?.[deps.tabId]?.[pane.id] + const normalizedPrompt = prompt.trim() + if ( + currentEntry?.agentType === 'command-code' && + currentEntry.state === 'done' && + (!normalizedPrompt || normalizedPrompt === currentEntry.prompt.trim()) + ) { + return + } + currentState.setAgentStatus( + cacheKey, + { + state: 'working', + prompt: normalizedPrompt || (currentEntry?.state === 'working' ? currentEntry.prompt : ''), + agentType: 'command-code' + }, + currentTitle + ) + } + + let commandCodeOutputDoneTimer: ReturnType | null = null + const clearCommandCodeOutputDoneTimer = (): void => { + if (commandCodeOutputDoneTimer !== null) { + clearTimeout(commandCodeOutputDoneTimer) + commandCodeOutputDoneTimer = null + } + } + const scheduleCommandCodeOutputDoneStatus = (prompt: string): void => { + clearCommandCodeOutputDoneTimer() + const normalizedPrompt = prompt.trim() + if (!normalizedPrompt) { + return + } + // Why: Command Code keeps rendering the composer while tools run. Only + // complete the row if no active status repaint arrives during this window. + commandCodeOutputDoneTimer = setTimeout(() => { + commandCodeOutputDoneTimer = null + if (disposed) { + return + } + const currentState = useAppStore.getState() + const currentEntry = currentState.agentStatusByPaneKey[cacheKey] + if (currentEntry?.agentType !== 'command-code' || currentEntry.state !== 'working') { + return + } + const currentPrompt = currentEntry.prompt.trim() + if (currentPrompt && currentPrompt !== normalizedPrompt) { + return + } + const currentTitle = currentState.runtimePaneTitlesByTabId?.[deps.tabId]?.[pane.id] + currentState.setAgentStatus( + cacheKey, + { + state: 'done', + prompt: currentPrompt || normalizedPrompt, + agentType: 'command-code' + }, + currentTitle + ) + }, COMMAND_CODE_OUTPUT_DONE_SETTLE_MS) + } + + const commandCodeOutputStatusDetector = createCommandCodeOutputStatusDetector({ + startupCommand: paneStartup?.command, + onWorking: seedCommandCodeOutputWorkingStatus, + onDone: scheduleCommandCodeOutputDoneStatus + }) + const onPtySpawn = (ptyId: string): void => { bindPanePtyId(pane.id, ptyId, deps.tabId) pane.container.dataset.ptyId = ptyId deps.syncPanePtyLayoutBinding(pane.id, ptyId) deps.updateTabPtyId(deps.tabId, ptyId) + // Why: Command Code has no prompt-start hook. Seed the visible working row + // once the PTY exists, then let real hook events refine or complete it. + applyInitialAgentStatus() // Spawn completion is when a pane gains a concrete PTY ID. The initial // frame-level sync often runs before that async result arrives. scheduleRuntimeGraphSync() @@ -1188,6 +1281,7 @@ export function connectPanePty( const dataCallback = (data: string): void => { observeTerminalBracketedPasteModeOutput(pane.terminal, data) + commandCodeOutputStatusDetector.observe(data) commandLifecycle.handlePtyData(data) // Why: visibility is the right gate — split-pane layouts have multiple // visible-but-inactive panes whose output the user is watching. Only @@ -1825,6 +1919,7 @@ export function connectPanePty( pendingTerminalInputWrite = null interruptInference.dispose() clearTitleOnlyInterruptTimer() + clearCommandCodeOutputDoneTimer() // Why: actively resolve any in-flight passphrase-gate waits so their // zustand subscribers + async IIFEs don't hang for the rest of the // session when the pane is torn down before SSH state changes. diff --git a/src/renderer/src/components/terminal-quick-commands/terminal-agent-quick-command-presets.test.ts b/src/renderer/src/components/terminal-quick-commands/terminal-agent-quick-command-presets.test.ts index 8c9c4b06d..e61f1c241 100644 --- a/src/renderer/src/components/terminal-quick-commands/terminal-agent-quick-command-presets.test.ts +++ b/src/renderer/src/components/terminal-quick-commands/terminal-agent-quick-command-presets.test.ts @@ -15,6 +15,7 @@ describe('terminal agent quick command presets', () => { gemini: "gemini --prompt-interactive 'your prompt here'", antigravity: "agy --prompt-interactive 'your prompt here'", cursor: "cursor-agent 'your prompt here'", + 'command-code': "command-code --trust 'your prompt here'", droid: "droid 'your prompt here'" } diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index fb94e2d2a..2e7d97bf0 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -1849,6 +1849,15 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS ? { startup: { command: startupPlan.launchCommand, + ...(startupPlan.env ? { env: startupPlan.env } : {}), + ...(tuiAgent === 'command-code' && submitStartupPrompt.trim().length > 0 + ? { + initialAgentStatus: { + agent: tuiAgent, + prompt: submitStartupPrompt.trim() + } + } + : {}), telemetry: composerTelemetry } } @@ -2102,6 +2111,14 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS startup: { command: startupPlan.launchCommand, ...(startupPlan.env ? { env: startupPlan.env } : {}), + ...(agent === 'command-code' && quickPrompt.trim().length > 0 + ? { + initialAgentStatus: { + agent, + prompt: quickPrompt.trim() + } + } + : {}), ...(quickTelemetry ? { telemetry: quickTelemetry } : {}) } } diff --git a/src/renderer/src/lib/launch-agent-background-session.test.ts b/src/renderer/src/lib/launch-agent-background-session.test.ts index 27afc646d..99cf6c894 100644 --- a/src/renderer/src/lib/launch-agent-background-session.test.ts +++ b/src/renderer/src/lib/launch-agent-background-session.test.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { createCompatibleRuntimeStatusResponseIfNeeded } from '@/runtime/runtime-compatibility-test-fixture' import { clearRuntimeCompatibilityCacheForTests } from '@/runtime/runtime-rpc-client' @@ -192,6 +193,23 @@ describe('launchAgentBackgroundSession', () => { ) }) + it('seeds a working status for Command Code prompt launches', async () => { + const { launchAgentBackgroundSession } = await import('./launch-agent-background-session') + + await launchAgentBackgroundSession({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'check the status spinner' + }) + + const paneKey = expectStablePaneSpawn() + expect(state.setAgentStatus).toHaveBeenCalledWith(paneKey, { + state: 'working', + prompt: 'check the status spinner', + agentType: 'command-code' + }) + }) + it('uses a sidecar exit watcher so completion survives terminal attachment', async () => { const unsubscribe = vi.fn() mockSubscribeToPtyExit.mockReturnValue(unsubscribe) diff --git a/src/renderer/src/lib/launch-agent-background-session.ts b/src/renderer/src/lib/launch-agent-background-session.ts index 03b0659d7..03e7cf532 100644 --- a/src/renderer/src/lib/launch-agent-background-session.ts +++ b/src/renderer/src/lib/launch-agent-background-session.ts @@ -184,6 +184,15 @@ export async function launchAgentBackgroundSession( } store.updateTabPtyId(tab.id, ptyId) store.setTabLayout(tab.id, singlePaneLayoutSnapshot(leafId, ptyId)) + if (agent === 'command-code' && hasPrompt && !isFollowupPath) { + // Why: Command Code does not expose a prompt-start hook; seed working for + // hidden prompt launches so sidebar/activity surfaces do not stay idle. + store.setAgentStatus(paneKey, { + state: 'working', + prompt: trimmedPrompt, + agentType: agent + }) + } let exitHandled = false let unsubscribeExit = (): void => {} let unsubscribeData = (): void => {} diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.test.ts b/src/renderer/src/lib/launch-agent-in-new-tab.test.ts new file mode 100644 index 000000000..8ae121335 --- /dev/null +++ b/src/renderer/src/lib/launch-agent-in-new-tab.test.ts @@ -0,0 +1,124 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mockCreateTab = vi.fn() +const mockQueueTabStartupCommand = vi.fn() +const mockSetActiveTabType = vi.fn() +const mockSetTabBarOrder = vi.fn() +const mockSetAgentStatus = vi.fn() +const mockPasteDraftWhenAgentReady = vi.fn() + +const LEAF_ID = '11111111-1111-4111-8111-111111111111' + +const store = { + settings: { agentCmdOverrides: {} }, + tabsByWorktree: { + 'wt-1': [{ id: 'tab-1' }] + }, + openFiles: [] as { id: string; worktreeId: string }[], + browserTabsByWorktree: {} as Record, + tabBarOrderByWorktree: {} as Record, + terminalLayoutsByTabId: {} as Record, + createTab: mockCreateTab, + queueTabStartupCommand: mockQueueTabStartupCommand, + setActiveTabType: mockSetActiveTabType, + setTabBarOrder: mockSetTabBarOrder, + setAgentStatus: mockSetAgentStatus +} + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => store + } +})) + +vi.mock('sonner', () => ({ + toast: { message: vi.fn() } +})) + +vi.mock('@/components/tab-bar/reconcile-order', () => ({ + reconcileTabOrder: vi.fn( + (_stored, termIds: string[], editorIds: string[], browserIds: string[]) => [ + ...termIds, + ...editorIds, + ...browserIds + ] + ) +})) + +vi.mock('@/lib/agent-paste-draft', () => ({ + pasteDraftWhenAgentReady: mockPasteDraftWhenAgentReady +})) + +vi.mock('@/lib/telemetry', () => ({ + track: vi.fn(), + tuiAgentToAgentKind: (agent: string) => agent +})) + +describe('launchAgentInNewTab', () => { + beforeEach(() => { + vi.clearAllMocks() + store.settings = { agentCmdOverrides: {} } + store.tabsByWorktree = { 'wt-1': [{ id: 'tab-1' }] } + store.openFiles = [] + store.browserTabsByWorktree = {} + store.tabBarOrderByWorktree = {} + store.terminalLayoutsByTabId = {} + mockCreateTab.mockReturnValue({ id: 'tab-1' }) + mockPasteDraftWhenAgentReady.mockResolvedValue(true) + }) + + it('queues initial working status for Command Code argv prompt launches', async () => { + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + + launchAgentInNewTab({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'fix the spinner' + }) + + expect(mockQueueTabStartupCommand).toHaveBeenCalledWith( + 'tab-1', + expect.objectContaining({ + command: "command-code --trust 'fix the spinner'", + initialAgentStatus: { + agent: 'command-code', + prompt: 'fix the spinner' + } + }) + ) + }) + + it('seeds working after Command Code submit-after-ready prompt delivery', async () => { + const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab') + + launchAgentInNewTab({ + agent: 'command-code', + worktreeId: 'wt-1', + prompt: 'large generated prompt', + promptDelivery: 'submit-after-ready' + }) + store.terminalLayoutsByTabId = { 'tab-1': { activeLeafId: LEAF_ID } } + await Promise.resolve() + + expect(mockQueueTabStartupCommand).toHaveBeenCalledWith( + 'tab-1', + expect.objectContaining({ + command: 'command-code --trust' + }) + ) + expect(mockPasteDraftWhenAgentReady).toHaveBeenCalledWith( + expect.objectContaining({ + tabId: 'tab-1', + content: 'large generated prompt', + agent: 'command-code', + submit: true, + forcePaste: true + }) + ) + expect(mockSetAgentStatus).toHaveBeenCalledWith(`tab-1:${LEAF_ID}`, { + state: 'working', + prompt: 'large generated prompt', + agentType: 'command-code' + }) + }) +}) diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.ts b/src/renderer/src/lib/launch-agent-in-new-tab.ts index 79170f70d..dd305a189 100644 --- a/src/renderer/src/lib/launch-agent-in-new-tab.ts +++ b/src/renderer/src/lib/launch-agent-in-new-tab.ts @@ -10,6 +10,7 @@ import { reconcileTabOrder } from '@/components/tab-bar/reconcile-order' import { track, tuiAgentToAgentKind } from '@/lib/telemetry' import { pasteDraftWhenAgentReady } from '@/lib/agent-paste-draft' import { TUI_AGENT_CONFIG } from '../../../shared/tui-agent-config' +import { makePaneKey } from '../../../shared/stable-pane-id' import type { TuiAgent } from '../../../shared/types' import type { LaunchSource } from '../../../shared/telemetry-events' @@ -38,6 +39,23 @@ export type LaunchAgentInNewTabResult = { pasteDraftAfterLaunch: boolean } | null +function seedCommandCodeSubmittedPromptStatus(tabId: string, prompt: string): void { + const state = useAppStore.getState() + const leafId = state.terminalLayoutsByTabId[tabId]?.activeLeafId + if (!leafId) { + return + } + try { + state.setAgentStatus(makePaneKey(tabId, leafId), { + state: 'working', + prompt, + agentType: 'command-code' + }) + } catch { + // Best-effort UI seed. Real hooks still own refinement/completion. + } +} + /** * Create a new terminal tab and queue the agent's launch command, optionally * with an initial prompt. @@ -162,6 +180,9 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI store.queueTabStartupCommand(tab.id, { command: startupPlan.launchCommand, ...(startupPlan.env ? { env: startupPlan.env } : {}), + ...(agent === 'command-code' && hasPrompt && promptDelivery === 'auto-submit' + ? { initialAgentStatus: { agent, prompt: trimmedPrompt } } + : {}), telemetry: { agent_kind: tuiAgentToAgentKind(agent), launch_source: launchSource ?? 'tab_bar_quick_launch', @@ -213,6 +234,11 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI } }).then((delivered) => { if (delivered) { + if (agent === 'command-code' && submitPastedPrompt) { + // Why: Command Code has no prompt-submit hook; when Orca submits a + // generated prompt after readiness, seed working at delivery time. + seedCommandCodeSubmittedPromptStatus(tabId, pasteDraftAfterLaunch) + } onPromptDelivered?.() } }) diff --git a/src/renderer/src/lib/tui-agent-startup.test.ts b/src/renderer/src/lib/tui-agent-startup.test.ts index f5655e35a..1ad0db187 100644 --- a/src/renderer/src/lib/tui-agent-startup.test.ts +++ b/src/renderer/src/lib/tui-agent-startup.test.ts @@ -150,7 +150,7 @@ describe('buildAgentStartupPlan', () => { }) }) - it('launches Command Code by its unambiguous binary and injects after startup', () => { + it('launches Command Code by its unambiguous binary with a positional prompt', () => { expect( buildAgentStartupPlan({ agent: 'command-code', @@ -160,9 +160,9 @@ describe('buildAgentStartupPlan', () => { }) ).toEqual({ agent: 'command-code', - launchCommand: 'command-code', + launchCommand: "command-code --trust 'Fix the issue'", expectedProcess: 'command-code', - followupPrompt: 'Fix the issue' + followupPrompt: null }) }) diff --git a/src/renderer/src/lib/worktree-activation.ts b/src/renderer/src/lib/worktree-activation.ts index 3f688cec4..ece817baa 100644 --- a/src/renderer/src/lib/worktree-activation.ts +++ b/src/renderer/src/lib/worktree-activation.ts @@ -1,4 +1,9 @@ -import type { SetupSplitDirection, Worktree, WorktreeSetupLaunch } from '../../../shared/types' +import type { + SetupSplitDirection, + TuiAgent, + Worktree, + WorktreeSetupLaunch +} from '../../../shared/types' import type { EventProps } from '../../../shared/telemetry-events' import { shouldAutoCreateInitialTerminal } from '@/components/terminal/initial-terminal' import { buildSetupRunnerCommand } from './setup-runner' @@ -47,6 +52,7 @@ type WorktreeActivationStore = { startup: { command: string env?: Record + initialAgentStatus?: { agent: TuiAgent; prompt: string } telemetry?: AgentStartedTelemetry } ) => void @@ -120,6 +126,7 @@ export function activateAndRevealWorktree( startup?: { command: string env?: Record + initialAgentStatus?: { agent: TuiAgent; prompt: string } telemetry?: AgentStartedTelemetry } setup?: WorktreeSetupLaunch @@ -200,7 +207,12 @@ export function activateAndRevealWorktree( export function ensureWorktreeHasInitialTerminal( store: WorktreeActivationStore, worktreeId: string, - startup?: { command: string; env?: Record; telemetry?: AgentStartedTelemetry }, + startup?: { + command: string + env?: Record + initialAgentStatus?: { agent: TuiAgent; prompt: string } + telemetry?: AgentStartedTelemetry + }, setup?: WorktreeSetupLaunch, issueCommand?: IssueCommandLaunch ): string | null { diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 425fbcb3f..81f764e94 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -6,6 +6,7 @@ import type { Tab, TerminalLayoutSnapshot, TerminalTab, + TuiAgent, Worktree, WorkspaceSessionState } from '../../../../shared/types' @@ -197,6 +198,8 @@ export type TerminalSlice = { * xterm can use bracketed paste before the submit Enter is sent. */ delivery?: 'terminal-paste' env?: Record + /** Initial prompt-start status for agents that lack native prompt hooks. */ + initialAgentStatus?: { agent: TuiAgent; prompt: string } /** Telemetry metadata for the `agent_started` event. Threaded all the * way to the `pty:spawn` IPC handler in main so the event fires only * after spawn confirms — never on click-intent. */ @@ -313,6 +316,7 @@ export type TerminalSlice = { command: string delivery?: 'terminal-paste' env?: Record + initialAgentStatus?: { agent: TuiAgent; prompt: string } telemetry?: AgentStartedTelemetry } ) => void diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 9f457cd81..fe7a3cd77 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1649,6 +1649,7 @@ function createAgentHooksApi(): NonNullable['agentHooks']> { | 'antigravity' | 'cursor' | 'droid' + | 'command-code' | 'grok' | 'copilot' | 'hermes' @@ -1667,6 +1668,7 @@ function createAgentHooksApi(): NonNullable['agentHooks']> { antigravityStatus: () => status('antigravity'), cursorStatus: () => status('cursor'), droidStatus: () => status('droid'), + commandCodeStatus: () => status('command-code'), grokStatus: () => status('grok'), copilotStatus: () => status('copilot'), hermesStatus: () => status('hermes') diff --git a/src/shared/agent-hook-listener.test.ts b/src/shared/agent-hook-listener.test.ts index 11f997c3c..6eeeb88c1 100644 --- a/src/shared/agent-hook-listener.test.ts +++ b/src/shared/agent-hook-listener.test.ts @@ -44,6 +44,7 @@ describe('shared agent-hook-listener', () => { expect(resolveHookSource('/hook/hermes')).toBe('hermes') expect(resolveHookSource('/hook/pi')).toBe('pi') expect(resolveHookSource('/hook/omp')).toBe('omp') + expect(resolveHookSource('/hook/command-code')).toBe('command-code') expect(resolveHookSource('/hook/unknown')).toBeNull() expect(resolveHookSource('/')).toBeNull() }) @@ -128,6 +129,80 @@ describe('shared agent-hook-listener', () => { }) }) + it('normalizes Command Code hooks and reads turn text from the transcript', () => { + const tmpDir = mkdtempSync(join(tmpdir(), 'orca-command-code-transcript-')) + const transcriptPath = join(tmpDir, 'transcript.jsonl') + try { + writeFileSync( + transcriptPath, + `${[ + JSON.stringify({ + role: 'user', + content: [{ type: 'text', text: 'Run pwd and report it' }] + }), + JSON.stringify({ + role: 'assistant', + content: [ + { type: 'reasoning', text: 'Need to run pwd.' }, + { type: 'text', text: 'The output is /tmp/project.' } + ] + }) + ].join('\n')}\n` + ) + + const tool = normalizeHookPayload( + state, + 'command-code', + { + paneKey: PANE_KEY, + tabId: 'tab-1', + worktreeId: 'wt', + env: 'production', + version: '1', + payload: { + hook_event_name: 'PreToolUse', + transcript_path: transcriptPath, + tool_name: 'shell_command', + tool_input: { command: 'pwd' } + } + }, + 'production' + ) + expect(tool?.payload).toMatchObject({ + state: 'working', + prompt: 'Run pwd and report it', + agentType: 'command-code', + toolName: 'shell_command', + toolInput: 'pwd' + }) + + const done = normalizeHookPayload( + state, + 'command-code', + { + paneKey: PANE_KEY, + tabId: 'tab-1', + worktreeId: 'wt', + env: 'production', + version: '1', + payload: { + hook_event_name: 'Stop', + transcript_path: transcriptPath + } + }, + 'production' + ) + expect(done?.payload).toMatchObject({ + state: 'done', + prompt: 'Run pwd and report it', + agentType: 'command-code', + lastAssistantMessage: 'The output is /tmp/project.' + }) + } finally { + rmSync(tmpDir, { recursive: true, force: true }) + } + }) + it('trims surrounding whitespace from extracted prompt text', () => { const event = normalizeHookPayload( state, diff --git a/src/shared/agent-hook-listener.ts b/src/shared/agent-hook-listener.ts index 2ea9c6672..6f6674d34 100644 --- a/src/shared/agent-hook-listener.ts +++ b/src/shared/agent-hook-listener.ts @@ -650,6 +650,68 @@ function readLastUserPromptFromTranscript(transcriptPath: unknown): string | und return readLastTextFromTranscriptOnce(transcriptPath, extractUserPromptTextFromLine) } +function extractCommandCodeUserPromptFromLine(line: string): string | undefined { + let entry: unknown + try { + entry = JSON.parse(line) + } catch { + return undefined + } + if (typeof entry !== 'object' || entry === null) { + return undefined + } + const record = entry as Record + return record.role === 'user' ? extractAssistantContentText(record.content) : undefined +} + +function extractCommandCodeAssistantTextFromLine(line: string): string | undefined { + let entry: unknown + try { + entry = JSON.parse(line) + } catch { + return undefined + } + if (typeof entry !== 'object' || entry === null) { + return undefined + } + const record = entry as Record + if (record.role !== 'assistant') { + return undefined + } + const content = record.content + if (typeof content === 'string' && content.trim().length > 0) { + return content + } + if (Array.isArray(content)) { + const textPart = content.find( + (part) => + typeof part === 'object' && + part !== null && + (part as Record).type === 'text' && + typeof (part as Record).text === 'string' && + ((part as Record).text as string).trim().length > 0 + ) as Record | undefined + if (typeof textPart?.text === 'string') { + return textPart.text + } + } + return extractAssistantContentText(content) +} + +function readLastCommandCodeUserPromptFromTranscript(transcriptPath: unknown): string | undefined { + if (typeof transcriptPath !== 'string' || transcriptPath.length === 0) { + return undefined + } + return readLastTextFromTranscriptOnce(transcriptPath, extractCommandCodeUserPromptFromLine) +} + +function readLastCommandCodeAssistantFromTranscript(transcriptPath: unknown): string | undefined { + if (typeof transcriptPath !== 'string' || transcriptPath.length === 0) { + return undefined + } + return readLastTextFromTranscriptOnce(transcriptPath, extractCommandCodeAssistantTextFromLine) +} + function parseHookBodyPayloadRecord(body: unknown): Record | null { if (typeof body !== 'object' || body === null) { return null @@ -1342,6 +1404,47 @@ function extractDroidToolFields( return {} } +function extractCommandCodeToolFields( + eventName: unknown, + hookPayload: Record +): ToolSnapshot { + if (eventName === 'PreToolUse' || eventName === 'PostToolUse') { + const toolName = + readString(hookPayload, 'tool_name') ?? + readString(hookPayload, 'toolName') ?? + readString(hookPayload, 'tool_display_name') + const toolInput = + deriveToolInputPreview(toolName, hookPayload.tool_input) ?? + deriveFallbackToolInputPreview(hookPayload.tool_input) + const update: ToolSnapshot = toolUpdate( + { toolName, toolInput }, + { hasToolInputField: hasOwnField(hookPayload, 'tool_input') } + ) + if (eventName === 'PostToolUse') { + const responseText = + extractToolResponseText(hookPayload.tool_response) ?? + extractToolResponseText(hookPayload.tool_output) + if (responseText) { + update.lastAssistantMessage = responseText + } + } + return update + } + if (eventName === 'Stop') { + const direct = readString(hookPayload, 'last_assistant_message') + if (direct) { + return { lastAssistantMessage: direct } + } + const fromTranscript = readLastCommandCodeAssistantFromTranscript( + hookPayload.transcript_path ?? hookPayload.transcriptPath + ) + if (fromTranscript) { + return { lastAssistantMessage: fromTranscript } + } + } + return {} +} + function normalizeHookEventName(value: unknown): string { if (typeof value !== 'string') { return '' @@ -1533,6 +1636,8 @@ function isNewTurnEvent(source: AgentHookSource, eventName: unknown): boolean { return eventName === 'before_agent_start' case 'droid': return eventName === 'UserPromptSubmit' + case 'command-code': + return false case 'grok': return isGrokEvent(eventName, 'user_prompt_submit') case 'copilot': { @@ -1574,6 +1679,8 @@ function extractToolFields( return extractPiToolFields(eventName, hookPayload) case 'droid': return extractDroidToolFields(eventName, hookPayload) + case 'command-code': + return extractCommandCodeToolFields(eventName, hookPayload) case 'grok': return extractGrokToolFields(eventName, hookPayload) case 'copilot': @@ -2074,6 +2181,50 @@ function normalizeDroidEvent( ) } +function normalizeCommandCodeEvent( + state: HookListenerState, + eventName: unknown, + promptText: string, + paneKey: string, + hookPayload: Record +): ParsedAgentStatusPayload | null { + const stateName = + eventName === 'PreToolUse' || eventName === 'PostToolUse' + ? 'working' + : eventName === 'Stop' + ? 'done' + : null + if (!stateName) { + return null + } + + const effectivePrompt = + promptText || + readLastCommandCodeUserPromptFromTranscript( + hookPayload.transcript_path ?? hookPayload.transcriptPath + ) || + '' + const snapshot = resolveToolState( + state, + paneKey, + extractToolFields('command-code', eventName, hookPayload), + { resetOnNewTurn: isNewTurnEvent('command-code', eventName) } + ) + + return parseAgentStatusPayload( + JSON.stringify({ + state: stateName, + prompt: resolvePrompt(state, paneKey, effectivePrompt, { + resetOnNewTurn: isNewTurnEvent('command-code', eventName) + }), + agentType: 'command-code', + toolName: snapshot.toolName, + toolInput: snapshot.toolInput, + lastAssistantMessage: snapshot.lastAssistantMessage + }) + ) +} + function normalizeGrokEvent( state: HookListenerState, eventName: unknown, @@ -2299,6 +2450,9 @@ export function normalizeHookPayload( case 'droid': payload = normalizeDroidEvent(state, eventName, promptText, paneKey, hookPayloadRecord) break + case 'command-code': + payload = normalizeCommandCodeEvent(state, eventName, promptText, paneKey, hookPayloadRecord) + break case 'grok': payload = normalizeGrokEvent(state, eventName, promptText, paneKey, hookPayloadRecord) break @@ -2347,6 +2501,7 @@ export const HOOK_SOURCE_BY_PATHNAME: Readonly> '/hook/pi': 'pi', '/hook/omp': 'omp', '/hook/droid': 'droid', + '/hook/command-code': 'command-code', '/hook/grok': 'grok', '/hook/copilot': 'copilot', '/hook/hermes': 'hermes' diff --git a/src/shared/agent-hook-relay.ts b/src/shared/agent-hook-relay.ts index 5e61f5ff3..fa2d696dd 100644 --- a/src/shared/agent-hook-relay.ts +++ b/src/shared/agent-hook-relay.ts @@ -40,6 +40,7 @@ export type AgentHookSource = | 'pi' | 'omp' | 'droid' + | 'command-code' | 'grok' | 'copilot' | 'hermes' diff --git a/src/shared/agent-hook-types.ts b/src/shared/agent-hook-types.ts index 2cd290819..911c5672f 100644 --- a/src/shared/agent-hook-types.ts +++ b/src/shared/agent-hook-types.ts @@ -10,6 +10,7 @@ export const AGENT_HOOK_TARGETS = [ 'antigravity', 'cursor', 'droid', + 'command-code', 'grok', 'copilot', 'hermes' diff --git a/src/shared/tui-agent-config.ts b/src/shared/tui-agent-config.ts index 1abc4183b..5e742ffe6 100644 --- a/src/shared/tui-agent-config.ts +++ b/src/shared/tui-agent-config.ts @@ -202,9 +202,13 @@ export const TUI_AGENT_CONFIG: Record = { // does not collide with Windows' built-in `cmd.exe` shell, which // agent-process-recognition normalizes to `cmd` after stripping the .exe. detectCmd: 'command-code', - launchCmd: 'command-code', + // Why: Command Code's documented positional prompt starts the turn, while + // paste-after-start can leave the prompt sitting in the composer. `--trust` + // mirrors the preflight trust behavior Orca applies to other first-run + // TUIs so launch prompts do not consume the task text. + launchCmd: 'command-code --trust', expectedProcess: 'command-code', - promptInjectionMode: 'stdin-after-start' + promptInjectionMode: 'argv' }, continue: { detectCmd: 'continue', diff --git a/src/shared/tui-agent-selection.test.ts b/src/shared/tui-agent-selection.test.ts index 70ec17108..0d0c340da 100644 --- a/src/shared/tui-agent-selection.test.ts +++ b/src/shared/tui-agent-selection.test.ts @@ -9,6 +9,7 @@ describe('pickTuiAgent', () => { it('falls back in desktop catalog order when the preference is absent or stale', () => { expect(pickTuiAgent(null, ['cursor', 'codex'])).toBe('codex') expect(pickTuiAgent('gemini', ['cursor', 'codex'])).toBe('codex') + expect(pickTuiAgent(null, ['continue', 'command-code'])).toBe('command-code') }) it('respects the explicit blank terminal preference', () => {