diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index b01c26997e17..9d1f25d1fafc 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -22,8 +22,7 @@ const { verifySkillsCliRuntime } = require('./scripts/verify-skills-cli-runtime. const isMacHourly = process.env.ORCA_MAC_HOURLY === '1' const isMacDaily = process.env.ORCA_MAC_DAILY === '1' const isMacAdhoc = process.env.ORCA_MAC_ADHOC === '1' -const isMacRelease = - process.env.ORCA_MAC_RELEASE === '1' || isMacHourly || isMacDaily || isMacAdhoc +const isMacRelease = process.env.ORCA_MAC_RELEASE === '1' || isMacHourly || isMacDaily || isMacAdhoc const isLinuxArm64Release = process.env.ORCA_LINUX_ARM64_RELEASE === '1' const localBuildVersion = isMacRelease ? undefined : process.env.ORCA_LOCAL_BUILD_VERSION const devChannelBuildVersion = isMacHourly @@ -309,6 +308,10 @@ module.exports = { from: 'native/windows-cli-launcher/.build/orca.exe', to: 'bin/orca.exe' }, + { + from: 'native/windows-agent-hook-launcher/.build/orca-agent-hook.exe', + to: 'bin/orca-agent-hook.exe' + }, { from: 'node_modules/agent-browser/bin/agent-browser-win32-x64.exe', to: 'agent-browser-win32-x64.exe' diff --git a/config/scripts/build-windows-cli-launcher.mjs b/config/scripts/build-windows-cli-launcher.mjs index 27c17b3d15c8..1991556b64de 100644 --- a/config/scripts/build-windows-cli-launcher.mjs +++ b/config/scripts/build-windows-cli-launcher.mjs @@ -15,27 +15,50 @@ if (process.platform !== 'win32') { const repoRoot = resolve(import.meta.dirname, '../..') const sourcePath = join(repoRoot, 'native', 'windows-cli-launcher', 'OrcaCliLauncher.cs') const outputPath = readArg('--output') ?? defaultOutputPath(repoRoot) +const hookSourcePath = join( + repoRoot, + 'native', + 'windows-agent-hook-launcher', + 'OrcaAgentHookLauncher.cs' +) +const hookOutputPath = + readArg('--hook-output') ?? + join(repoRoot, 'native', 'windows-agent-hook-launcher', '.build', 'orca-agent-hook.exe') const compilerPath = findFrameworkCompiler(process.env) if (!compilerPath) { - throw new Error('Unable to find the .NET Framework C# compiler required for orca.exe.') + throw new Error( + 'Unable to find the .NET Framework C# compiler required for orca.exe and orca-agent-hook.exe.' + ) } -mkdirSync(dirname(outputPath), { recursive: true }) -const result = spawnSync( - compilerPath, - ['/nologo', '/target:exe', '/optimize+', '/warnaserror+', `/out:${outputPath}`, sourcePath], - { cwd: repoRoot, stdio: 'inherit' } -) +compile(sourcePath, outputPath, 'exe') +compile(hookSourcePath, hookOutputPath, 'winexe') -if (result.signal) { - process.kill(process.pid, result.signal) -} -if (result.error) { - throw result.error -} -if (result.status !== 0) { - process.exit(result.status ?? 1) +function compile(inputPath, destinationPath, target) { + mkdirSync(dirname(destinationPath), { recursive: true }) + const result = spawnSync( + compilerPath, + [ + '/nologo', + `/target:${target}`, + '/optimize+', + '/warnaserror+', + `/out:${destinationPath}`, + inputPath + ], + { cwd: repoRoot, stdio: 'inherit' } + ) + + if (result.signal) { + process.kill(process.pid, result.signal) + } + if (result.error) { + throw result.error + } + if (result.status !== 0) { + process.exit(result.status ?? 1) + } } function defaultOutputPath(projectRoot) { diff --git a/native/windows-agent-hook-launcher/OrcaAgentHookLauncher.cs b/native/windows-agent-hook-launcher/OrcaAgentHookLauncher.cs new file mode 100644 index 000000000000..39a08681438e --- /dev/null +++ b/native/windows-agent-hook-launcher/OrcaAgentHookLauncher.cs @@ -0,0 +1,144 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +internal static class OrcaAgentHookLauncher +{ + private const int StandardInputTimeoutMilliseconds = 1000; + private const int ChildExitTimeoutMilliseconds = 2500; + + private static int Main(string[] args) + { + bool emitNeutralJson = args.Length == 2 && args[0] == "--neutral-json"; + string scriptPath = args.Length == (emitNeutralJson ? 2 : 1) ? args[args.Length - 1] : null; + if (scriptPath == null || !File.Exists(scriptPath)) + { + DrainStandardInputWithTimeout(); + WriteNeutralJson(emitNeutralJson); + return 0; + } + + try + { + string systemDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System); + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = Path.Combine(systemDirectory, "cmd.exe"), + Arguments = "/d /s /c \"\"%ORCA_AGENT_HOOK_SCRIPT%\"\"", + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + startInfo.EnvironmentVariables["ORCA_AGENT_HOOK_SCRIPT"] = scriptPath; + + using (Process child = Process.Start(startInfo)) + { + Task inputTask = CopyStandardInputAsync(child.StandardInput.BaseStream); + Task outputTask = child.StandardOutput.ReadToEndAsync(); + Task errorTask = child.StandardError.ReadToEndAsync(); + inputTask.Wait(StandardInputTimeoutMilliseconds); + TryClose(child.StandardInput); + + bool childTimedOut = !child.WaitForExit(ChildExitTimeoutMilliseconds); + if (childTimedOut) + { + KillProcessTree(child, systemDirectory); + } + Task.WaitAll(new Task[] { outputTask, errorTask }, ChildExitTimeoutMilliseconds); + WriteNeutralJson(emitNeutralJson); + return childTimedOut ? 0 : child.ExitCode; + } + } + catch + { + DrainStandardInputWithTimeout(); + WriteNeutralJson(emitNeutralJson); + return 0; + } + } + + private static void KillProcessTree(Process child, string systemDirectory) + { + try + { + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = Path.Combine(systemDirectory, "taskkill.exe"), + Arguments = "/PID " + child.Id + " /T /F", + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + using (Process treeKiller = Process.Start(startInfo)) + { + treeKiller.BeginOutputReadLine(); + treeKiller.BeginErrorReadLine(); + if (!treeKiller.WaitForExit(ChildExitTimeoutMilliseconds)) + { + treeKiller.Kill(); + } + } + } + catch { } + + if (!child.HasExited) + { + try + { + child.Kill(); + } + catch { } + } + child.WaitForExit(ChildExitTimeoutMilliseconds); + } + + private static Task CopyStandardInputAsync(Stream destination) + { + return Task.Run(() => + { + try + { + Console.OpenStandardInput().CopyTo(destination); + destination.Flush(); + } + catch + { + // The caller may leave stdin open after the payload is complete. + } + }); + } + + private static void DrainStandardInputWithTimeout() + { + CopyStandardInputAsync(Stream.Null).Wait(StandardInputTimeoutMilliseconds); + } + + private static void TryClose(TextWriter writer) + { + try + { + writer.Close(); + } + catch { } + } + + private static void WriteNeutralJson(bool enabled) + { + if (!enabled) return; + try + { + byte[] output = Encoding.UTF8.GetBytes("{}\n"); + Stream stdout = Console.OpenStandardOutput(); + stdout.Write(output, 0, output.Length); + stdout.Flush(); + } + catch { } + } +} diff --git a/src/main/agent-hooks/managed-hook-config-refresh.ts b/src/main/agent-hooks/managed-hook-config-refresh.ts new file mode 100644 index 000000000000..470352d5a5c3 --- /dev/null +++ b/src/main/agent-hooks/managed-hook-config-refresh.ts @@ -0,0 +1,224 @@ +import { randomUUID } from 'node:crypto' +import { copyFile, lstat, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { + createManagedCommandMatcher, + isPlainObject, + type HookDefinition, + type HooksConfig +} from './installer-utils' +import { parseHooksJsonText } from './hooks-json-read' + +export type ManagedHookCommandMigration = { + scriptFileName: string + resolveCommand: () => Promise +} + +type RefreshManagedHookCommandsOptions = { + configPath: string + scriptFileName: string + resolveCommand: () => Promise + additionalMigrations?: ManagedHookCommandMigration[] +} + +function isMissingPathError(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT' +} + +async function readExistingConfig( + configPath: string +): Promise<{ config: HooksConfig; raw: string } | null> { + try { + const raw = await readFile(configPath, 'utf-8') + const config = parseHooksJsonText(raw) + return config ? { config, raw } : null + } catch (error) { + if (isMissingPathError(error)) { + return null + } + throw error + } +} + +function replaceManagedCommand( + definition: HookDefinition, + matches: (command: string | undefined) => boolean, + command: string +): HookDefinition { + const next = { ...definition } + const directKeys = ['command', 'bash', 'powershell'] as const + if (directKeys.some((key) => matches(next[key]))) { + next.command = command + delete next.bash + delete next.powershell + } + if (Array.isArray(next.hooks)) { + next.hooks = next.hooks.map((hook) => { + const args = Array.isArray(hook.args) ? hook.args : [] + if (!matches(hook.command) && !args.some((arg) => typeof arg === 'string' && matches(arg))) { + return hook + } + const migrated = { ...hook, command } + delete migrated.args + return migrated + }) + } + return next +} + +function migrateManagedCommands( + config: HooksConfig, + scriptFileName: string, + command: string +): HooksConfig { + const matches = createManagedCommandMatcher(scriptFileName) + const hooks = Object.fromEntries( + Object.entries(config.hooks ?? {}).map(([eventName, definitions]) => [ + eventName, + Array.isArray(definitions) + ? definitions.map((definition) => replaceManagedCommand(definition, matches, command)) + : definitions + ]) + ) + const statusLine = config.statusLine + if ( + !isPlainObject(statusLine) || + typeof statusLine.command !== 'string' || + !matches(statusLine.command) + ) { + return { ...config, hooks } + } + return { ...config, hooks, statusLine: { ...statusLine, command } } +} + +function configHasManagedCommand( + config: HooksConfig, + matches: (command: string | undefined) => boolean +): boolean { + const statusLine = config.statusLine + if ( + isPlainObject(statusLine) && + typeof statusLine.command === 'string' && + matches(statusLine.command) + ) { + return true + } + return Object.values(config.hooks ?? {}).some( + (definitions) => + Array.isArray(definitions) && + definitions.some((definition) => { + const direct = + matches(definition.command) || matches(definition.bash) || matches(definition.powershell) + return ( + direct || + (Array.isArray(definition.hooks) && + definition.hooks.some( + (hook) => + matches(hook.command) || + (Array.isArray(hook.args) && + hook.args.some((arg) => typeof arg === 'string' && matches(arg))) + )) + ) + }) + ) +} + +async function resolveWritePath(configPath: string): Promise { + try { + return (await lstat(configPath)).isSymbolicLink() ? await realpath(configPath) : configPath + } catch (error) { + if (isMissingPathError(error)) { + return configPath + } + throw error + } +} + +async function writeBackup(sourcePath: string): Promise { + const backupPath = `${sourcePath}.bak` + try { + if ((await lstat(backupPath)).isSymbolicLink()) { + throw new Error(`Refusing to overwrite symlinked backup: ${backupPath}`) + } + } catch (error) { + if (!isMissingPathError(error)) { + throw error + } + } + const temporaryPath = `${backupPath}.${process.pid}.${randomUUID()}.tmp` + try { + await copyFile(sourcePath, temporaryPath) + await rename(temporaryPath, backupPath) + } finally { + await rm(temporaryPath, { force: true }).catch(() => undefined) + } +} + +async function writeConfigIfUnchanged( + configPath: string, + expectedRaw: string, + config: HooksConfig +): Promise { + const writePath = await resolveWritePath(configPath) + let currentRaw: string + try { + currentRaw = await readFile(writePath, 'utf-8') + } catch (error) { + if (isMissingPathError(error)) { + return false + } + throw error + } + if (currentRaw !== expectedRaw) { + return false + } + const serialized = `${JSON.stringify(config, null, 2)}\n` + if (serialized === currentRaw) { + return true + } + const temporaryPath = join(dirname(writePath), `.${Date.now()}-${randomUUID()}.tmp`) + try { + const mode = (await stat(writePath)).mode + await writeFile(temporaryPath, serialized, { encoding: 'utf-8', mode }) + if ((await readFile(writePath, 'utf-8')) !== expectedRaw) { + return false + } + await writeBackup(writePath) + await rename(temporaryPath, writePath) + return true + } finally { + await rm(temporaryPath, { force: true }).catch(() => undefined) + } +} + +// Why: stale user-wide configs need launcher migration even when the agent CLI is absent. +export async function refreshManagedHookCommandsIfPresent( + options: RefreshManagedHookCommandsOptions +): Promise { + const snapshot = await readExistingConfig(options.configPath) + if (!snapshot) { + return false + } + const migrations = [ + { scriptFileName: options.scriptFileName, resolveCommand: options.resolveCommand }, + ...(options.additionalMigrations ?? []) + ] + const applicable = migrations.filter((migration) => + configHasManagedCommand(snapshot.config, createManagedCommandMatcher(migration.scriptFileName)) + ) + if (applicable.length === 0) { + return false + } + const resolved = await Promise.all( + applicable.map(async (migration) => ({ + scriptFileName: migration.scriptFileName, + command: await migration.resolveCommand() + })) + ) + const migrated = resolved.reduce( + (config, migration) => + migrateManagedCommands(config, migration.scriptFileName, migration.command), + snapshot.config + ) + return writeConfigIfUnchanged(options.configPath, snapshot.raw, migrated) +} diff --git a/src/main/agent-hooks/managed-hook-script-refresh.test.ts b/src/main/agent-hooks/managed-hook-script-refresh.test.ts index 799f8acf58ce..5b264f5461c9 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh.test.ts +++ b/src/main/agent-hooks/managed-hook-script-refresh.test.ts @@ -54,7 +54,25 @@ vi.mock('os', async (importOriginal) => { } }) +vi.mock('./windows-agent-hook-launcher', async () => { + const { join } = await import('node:path') + const launcherPath = () => join(homedirMock(), '.orca', 'agent-hooks', 'orca-agent-hook.exe') + return { + installWindowsAgentHookLauncher: launcherPath, + installWindowsAgentHookLauncherAsync: async () => launcherPath(), + getWindowsAgentHookCommand: (scriptPath: string) => `"${launcherPath()}" "${scriptPath}"`, + getWindowsAgentHookCommandAsync: async (scriptPath: string) => + `"${launcherPath()}" "${scriptPath}"`, + getWindowsAgentHookJsonCommand: (scriptPath: string) => + `"${launcherPath()}" --neutral-json "${scriptPath}"`, + getWindowsAgentHookJsonCommandAsync: async (scriptPath: string) => + `"${launcherPath()}" --neutral-json "${scriptPath}"` + } +}) + import { refreshManagedScriptIfPresent } from './managed-hook-script-refresh' +import { refreshManagedHookCommandsIfPresent } from './managed-hook-config-refresh' +import { wrapRuntimeHomeHookCommand } from './runtime-home-hook-command' import { MANAGED_AGENT_HOOK_INSTALLERS, MANAGED_AGENT_HOOK_SCRIPT_REFRESHERS @@ -138,6 +156,87 @@ describe('managed hook script refresh', () => { } }) + it('migrates existing Windows hooks and statusline when CLI presence is unavailable', async () => { + const home = mkdtempSync(join(tmpdir(), 'orca-hook-refresh-config-')) + homedirMock.mockReturnValue(home) + try { + const hooksDir = join(home, '.orca', 'agent-hooks') + const configDir = join(home, '.claude') + mkdirSync(hooksDir, { recursive: true }) + mkdirSync(configDir, { recursive: true }) + const scriptPath = join(hooksDir, 'claude-hook.cmd') + const statusLineScriptPath = join(hooksDir, 'claude-statusline.cmd') + writeFileSync(scriptPath, STALE_WINDOWS_HOOK) + writeFileSync(statusLineScriptPath, 'stale statusline') + writeFileSync( + join(configDir, 'settings.json'), + `${JSON.stringify({ + hooks: { + UserPromptSubmit: [ + { + hooks: [ + { + type: 'command', + command: 'C:\\Windows\\System32\\conhost.exe', + args: ['--headless', 'C:\\Windows\\System32\\cmd.exe', '/d', '/c', scriptPath] + } + ] + } + ] + }, + statusLine: { + type: 'command', + command: wrapRuntimeHomeHookCommand('claude-statusline') + } + })}\n` + ) + + await withPlatform('win32', () => new ClaudeHookService().refreshManagedScripts()) + + const config = JSON.parse(readFileSync(join(configDir, 'settings.json'), 'utf8')) + const hook = config.hooks.UserPromptSubmit[0].hooks[0] + expect(hook.command).toBe( + `"${join(hooksDir, 'orca-agent-hook.exe')}" --neutral-json "${scriptPath}"` + ) + expect(hook.args).toBeUndefined() + expect(config.statusLine.command).toBe( + `"${join(hooksDir, 'orca-agent-hook.exe')}" "${statusLineScriptPath}"` + ) + } finally { + homedirMock.mockImplementation(() => process.env.HOME ?? tmpdir()) + rmSync(home, { recursive: true, force: true }) + } + }) + + it('treats a concurrently deleted config as an aborted refresh', async () => { + const home = mkdtempSync(join(tmpdir(), 'orca-hook-refresh-deleted-config-')) + const configPath = join(home, 'settings.json') + const scriptPath = join(home, '.orca', 'agent-hooks', 'claude-hook.cmd') + writeFileSync( + configPath, + `${JSON.stringify({ + hooks: { + Stop: [{ hooks: [{ type: 'command', command: scriptPath }] }] + } + })}\n` + ) + try { + await expect( + refreshManagedHookCommandsIfPresent({ + configPath, + scriptFileName: 'claude-hook.cmd', + resolveCommand: async () => { + rmSync(configPath) + return 'replacement' + } + }) + ).resolves.toBe(false) + expect(existsSync(configPath)).toBe(false) + } finally { + rmSync(home, { recursive: true, force: true }) + } + }) + it('covers every shared launcher script with a refresher', async () => { const home = mkdtempSync(join(tmpdir(), 'orca-hook-refresh-coverage-')) homedirMock.mockReturnValue(home) diff --git a/src/main/agent-hooks/windows-agent-hook-launcher.test.ts b/src/main/agent-hooks/windows-agent-hook-launcher.test.ts new file mode 100644 index 000000000000..f11003ac9541 --- /dev/null +++ b/src/main/agent-hooks/windows-agent-hook-launcher.test.ts @@ -0,0 +1,85 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, dirname, join } from 'node:path' +import type * as osModule from 'node:os' + +const { homedirMock } = vi.hoisted(() => ({ + homedirMock: vi.fn<() => string>() +})) + +vi.mock('node:os', async () => { + const actual = await vi.importActual('node:os') + return { ...actual, homedir: homedirMock } +}) + +import { + getWindowsAgentHookCommand, + getWindowsAgentHookJsonCommand, + installWindowsAgentHookLauncher, + installWindowsAgentHookLauncherAsync +} from './windows-agent-hook-launcher' + +describe('Windows agent hook launcher', () => { + let homeDir: string + + beforeEach(() => { + homeDir = mkdtempSync(join(tmpdir(), 'orca-hook-launcher-home-')) + homedirMock.mockReturnValue(homeDir) + }) + + afterEach(() => { + vi.clearAllMocks() + rmSync(homeDir, { recursive: true, force: true }) + }) + + it('installs the bundled launcher under the shared hook directory', () => { + const sourcePath = join(homeDir, 'source.exe') + writeFileSync(sourcePath, Buffer.from([0x4d, 0x5a, 0x01, 0x02])) + + const installedPath = installWindowsAgentHookLauncher(sourcePath) + + expect(dirname(installedPath)).toBe(join(homeDir, '.orca', 'agent-hooks')) + expect(basename(installedPath)).toMatch(/^orca-agent-hook-[a-f0-9]{16}\.exe$/) + expect(readFileSync(installedPath)).toEqual(readFileSync(sourcePath)) + }) + + it('reuses the content-addressed launcher across repeated installs', async () => { + const sourcePath = join(homeDir, 'source.exe') + writeFileSync(sourcePath, Buffer.from([0x4d, 0x5a, 0x03, 0x04])) + + const firstPath = installWindowsAgentHookLauncher(sourcePath) + const secondPath = installWindowsAgentHookLauncher(sourcePath) + const asyncPath = await installWindowsAgentHookLauncherAsync(sourcePath) + + expect(secondPath).toBe(firstPath) + expect(asyncPath).toBe(firstPath) + expect(readdirSync(dirname(firstPath))).toEqual([basename(firstPath)]) + }) + + it('quotes launcher and script paths without adding a shell layer', () => { + const command = getWindowsAgentHookCommand( + 'C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\cursor-hook.cmd', + 'C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\orca-agent-hook.exe' + ) + + expect(command).toBe( + '"C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\orca-agent-hook.exe" ' + + '"C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\cursor-hook.cmd"' + ) + expect(command).not.toContain('powershell') + expect(command).not.toContain('conhost') + }) + + it('requests neutral JSON for Claude-compatible lifecycle hooks', () => { + const command = getWindowsAgentHookJsonCommand( + 'C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\claude-hook.cmd', + 'C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\orca-agent-hook.exe' + ) + + expect(command).toBe( + '"C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\orca-agent-hook.exe" --neutral-json ' + + '"C:\\Users\\Jorge Silva\\.orca\\agent-hooks\\claude-hook.cmd"' + ) + }) +}) diff --git a/src/main/agent-hooks/windows-agent-hook-launcher.ts b/src/main/agent-hooks/windows-agent-hook-launcher.ts new file mode 100644 index 000000000000..649aabefff25 --- /dev/null +++ b/src/main/agent-hooks/windows-agent-hook-launcher.ts @@ -0,0 +1,149 @@ +import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs' +import { access, copyFile, mkdir, readFile, rename, rm } from 'node:fs/promises' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' +import { createHash, randomUUID } from 'node:crypto' + +const LAUNCHER_FILE_NAME = 'orca-agent-hook.exe' + +function getVersionedLauncherFileName(source: Buffer): string { + const digest = createHash('sha256').update(source).digest('hex').slice(0, 16) + return `orca-agent-hook-${digest}.exe` +} + +function getBundledLauncherCandidatePaths(): string[] { + return [ + ...(process.resourcesPath ? [join(process.resourcesPath, 'bin', LAUNCHER_FILE_NAME)] : []), + ...(process.env.ORCA_DEV_REPO_ROOT + ? [ + join( + process.env.ORCA_DEV_REPO_ROOT, + 'native', + 'windows-agent-hook-launcher', + '.build', + LAUNCHER_FILE_NAME + ) + ] + : []), + join(process.cwd(), 'native', 'windows-agent-hook-launcher', '.build', LAUNCHER_FILE_NAME) + ] +} + +function resolveBundledLauncherPath(): string { + const candidates = getBundledLauncherCandidatePaths() + const sourcePath = candidates.find((candidate) => existsSync(candidate)) + if (!sourcePath) { + throw new Error('Missing bundled Windows agent hook launcher.') + } + return sourcePath +} + +async function resolveBundledLauncherPathAsync(): Promise { + const candidates = getBundledLauncherCandidatePaths() + for (const candidate of candidates) { + try { + await access(candidate) + return candidate + } catch { + // Try the next packaged or development location. + } + } + throw new Error('Missing bundled Windows agent hook launcher.') +} + +export function installWindowsAgentHookLauncher(sourcePath = resolveBundledLauncherPath()): string { + const source = readFileSync(sourcePath) + const destinationPath = join( + homedir(), + '.orca', + 'agent-hooks', + getVersionedLauncherFileName(source) + ) + mkdirSync(dirname(destinationPath), { recursive: true }) + if (existsSync(destinationPath) && readFileSync(destinationPath).equals(source)) { + return destinationPath + } + + const temporaryPath = join(dirname(destinationPath), `.${LAUNCHER_FILE_NAME}-${randomUUID()}.tmp`) + try { + copyFileSync(sourcePath, temporaryPath) + try { + renameSync(temporaryPath, destinationPath) + } catch (error) { + // Why: concurrent installers can race to publish the same content-addressed launcher. + if (!existsSync(destinationPath) || !readFileSync(destinationPath).equals(source)) { + throw error + } + } + } finally { + if (existsSync(temporaryPath)) { + unlinkSync(temporaryPath) + } + } + return destinationPath +} + +export async function installWindowsAgentHookLauncherAsync(sourcePath?: string): Promise { + const resolvedSourcePath = sourcePath ?? (await resolveBundledLauncherPathAsync()) + const source = await readFile(resolvedSourcePath) + const destinationPath = join( + homedir(), + '.orca', + 'agent-hooks', + getVersionedLauncherFileName(source) + ) + await mkdir(dirname(destinationPath), { recursive: true }) + try { + if ((await readFile(destinationPath)).equals(source)) { + return destinationPath + } + } catch { + // Publish the bundled launcher below. + } + + const temporaryPath = join(dirname(destinationPath), `.${LAUNCHER_FILE_NAME}-${randomUUID()}.tmp`) + try { + await copyFile(resolvedSourcePath, temporaryPath) + try { + await rename(temporaryPath, destinationPath) + } catch (error) { + try { + if ((await readFile(destinationPath)).equals(source)) { + return destinationPath + } + } catch { + // Re-throw the publication error below. + } + throw error + } + } finally { + await rm(temporaryPath, { force: true }).catch(() => undefined) + } + return destinationPath +} + +function quoteWindowsCommandArgument(value: string): string { + return `"${value.replaceAll('"', '\\"')}"` +} + +export function getWindowsAgentHookCommand( + scriptPath: string, + launcherPath = installWindowsAgentHookLauncher() +): string { + return `${quoteWindowsCommandArgument(launcherPath)} ${quoteWindowsCommandArgument(scriptPath)}` +} + +export function getWindowsAgentHookJsonCommand( + scriptPath: string, + launcherPath = installWindowsAgentHookLauncher() +): string { + return `${quoteWindowsCommandArgument(launcherPath)} --neutral-json ${quoteWindowsCommandArgument(scriptPath)}` +} + +export async function getWindowsAgentHookCommandAsync(scriptPath: string): Promise { + return getWindowsAgentHookCommand(scriptPath, await installWindowsAgentHookLauncherAsync()) +} + +export async function getWindowsAgentHookJsonCommandAsync(scriptPath: string): Promise { + return getWindowsAgentHookJsonCommand(scriptPath, await installWindowsAgentHookLauncherAsync()) +} diff --git a/src/main/claude/claude-managed-script-refresh.ts b/src/main/claude/claude-managed-script-refresh.ts new file mode 100644 index 000000000000..58f12605c215 --- /dev/null +++ b/src/main/claude/claude-managed-script-refresh.ts @@ -0,0 +1,40 @@ +import { refreshManagedHookCommandsIfPresent } from '../agent-hooks/managed-hook-config-refresh' +import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { + getConfigPath, + getManagedScriptPath, + getStatusLineScriptPath, + getWindowsManagedCommandMigrations, + type ClaudeCompatibleHookSettings +} from './hook-settings' +import { getManagedStatusLineScript } from './statusline-script' + +export async function refreshClaudeManagedScripts( + settings: ClaudeCompatibleHookSettings, + lifecycleScript: string +): Promise { + const lifecycleScriptPresent = await refreshManagedScriptIfPresent( + getManagedScriptPath(settings), + lifecycleScript + ) + const statusLineScriptPresent = await refreshManagedScriptIfPresent( + getStatusLineScriptPath(settings), + getManagedStatusLineScript('local') + ) + if (process.platform !== 'win32') { + return + } + const [migration, ...additionalMigrations] = getWindowsManagedCommandMigrations( + settings, + lifecycleScriptPresent, + statusLineScriptPresent + ) + if (!migration) { + return + } + await refreshManagedHookCommandsIfPresent({ + configPath: getConfigPath(settings), + ...migration, + additionalMigrations + }) +} diff --git a/src/main/claude/hook-service.test.ts b/src/main/claude/hook-service.test.ts index b3fa02debc56..2829a63d8c04 100644 --- a/src/main/claude/hook-service.test.ts +++ b/src/main/claude/hook-service.test.ts @@ -14,6 +14,23 @@ vi.mock('electron', () => ({ } })) +vi.mock('../agent-hooks/windows-agent-hook-launcher', async () => { + const { homedir } = await import('node:os') + const { join } = await import('node:path') + const launcherPath = () => join(homedir(), '.orca', 'agent-hooks', 'orca-agent-hook.exe') + return { + installWindowsAgentHookLauncher: launcherPath, + installWindowsAgentHookLauncherAsync: async () => launcherPath(), + getWindowsAgentHookCommand: (scriptPath: string) => `"${launcherPath()}" "${scriptPath}"`, + getWindowsAgentHookCommandAsync: async (scriptPath: string) => + `"${launcherPath()}" "${scriptPath}"`, + getWindowsAgentHookJsonCommand: (scriptPath: string) => + `"${launcherPath()}" --neutral-json "${scriptPath}"`, + getWindowsAgentHookJsonCommandAsync: async (scriptPath: string) => + `"${launcherPath()}" --neutral-json "${scriptPath}"` + } +}) + import type { SFTPWrapper } from 'ssh2' import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' import { ClaudeHookService } from './hook-service' @@ -38,10 +55,9 @@ describe('getWindowsManagedLifecycleHook', () => { const scriptPath = 'C:\\Users\\%name%\\a^b&c\\.orca\\agent-hooks\\claude-hook.cmd' const hook = getWindowsManagedLifecycleHook(scriptPath) - expect(hook.args?.[0]).toBe('--headless') - expect(hook.args?.[1]).toMatch(/\\System32\\cmd\.exe$/i) - expect(hook.args?.at(-1)).toBe('%USERPROFILE%\\.orca\\agent-hooks\\claude-hook.cmd') - expect(hook.args).not.toContain(scriptPath) + expect(hook.command).toContain('orca-agent-hook.exe" --neutral-json') + expect(hook.command).toContain(`"${scriptPath}"`) + expect(hook.args).toBeUndefined() }) }) @@ -219,11 +235,8 @@ describe('ClaudeHookService.install', () => { readFileSync(join(tmpHome, '.claude', 'settings.json'), 'utf-8') ) as { statusLine?: { type: string; command: string } } expect(settings.statusLine?.type).toBe('command') - expect(settings.statusLine?.command).toContain( - '"$HOME/.orca/agent-hooks/claude-statusline.cmd"' - ) - expect(settings.statusLine?.command).toContain( - '"$HOME/.orca/agent-hooks/claude-statusline.sh"' + expect(settings.statusLine?.command).toMatch( + /^"[^"]*\\orca-agent-hook\.exe" "[^"]*\\claude-statusline\.cmd"$/i ) expect(settings.statusLine?.command).not.toContain(tmpHome.replaceAll('\\', '/')) @@ -339,7 +352,7 @@ describe('ClaudeHookService.install', () => { }) it.skipIf(process.platform !== 'win32')( - 'runs portable managed hooks through headless exec form', + 'runs managed hooks through the native headless launcher', () => { const tmpHome = mkdtempSync(join(tmpdir(), 'orca claude home with spaces ')) vi.stubEnv('HOME', tmpHome) @@ -351,24 +364,16 @@ describe('ClaudeHookService.install', () => { readFileSync(join(tmpHome, '.claude', 'settings.json'), 'utf-8') ) as { hooks: Record } - const system32 = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32') const scriptPath = join(tmpHome, '.orca', 'agent-hooks', CLAUDE_SCRIPT_FILE_NAME) - const runtimeScriptPath = join( - '%USERPROFILE%', - '.orca', - 'agent-hooks', - CLAUDE_SCRIPT_FILE_NAME - ) + const launcherPath = join(tmpHome, '.orca', 'agent-hooks', 'orca-agent-hook.exe') for (const eventName of ['UserPromptSubmit', 'Stop', 'StopFailure']) { 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', runtimeScriptPath], + command: `"${launcherPath}" --neutral-json "${scriptPath}"`, timeout: 10 }) - expect(hook.args).not.toContain(scriptPath) } } finally { vi.unstubAllEnvs() @@ -522,9 +527,9 @@ describe('OpenClaudeHookService-compatible install', () => { for (const event of ['UserPromptSubmit', 'Stop', 'StopFailure']) { const command = parsed.hooks[event][0].hooks[0].command as string expect(isOpenClaudeManagedCommand(command)).toBe(true) - expect(command).toContain('"$HOME/.orca/agent-hooks/openclaude-hook.cmd"') - expect(command).toContain('"$HOME/.orca/agent-hooks/openclaude-hook.sh"') - expect(command).not.toContain(tmpHome.replaceAll('\\', '/')) + expect(command).toMatch( + /^"[^"]*\\orca-agent-hook\.exe" --neutral-json "[^"]*\\openclaude-hook\.cmd"$/i + ) } expect( readFileSync(join(tmpHome, '.orca', 'agent-hooks', OPENCLAUDE_SCRIPT_FILE_NAME), 'utf-8') diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts index 47269b1e17d5..22490d83ebaa 100644 --- a/src/main/claude/hook-service.ts +++ b/src/main/claude/hook-service.ts @@ -14,7 +14,6 @@ import { writeHooksJsonRemote, writeManagedScriptRemote } from '../agent-hooks/installer-utils-remote' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' import { buildPosixHookPayloadCapture, buildWindowsHookEnvironmentGuardLines, @@ -22,6 +21,7 @@ import { WINDOWS_HOOK_STDIN_DRAIN_LABEL } from '../agent-hooks/hook-stdin-contract' import { getManagedStatusLineScript } from './statusline-script' +import { refreshClaudeManagedScripts } from './claude-managed-script-refresh' import { applyManagedHooks, applyManagedStatusLine, @@ -29,7 +29,7 @@ import { CLAUDE_HOOK_SETTINGS, getManagedScriptFileName, getConfigPath, - getManagedCommand, + getLocalManagedCommand, getManagedLifecycleHook, getManagedScriptPath, getPosixManagedScriptFileName, @@ -143,7 +143,7 @@ export class ClaudeHookService { } // Why: report partial registration instead of a false installed state. - const expectedHook = getManagedLifecycleHook(scriptPath, this.options.settings) + const expectedHook = getManagedLifecycleHook(scriptPath) const missing: string[] = [] let presentCount = 0 for (const event of CLAUDE_EVENTS) { @@ -176,15 +176,10 @@ export class ClaudeHookService { } async refreshManagedScripts(): Promise { - await refreshManagedScriptIfPresent( - getManagedScriptPath(this.options.settings), + await refreshClaudeManagedScripts( + this.options.settings, getManagedScript('local', { skipWhenDevinImportsClaude: this.options.agent === 'claude' }) ) - // Why: no agent gate — the statusline script only ever exists for claude, so presence is the gate. - await refreshManagedScriptIfPresent( - getStatusLineScriptPath(this.options.settings), - getManagedStatusLineScript('local') - ) } install(): AgentHookInstallStatus { @@ -201,7 +196,7 @@ export class ClaudeHookService { } } - const hook = getManagedLifecycleHook(scriptPath, this.options.settings) + const hook = getManagedLifecycleHook(scriptPath) let nextConfig = applyManagedHooks( config, hook, @@ -232,7 +227,7 @@ export class ClaudeHookService { writeManagedScript(statusLineScriptPath, getManagedStatusLineScript('local')) const next = applyManagedStatusLine( config, - getManagedCommand(statusLineScriptPath), + getLocalManagedCommand(statusLineScriptPath), scriptFileName ) try { diff --git a/src/main/claude/hook-settings.ts b/src/main/claude/hook-settings.ts index d39b8e27bcb9..5c385e88a2e7 100644 --- a/src/main/claude/hook-settings.ts +++ b/src/main/claude/hook-settings.ts @@ -1,34 +1,37 @@ import { homedir } from 'node:os' -import { basename, extname, join, win32 } from 'node:path' +import { basename, extname, join } from 'node:path' import { buildManagedCommandHook, createManagedCommandMatcher, getSharedManagedScriptPath, isPlainObject, - MANAGED_HOOK_TIMEOUT_SECONDS, removeManagedCommands, type HookCommandConfig, type HookDefinition, type HooksConfig } from '../agent-hooks/installer-utils' +import type { ManagedHookCommandMigration } from '../agent-hooks/managed-hook-config-refresh' import { wrapRuntimeHomeHookCommand } from '../agent-hooks/runtime-home-hook-command' +import { + getWindowsAgentHookCommand, + getWindowsAgentHookCommandAsync, + getWindowsAgentHookJsonCommand, + getWindowsAgentHookJsonCommandAsync +} from '../agent-hooks/windows-agent-hook-launcher' export type ClaudeCompatibleHookSettings = { configDirName: '.claude' | '.openclaude' scriptBaseName: 'claude-hook' | 'openclaude-hook' - supportsExecHookArgs: boolean } export const CLAUDE_HOOK_SETTINGS: ClaudeCompatibleHookSettings = { configDirName: '.claude', - scriptBaseName: 'claude-hook', - supportsExecHookArgs: true + scriptBaseName: 'claude-hook' } export const OPENCLAUDE_HOOK_SETTINGS: ClaudeCompatibleHookSettings = { configDirName: '.openclaude', - scriptBaseName: 'openclaude-hook', - supportsExecHookArgs: false + scriptBaseName: 'openclaude-hook' } export const CLAUDE_EVENTS = [ @@ -116,31 +119,44 @@ export function getManagedCommand(scriptPath: string): string { ) } -export function getManagedLifecycleHook( - scriptPath: string, - settings = CLAUDE_HOOK_SETTINGS -): HookCommandConfig { - if (process.platform !== 'win32' || !settings.supportsExecHookArgs) { +export function getManagedLifecycleHook(scriptPath: string): HookCommandConfig { + if (process.platform !== 'win32') { return buildManagedCommandHook(getManagedCommand(scriptPath)) } return getWindowsManagedLifecycleHook(scriptPath) } -export function getWindowsManagedLifecycleHook(scriptPath: string): HookCommandConfig { - const system32 = win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32') - const runtimeScriptPath = win32.join( - '%USERPROFILE%', - '.orca', - 'agent-hooks', - win32.basename(scriptPath) - ) - // 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', win32.join(system32, 'cmd.exe'), '/d', '/c', runtimeScriptPath], - timeout: MANAGED_HOOK_TIMEOUT_SECONDS +export function getLocalManagedCommand(scriptPath: string): string { + return process.platform === 'win32' + ? getWindowsAgentHookCommand(scriptPath) + : getManagedCommand(scriptPath) +} + +export function getWindowsManagedCommandMigrations( + settings: ClaudeCompatibleHookSettings, + lifecycleScriptPresent: boolean, + statusLineScriptPresent: boolean +): ManagedHookCommandMigration[] { + const migrations: ManagedHookCommandMigration[] = [] + if (lifecycleScriptPresent) { + const scriptPath = getManagedScriptPath(settings) + migrations.push({ + scriptFileName: getManagedScriptFileName(settings), + resolveCommand: () => getWindowsAgentHookJsonCommandAsync(scriptPath) + }) + } + if (statusLineScriptPresent) { + const scriptPath = getStatusLineScriptPath(settings) + migrations.push({ + scriptFileName: getStatusLineScriptFileName(settings), + resolveCommand: () => getWindowsAgentHookCommandAsync(scriptPath) + }) } + return migrations +} + +export function getWindowsManagedLifecycleHook(scriptPath: string): HookCommandConfig { + return buildManagedCommandHook(getWindowsAgentHookJsonCommand(scriptPath)) } export function hasSameManagedHookInvocation( diff --git a/src/main/cursor/hook-service.test.ts b/src/main/cursor/hook-service.test.ts index f861d4f2a669..56eb28106b1e 100644 --- a/src/main/cursor/hook-service.test.ts +++ b/src/main/cursor/hook-service.test.ts @@ -15,6 +15,18 @@ vi.mock('os', async () => { } }) +vi.mock('../agent-hooks/windows-agent-hook-launcher', async () => { + const { join } = await import('node:path') + const launcherPath = () => join(homedirMock(), '.orca', 'agent-hooks', 'orca-agent-hook.exe') + return { + installWindowsAgentHookLauncher: launcherPath, + installWindowsAgentHookLauncherAsync: async () => launcherPath(), + getWindowsAgentHookCommand: (scriptPath: string) => `"${launcherPath()}" "${scriptPath}"`, + getWindowsAgentHookCommandAsync: async (scriptPath: string) => + `"${launcherPath()}" "${scriptPath}"` + } +}) + import { CursorHookService } from './hook-service' import { POSIX_HOOK_STDIN_READER } from '../agent-hooks/hook-stdin-contract' @@ -30,8 +42,7 @@ const CURSOR_EVENTS = [ ] const CURSOR_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'cursor-hook.cmd' : 'cursor-hook.sh' -const WINDOWS_POWERSHELL_LAUNCHER = - /^[A-Za-z]:\/[^"]*\/System32\/WindowsPowerShell\/v1\.0\/powershell\.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand \S+$/ +const WINDOWS_HEADLESS_LAUNCHER = /^"[^"]*\\orca-agent-hook\.exe" "[^"]*\\cursor-hook\.cmd"$/i describe('CursorHookService', () => { let homeDir: string @@ -62,7 +73,7 @@ describe('CursorHookService', () => { for (const eventName of CURSOR_EVENTS) { const definition = config.hooks[eventName]?.[0] expect(definition?.command).toMatch( - process.platform === 'win32' ? WINDOWS_POWERSHELL_LAUNCHER : /cursor-hook/ + process.platform === 'win32' ? WINDOWS_HEADLESS_LAUNCHER : /cursor-hook/ ) if (process.platform !== 'win32') { expect(definition?.command).toContain(join(homeDir, '.orca')) @@ -106,7 +117,7 @@ describe('CursorHookService', () => { for (const eventName of ['beforeSubmitPrompt', 'stop']) { const command = config.hooks[eventName]?.[0]?.command - expect(command).toMatch(WINDOWS_POWERSHELL_LAUNCHER) + expect(command).toMatch(WINDOWS_HEADLESS_LAUNCHER) } } finally { rmSync(spaceHome, { recursive: true, force: true }) @@ -148,7 +159,7 @@ describe('CursorHookService', () => { expect( promptCommands.filter((command) => process.platform === 'win32' - ? command !== undefined && WINDOWS_POWERSHELL_LAUNCHER.test(command) + ? command !== undefined && WINDOWS_HEADLESS_LAUNCHER.test(command) : command?.includes(CURSOR_SCRIPT_FILE_NAME) ) ).toHaveLength(1) diff --git a/src/main/cursor/hook-service.ts b/src/main/cursor/hook-service.ts index ab9d07b25eba..c39e7fbadfa6 100644 --- a/src/main/cursor/hook-service.ts +++ b/src/main/cursor/hook-service.ts @@ -10,11 +10,15 @@ import { readHooksJson, removeManagedCommands, wrapPosixHookCommand, - wrapWindowsHookCommand, writeHooksJson, writeManagedScript, type HookDefinition } from '../agent-hooks/installer-utils' +import { refreshManagedHookCommandsIfPresent } from '../agent-hooks/managed-hook-config-refresh' +import { + getWindowsAgentHookCommand, + getWindowsAgentHookCommandAsync +} from '../agent-hooks/windows-agent-hook-launcher' import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' import { readHooksJsonRemote, @@ -54,7 +58,7 @@ function getManagedScriptPath(): string { function getManagedCommand(scriptPath: string): string { return process.platform === 'win32' - ? wrapWindowsHookCommand(scriptPath) + ? getWindowsAgentHookCommand(scriptPath) : wrapPosixHookCommand(scriptPath) } @@ -103,7 +107,17 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string { export class CursorHookService { async refreshManagedScripts(): Promise { - await refreshManagedScriptIfPresent(getManagedScriptPath(), getManagedScript()) + const scriptPresent = await refreshManagedScriptIfPresent( + getManagedScriptPath(), + getManagedScript() + ) + if (process.platform === 'win32' && scriptPresent) { + await refreshManagedHookCommandsIfPresent({ + configPath: getConfigPath(), + scriptFileName: getManagedScriptFileName(), + resolveCommand: () => getWindowsAgentHookCommandAsync(getManagedScriptPath()) + }) + } } getStatus(): AgentHookInstallStatus { diff --git a/src/main/grok/hook-service.test.ts b/src/main/grok/hook-service.test.ts index ba469506316b..ec17be0681ee 100644 --- a/src/main/grok/hook-service.test.ts +++ b/src/main/grok/hook-service.test.ts @@ -17,13 +17,24 @@ vi.mock('os', async () => { } }) +vi.mock('../agent-hooks/windows-agent-hook-launcher', async () => { + const { join } = await import('node:path') + const launcherPath = () => join(homedirMock(), '.orca', 'agent-hooks', 'orca-agent-hook.exe') + return { + installWindowsAgentHookLauncher: launcherPath, + installWindowsAgentHookLauncherAsync: async () => launcherPath(), + getWindowsAgentHookCommand: (scriptPath: string) => `"${launcherPath()}" "${scriptPath}"`, + getWindowsAgentHookCommandAsync: async (scriptPath: string) => + `"${launcherPath()}" "${scriptPath}"` + } +}) + import { getGrokToolEventMatcherForTests, GrokHookService } from './hook-service' import { buildWindowsGrokHookScript } from './windows-grok-hook-script' import { POSIX_HOOK_STDIN_READER } from '../agent-hooks/hook-stdin-contract' const GROK_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'grok-hook.cmd' : 'grok-hook.sh' -const WINDOWS_POWERSHELL_LAUNCHER = - /^[A-Za-z]:\/[^"]*\/System32\/WindowsPowerShell\/v1\.0\/powershell\.exe -NoProfile -ExecutionPolicy Bypass -EncodedCommand \S+$/ +const WINDOWS_HEADLESS_LAUNCHER = /^"[^"]*\\orca-agent-hook\.exe" "[^"]*\\grok-hook\.cmd"$/i type WindowsGrokHookRun = { status: number | null @@ -254,7 +265,7 @@ describe('GrokHookService', () => { const bareStar = ['*', ''].join('') expect(() => new RegExp(bareStar)).toThrow() expect(config.hooks.PreToolUse[0].hooks[0].command).toMatch( - process.platform === 'win32' ? WINDOWS_POWERSHELL_LAUNCHER : /grok-hook/ + process.platform === 'win32' ? WINDOWS_HEADLESS_LAUNCHER : /grok-hook/ ) if (process.platform !== 'win32') { expect(config.hooks.PreToolUse[0].hooks[0].command).toContain(join(homeDir, '.orca')) @@ -302,7 +313,7 @@ describe('GrokHookService', () => { for (const eventName of ['SessionStart', 'UserPromptSubmit', 'Stop']) { const command = config.hooks[eventName]?.[0]?.hooks?.[0]?.command - expect(command).toMatch(WINDOWS_POWERSHELL_LAUNCHER) + expect(command).toMatch(WINDOWS_HEADLESS_LAUNCHER) } } finally { rmSync(spaceHome, { recursive: true, force: true }) @@ -363,7 +374,7 @@ describe('GrokHookService', () => { expect( commands.some((command) => process.platform === 'win32' - ? WINDOWS_POWERSHELL_LAUNCHER.test(command) + ? WINDOWS_HEADLESS_LAUNCHER.test(command) : command.includes(GROK_SCRIPT_FILE_NAME) ) ).toBe(true) diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index 1b6e8bba1653..a333a1153d8d 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -9,11 +9,15 @@ import { readHooksJson, removeManagedCommands, wrapPosixHookCommand, - wrapWindowsHookCommand, writeHooksJson, writeManagedScript, type HookDefinition } from '../agent-hooks/installer-utils' +import { refreshManagedHookCommandsIfPresent } from '../agent-hooks/managed-hook-config-refresh' +import { + getWindowsAgentHookCommand, + getWindowsAgentHookCommandAsync +} from '../agent-hooks/windows-agent-hook-launcher' import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' import { readHooksJsonRemote, @@ -103,7 +107,7 @@ function getManagedScriptPath(): string { function getManagedCommand(scriptPath: string): string { return process.platform === 'win32' - ? wrapWindowsHookCommand(scriptPath) + ? getWindowsAgentHookCommand(scriptPath) : wrapPosixHookCommand(scriptPath) } @@ -184,7 +188,17 @@ function buildInstalledConfig( export class GrokHookService { async refreshManagedScripts(): Promise { - await refreshManagedScriptIfPresent(getManagedScriptPath(), getManagedScript()) + const scriptPresent = await refreshManagedScriptIfPresent( + getManagedScriptPath(), + getManagedScript() + ) + if (process.platform === 'win32' && scriptPresent) { + await refreshManagedHookCommandsIfPresent({ + configPath: getConfigPath(), + scriptFileName: getManagedScriptFileName(), + resolveCommand: () => getWindowsAgentHookCommandAsync(getManagedScriptPath()) + }) + } } getStatus(): AgentHookInstallStatus { diff --git a/src/main/hooks.test.ts b/src/main/hooks.test.ts index 0f8a1817e7aa..24710c78048b 100644 --- a/src/main/hooks.test.ts +++ b/src/main/hooks.test.ts @@ -954,7 +954,8 @@ describe('runHook', () => { 'echo hello', expect.objectContaining({ cwd: 'C:\\repo\\worktree', - shell: 'C:\\Windows\\System32\\cmd.exe' + shell: 'C:\\Windows\\System32\\cmd.exe', + windowsHide: true }), expect.any(Function) ) @@ -1029,6 +1030,7 @@ describe('runHook', () => { callback?.(null, '', '') expect(options).toEqual( expect.objectContaining({ + windowsHide: true, env: expect.objectContaining({ ORCA_ROOT_PATH: '/mnt/c/Users/jinwo/git/orca', ORCA_WORKTREE_PATH: '/home/jin/feature', diff --git a/src/main/hooks.ts b/src/main/hooks.ts index cbbb2edddee4..25102ed03cab 100644 --- a/src/main/hooks.ts +++ b/src/main/hooks.ts @@ -753,7 +753,8 @@ export function runHook( // across the wsl.exe boundary. Wrap hookEnv (not a fresh env) so // the setup-var WSLENV entries registered above (#9206) are kept — // promptGuardShellEnv appends its own keys to the existing WSLENV. - env: promptGuardShellEnv(hookEnv) + env: promptGuardShellEnv(hookEnv), + windowsHide: true }, (error, stdout, stderr) => { finish(error ?? null, stdout, stderr) @@ -776,7 +777,8 @@ export function runHook( env: promptGuardShellEnv({ ...process.env, ...getSetupEnvVars(repo, cwd) - }) + }), + windowsHide: true }, (error, stdout, stderr) => { if (error) {