Skip to content
Closed
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
4 changes: 4 additions & 0 deletions config/electron-builder.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,10 @@ module.exports = {
from: 'native/windows-cli-launcher/.build/orca.exe',
to: 'bin/orca.exe'
},
{
from: 'native/windows-grok-hook-launcher/.build/orca-grok-hook.exe',
to: 'bin/orca-grok-hook.exe'
},
{
from: 'node_modules/agent-browser/bin/agent-browser-win32-x64.exe',
to: 'agent-browser-win32-x64.exe'
Expand Down
58 changes: 58 additions & 0 deletions config/scripts/build-windows-grok-hook-launcher.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env node

import { spawnSync } from 'node:child_process'
import { existsSync, mkdirSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'

if (process.platform !== 'win32') {
throw new Error(
'Windows Grok hook launcher compilation requires a Windows host; refusing to package without it.'
)
}

const repoRoot = resolve(import.meta.dirname, '../..')
const sourcePath = join(repoRoot, 'native', 'windows-grok-hook-launcher', 'OrcaGrokHookLauncher.cs')
const outputPath = readArg('--output') ?? defaultOutputPath(repoRoot)
const compilerPath = findFrameworkCompiler(process.env)

if (!compilerPath) {
throw new Error('Unable to find the .NET Framework C# compiler required for orca-grok-hook.exe.')
}

mkdirSync(dirname(outputPath), { recursive: true })
const result = spawnSync(
compilerPath,
['/nologo', '/target:winexe', '/optimize+', '/warnaserror+', `/out:${outputPath}`, sourcePath],
{ 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) {
return join(projectRoot, 'native', 'windows-grok-hook-launcher', '.build', 'orca-grok-hook.exe')
}

function findFrameworkCompiler(env) {
const windowsDirectory = env.WINDIR ?? env.SystemRoot
if (!windowsDirectory) {
return null
}
const candidates = [
join(windowsDirectory, 'Microsoft.NET', 'Framework64', 'v4.0.30319', 'csc.exe'),
join(windowsDirectory, 'Microsoft.NET', 'Framework', 'v4.0.30319', 'csc.exe')
]
return candidates.find((candidate) => existsSync(candidate)) ?? null
}

function readArg(name) {
const index = process.argv.indexOf(name)
return index !== -1 ? process.argv[index + 1] : undefined
}
4 changes: 4 additions & 0 deletions config/scripts/electron-builder-config.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ describe('electron-builder config', () => {
expect.objectContaining({
from: 'native/windows-cli-launcher/.build/orca.exe',
to: 'bin/orca.exe'
}),
expect.objectContaining({
from: 'native/windows-grok-hook-launcher/.build/orca-grok-hook.exe',
to: 'bin/orca-grok-hook.exe'
})
])
)
Expand Down
4 changes: 4 additions & 0 deletions config/scripts/electron-builder-native-rebuild.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ function runElectronBuilderNativeRebuild(context, runner = execFileSync, runtime
cwd: projectDir,
stdio: 'inherit'
})
runner(process.execPath, ['config/scripts/build-windows-grok-hook-launcher.mjs'], {
cwd: projectDir,
stdio: 'inherit'
})
}
runner(process.execPath, args, {
cwd: projectDir,
Expand Down
5 changes: 5 additions & 0 deletions config/scripts/electron-builder-native-rebuild.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ describe('electron-builder native rebuild hook', () => {
['config/scripts/build-windows-cli-launcher.mjs'],
expect.objectContaining({ stdio: 'inherit' })
],
[
process.execPath,
['config/scripts/build-windows-grok-hook-launcher.mjs'],
expect.objectContaining({ stdio: 'inherit' })
],
[
process.execPath,
['config/scripts/rebuild-native-deps.mjs', '--platform=win32', '--arch=x64', '--force'],
Expand Down
1 change: 1 addition & 0 deletions native/windows-grok-hook-launcher/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.build/
100 changes: 100 additions & 0 deletions native/windows-grok-hook-launcher/OrcaGrokHookLauncher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;

internal static class OrcaGrokHookLauncher
{
private const int ChildExitTimeoutMilliseconds = 4000;

[STAThread]
private static int Main()
{
try
{
string launcherDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string scriptPath = Path.Combine(launcherDirectory ?? ".", "grok-hook.cmd");
if (!File.Exists(scriptPath))
{
string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
scriptPath = Path.Combine(home, ".orca", "agent-hooks", "grok-hook.cmd");
}
if (!File.Exists(scriptPath))
{
return 0;
}
Comment on lines +23 to +26

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Drain stdin before returning when the script is missing.

The existing PowerShell fallback drains stdin for this case. Returning immediately closes the hook input pipe. Grok can then receive a broken-pipe error while it writes the event payload.

Proposed fix
             if (!File.Exists(scriptPath))
             {
+                DrainStandardInput();
                 return 0;
             }

Add DrainStandardInput with the same best-effort Console.OpenStandardInput().CopyTo(Stream.Null) behavior used by the child-input forwarding path.


ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = Environment.GetEnvironmentVariable("ComSpec") ?? "cmd.exe";
startInfo.Arguments = "/d /c \"" + scriptPath + "\"";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
using (Process child = Process.Start(startInfo))
{
if (child == null)
{
return 0;
}

Thread stdinThread = new Thread(() =>
{
try
{
using (Stream input = Console.OpenStandardInput())
{
input.CopyTo(child.StandardInput.BaseStream);
}
child.StandardInput.Close();
}
catch
{
}
});
stdinThread.IsBackground = true;
stdinThread.Start();

Drain(child.StandardOutput.BaseStream);
Drain(child.StandardError.BaseStream);
if (!child.WaitForExit(ChildExitTimeoutMilliseconds))
{
try
{
child.Kill();
}
catch
{
}
}
}
}
catch
{
}

return 0;
}

private static void Drain(Stream stream)
{
Thread thread = new Thread(() =>
{
try
{
byte[] buffer = new byte[4096];
while (stream.Read(buffer, 0, buffer.Length) > 0)
{
}
}
catch
{
}
});
thread.IsBackground = true;
thread.Start();
}
}
6 changes: 4 additions & 2 deletions src/main/grok/hook-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ 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 -WindowStyle Hidden -EncodedCommand \S+$/
const WINDOWS_GROK_HOOK_COMMAND =
/orca-grok-hook\.exe$|[A-Za-z]:\/[^"]*\/System32\/WindowsPowerShell\/v1\.0\/powershell\.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand \S+$/

type WindowsGrokHookRun = {
status: number | null
Expand Down Expand Up @@ -254,7 +256,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_GROK_HOOK_COMMAND : /grok-hook/
)
if (process.platform !== 'win32') {
expect(config.hooks.PreToolUse[0].hooks[0].command).toContain(join(homeDir, '.orca'))
Expand Down Expand Up @@ -367,7 +369,7 @@ describe('GrokHookService', () => {
expect(
commands.some((command) =>
process.platform === 'win32'
? WINDOWS_POWERSHELL_LAUNCHER.test(command)
? WINDOWS_GROK_HOOK_COMMAND.test(command)
: command.includes(GROK_SCRIPT_FILE_NAME)
)
).toBe(true)
Expand Down
53 changes: 47 additions & 6 deletions src/main/grok/hook-service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { join } from 'node:path'
import { copyFileSync, existsSync, mkdirSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import type { SFTPWrapper } from 'ssh2'
import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types'
import { resolveGrokHomeDir } from '../../shared/grok-session-paths'
Expand Down Expand Up @@ -101,10 +103,49 @@ function getManagedScriptPath(): string {
return getSharedManagedScriptPath(getManagedScriptFileName())
}

const WINDOWS_GROK_HOOK_LAUNCHER_NAME = 'orca-grok-hook.exe'

function isGrokManagedCommand(command: string | undefined): boolean {
if (createManagedCommandMatcher(getManagedScriptFileName())(command)) {
return true
}
return Boolean(command?.replaceAll('\\', '/').includes(WINDOWS_GROK_HOOK_LAUNCHER_NAME))
}
Comment on lines +108 to +113

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Restrict launcher matching to the managed launcher path.

Line 112 matches any command that contains orca-grok-hook.exe. removeManagedCommands can then remove a user-authored hook that only references that executable name. Match the normalized managed path, such as agent-hooks/orca-grok-hook.exe, instead.

Proposed fix
-  return Boolean(command?.replaceAll('\\', '/').includes(WINDOWS_GROK_HOOK_LAUNCHER_NAME))
+  return Boolean(
+    command
+      ?.replaceAll('\\', '/')
+      .endsWith(`/agent-hooks/${WINDOWS_GROK_HOOK_LAUNCHER_NAME}`)
+  )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function isGrokManagedCommand(command: string | undefined): boolean {
if (createManagedCommandMatcher(getManagedScriptFileName())(command)) {
return true
}
return Boolean(command?.replaceAll('\\', '/').includes(WINDOWS_GROK_HOOK_LAUNCHER_NAME))
}
function isGrokManagedCommand(command: string | undefined): boolean {
if (createManagedCommandMatcher(getManagedScriptFileName())(command)) {
return true
}
return Boolean(
command
?.replaceAll('\\', '/')
.endsWith(`/agent-hooks/${WINDOWS_GROK_HOOK_LAUNCHER_NAME}`)
)
}


function bundledWindowsGrokHookLauncherPath(): string | null {
const candidates = [
...(process.resourcesPath
? [join(process.resourcesPath, 'bin', WINDOWS_GROK_HOOK_LAUNCHER_NAME)]
: []),
join(process.cwd(), 'native', 'windows-grok-hook-launcher', '.build', WINDOWS_GROK_HOOK_LAUNCHER_NAME)
]
return candidates.find((candidate) => existsSync(candidate)) ?? null
}

function publishWindowsGrokHookLauncher(): string | null {
const source = bundledWindowsGrokHookLauncherPath()
if (!source) {
return null
}
const destination = join(homedir(), '.orca', 'agent-hooks', WINDOWS_GROK_HOOK_LAUNCHER_NAME)
mkdirSync(dirname(destination), { recursive: true })
copyFileSync(source, destination)
return destination
Comment on lines +125 to +133

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not overwrite the launcher during status checks.

getStatus() calls getManagedCommand(), so this function copies the executable on every status read. If a hook is running, Windows can reject the overwrite with a sharing violation. The uncaught error then makes status reporting fail. Publish only during install or use a non-mutating status path that reuses an existing destination.

}

function getManagedCommand(scriptPath: string): string {
return process.platform === 'win32'
? wrapWindowsHookCommand(scriptPath)
: wrapPosixHookCommand(scriptPath)
if (process.platform !== 'win32') {
return wrapPosixHookCommand(scriptPath)
}
// Why: Grok treats a command string with spaces as a pwsh -Command script
// (#14828). A single space-free GUI-subsystem exe is spawned directly, so
// no console window appears. Profile paths with spaces still need the
// encoded PowerShell launcher (#6078).
const launcher = publishWindowsGrokHookLauncher()
if (launcher && !/\s/.test(launcher)) {
return launcher.replaceAll('\\', '/')
}
return wrapWindowsHookCommand(scriptPath)
Comment on lines 136 to +148

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Recognize stale PowerShell commands in getStatus().

When the executable is available, this function returns its path. Lines 252-254 then use exact equality, so existing encoded PowerShell hook commands report not_installed even though isGrokManagedCommand preserves and removes them. Use the managed-command predicate for status detection and add a stale-PowerShell status test.

}

function getManagedScript(target: 'local' | 'posix' = 'local'): string {
Expand Down Expand Up @@ -152,7 +193,7 @@ function buildInstalledConfig(
scriptFileName: string
): void {
const nextHooks = { ...config.hooks }
const isManagedCommand = createManagedCommandMatcher(scriptFileName)
const isManagedCommand = isGrokManagedCommand
const managedEvents = new Set<string>(GROK_EVENTS.map((event) => event.eventName))

// Why: Orca owns only grok-hook.* entries. Sweep stale managed commands out
Expand Down Expand Up @@ -312,7 +353,7 @@ export class GrokHookService {
}

const nextHooks = { ...config.hooks }
const isManagedCommand = createManagedCommandMatcher(getManagedScriptFileName())
const isManagedCommand = isGrokManagedCommand
for (const [eventName, definitions] of Object.entries(nextHooks)) {
if (!Array.isArray(definitions)) {
continue
Expand Down
Loading