diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installer-utils.test.ts index 75aabc6fc7ea..9e41b374828f 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installer-utils.test.ts @@ -320,6 +320,53 @@ describe('removeManagedCommands', () => { expect(cleaned).toEqual([{ hooks: [{ type: 'command', command: 'echo keep me' }] }]) }) + + it('removes exec-form hooks whose managed script path is an argument', () => { + const cleaned = removeManagedCommands( + [ + { + hooks: [ + { + type: 'command', + command: 'C:\\Windows\\System32\\conhost.exe', + args: [ + '--headless', + 'C:\\Windows\\System32\\cmd.exe', + '/d', + '/c', + 'C:\\Users\\alice\\.orca\\agent-hooks\\copilot-hook.cmd' + ] + }, + { type: 'command', command: 'echo keep me' } + ] + } + ], + match + ) + + expect(cleaned).toEqual([{ hooks: [{ type: 'command', command: 'echo keep me' }] }]) + }) + + it('preserves user hooks with malformed args fields', () => { + const definitions = [ + { + hooks: [ + { + type: 'command' as const, + command: 'echo keep me', + args: 'not-an-array' as unknown as string[] + }, + { + type: 'command' as const, + command: 'echo keep me too', + args: [42] as unknown as string[] + } + ] + } + ] + + expect(removeManagedCommands(definitions, match)).toEqual(definitions) + }) }) describe('hookDefinitionHasManagedCommand', () => { @@ -338,6 +385,34 @@ describe('hookDefinitionHasManagedCommand', () => { match ) ).toBe(true) + expect( + hookDefinitionHasManagedCommand( + { + hooks: [ + { + type: 'command', + command: 'C:\\Windows\\System32\\conhost.exe', + args: ['--headless', 'C:\\Users\\alice\\.orca\\agent-hooks\\copilot-hook.cmd'] + } + ] + }, + match + ) + ).toBe(true) + expect( + hookDefinitionHasManagedCommand( + { + hooks: [ + { + type: 'command', + command: 'echo no', + args: 'not-an-array' as unknown as string[] + } + ] + }, + match + ) + ).toBe(false) expect(hookDefinitionHasManagedCommand({ bash: 'echo no' }, match)).toBe(false) }) }) diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts index a6d5d61fd416..0c06d78acbfc 100644 --- a/src/main/agent-hooks/installer-utils.ts +++ b/src/main/agent-hooks/installer-utils.ts @@ -20,6 +20,7 @@ import { writeRollingFileBackup } from '../rolling-file-backup' export type HookCommandConfig = { type: 'command' command: string + args?: string[] timeout?: number async?: boolean statusMessage?: string @@ -215,7 +216,8 @@ export function removeManagedCommands( const directManagedKeys = directCommandKeys.filter((key) => isManagedCommand(definition[key])) const hasNestedHooks = Array.isArray(definition.hooks) const hasManagedNestedHook = - hasNestedHooks && definition.hooks!.some((hook) => isManagedCommand(hook.command)) + hasNestedHooks && + definition.hooks!.some((hook) => hookHasManagedCommand(hook, isManagedCommand)) if (directManagedKeys.length === 0 && !hasManagedNestedHook) { return [definition] @@ -227,7 +229,9 @@ export function removeManagedCommands( } if (hasManagedNestedHook) { - const filteredHooks = definition.hooks!.filter((hook) => !isManagedCommand(hook.command)) + const filteredHooks = definition.hooks!.filter( + (hook) => !hookHasManagedCommand(hook, isManagedCommand) + ) if (filteredHooks.length > 0) { nextDefinition.hooks = filteredHooks } else { @@ -246,6 +250,11 @@ export function removeManagedCommands( }) } +function hookHasManagedCommand(hook: HookCommandConfig, matches: (value?: string) => boolean) { + const args = Array.isArray(hook.args) ? hook.args : [] + return matches(hook.command) || args.some((arg) => typeof arg === 'string' && matches(arg)) +} + export function hookDefinitionHasManagedCommand( definition: HookDefinition, isManagedCommand: (command: string | undefined) => boolean @@ -255,7 +264,7 @@ export function hookDefinitionHasManagedCommand( isManagedCommand(definition.bash) || isManagedCommand(definition.powershell) || (Array.isArray(definition.hooks) && - definition.hooks.some((hook) => isManagedCommand(hook.command))) + definition.hooks.some((hook) => hookHasManagedCommand(hook, isManagedCommand))) ) } diff --git a/src/main/claude/hook-service.test.ts b/src/main/claude/hook-service.test.ts index 0d390c3a9e3a..76bf9dce9acd 100644 --- a/src/main/claude/hook-service.test.ts +++ b/src/main/claude/hook-service.test.ts @@ -17,18 +17,35 @@ vi.mock('electron', () => ({ import type { SFTPWrapper } from 'ssh2' import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' import { ClaudeHookService } from './hook-service' -import { OPENCLAUDE_HOOK_SETTINGS } from './hook-settings' +import { getWindowsManagedLifecycleHook, OPENCLAUDE_HOOK_SETTINGS } from './hook-settings' const CLAUDE_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'claude-hook.cmd' : 'claude-hook.sh' const STATUSLINE_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'claude-statusline.cmd' : 'claude-statusline.sh' const OPENCLAUDE_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'openclaude-hook.cmd' : 'openclaude-hook.sh' -const WINDOWS_POWERSHELL_LAUNCHER = - /^[A-Za-z]:\/[^"]*\/System32\/WindowsPowerShell\/v1\.0\/powershell\.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand \S+$/ const isClaudeManagedCommand = createManagedCommandMatcher(CLAUDE_SCRIPT_FILE_NAME) const isOpenClaudeManagedCommand = createManagedCommandMatcher(OPENCLAUDE_SCRIPT_FILE_NAME) +type TestHook = { command: string; args?: string[] } + +function hasManagedCommand(hook: TestHook, matcher: (command: string | undefined) => boolean) { + return matcher(hook.command) || hook.args?.some(matcher) === true +} + +describe('getWindowsManagedLifecycleHook', () => { + it('keeps cmd metacharacters out of the headless client command line', () => { + const scriptPath = 'C:\\Users\\%name%\\a^b&c\\.orca\\agent-hooks\\claude-hook.cmd' + const hook = getWindowsManagedLifecycleHook(scriptPath) + const encodedCommand = hook.args?.at(-1) + + expect(hook.args?.[0]).toBe('--headless') + expect(hook.args?.[1]).toMatch(/\\WindowsPowerShell\\v1\.0\\powershell\.exe$/i) + expect(hook.args).not.toContain(scriptPath) + expect(Buffer.from(encodedCommand!, 'base64').toString('utf16le')).toContain(scriptPath) + }) +}) + type FakeFs = { files: Map dirs: Set @@ -162,18 +179,23 @@ describe('ClaudeHookService.install', () => { AWS_REGION: 'us-west-2' } }) - const legacyCommands = legacy.hooks.Stop.flatMap( - (definition: { hooks: { command: string }[] }) => - definition.hooks.map((hook) => hook.command) + const legacyHooks = legacy.hooks.Stop.flatMap( + (definition: { hooks: TestHook[] }) => definition.hooks + ) + expect(legacyHooks.map((hook: TestHook) => hook.command)).toContain( + '/usr/local/bin/user-hook' ) - expect(legacyCommands).toContain('/usr/local/bin/user-hook') - expect(legacyCommands.some((command: string) => isClaudeManagedCommand(command))).toBe(true) expect( - legacyCommands.some((command: string) => - command.includes('/Users/old/.orca/agent-hooks/claude-hook.sh') + legacyHooks.some((hook: TestHook) => hasManagedCommand(hook, isClaudeManagedCommand)) + ).toBe(true) + expect( + legacyHooks.some((hook: TestHook) => + hook.command.includes('/Users/old/.orca/agent-hooks/claude-hook.sh') ) ).toBe(false) - expect(isClaudeManagedCommand(legacy.hooks.StopFailure[0].hooks[0].command)).toBe(true) + expect(hasManagedCommand(legacy.hooks.StopFailure[0].hooks[0], isClaudeManagedCommand)).toBe( + true + ) expect( readFileSync(join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME), 'utf-8') ).toContain('DEVIN_PROJECT_DIR') @@ -307,12 +329,8 @@ describe('ClaudeHookService.install', () => { } }) - // Why: #6078 — Claude Code runs hooks through Git Bash, and an unquoted path - // with a space (e.g. `C:/Users/Jane Doe`) splits at the space. The managed - // command must use an encoded launcher so Git Bash/cmd.exe never splits or - // expands the raw path before invoking the managed .cmd. it.skipIf(process.platform !== 'win32')( - 'wraps the managed hook command to survive spaces in the profile path (#6078)', + 'runs managed hooks through headless exec form and preserves profile-path spaces', () => { const tmpHome = mkdtempSync(join(tmpdir(), 'orca claude home with spaces ')) vi.stubEnv('HOME', tmpHome) @@ -322,11 +340,19 @@ describe('ClaudeHookService.install', () => { const settings = JSON.parse( readFileSync(join(tmpHome, '.claude', 'settings.json'), 'utf-8') - ) as { hooks: Record } + ) as { hooks: Record } + + const system32 = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32') + const scriptPath = join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME) for (const eventName of ['UserPromptSubmit', 'Stop', 'StopFailure']) { - const command = settings.hooks[eventName]?.[0]?.hooks?.[0]?.command - expect(command).toMatch(WINDOWS_POWERSHELL_LAUNCHER) + const hook = settings.hooks[eventName]?.[0]?.hooks?.[0] + expect(hook).toEqual({ + type: 'command', + command: join(system32, 'conhost.exe'), + args: ['--headless', join(system32, 'cmd.exe'), '/d', '/c', scriptPath], + timeout: 10 + }) } } finally { vi.unstubAllEnvs() @@ -335,9 +361,6 @@ describe('ClaudeHookService.install', () => { } ) - // Why: the launcher must stay PowerShell-encoded for Git Bash, but the hook - // POST inside the .cmd should use curl.exe so each hook spawns one - // interpreter, not two. Posting via a second PowerShell was the slow path. it.skipIf(process.platform !== 'win32')( 'posts from the managed .cmd via curl.exe, not a second PowerShell', () => { diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts index ba2dfac13513..f87669ef180c 100644 --- a/src/main/claude/hook-service.ts +++ b/src/main/claude/hook-service.ts @@ -2,6 +2,7 @@ import { existsSync, rmSync, writeFileSync } from 'node:fs' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types' import { + buildManagedCommandHook, buildWindowsAgentHookCurlPostCommand, readHooksJson, writeHooksJson, @@ -28,6 +29,7 @@ import { getManagedScriptFileName, getConfigPath, getManagedCommand, + getManagedLifecycleHook, getManagedScriptPath, getPosixManagedScriptFileName, getRemoteConfigPath, @@ -36,6 +38,7 @@ import { getStatusLineScriptFileName, getStatusLineScriptPath, getStatusLineSlotState, + hasSameManagedHookInvocation, removeManagedHooks, removeManagedStatusLine, type ClaudeCompatibleHookSettings @@ -139,7 +142,7 @@ export class ClaudeHookService { } // Why: report partial registration instead of a false installed state. - const command = getManagedCommand(scriptPath) + const expectedHook = getManagedLifecycleHook(scriptPath, this.options.settings) const missing: string[] = [] let presentCount = 0 for (const event of CLAUDE_EVENTS) { @@ -147,7 +150,7 @@ export class ClaudeHookService { ? config.hooks![event.eventName]! : [] const hasCommand = definitions.some((definition) => - (definition.hooks ?? []).some((hook) => hook.command === command) + (definition.hooks ?? []).some((hook) => hasSameManagedHookInvocation(hook, expectedHook)) ) if (hasCommand) { presentCount += 1 @@ -185,10 +188,10 @@ export class ClaudeHookService { } } - const command = getManagedCommand(scriptPath) + const hook = getManagedLifecycleHook(scriptPath, this.options.settings) let nextConfig = applyManagedHooks( config, - command, + hook, getManagedScriptFileName(this.options.settings) ) writeManagedScript( @@ -247,8 +250,8 @@ export class ClaudeHookService { } // Why: the POSIX wrapper is identical regardless of where the script lands; only the path differs. - const command = getRemoteManagedCommand(remoteScriptPath) - const nextConfig = applyManagedHooks(config, command, remoteScriptFileName) + const hook = buildManagedCommandHook(getRemoteManagedCommand(remoteScriptPath)) + const nextConfig = applyManagedHooks(config, hook, remoteScriptFileName) // Why: write scripts before settings to avoid settings pointing to missing scripts. // Why: SSH scripts always use POSIX .sh paths, regardless of the local OS. diff --git a/src/main/claude/hook-settings.ts b/src/main/claude/hook-settings.ts index de9322765457..c9e69abc762f 100644 --- a/src/main/claude/hook-settings.ts +++ b/src/main/claude/hook-settings.ts @@ -1,13 +1,16 @@ import { homedir } from 'node:os' -import { join } from 'node:path' +import { join, win32 } from 'node:path' import { buildManagedCommandHook, createManagedCommandMatcher, getSharedManagedScriptPath, isPlainObject, + MANAGED_HOOK_TIMEOUT_SECONDS, removeManagedCommands, wrapPosixHookCommand, wrapWindowsGitBashHookCommand, + wrapWindowsHookCommand, + type HookCommandConfig, type HookDefinition, type HooksConfig } from '../agent-hooks/installer-utils' @@ -15,16 +18,19 @@ import { export type ClaudeCompatibleHookSettings = { configDirName: '.claude' | '.openclaude' scriptBaseName: 'claude-hook' | 'openclaude-hook' + supportsExecHookArgs: boolean } export const CLAUDE_HOOK_SETTINGS: ClaudeCompatibleHookSettings = { configDirName: '.claude', - scriptBaseName: 'claude-hook' + scriptBaseName: 'claude-hook', + supportsExecHookArgs: true } export const OPENCLAUDE_HOOK_SETTINGS: ClaudeCompatibleHookSettings = { configDirName: '.openclaude', - scriptBaseName: 'openclaude-hook' + scriptBaseName: 'openclaude-hook', + supportsExecHookArgs: false } export const CLAUDE_EVENTS = [ @@ -110,13 +116,61 @@ export function getManagedCommand(scriptPath: string): string { : wrapPosixHookCommand(scriptPath) } +export function getManagedLifecycleHook( + scriptPath: string, + settings = CLAUDE_HOOK_SETTINGS +): HookCommandConfig { + if (process.platform !== 'win32' || !settings.supportsExecHookArgs) { + return buildManagedCommandHook(getManagedCommand(scriptPath)) + } + return getWindowsManagedLifecycleHook(scriptPath) +} + +const WINDOWS_CMD_ARGUMENT_META = /[%!^&|<>()"\r\n]/ + +export function getWindowsManagedLifecycleHook(scriptPath: string): HookCommandConfig { + const system32 = win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32') + let clientArgs = [win32.join(system32, 'cmd.exe'), '/d', '/c', scriptPath] + if (WINDOWS_CMD_ARGUMENT_META.test(scriptPath)) { + const encodedCommand = wrapWindowsHookCommand(scriptPath).match(/ -EncodedCommand (\S+)$/)?.[1] + if (!encodedCommand) { + throw new Error('Failed to encode managed Claude hook path') + } + clientArgs = [ + win32.join(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe'), + '-NoProfile', + '-ExecutionPolicy', + 'Bypass', + '-EncodedCommand', + encodedCommand + ] + } + // Why: Claude's Windows shell form opens Git Bash consoles; exec form hosts the client in a windowless console. + return { + type: 'command', + command: win32.join(system32, 'conhost.exe'), + args: ['--headless', ...clientArgs], + timeout: MANAGED_HOOK_TIMEOUT_SECONDS + } +} + +export function hasSameManagedHookInvocation( + actual: HookCommandConfig, + expected: HookCommandConfig +): boolean { + return ( + actual.command === expected.command && + JSON.stringify(actual.args ?? []) === JSON.stringify(expected.args ?? []) + ) +} + export function getRemoteManagedCommand(scriptPath: string): string { return wrapPosixHookCommand(scriptPath) } export function applyManagedHooks( config: HooksConfig, - command: string, + hook: HookCommandConfig, scriptFileName = getManagedScriptFileName() ): HooksConfig { const nextHooks = { ...config.hooks } @@ -127,7 +181,7 @@ export function applyManagedHooks( const cleaned = removeManagedCommands(current, isManagedCommand) const definition: HookDefinition = { ...event.definition, - hooks: [buildManagedCommandHook(command)] + hooks: [hook] } nextHooks[event.eventName] = [...cleaned, definition] }