diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index 8995ee382..be6176276 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -54,6 +54,7 @@ const ORCA_SHELL_WRAPPER_ENV = [ ] as const const POWERSHELL_OSC133_COMMAND_ARGS = ['-NoLogo', '-NoExit', '-EncodedCommand', expect.any(String)] const ZSH_SHELL_READY_DIR = /shell-ready[\\/]zsh/ +const itOnMacHost = process.platform === 'darwin' ? it : it.skip function mockPtyProcess(pid = 12345) { const onDataListeners: ((data: string) => void)[] = [] @@ -148,7 +149,7 @@ describe('createPtySubprocess', () => { ) }) - it('repairs a deleted macOS daemon cwd before spawning node-pty', () => { + itOnMacHost('repairs a deleted macOS daemon cwd before spawning node-pty', () => { const proc = mockPtyProcess() spawnMock.mockReturnValue(proc) const platform = Object.getOwnPropertyDescriptor(process, 'platform') @@ -231,7 +232,11 @@ describe('createPtySubprocess', () => { }) expect(handle.getForegroundProcess()).toBe('node') - expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith(proc.pid, 'node') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + proc.pid, + 'node', + expect.any(Object) + ) resolveForeground('codex') await vi.waitFor(() => expect(handle.getForegroundProcess()).toBe('codex')) @@ -263,7 +268,11 @@ describe('createPtySubprocess', () => { }) expect(handle.getForegroundProcess()).toBe('node.exe') - expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith(proc.pid, 'node.exe') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + proc.pid, + 'node.exe', + expect.any(Object) + ) resolveForeground('codex') await vi.waitFor(() => expect(handle.getForegroundProcess()).toBe('codex')) @@ -274,6 +283,197 @@ describe('createPtySubprocess', () => { } }) + it('serves daemon shell-rooted agent foreground from an async cache', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + let resolveForeground!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveForeground = resolve + }) + ) + + try { + const handle = createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24 + }) + + expect(handle.getForegroundProcess()).toBe('powershell.exe') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + proc.pid, + 'powershell.exe', + expect.any(Object) + ) + + resolveForeground('codex') + await vi.waitFor(() => expect(handle.getForegroundProcess()).toBe('codex')) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('does not let stale shell enrichment clear a newer direct agent foreground cache', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + let resolveForeground!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveForeground = resolve + }) + ) + + try { + const handle = createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24 + }) + + expect(handle.getForegroundProcess()).toBe('powershell.exe') + proc.process = 'codex' + expect(handle.getForegroundProcess()).toBe('codex') + + resolveForeground('powershell.exe') + await Promise.resolve() + await Promise.resolve() + + proc.process = 'powershell.exe' + expect(handle.getForegroundProcess()).toBe('codex') + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('keeps menu startup agent foreground through early negative shell enrichment', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-06-16T12:00:00.000Z')) + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue('powershell.exe') + + try { + const handle = createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24, + command: 'codex' + }) + + expect(handle.getForegroundProcess()).toBe('codex') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + proc.pid, + 'powershell.exe', + expect.any(Object) + ) + + await Promise.resolve() + expect(handle.getForegroundProcess()).toBe('codex') + + vi.advanceTimersByTime(4_999) + expect(handle.getForegroundProcess()).toBe('codex') + + vi.advanceTimersByTime(2) + expect(handle.getForegroundProcess()).toBe('powershell.exe') + } finally { + vi.useRealTimers() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('keeps menu startup agent foreground during a slow Windows shell enrichment window', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-06-16T12:00:00.000Z')) + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + let resolveForeground!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveForeground = resolve + }) + ) + + try { + const handle = createPtySubprocess({ + sessionId: 'repo::C:\\repo\\orca@@deadbeef', + cols: 80, + rows: 24, + cwd: 'C:\\repo\\orca', + command: 'codex' + }) + + expect(handle.getForegroundProcess()).toBe('codex') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + proc.pid, + 'powershell.exe', + expect.objectContaining({ + contextPaths: expect.arrayContaining(['C:\\repo\\orca']) + }) + ) + + vi.advanceTimersByTime(2_500) + expect(handle.getForegroundProcess()).toBe('codex') + + resolveForeground('powershell.exe') + await vi.runAllTimersAsync() + } finally { + vi.useRealTimers() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('uses the spawned Windows shell when node-pty reports only the terminal name', async () => { + const proc = mockPtyProcess() + proc.process = 'xterm-256color' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue('codex') + + try { + const handle = createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24, + shellOverride: 'powershell.exe' + }) + + expect(handle.getForegroundProcess()).toBe('powershell.exe') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + proc.pid, + 'powershell.exe', + expect.any(Object) + ) + + await vi.waitFor(() => expect(handle.getForegroundProcess()).toBe('codex')) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + it('does not schedule foreground enrichment for arbitrary Windows TUIs', () => { const proc = mockPtyProcess() proc.process = 'vim.exe' @@ -301,14 +501,22 @@ describe('createPtySubprocess', () => { const proc = mockPtyProcess() proc.process = 'xterm-256color' spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'linux' }) - const handle = createPtySubprocess({ - sessionId: 'test', - cols: 80, - rows: 24 - }) + try { + const handle = createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24 + }) - expect(handle.getForegroundProcess()).toBeNull() + expect(handle.getForegroundProcess()).toBeNull() + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } }) it('does not inherit parent Orca pane identity when caller omits pane env', () => { diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts index 792bcc324..fb02428f2 100644 --- a/src/main/daemon/pty-subprocess.ts +++ b/src/main/daemon/pty-subprocess.ts @@ -30,12 +30,17 @@ import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' import { resolveAgentForegroundProcess } from '../providers/agent-foreground-process' import { isAgentForegroundWrapperProcess, - recognizeAgentProcess + recognizeAgentProcess, + recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' import { isShellProcess } from '../../shared/shell-process-detection' +import { parsePtySessionId } from './pty-session-id' +import { getAgentForegroundContextPaths } from '../providers/agent-foreground-context-paths' const PANE_IDENTITY_ENV_KEYS = ['ORCA_PANE_KEY', 'ORCA_TAB_ID', 'ORCA_WORKTREE_ID'] as const const FOREGROUND_AGENT_CACHE_TTL_MS = 1000 +const SHELL_FOREGROUND_REFRESH_RETRY_MS = 5_000 +const STARTUP_AGENT_FOREGROUND_BOOTSTRAP_MS = 5_000 const PTY_SPAWN_HEALTH_TIMEOUT_MS = 2_000 export type PtySubprocessOptions = { @@ -316,6 +321,19 @@ function normalizeForegroundProcessName(processName: string | null | undefined): return trimmed.split(/[\\/]/).pop() || null } +function resolveFallbackForegroundProcess( + processName: string | null | undefined, + shellPath: string +): string | null { + const normalized = normalizeForegroundProcessName(processName) + if (normalized || process.platform !== 'win32') { + return normalized + } + // Why: Windows node-pty can report the terminal name instead of the shell. + // Use the spawned shell so shell-rooted foreground enrichment still runs. + return normalizeForegroundProcessName(pathWin32.basename(shellPath)) +} + export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandle { const size = normalizePtySize(opts.cols, opts.rows) const env: Record = { @@ -540,40 +558,84 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl let disposed = false let nodePtyKillIssued = false let cachedAgentForeground: { processName: string; refreshedAt: number } | null = null + const agentForegroundContextPaths = getAgentForegroundContextPaths({ + cwd: opts.cwd, + worktreeId: parsePtySessionId(opts.sessionId).worktreeId + }) + const startupAgentRecognition = recognizeAgentProcessFromCommandLine(opts.command) + let startupAgentForeground: { processName: string; expiresAt: number } | null = + startupAgentRecognition + ? { + processName: startupAgentRecognition.processName, + expiresAt: Date.now() + STARTUP_AGENT_FOREGROUND_BOOTSTRAP_MS + } + : null let foregroundRefreshInFlight = false let lastForegroundRefreshStartedAt = 0 const getFallbackForegroundProcess = (): string | null => - normalizeForegroundProcessName(proc.process) + resolveFallbackForegroundProcess(proc.process, shellPath) + const getActiveStartupAgentForeground = ( + now = Date.now() + ): { processName: string; expiresAt: number } | null => { + if (!startupAgentForeground) { + return null + } + if (now > startupAgentForeground.expiresAt) { + startupAgentForeground = null + return null + } + return startupAgentForeground + } + const shouldInspectFallbackForegroundProcess = (fallbackProcess: string | null): boolean => + fallbackProcess !== null && + (isShellProcess(fallbackProcess) || isAgentForegroundWrapperProcess(fallbackProcess)) const scheduleAgentForegroundRefresh = (fallbackProcess: string | null): void => { if (dead || !proc.pid) { return } + const fallbackIsShell = fallbackProcess !== null && isShellProcess(fallbackProcess) if ( !fallbackProcess || - isShellProcess(fallbackProcess) || recognizeAgentProcess(fallbackProcess) || - !isAgentForegroundWrapperProcess(fallbackProcess) + !shouldInspectFallbackForegroundProcess(fallbackProcess) ) { return } const now = Date.now() - if ( - foregroundRefreshInFlight || - now - lastForegroundRefreshStartedAt < FOREGROUND_AGENT_CACHE_TTL_MS - ) { + const retryMs = + fallbackIsShell && !getActiveStartupAgentForeground(now) && !cachedAgentForeground + ? SHELL_FOREGROUND_REFRESH_RETRY_MS + : FOREGROUND_AGENT_CACHE_TTL_MS + if (foregroundRefreshInFlight || now - lastForegroundRefreshStartedAt < retryMs) { return } foregroundRefreshInFlight = true lastForegroundRefreshStartedAt = now - // Why: daemon `getForegroundProcess()` is sync and runs on the IPC hot path. - // Refresh wrapper-derived identities (node/python → codex/gemini/etc.) in - // the background and serve them from a short cache on later reads. - void resolveAgentForegroundProcess(proc.pid, fallbackProcess) + // Why: daemon foreground reads are sync and run on the IPC hot path. + // Refresh shell/wrapper-derived identities (powershell/node -> codex/etc.) + // in the background and serve them from a short cache on later reads. + void resolveAgentForegroundProcess(proc.pid, fallbackProcess, { + contextPaths: agentForegroundContextPaths + }) .then((processName) => { - if (dead || !processName || !recognizeAgentProcess(processName)) { + if (dead) { + return + } + if (!processName || !recognizeAgentProcess(processName)) { + const currentFallbackProcess = getFallbackForegroundProcess() + if ( + fallbackIsShell && + !getActiveStartupAgentForeground() && + currentFallbackProcess !== null && + isShellProcess(currentFallbackProcess) + ) { + cachedAgentForeground = null + startupAgentForeground = null + } return } cachedAgentForeground = { processName, refreshedAt: Date.now() } + startupAgentForeground = null }) .catch(() => { // Best-effort only: foreground enrichment must never affect PTY health. @@ -585,6 +647,7 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl proc.onExit(() => { dead = true cachedAgentForeground = null + startupAgentForeground = null // Why: UnixTerminal.destroy() registers `_socket.once('close', () => this.kill('SIGHUP'))` // (unixTerminal.js:219-229). After the child exits, the master socket's // 'close' event can fire before our dispose() path gets to neutralize @@ -611,21 +674,23 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl } try { const fallbackProcess = getFallbackForegroundProcess() - if (fallbackProcess && isShellProcess(fallbackProcess)) { - cachedAgentForeground = null - return fallbackProcess - } if (fallbackProcess && recognizeAgentProcess(fallbackProcess)) { cachedAgentForeground = { processName: fallbackProcess, refreshedAt: Date.now() } + startupAgentForeground = null return fallbackProcess } scheduleAgentForegroundRefresh(fallbackProcess) + const now = Date.now() if ( cachedAgentForeground && - Date.now() - cachedAgentForeground.refreshedAt <= FOREGROUND_AGENT_CACHE_TTL_MS + now - cachedAgentForeground.refreshedAt <= FOREGROUND_AGENT_CACHE_TTL_MS ) { return cachedAgentForeground.processName } + const activeStartupAgentForeground = getActiveStartupAgentForeground(now) + if (fallbackProcess && isShellProcess(fallbackProcess) && activeStartupAgentForeground) { + return activeStartupAgentForeground.processName + } return fallbackProcess } catch { return null diff --git a/src/main/providers/agent-foreground-context-paths.ts b/src/main/providers/agent-foreground-context-paths.ts new file mode 100644 index 000000000..7ff8a6d3e --- /dev/null +++ b/src/main/providers/agent-foreground-context-paths.ts @@ -0,0 +1,11 @@ +import { splitWorktreeIdForFilesystem } from '../../shared/worktree-id' + +export function getAgentForegroundContextPaths(options: { + cwd?: string + worktreeId?: string | null +}): string[] { + const worktreePath = options.worktreeId + ? splitWorktreeIdForFilesystem(options.worktreeId)?.worktreePath + : undefined + return [...new Set([options.cwd, worktreePath].filter((path): path is string => Boolean(path)))] +} diff --git a/src/main/providers/agent-foreground-process.test.ts b/src/main/providers/agent-foreground-process.test.ts index 63b9b8847..5d551b3a6 100644 --- a/src/main/providers/agent-foreground-process.test.ts +++ b/src/main/providers/agent-foreground-process.test.ts @@ -19,14 +19,46 @@ function mockPs(stdout: string): void { }) } -function windowsProcessRows(): string { +function windowsProcessJsonRows( + rows: { + CommandLine: string | null + Name: string + ParentProcessId: number + ProcessId: number + ExecutablePath?: string | null + }[] = [ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'node C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd', + Name: 'node.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ] +): string { + return JSON.stringify( + rows.map((row) => ({ + ExecutablePath: row.ExecutablePath ?? null, + ...row + })) + ) +} + +function windowsProcessValueRows(): string { return [ 'CommandLine=powershell.exe', + 'ExecutablePath=C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', 'Name=powershell.exe', 'ParentProcessId=99', 'ProcessId=100', '', 'CommandLine=node C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd', + 'ExecutablePath=C:\\Program Files\\nodejs\\node.exe', 'Name=node.exe', 'ParentProcessId=100', 'ProcessId=101', @@ -95,7 +127,7 @@ describe('resolveAgentForegroundProcess', () => { execFileMock.mockImplementation( (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void - callback(null, { stdout: windowsProcessRows(), stderr: '' }) + callback(null, { stdout: windowsProcessJsonRows(), stderr: '' }) } ) @@ -108,6 +140,79 @@ describe('resolveAgentForegroundProcess', () => { ) }) + it('recognizes Windows shell-rooted agent launches from descendant command lines', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { stdout: windowsProcessJsonRows(), stderr: '' }) + } + ) + + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe('codex') + }) + + it('recognizes Windows Git Bash shell-rooted agent launches', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: windowsProcessJsonRows([ + { + CommandLine: 'C:\\Program Files\\Git\\bin\\bash.exe --login -i', + Name: 'bash.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'node C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd', + Name: 'node.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]), + stderr: '' + }) + } + ) + + await expect(resolveAgentForegroundProcess(100, 'bash.exe')).resolves.toBe('codex') + }) + + it('keeps multiline Windows command lines inside the parsed process row', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: [ + 'node', + 'C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\@openai\\codex\\bin\\codex.js', + '--prompt', + '"line one\r\nName=gemini.exe\r\nProcessId=999"' + ].join(' '), + Name: 'node.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]), + stderr: '' + }) + } + ) + + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe('codex') + }) + it('falls back to WMIC when Windows PowerShell process enumeration fails', async () => { Object.defineProperty(process, 'platform', { value: 'win32' }) execFileMock.mockImplementation((cmd: string, _args: string[], _opts: unknown, cb: unknown) => { @@ -116,7 +221,27 @@ describe('resolveAgentForegroundProcess', () => { callback(new Error('powershell unavailable'), { stdout: '', stderr: '' }) return } - callback(null, { stdout: windowsProcessRows(), stderr: '' }) + callback(null, { stdout: windowsProcessValueRows(), stderr: '' }) + }) + + await expect(resolveAgentForegroundProcess(100, 'node.exe')).resolves.toBe('codex') + expect(execFileMock).toHaveBeenCalledWith( + 'wmic', + expect.any(Array), + expect.objectContaining({ timeout: 3000 }), + expect.any(Function) + ) + }) + + it('falls back to WMIC when Windows PowerShell returns no process rows', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation((cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + if (cmd === 'powershell.exe') { + callback(null, { stdout: ' \r\n', stderr: '' }) + return + } + callback(null, { stdout: windowsProcessValueRows(), stderr: '' }) }) await expect(resolveAgentForegroundProcess(100, 'node.exe')).resolves.toBe('codex') @@ -159,6 +284,162 @@ describe('resolveAgentForegroundProcess', () => { await expect(resolveAgentForegroundProcess(100, 'node.exe')).resolves.toBe('node.exe') }) + it('fails closed for ambiguous Windows shell-rooted agent descendants', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: [ + 'CommandLine=powershell.exe', + 'Name=powershell.exe', + 'ParentProcessId=99', + 'ProcessId=100', + '', + 'CommandLine=node C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\@openai\\codex\\bin\\codex.js', + 'Name=node.exe', + 'ParentProcessId=100', + 'ProcessId=101', + '', + 'CommandLine=node C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\@google\\gemini-cli\\bundle\\gemini.mjs', + 'Name=node.exe', + 'ParentProcessId=100', + 'ProcessId=102', + '' + ].join('\r\n'), + stderr: '' + }) + } + ) + + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + + it('recognizes a Windows shell-rooted agent when only one candidate matches the worktree path', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: [ + 'CommandLine=powershell.exe', + 'CreationDate=20260616110000.000000-000', + 'ExecutablePath=C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + 'Name=powershell.exe', + 'ParentProcessId=99', + 'ProcessId=100', + '', + 'CommandLine=node C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\@openai\\codex\\bin\\codex.js --cwd C:\\repo\\orca', + 'CreationDate=20260616110100.000000-000', + 'ExecutablePath=C:\\Program Files\\nodejs\\node.exe', + 'Name=node.exe', + 'ParentProcessId=100', + 'ProcessId=101', + '', + 'CommandLine=node C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\@google\\gemini-cli\\bundle\\gemini.mjs --cwd C:\\repo\\other', + 'CreationDate=20260616110200.000000-000', + 'ExecutablePath=C:\\Program Files\\nodejs\\node.exe', + 'Name=node.exe', + 'ParentProcessId=100', + 'ProcessId=102', + '' + ].join('\r\n'), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcess(100, 'powershell.exe', { + contextPaths: ['C:\\repo\\orca'] + }) + ).resolves.toBe('codex') + }) + + it('recognizes the deepest Windows shell-rooted agent when candidates share one lineage', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: [ + 'CommandLine=powershell.exe', + 'CreationDate=20260616110000.000000-000', + 'ExecutablePath=C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + 'Name=powershell.exe', + 'ParentProcessId=99', + 'ProcessId=100', + '', + 'CommandLine=codex --cwd C:\\repo\\orca', + 'CreationDate=20260616110100.000000-000', + 'ExecutablePath=C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd', + 'Name=codex.exe', + 'ParentProcessId=100', + 'ProcessId=101', + '', + 'CommandLine=gemini --cwd C:\\repo\\orca', + 'CreationDate=20260616110200.000000-000', + 'ExecutablePath=C:\\Users\\dev\\AppData\\Roaming\\npm\\gemini.cmd', + 'Name=gemini.exe', + 'ParentProcessId=101', + 'ProcessId=102', + '' + ].join('\r\n'), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcess(100, 'powershell.exe', { + contextPaths: ['C:\\repo\\orca'] + }) + ).resolves.toBe('gemini') + }) + + it('fails closed for sibling Windows agents that both match the same worktree path', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: [ + 'CommandLine=powershell.exe', + 'CreationDate=20260616110000.000000-000', + 'ExecutablePath=C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + 'Name=powershell.exe', + 'ParentProcessId=99', + 'ProcessId=100', + '', + 'CommandLine=codex --cwd C:\\repo\\orca', + 'CreationDate=20260616110100.000000-000', + 'ExecutablePath=C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd', + 'Name=codex.exe', + 'ParentProcessId=100', + 'ProcessId=101', + '', + 'CommandLine=gemini --cwd C:\\repo\\orca', + 'CreationDate=20260616110200.000000-000', + 'ExecutablePath=C:\\Users\\dev\\AppData\\Roaming\\npm\\gemini.cmd', + 'Name=gemini.exe', + 'ParentProcessId=100', + 'ProcessId=102', + '' + ].join('\r\n'), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcess(100, 'powershell.exe', { + contextPaths: ['C:\\repo\\orca'] + }) + ).resolves.toBe('powershell.exe') + }) + it('fails closed when Windows has multiple matching wrapper descendants', async () => { Object.defineProperty(process, 'platform', { value: 'win32' }) execFileMock.mockImplementation( diff --git a/src/main/providers/agent-foreground-process.ts b/src/main/providers/agent-foreground-process.ts index a748f8e2a..1d090cc23 100644 --- a/src/main/providers/agent-foreground-process.ts +++ b/src/main/providers/agent-foreground-process.ts @@ -1,10 +1,13 @@ import { execFile } from 'child_process' import { promisify } from 'util' +import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' import { - isAgentForegroundWrapperProcess, - isExpectedAgentProcess, - recognizeAgentProcessFromCommandLine -} from '../../shared/agent-process-recognition' + resolveWindowsAgentForegroundProcess, + shouldInspectWindowsAgentForeground, + type AgentForegroundResolutionOptions +} from './windows-agent-foreground-process' + +export type { AgentForegroundResolutionOptions } from './windows-agent-foreground-process' const execFileAsync = promisify(execFile) @@ -15,13 +18,6 @@ type ProcessRow = { command: string } -type WindowsProcessRow = { - pid: number - ppid: number - name: string - command: string -} - function parsePsRows(stdout: string): ProcessRow[] { const rows: ProcessRow[] = [] for (const line of stdout.split('\n')) { @@ -39,49 +35,6 @@ function parsePsRows(stdout: string): ProcessRow[] { return rows } -function parseWindowsProcessRows(stdout: string): WindowsProcessRow[] { - const rows: WindowsProcessRow[] = [] - let command = '' - let name = '' - let pid = Number.NaN - let ppid = Number.NaN - - const flush = (): void => { - if (Number.isFinite(pid) && Number.isFinite(ppid)) { - rows.push({ pid, ppid, name, command: command || name }) - } - command = '' - name = '' - pid = Number.NaN - ppid = Number.NaN - } - - for (const raw of stdout.split(/\r?\n/)) { - const line = raw.trim() - if (!line) { - flush() - continue - } - const eq = line.indexOf('=') - if (eq < 0) { - continue - } - const key = line.slice(0, eq) - const value = line.slice(eq + 1) - if (key === 'CommandLine') { - command = value - } else if (key === 'Name') { - name = value - } else if (key === 'ParentProcessId') { - ppid = Number.parseInt(value, 10) - } else if (key === 'ProcessId') { - pid = Number.parseInt(value, 10) - } - } - flush() - return rows -} - function collectDescendants( rows: Row[], rootPid: number @@ -114,18 +67,20 @@ function candidateScore(row: ProcessRow & { depth: number }): number { export async function resolveAgentForegroundProcess( shellPid: number | null | undefined, - fallbackProcess: string | null + fallbackProcess: string | null, + options: AgentForegroundResolutionOptions = {} ): Promise { if (!shellPid) { return fallbackProcess } if (process.platform === 'win32') { - if (!fallbackProcess || !isAgentForegroundWrapperProcess(fallbackProcess)) { + if (!fallbackProcess || !shouldInspectWindowsAgentForeground(fallbackProcess)) { return fallbackProcess } return ( - (await resolveAgentForegroundProcessFromWindows(shellPid, fallbackProcess)) ?? fallbackProcess + (await resolveWindowsAgentForegroundProcess(shellPid, fallbackProcess, options)) ?? + fallbackProcess ) } @@ -143,93 +98,6 @@ export async function resolveAgentForegroundProcess( return fallbackProcess } -async function resolveAgentForegroundProcessFromWindows( - shellPid: number, - fallbackProcess: string -): Promise { - const stdout = - (await queryWindowsProcessesWithPowerShell()) ?? (await queryWindowsProcessesWithWmic()) - return stdout - ? resolveAgentForegroundProcessFromWindowsRows(stdout, shellPid, fallbackProcess) - : null -} - -async function queryWindowsProcessesWithPowerShell(): Promise { - try { - const { stdout } = await execFileAsync( - 'powershell.exe', - [ - '-NoProfile', - '-NonInteractive', - '-Command', - 'Get-CimInstance Win32_Process | ForEach-Object { "CommandLine=$($_.CommandLine)"; "Name=$($_.Name)"; "ParentProcessId=$($_.ParentProcessId)"; "ProcessId=$($_.ProcessId)"; "" }' - ], - { - encoding: 'utf8', - timeout: 3000, - maxBuffer: 8 * 1024 * 1024 - } - ) - return stdout - } catch { - return null - } -} - -async function queryWindowsProcessesWithWmic(): Promise { - try { - const { stdout } = await execFileAsync( - 'wmic', - ['process', 'get', 'CommandLine,Name,ParentProcessId,ProcessId', '/format:value'], - { - encoding: 'utf8', - timeout: 3000, - maxBuffer: 8 * 1024 * 1024 - } - ) - return stdout - } catch { - // Best-effort: Windows process enumeration may be disabled, so callers - // still fall back to node-pty's process name when both probes fail. - return null - } -} - -function resolveAgentForegroundProcessFromWindowsRows( - stdout: string, - shellPid: number, - fallbackProcess: string -): string | null { - const candidates = collectDescendants(parseWindowsProcessRows(stdout), shellPid).sort( - (a, b) => b.depth - a.depth - ) - const wrapperCandidates = candidates.filter((candidate) => - windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess) - ) - if (wrapperCandidates.length !== 1) { - return null - } - const [candidate] = wrapperCandidates - const recognized = - recognizeAgentProcessFromCommandLine(candidate.command) ?? - recognizeAgentProcessFromCommandLine(candidate.name) - if (recognized) { - return recognized.processName - } - return null -} - -function windowsCandidateMatchesFallbackWrapper( - candidate: WindowsProcessRow, - fallbackProcess: string -): boolean { - const commandToken = candidate.command.trim().split(/\s+/, 1)[0] ?? '' - return ( - isExpectedAgentProcess(candidate.name, fallbackProcess) || - isExpectedAgentProcess(commandToken, fallbackProcess) - ) -} - function resolveAgentForegroundProcessFromPs(stdout: string, shellPid: number): string | null { const rows = parsePsRows(stdout) const shellRow = rows.find((row) => row.pid === shellPid) diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts index 5a92c2cef..19c8cd81d 100644 --- a/src/main/providers/local-pty-provider.test.ts +++ b/src/main/providers/local-pty-provider.test.ts @@ -7,14 +7,16 @@ const { accessSyncMock, mkdirSyncMock, writeFileSyncMock, - spawnMock + spawnMock, + resolveAgentForegroundProcessMock } = vi.hoisted(() => ({ existsSyncMock: vi.fn(), statSyncMock: vi.fn(), accessSyncMock: vi.fn(), mkdirSyncMock: vi.fn(), writeFileSyncMock: vi.fn(), - spawnMock: vi.fn() + spawnMock: vi.fn(), + resolveAgentForegroundProcessMock: vi.fn() })) vi.mock('fs', () => ({ @@ -37,6 +39,10 @@ vi.mock('node-pty', () => ({ spawn: spawnMock })) +vi.mock('./agent-foreground-process', () => ({ + resolveAgentForegroundProcess: resolveAgentForegroundProcessMock +})) + vi.mock('../wsl', () => ({ parseWslPath: (path: string) => { const match = path.match(/^\\\\wsl\.localhost\\([^\\]+)(.*)$/) @@ -82,6 +88,10 @@ describe('LocalPtyProvider', () => { accessSyncMock.mockReturnValue(undefined) mkdirSyncMock.mockReset() writeFileSyncMock.mockReset() + resolveAgentForegroundProcessMock.mockReset() + resolveAgentForegroundProcessMock.mockImplementation( + async (_pid: number, fallbackProcess: string | null) => fallbackProcess + ) exitCb = undefined mockProc = { @@ -650,6 +660,24 @@ describe('LocalPtyProvider', () => { expect(await provider.getForegroundProcess(id)).toBe('zsh') }) + it('uses the spawned Windows shell when node-pty reports only the terminal name', async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + mockProc.process = 'xterm-256color' + + const { id } = await provider.spawn({ + cols: 80, + rows: 24, + shellOverride: 'powershell.exe' + }) + + expect(await provider.getForegroundProcess(id)).toBe('powershell.exe') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledWith( + mockProc.pid, + 'powershell.exe', + expect.any(Object) + ) + }) + it('returns null for unknown PTY ids', async () => { expect(await provider.getForegroundProcess('nonexistent')).toBeNull() }) diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 2115e5084..7d301cfc5 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -40,12 +40,14 @@ import { } from '../git-bash' import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' import { resolveAgentForegroundProcess } from './agent-foreground-process' +import { getAgentForegroundContextPaths } from './agent-foreground-context-paths' const PANE_IDENTITY_ENV_KEYS = ['ORCA_PANE_KEY', 'ORCA_TAB_ID', 'ORCA_WORKTREE_ID'] as const let ptyCounter = 0 const ptyProcesses = new Map() const ptyShellName = new Map() +const ptyAgentForegroundContextPaths = new Map() // Why: node-pty's onData/onExit register native NAPI ThreadSafeFunction // callbacks. If the PTY is killed without disposing these listeners, the // stale callbacks survive into node::FreeEnvironment() where NAPI attempts @@ -133,6 +135,7 @@ function clearPtyState(id: string): void { disposePtyListeners(id) ptyProcesses.delete(id) ptyShellName.delete(id) + ptyAgentForegroundContextPaths.delete(id) ptyLoadGeneration.delete(id) } @@ -156,6 +159,26 @@ function normalizeLocalCallerSessionId(sessionId: string | undefined): string | return requested } +function normalizeForegroundProcessName(processName: string | null | undefined): string | null { + const trimmed = processName?.trim().replace(/^["']|["']$/g, '') ?? '' + if (!trimmed || trimmed === 'xterm-256color') { + return null + } + return trimmed.split(/[\\/]/).pop() || null +} + +function resolveForegroundFallbackProcess( + processName: string | null | undefined, + shellName: string | undefined +): string | null { + if (process.platform !== 'win32' || normalizeForegroundProcessName(processName)) { + return processName || null + } + // Why: Windows node-pty can expose only the terminal name (`xterm-256color`). + // The spawned shell is the best fallback for agent foreground enrichment. + return shellName ?? processName ?? null +} + function destroyPtyProcess(proc: pty.IPty, options: { alreadyKilled?: boolean } = {}): void { // Why: node-pty's UnixTerminal.destroy() closes the master socket, which // releases the ptmx fd to the OS — without this call the fd leaks until GC @@ -507,6 +530,10 @@ export class LocalPtyProvider implements IPtyProvider { const proc = spawnResult.process ptyProcesses.set(id, proc) ptyShellName.set(id, basename(shellPath)) + ptyAgentForegroundContextPaths.set( + id, + getAgentForegroundContextPaths({ cwd: args.cwd, worktreeId: args.worktreeId }) + ) ptyLoadGeneration.set(id, loadGeneration) this.opts.onSpawned?.(id) @@ -644,6 +671,7 @@ export class LocalPtyProvider implements IPtyProvider { destroyPtyProcess(proc, { alreadyKilled: true }) ptyProcesses.delete(id) ptyShellName.delete(id) + ptyAgentForegroundContextPaths.delete(id) ptyLoadGeneration.delete(id) this.opts.onExit?.(id, -1) for (const cb of exitListeners) { @@ -711,7 +739,13 @@ export class LocalPtyProvider implements IPtyProvider { return null } try { - return await resolveAgentForegroundProcess(proc.pid, proc.process || null) + return await resolveAgentForegroundProcess( + proc.pid, + resolveForegroundFallbackProcess(proc.process || null, ptyShellName.get(id)), + { + contextPaths: ptyAgentForegroundContextPaths.get(id) + } + ) } catch { return null } diff --git a/src/main/providers/windows-agent-foreground-process.ts b/src/main/providers/windows-agent-foreground-process.ts new file mode 100644 index 000000000..39447432a --- /dev/null +++ b/src/main/providers/windows-agent-foreground-process.ts @@ -0,0 +1,217 @@ +import { + isAgentForegroundWrapperProcess, + isExpectedAgentProcess, + recognizeAgentProcessFromCommandLine +} from '../../shared/agent-process-recognition' +import { isShellProcess } from '../../shared/shell-process-detection' +import { + queryWindowsProcessDescendants, + type WindowsProcessCandidate, + type WindowsProcessRow +} from './windows-foreground-process-rows' + +export type AgentForegroundResolutionOptions = { + contextPaths?: readonly string[] +} + +export function shouldInspectWindowsAgentForeground(fallbackProcess: string): boolean { + return isAgentForegroundWrapperProcess(fallbackProcess) || isShellProcess(fallbackProcess) +} + +export async function resolveWindowsAgentForegroundProcess( + shellPid: number, + fallbackProcess: string, + options: AgentForegroundResolutionOptions +): Promise { + const candidates = await queryWindowsProcessDescendants(shellPid) + if (!candidates) { + return null + } + if (isShellProcess(fallbackProcess)) { + return resolveShellForegroundProcessFromWindowsCandidates(candidates, options.contextPaths) + } + const wrapperCandidates = candidates.filter((candidate) => + windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess) + ) + if (wrapperCandidates.length !== 1) { + return resolveWrapperForegroundProcessFromWindowsCandidates( + wrapperCandidates, + options.contextPaths + ) + } + const [candidate] = wrapperCandidates + const recognized = + recognizeAgentProcessFromCommandLine(candidate.command) ?? + recognizeAgentProcessFromCommandLine(candidate.name) + if (recognized) { + return recognized.processName + } + return null +} + +function resolveShellForegroundProcessFromWindowsCandidates( + candidates: readonly WindowsProcessCandidate[], + contextPaths: readonly string[] | undefined +): string | null { + const recognizedCandidates = createRecognizedWindowsProcessCandidates(candidates, contextPaths) + const contextCandidates = recognizedCandidates.filter((candidate) => candidate.contextMatch) + if (contextCandidates.length > 0) { + return resolveRecognizedWindowsProcessCandidates(contextCandidates, candidates) + } + return resolveRecognizedWindowsProcessCandidates(recognizedCandidates, candidates) +} + +function resolveWrapperForegroundProcessFromWindowsCandidates( + candidates: readonly WindowsProcessCandidate[], + contextPaths: readonly string[] | undefined +): string | null { + const contextCandidates = createRecognizedWindowsProcessCandidates( + candidates, + contextPaths + ).filter((candidate) => candidate.contextMatch) + return contextCandidates.length > 0 + ? resolveRecognizedWindowsProcessCandidates(contextCandidates, candidates) + : null +} + +type RecognizedWindowsProcessCandidate = WindowsProcessRow & { + contextMatch: boolean + depth: number + processName: string +} + +function createRecognizedWindowsProcessCandidates( + candidates: readonly WindowsProcessCandidate[], + contextPaths: readonly string[] | undefined +): RecognizedWindowsProcessCandidate[] { + const normalizedContextPaths = normalizeContextPaths(contextPaths) + return candidates.flatMap((candidate) => { + const recognized = recognizeWindowsProcessCandidate(candidate) + if (!recognized) { + return [] + } + return [ + { + ...candidate, + contextMatch: candidateMatchesContextPath(candidate, normalizedContextPaths), + processName: recognized + } + ] + }) +} + +function resolveRecognizedWindowsProcessCandidates( + recognizedCandidates: readonly RecognizedWindowsProcessCandidate[], + allCandidates: readonly WindowsProcessCandidate[] +): string | null { + if (recognizedCandidates.length === 0) { + return null + } + const recognizedProcessNames = new Set( + recognizedCandidates.map((candidate) => candidate.processName) + ) + if (recognizedProcessNames.size === 1) { + return [...recognizedProcessNames][0] + } + + const candidatesByPid = new Map(allCandidates.map((candidate) => [candidate.pid, candidate])) + const leafCandidates = recognizedCandidates.filter( + (candidate) => + !recognizedCandidates.some( + (other) => + other.pid !== candidate.pid && + windowsCandidateIsAncestor(candidate, other, candidatesByPid) + ) + ) + const leafProcessNames = new Set(leafCandidates.map((candidate) => candidate.processName)) + // Why: Windows lacks a cheap PTY foreground marker like POSIX '+'. A single + // recognized lineage leaf is strong enough; sibling agent leaves are not. + return leafProcessNames.size === 1 ? [...leafProcessNames][0] : null +} + +function windowsCandidateIsAncestor( + candidate: WindowsProcessRow, + other: WindowsProcessRow, + candidatesByPid: ReadonlyMap +): boolean { + let current = candidatesByPid.get(other.ppid) + while (current) { + if (current.pid === candidate.pid) { + return true + } + current = candidatesByPid.get(current.ppid) + } + return false +} + +function normalizeContextPaths(contextPaths: readonly string[] | undefined): string[] { + const normalized = new Set() + for (const contextPath of contextPaths ?? []) { + const candidate = normalizePathForCommandMatch(contextPath) + if (isSafeContextPath(candidate)) { + normalized.add(candidate) + } + } + return [...normalized].sort((a, b) => b.length - a.length) +} + +function isSafeContextPath(contextPath: string): boolean { + return contextPath.length >= 4 && (/^[a-z]:\//.test(contextPath) || contextPath.startsWith('//')) +} + +function candidateMatchesContextPath( + candidate: WindowsProcessRow, + normalizedContextPaths: readonly string[] +): boolean { + if (normalizedContextPaths.length === 0) { + return false + } + const haystack = normalizePathForCommandMatch( + [candidate.command, candidate.executablePath].filter(Boolean).join('\n') + ) + return normalizedContextPaths.some((contextPath) => + commandLineContainsPath(haystack, contextPath) + ) +} + +function normalizePathForCommandMatch(value: string): string { + return value + .trim() + .replace(/^["']|["']$/g, '') + .replace(/\\/g, '/') + .replace(/\/+$/g, '') + .toLowerCase() +} + +function commandLineContainsPath(haystack: string, contextPath: string): boolean { + let index = haystack.indexOf(contextPath) + while (index !== -1) { + const before = index > 0 ? haystack[index - 1] : '' + const after = haystack[index + contextPath.length] ?? '' + const beforeOk = !before || /[\s"'(=]/.test(before) + const afterOk = !after || after === '/' || /[\s"'),;]/.test(after) + if (beforeOk && afterOk) { + return true + } + index = haystack.indexOf(contextPath, index + 1) + } + return false +} + +function recognizeWindowsProcessCandidate(candidate: WindowsProcessRow): string | null { + const recognized = + recognizeAgentProcessFromCommandLine(candidate.command) ?? + recognizeAgentProcessFromCommandLine(candidate.name) + return recognized?.processName ?? null +} + +function windowsCandidateMatchesFallbackWrapper( + candidate: WindowsProcessRow, + fallbackProcess: string +): boolean { + const commandToken = candidate.command.trim().split(/\s+/, 1)[0] ?? '' + return ( + isExpectedAgentProcess(candidate.name, fallbackProcess) || + isExpectedAgentProcess(commandToken, fallbackProcess) + ) +} diff --git a/src/main/providers/windows-foreground-process-rows.ts b/src/main/providers/windows-foreground-process-rows.ts new file mode 100644 index 000000000..2dd23ad5b --- /dev/null +++ b/src/main/providers/windows-foreground-process-rows.ts @@ -0,0 +1,206 @@ +import { execFile } from 'child_process' +import { promisify } from 'util' + +const execFileAsync = promisify(execFile) +const WINDOWS_PROCESS_QUERY_TIMEOUT_MS = 3_000 +// Why: CommandLine can contain CR/LF text. JSON keeps process fields structured +// so an argument cannot masquerade as another `Name=` / `ProcessId=` row. +const POWERSHELL_PROCESS_QUERY = + '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ' + + 'Get-CimInstance -ClassName Win32_Process ' + + '-Property CommandLine,ExecutablePath,Name,ParentProcessId,ProcessId | ' + + 'Select-Object CommandLine,ExecutablePath,Name,ParentProcessId,ProcessId | ' + + 'ConvertTo-Json -Compress' + +export type WindowsProcessRow = { + pid: number + ppid: number + name: string + command: string + executablePath: string +} + +export type WindowsProcessCandidate = WindowsProcessRow & { depth: number } + +export async function queryWindowsProcessDescendants( + rootPid: number +): Promise { + const rows = + (await queryWindowsProcessesWithPowerShell()) ?? (await queryWindowsProcessesWithWmic()) + return rows ? collectDescendants(rows, rootPid).sort((a, b) => b.depth - a.depth) : null +} + +function parseWindowsProcessValueRows(stdout: string): WindowsProcessRow[] { + const rows: WindowsProcessRow[] = [] + let command = '' + let executablePath = '' + let name = '' + let pid = Number.NaN + let ppid = Number.NaN + + const flush = (): void => { + if (Number.isFinite(pid) && Number.isFinite(ppid)) { + rows.push({ pid, ppid, name, command: command || name, executablePath }) + } + command = '' + executablePath = '' + name = '' + pid = Number.NaN + ppid = Number.NaN + } + + for (const raw of stdout.split(/\r?\n/)) { + const line = raw.trim() + if (!line) { + flush() + continue + } + const eq = line.indexOf('=') + if (eq < 0) { + continue + } + const key = line.slice(0, eq) + const value = line.slice(eq + 1) + if (key === 'CommandLine') { + command = value + } else if (key === 'ExecutablePath') { + executablePath = value + } else if (key === 'Name') { + name = value + } else if (key === 'ParentProcessId') { + ppid = Number.parseInt(value, 10) + } else if (key === 'ProcessId') { + pid = Number.parseInt(value, 10) + } + } + flush() + return rows +} + +type WindowsProcessJsonRow = { + CommandLine?: unknown + ExecutablePath?: unknown + Name?: unknown + ParentProcessId?: unknown + ProcessId?: unknown +} + +function parseWindowsProcessJsonRows(stdout: string): WindowsProcessRow[] | null { + const trimmed = stdout.trim() + if (!trimmed) { + return [] + } + try { + const parsed = JSON.parse(trimmed) as unknown + const items = Array.isArray(parsed) ? parsed : [parsed] + return items.flatMap((item) => { + if (!item || typeof item !== 'object') { + return [] + } + const row = item as WindowsProcessJsonRow + const pid = numberFromWindowsProcessField(row.ProcessId) + const ppid = numberFromWindowsProcessField(row.ParentProcessId) + if (!Number.isFinite(pid) || !Number.isFinite(ppid)) { + return [] + } + const name = stringFromWindowsProcessField(row.Name) + const command = stringFromWindowsProcessField(row.CommandLine) || name + return [ + { + pid, + ppid, + name, + command, + executablePath: stringFromWindowsProcessField(row.ExecutablePath) + } + ] + }) + } catch { + return null + } +} + +function stringFromWindowsProcessField(value: unknown): string { + if (typeof value === 'string') { + return value + } + if (value === null || value === undefined) { + return '' + } + return String(value) +} + +function numberFromWindowsProcessField(value: unknown): number { + if (typeof value === 'number') { + return value + } + if (typeof value === 'string') { + return Number.parseInt(value, 10) + } + return Number.NaN +} + +function collectDescendants( + rows: Row[], + rootPid: number +): (Row & { depth: number })[] { + const childrenByParent = new Map() + for (const row of rows) { + const children = childrenByParent.get(row.ppid) ?? [] + children.push(row) + childrenByParent.set(row.ppid, children) + } + + const descendants: (Row & { depth: number })[] = [] + const stack = (childrenByParent.get(rootPid) ?? []).map((row) => ({ row, depth: 1 })) + while (stack.length > 0) { + const { row, depth } = stack.pop()! + descendants.push({ ...row, depth }) + for (const child of childrenByParent.get(row.pid) ?? []) { + stack.push({ row: child, depth: depth + 1 }) + } + } + return descendants +} + +async function queryWindowsProcessesWithPowerShell(): Promise { + try { + const { stdout } = await execFileAsync( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-Command', POWERSHELL_PROCESS_QUERY], + { + encoding: 'utf8', + timeout: WINDOWS_PROCESS_QUERY_TIMEOUT_MS, + maxBuffer: 8 * 1024 * 1024 + } + ) + const rows = parseWindowsProcessJsonRows(stdout) + return rows && rows.length > 0 ? rows : null + } catch { + return null + } +} + +async function queryWindowsProcessesWithWmic(): Promise { + try { + const { stdout } = await execFileAsync( + 'wmic', + [ + 'process', + 'get', + 'CommandLine,ExecutablePath,Name,ParentProcessId,ProcessId', + '/format:value' + ], + { + encoding: 'utf8', + timeout: WINDOWS_PROCESS_QUERY_TIMEOUT_MS, + maxBuffer: 8 * 1024 * 1024 + } + ) + return parseWindowsProcessValueRows(stdout) + } catch { + // Best-effort: Windows process enumeration may be disabled, so callers + // still fall back to node-pty's process name when both probes fail. + return null + } +} diff --git a/src/relay/pty-shell-utils.test.ts b/src/relay/pty-shell-utils.test.ts index e308bb88c..61180b889 100644 --- a/src/relay/pty-shell-utils.test.ts +++ b/src/relay/pty-shell-utils.test.ts @@ -30,6 +30,21 @@ function mockExecFile( ) } +async function withProcessPlatform( + platform: NodeJS.Platform, + run: () => T | Promise +): Promise { + const descriptor = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + try { + return await run() + } finally { + if (descriptor) { + Object.defineProperty(process, 'platform', descriptor) + } + } +} + beforeEach(() => { execFileMock.mockReset() }) @@ -115,66 +130,106 @@ describe('getForegroundProcessName', () => { }) it('recognizes SSH relay node-wrapped agents from descendant command lines', async () => { - mockExecFile((_command, args) => { - if (args[0] === '-axo') { - return { - stdout: ['100 99 Ss bash -l', '101 100 S+ node /home/dev/.local/bin/codex'].join('\n') + await withProcessPlatform('linux', async () => { + mockExecFile((_command, args) => { + if (args[0] === '-axo') { + return { + stdout: ['100 99 Ss bash -l', '101 100 S+ node /home/dev/.local/bin/codex'].join( + '\n' + ) + } } - } - return new Error('unexpected command') - }) + return new Error('unexpected command') + }) - await expect(getForegroundProcessName(100, 'node')).resolves.toBe('codex') + await expect(getForegroundProcessName(100, 'node')).resolves.toBe('codex') + }) + }) + + it('recognizes Windows SSH relay shell-rooted agent descendants', async () => { + await withProcessPlatform('win32', async () => { + mockExecFile((command) => { + if (command === 'powershell.exe') { + return { + stdout: JSON.stringify([ + { + CommandLine: 'powershell.exe', + ExecutablePath: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'node C:\\Users\\dev\\AppData\\Roaming\\npm\\codex.cmd', + ExecutablePath: 'C:\\Program Files\\nodejs\\node.exe', + Name: 'node.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]) + } + } + return new Error('unexpected command') + }) + + await expect(getForegroundProcessName(100, 'powershell.exe')).resolves.toBe('codex') + }) }) it('recognizes SSH relay wrapped agents when no foreground marker is available', async () => { - mockExecFile((_command, args) => { - if (args[0] === '-axo') { - return { - stdout: [ - '100 99 Ss bash -l', - '101 100 S node /home/dev/.local/bin/node_modules/@google/gemini-cli/bundle/gemini.mjs' - ].join('\n') + await withProcessPlatform('linux', async () => { + mockExecFile((_command, args) => { + if (args[0] === '-axo') { + return { + stdout: [ + '100 99 Ss bash -l', + '101 100 S node /home/dev/.local/bin/node_modules/@google/gemini-cli/bundle/gemini.mjs' + ].join('\n') + } } - } - return new Error('unexpected command') - }) + return new Error('unexpected command') + }) - await expect(getForegroundProcessName(100, 'node')).resolves.toBe('gemini') + await expect(getForegroundProcessName(100, 'node')).resolves.toBe('gemini') + }) }) it('does not guess when SSH relay wrapper descendants are ambiguous', async () => { - mockExecFile((_command, args) => { - if (args[0] === '-axo') { - return { - stdout: [ - '100 99 Ss bash -l', - '101 100 S node /home/dev/project/server.js', - '102 100 S node /home/dev/.local/bin/node_modules/@openai/codex/bin/codex.js' - ].join('\n') + await withProcessPlatform('linux', async () => { + mockExecFile((_command, args) => { + if (args[0] === '-axo') { + return { + stdout: [ + '100 99 Ss bash -l', + '101 100 S node /home/dev/project/server.js', + '102 100 S node /home/dev/.local/bin/node_modules/@openai/codex/bin/codex.js' + ].join('\n') + } } - } - return new Error('unexpected command') - }) + return new Error('unexpected command') + }) - await expect(getForegroundProcessName(100, 'node')).resolves.toBe('node') + await expect(getForegroundProcessName(100, 'node')).resolves.toBe('node') + }) }) it('does not report a stopped SSH relay agent when another process has foreground', async () => { - mockExecFile((_command, args) => { - if (args[0] === '-axo') { - return { - stdout: [ - '100 99 Ss bash -l', - '101 100 T node /home/dev/.local/bin/codex', - '102 100 S+ vim notes.txt' - ].join('\n') + await withProcessPlatform('linux', async () => { + mockExecFile((_command, args) => { + if (args[0] === '-axo') { + return { + stdout: [ + '100 99 Ss bash -l', + '101 100 T node /home/dev/.local/bin/codex', + '102 100 S+ vim notes.txt' + ].join('\n') + } } - } - return new Error('unexpected command') - }) + return new Error('unexpected command') + }) - await expect(getForegroundProcessName(100, 'node')).resolves.toBe('node') + await expect(getForegroundProcessName(100, 'node')).resolves.toBe('node') + }) }) it('falls back to the root process command when descendant inspection fails', async () => { diff --git a/src/relay/pty-shell-utils.ts b/src/relay/pty-shell-utils.ts index 4a14742a7..af5ad0d3c 100644 --- a/src/relay/pty-shell-utils.ts +++ b/src/relay/pty-shell-utils.ts @@ -10,6 +10,10 @@ import { recognizeAgentProcessFromCommandLine } from '../shared/agent-process-recognition' import { isShellProcess } from '../shared/shell-process-detection' +import { + resolveWindowsAgentForegroundProcess, + shouldInspectWindowsAgentForeground +} from '../main/providers/windows-agent-foreground-process' const execFile = promisify(execFileCb) @@ -259,6 +263,14 @@ export async function getForegroundProcessName( if (fallbackRecognition) { return fallbackRecognition.processName } + if (process.platform === 'win32') { + if (!shouldInspectWindowsAgentForeground(fallbackProcess)) { + return fallbackProcess + } + return ( + (await resolveWindowsAgentForegroundProcess(pid, fallbackProcess, {})) ?? fallbackProcess + ) + } if (!isShellProcess(fallbackProcess) && !isAgentForegroundWrapperProcess(fallbackProcess)) { return fallbackProcess } diff --git a/src/renderer/src/lib/tui-agent-startup.test.ts b/src/renderer/src/lib/tui-agent-startup.test.ts index 81be829d8..7fcb743d7 100644 --- a/src/renderer/src/lib/tui-agent-startup.test.ts +++ b/src/renderer/src/lib/tui-agent-startup.test.ts @@ -305,6 +305,7 @@ describe('buildAgentDraftLaunchPlan', () => { describe('isShellProcess', () => { it('treats common shells as non-agent foreground processes', () => { expect(isShellProcess('bash')).toBe(true) + expect(isShellProcess('C:\\Program Files\\Git\\bin\\bash.exe')).toBe(true) expect(isShellProcess('pwsh.exe')).toBe(true) expect(isShellProcess('/bin/zsh')).toBe(true) expect(isShellProcess('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe')).toBe( diff --git a/src/shared/shell-process-detection.ts b/src/shared/shell-process-detection.ts index 729bfe110..381b3bc42 100644 --- a/src/shared/shell-process-detection.ts +++ b/src/shared/shell-process-detection.ts @@ -4,13 +4,20 @@ const SHELL_NAMES = new Set( '|bash|zsh|sh|fish|cmd|cmd.exe|powershell|powershell.exe|pwsh|pwsh.exe|nu'.split('|') ) +const WINDOWS_PROCESS_EXTENSION_RE = /\.(?:exe|cmd|bat|ps1)$/i export function isShellProcess(processName: string): boolean { const normalized = processName .trim() .replace(/^["']|["']$/g, '') .toLowerCase() + const basename = normalized.split(/[\\/]/).pop() ?? normalized + // Why: Windows node-pty reports Git Bash and similar shells as `bash.exe`; + // those still need the same shell-safe handling as their POSIX basenames. + const basenameWithoutWindowsExtension = basename.replace(WINDOWS_PROCESS_EXTENSION_RE, '') return ( - SHELL_NAMES.has(normalized) || SHELL_NAMES.has(normalized.split(/[\\/]/).pop() ?? normalized) + SHELL_NAMES.has(normalized) || + SHELL_NAMES.has(basename) || + SHELL_NAMES.has(basenameWithoutWindowsExtension) ) }