Skip to content

fix(windows): make managed grok-hook.cmd safe when GROK_HOME is unset - #11782

Merged
OrcaWin merged 4 commits into
stablyai:mainfrom
Kyou12138:fix/windows-grok-hook-empty-grok-home
Aug 5, 2026
Merged

OrcaWin merged 4 commits into
stablyai:mainfrom
Kyou12138:fix/windows-grok-hook-empty-grok-home

Conversation

@Kyou12138

Copy link
Copy Markdown
Contributor

Summary

Fixes #9358 and #9941.

Managed ~/.orca/agent-hooks/grok-hook.cmd fails with exit code 1/255 and
The syntax of the command is incorrect on every Grok hook event
(SessionStart, UserPromptSubmit, tool lifecycle, …) when GROK_HOME is
unset — the default for Grok launched outside an Orca-managed terminal.

Root cause

cmd.exe expands %VAR:~n,m% at parse time. The generated template did:

set "ORCA_GROK_HOME=%GROK_HOME%"
if not "%GROK_HOME:~4096,1%"=="" set "ORCA_GROK_HOME="
if "%ORCA_GROK_HOME:~-1%"=="\" set "ORCA_GROK_HOME=%ORCA_GROK_HOME%."

When GROK_HOME is undefined:

  1. Substring expansion leaves literal ~… junk instead of empty.
  2. The trailing-backslash guard uses "\" as the RHS, which itself is a
    cmd quote-parser syntax error even when the variable is defined.

So every managed Grok hook aborted before the curl POST to /hook/grok.

Fix

  1. Default ORCA_GROK_HOME= and if not defined GROK_HOME goto past all
    substring work (not a parenthesized block — those still parse-expand early).
  2. Length-cap against %ORCA_GROK_HOME:~4096,1% only after assignment.
  3. Trailing \ detection via findstr /r /c:"\\$" — never =="\".
  4. Extract builder to windows-grok-hook-script.ts for testability.

Why not just the existing open PRs?

Several open PRs guard with if defined but still emit
if "%ORCA_GROK_HOME:~-1%"=="\", which fails as soon as GROK_HOME is set
(e.g. inside Orca, or after the user applies the documented workaround). This
PR removes that comparison entirely.

Related Issue

Closes #9358
Closes #9941

Type of Change

  • Bug fix (non-breaking)
  • Tests

Changes Made

  • src/main/grok/windows-grok-hook-script.ts — Windows script template
  • src/main/grok/hook-service.ts — use the safe builder
  • src/main/grok/hook-service.test.ts — template assertions + Windows cmd
    spawn tests (unset GROK_HOME, trailing-backslash path)

How to Test

npx vitest run src/main/grok/hook-service.test.ts

On Windows (covered by the spawn tests):

  1. Clear GROK_HOME
  2. Reinstall managed Grok hooks / launch Grok outside Orca
  3. Submit a prompt — global/orca-status:user_prompt_submit should no longer
    fail with exit code 1

Platform / SSH

  • Windows managed script path only; POSIX grok-hook.sh unchanged
  • Remote POSIX install path unchanged

AI Review Notes

  • Cross-platform: Windows-only template; tests skip spawn cases on non-Windows
  • Security: no new network surface; still best-effort local curl to loopback
  • Performance: one optional findstr when GROK_HOME is set

Checklist

  • Tests pass locally (7/7 on Windows host)
  • Scope limited to the linked issues
  • No workflow / packaging changes

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a Windows-only crash (exit 1/255, "The syntax of the command is incorrect") that hit every managed Grok hook event when GROK_HOME was unset — the default for Grok launched outside an Orca terminal. The root cause was two cmd.exe parse-time problems: %VAR:~n,m% substring expansion on an undefined variable produces junk instead of an empty string, and ==\"\\\" is a quote-parser syntax error that fires even when the variable is defined.

  • Extracts the Windows grok-hook.cmd generator to windows-grok-hook-script.ts, using if not defined GROK_HOME goto :orca_grok_home_ready (a label jump, not a parenthesized if block, which would still parse-expand early) to skip all substring work when GROK_HOME is absent.
  • Replaces the broken trailing-backslash check with echo.%ORCA_GROK_HOME%| findstr /r /c:"\\$", avoiding both the quote-parser bug and parse-time expansion.
  • Adds extraFormLines to buildWindowsAgentHookPostCommand so grokHome can be injected without a fragile String.prototype.replace() on the shared template.

