Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/main/agent-hooks/installer-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -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)
})
})
Expand Down
15 changes: 12 additions & 3 deletions src/main/agent-hooks/installer-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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)))
)
}

Expand Down
67 changes: 45 additions & 22 deletions src/main/claude/hook-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>
dirs: Set<string>
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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)
Expand All @@ -322,11 +340,19 @@ describe('ClaudeHookService.install', () => {

const settings = JSON.parse(
readFileSync(join(tmpHome, '.claude', 'settings.json'), 'utf-8')
) as { hooks: Record<string, { hooks: { command: string }[] }[]> }
) as { hooks: Record<string, { hooks: TestHook[] }[]> }

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()
Expand All @@ -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',
() => {
Expand Down
15 changes: 9 additions & 6 deletions src/main/claude/hook-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -28,6 +29,7 @@ import {
getManagedScriptFileName,
getConfigPath,
getManagedCommand,
getManagedLifecycleHook,
getManagedScriptPath,
getPosixManagedScriptFileName,
getRemoteConfigPath,
Expand All @@ -36,6 +38,7 @@ import {
getStatusLineScriptFileName,
getStatusLineScriptPath,
getStatusLineSlotState,
hasSameManagedHookInvocation,
removeManagedHooks,
removeManagedStatusLine,
type ClaudeCompatibleHookSettings
Expand Down Expand Up @@ -139,15 +142,15 @@ 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) {
const definitions = Array.isArray(config.hooks?.[event.eventName])
? 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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand Down
Loading