Confidence Score: 5/5

Safe to merge — the change is scoped entirely to Windows cmd.exe script generation for the Grok hook, with no impact on POSIX paths or other hook services.

The fix correctly addresses both cmd.exe parse-time failures: the goto-based guard prevents substring expansion on an undefined variable, and the findstr approach eliminates the broken quote-parser comparison. The extraFormLines refactor removes the only fragile coupling between the Grok template and the shared post-command builder. Template-assertion and Windows spawn tests cover the unset-GROK_HOME, trailing-backslash, and structural contract cases. No logic issues found across all four changed files.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/grok/windows-grok-hook-script.ts New module containing the corrected Windows grok-hook.cmd generator; uses goto-based guard and findstr for trailing-backslash detection — core of the fix.
src/main/agent-hooks/installer-utils.ts Adds optional extraFormLines parameter to buildWindowsAgentHookPostCommand, removing the need for fragile string-replace to inject grokHome; backward-compatible with default [].
src/main/grok/hook-service.ts Simplified to delegate Windows script generation to buildWindowsGrokHookScript(); imports GROK_HOME_ENVELOPE_MAX_LENGTH for use in the POSIX branch.
src/main/grok/hook-service.test.ts New template-assertion test (cross-platform) plus two Windows-only spawn tests covering unset GROK_HOME and trailing-backslash path; spawn tests correctly delete the key rather than empty it.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[grok-hook.cmd starts] --> B[setlocal / env hook call]
    B --> C{ORCA_AGENT_HOOK_PORT\nORCA_AGENT_HOOK_TOKEN\nORCA_PANE_KEY set?}
    C -- no --> D[drain stdin → exit 0]
    C -- yes --> E[set ORCA_GROK_HOME= empty]
    E --> F{GROK_HOME defined?}
    F -- no --> K[:orca_grok_home_ready]
    F -- yes --> G[set ORCA_GROK_HOME=%GROK_HOME%]
    G --> H{len > 4096?}
    H -- yes --> I[clear ORCA_GROK_HOME]
    H -- no --> J{ORCA_GROK_HOME defined\nand ends with backslash?\nfindstr /r /c:\\\$}
    I --> K
    J -- yes --> L[append . to strip backslash]
    J -- no --> K
    L --> K
    K[curl POST /hook/grok\nwith grokHome=%ORCA_GROK_HOME%] --> M[exit /b 0]
Loading

Reviews (2): Last reviewed commit: "fix(windows): harden grok-hook GROK_HOME..." | Re-trigger Greptile

Comment thread src/main/grok/hook-service.test.ts Resolved
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e653c79f-2e8d-42ef-bc7c-2d86565003c7

📥 Commits

Reviewing files that changed from the base of the PR and between 5ed4573 and 3575c3d.

📒 Files selected for processing (5)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/installer-utils.ts
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/grok/windows-grok-hook-script.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/installer-utils.ts
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/grok/windows-grok-hook-script.ts

📝 Walkthrough

Walkthrough

This PR extracts Windows Grok hook script generation into a new module. The module exports the GROK_HOME limit and builds the Windows script. The script validates and normalizes GROK_HOME, posts the hook payload, drains stdin, and exits successfully. hook-service.ts now delegates script generation to the module. The Windows POST command accepts additional form-data lines. Tests cover unset, trailing-backslash, oversized, and maximum-length GROK_HOME values.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the Windows Grok hook fix for an unset GROK_HOME.
Description check ✅ Passed The description covers the bug, fix, scope, tests, and review notes, although it omits some template headings and audit detail.
Linked Issues check ✅ Passed The implementation and tests address unset or empty GROK_HOME, syntax safety, the 4096-character cap, trailing-backslash normalization, and /hook/grok delivery [#9358] [#9941].
Out of Scope Changes check ✅ Passed All changes support the linked Windows Grok hook fix, including the builder, utility extension, configuration inclusion, and regression tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/main/grok/hook-service.test.ts (1)

47-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid hardcoding the length-cap literal in assertions.

expect(script).toContain('%ORCA_GROK_HOME:~4096,1%') hardcodes 4096 instead of interpolating the imported GROK_HOME_ENVELOPE_MAX_LENGTH constant. If the constant changes later, this assertion keeps checking the old value instead of failing loudly or tracking the new one.

♻️ Proposed fix
-import { buildWindowsGrokHookScript } from './windows-grok-hook-script'
+import { buildWindowsGrokHookScript, GROK_HOME_ENVELOPE_MAX_LENGTH } from './windows-grok-hook-script'
...
-    expect(script).toContain('%ORCA_GROK_HOME:~4096,1%')
+    expect(script).toContain(`%ORCA_GROK_HOME:~${GROK_HOME_ENVELOPE_MAX_LENGTH},1%`)

Also applies to: 160-160


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8e7d5824-e70b-4489-9171-216625987846

📥 Commits

Reviewing files that changed from the base of the PR and between 79251d7 and b8822be4824d1c0944108c4238c367317e1a4773.

📒 Files selected for processing (3)
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/grok/windows-grok-hook-script.ts

Comment thread src/main/grok/hook-service.test.ts Resolved
Comment on lines +10 to +15
const WINDOWS_HOOK_PAYLOAD_FORM_LINE = ' --data-urlencode "payload@-" >nul 2>nul'

const WINDOWS_GROK_HOOK_POST_COMMAND = buildWindowsAgentHookPostCommand('grok').replace(
WINDOWS_HOOK_PAYLOAD_FORM_LINE,
` --data-urlencode "grokHome=%ORCA_GROK_HOME%" ^\r\n${WINDOWS_HOOK_PAYLOAD_FORM_LINE}`
)

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

Harden the grokHome injection against silent drift.

WINDOWS_GROK_HOOK_POST_COMMAND depends on an exact literal-string match between WINDOWS_HOOK_PAYLOAD_FORM_LINE and the last line produced by buildWindowsAgentHookPostCommand('grok') in installer-utils.ts. If that shared builder's output changes (whitespace, flag order, new line), .replace() finds no match and returns the string unchanged. The script would then post to /hook/grok without a grokHome parameter, with no error and no test failure, since no test currently asserts that grokHome=%ORCA_GROK_HOME% appears in the built command.

Add a guard that fails loudly if the replacement did not occur, and add a test asserting the grokHome data-urlencode line is present in the generated script.

🛡️ Proposed fix to fail loudly on drift
-const WINDOWS_GROK_HOOK_POST_COMMAND = buildWindowsAgentHookPostCommand('grok').replace(
-  WINDOWS_HOOK_PAYLOAD_FORM_LINE,
-  `  --data-urlencode "grokHome=%ORCA_GROK_HOME%" ^\r\n${WINDOWS_HOOK_PAYLOAD_FORM_LINE}`
-)
+const WINDOWS_GROK_HOOK_POST_COMMAND_BASE = buildWindowsAgentHookPostCommand('grok')
+const WINDOWS_GROK_HOOK_POST_COMMAND = WINDOWS_GROK_HOOK_POST_COMMAND_BASE.replace(
+  WINDOWS_HOOK_PAYLOAD_FORM_LINE,
+  `  --data-urlencode "grokHome=%ORCA_GROK_HOME%" ^\r\n${WINDOWS_HOOK_PAYLOAD_FORM_LINE}`
+)
+if (WINDOWS_GROK_HOOK_POST_COMMAND === WINDOWS_GROK_HOOK_POST_COMMAND_BASE) {
+  throw new Error(
+    'buildWindowsAgentHookPostCommand output no longer matches WINDOWS_HOOK_PAYLOAD_FORM_LINE; grokHome injection failed.'
+  )
+}

Fixes stablyai#9358 and stablyai#9941.

cmd.exe expands %VAR:~n,m% at parse time. When GROK_HOME is unset (default
outside Orca terminals), the generated length/trailing-backslash guards
became a syntax error and every Grok hook event failed with exit 255.

- Skip substring work when GROK_HOME is undefined (if defined + goto)
- Replace if "%x:~-1%"=="\" (itself a quote-parser bug) with findstr
- Extract Windows script builder; add template + spawn tests
Address review on stablyai#11782:
- Inject grokHome via buildWindowsAgentHookPostCommand extra form lines
  (no fragile string replace of the shared payload line)
- Spawn tests delete GROK_HOME and keep PORT/TOKEN/PANE_KEY set so the
  GROK_HOME path actually runs before curl
@Kyou12138
Kyou12138 force-pushed the fix/windows-grok-hook-empty-grok-home branch from b8822be to db5b578 Compare August 2, 2026 05:30
@AmethystLiang

Copy link
Copy Markdown
Contributor

Dedupe note

#9941 was closed as Duplicate of #9358 (same Windows grok-hook.cmd / empty GROK_HOME bug). This PR already Closes #9358 and Closes #9941, so it remains the single preferred landing PR for the combined issue.

Related earlier PR for the same root cause: #10049 (@innocarpe, claimed on #9941 with a narrower if defined guard). That PR is being closed as a duplicate of this one so review concentrates here. If anything from #10049 should be cherry-picked, call it out on this thread.

@OrcaWin

OrcaWin commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Taking a look!

@OrcaWin

OrcaWin commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Reviewed and hardened the Windows Grok hook fix.

  • Skip cmd.exe substring expansion when GROK_HOME is unset.
  • Normalize a trailing backslash only when the resulting value stays within the 4096-character envelope.
  • Reject oversized values before they can overflow a Windows command line.
  • Add listener-backed Windows tests that verify the actual /hook/grok form post for unset, trailing, boundary, and oversized values.

Validated with the targeted Windows suite (9/9), typecheck, focused lint, a fresh independent review/performance pass, and Electron headless status-lifecycle coverage.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@OrcaWin
OrcaWin merged commit 74ac704 into stablyai:main Aug 5, 2026
42 checks passed
@brennanb2025

Copy link
Copy Markdown
Contributor

Thank you for the PR!

OrcaWin added a commit that referenced this pull request Aug 21, 2026
…ace (#14221)

On Windows any open read handle on the target - AV scanner, backup agent,
search indexer, editor - fails rename() with EPERM. refreshExistingManagedScripts
only logs, so the script stays frozen at whatever an older Orca generated and the
agent keeps invoking it, with no user-visible signal and no self-heal on relaunch.

That is how #14221 reports a pre-#11782 grok-hook.cmd on v1.4.180: the builder is
correct, the file on disk was never replaced. An in-place write still lands against
that handle, so fall back to it rather than strand a stale script.

Verified on Windows: rename EPERMs against an open read handle where writeFile
succeeds; cmd.exe executing the script does not block either.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#11782)

* fix(windows): make managed grok-hook.cmd safe when GROK_HOME is unset

Fixes stablyai#9358 and stablyai#9941.

cmd.exe expands %VAR:~n,m% at parse time. When GROK_HOME is unset (default
outside Orca terminals), the generated length/trailing-backslash guards
became a syntax error and every Grok hook event failed with exit 255.

- Skip substring work when GROK_HOME is undefined (if defined + goto)
- Replace if "%x:~-1%"=="\" (itself a quote-parser bug) with findstr
- Extract Windows script builder; add template + spawn tests

* fix(windows): harden grok-hook GROK_HOME guards and tests

Address review on stablyai#11782:
- Inject grokHome via buildWindowsAgentHookPostCommand extra form lines
  (no fragile string replace of the shared payload line)
- Spawn tests delete GROK_HOME and keep PORT/TOKEN/PANE_KEY set so the
  GROK_HOME path actually runs before curl

* fix(windows): cover Grok hook home boundaries

---------

Co-authored-by: OrcaWin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants