Skip to content

fix(windows): stop agent hooks from flashing console windows - #14845

Closed
Tauri-EPO wants to merge 3 commits into
stablyai:mainfrom
Tauri-EPO:fix/windows-agent-hook-launcher
Closed

Tauri-EPO wants to merge 3 commits into
stablyai:mainfrom
Tauri-EPO:fix/windows-agent-hook-launcher

Conversation

@Tauri-EPO

@Tauri-EPO Tauri-EPO commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

On Windows, agent hooks could briefly open black terminal windows, steal focus, hang after a tool call, or expose hook protocol output such as raw JSON. Orca now runs those hooks through a small windowless launcher, gives Claude-compatible hooks the valid neutral JSON they expect, and forcibly bounds abandoned stdin and child processes so no console or orphan remains.

What Changed

  • Added a packaged Windows GUI-subsystem launcher for managed agent hooks. It starts the system cmd.exe with no window, redirects all standard streams, and never resolves executables through the workspace or PATH.
  • Added bounded lifecycle handling: stdin is accepted for up to 1 second, the child gets up to 2.5 seconds, and a timed-out child is terminated.
  • Claude and OpenClaude lifecycle hooks now use one command string with --neutral-json, avoiding the older-Claude behavior that ignored separate args and rejected empty stdout.
  • Cursor and Grok hooks use the same windowless launcher without emitting stdout.
  • Launcher filenames are content-addressed, so an Orca update does not need to replace an .exe that a concurrent hook still has open.
  • Existing managed Claude, Cursor, and Grok configs are migrated asynchronously even if the agent CLI is no longer on PATH. Missing or user-removed configs are not recreated, legacy Claude args are removed, symlinked configs remain attached to their targets, and writes remain guarded and atomic.
  • Direct local Windows and WSL hook subprocesses set windowsHide: true as a second backstop.
  • Added packaging, build, migration, main-thread I/O, command-shape, and subprocess-option regression coverage.

Why

The previous Windows paths had several related failure modes:

  • shell-form hooks could create a visible conhost.exe window and steal focus;
  • Claude versions that ignored hook args could execute only the host command or treat empty stdout as invalid JSON;
  • callers that left stdin open could keep cmd.exe / curl.exe chains alive;
  • already-installed user configs continued invoking stale launchers when the CLI presence gate no longer ran installation.

A GUI-subsystem launcher fixes the window creation at the process boundary. Bounded redirected streams solve the hang/orphan class, while protocol-specific neutral JSON keeps Claude fail-open without leaking output into a visible terminal.

Linked Issue

Fixes #14815
Fixes #14818
Fixes #14828
Fixes #14837

Related PRs

Canonical Windows hook fix for #14815 (Claude, Cursor, and Grok). #14825 is a Claude-only predecessor that still emits conhost.exe --headless plus encoded PowerShell; it does not cover Cursor/Grok and does not address the #14837 conhost hang class or Cursor's invalid-JSON block (#14818). Prefer this PR; do not merge #14825 first.

Hosted CI

This is a cross-repository fork PR (Tauri-EPO/orca → stablyai/orca). GitHub Actions on b157fd3101a56206bddf06d2221b5f2b965a29a4 have not produced check runs: gh pr checks reports none, commit statuses total_count: 0, statusCheckRollup is empty, mergeStateStatus is UNSTABLE. Workflow runs exist but never spawned jobs (conclusion: action_required, fork-workflow approval, approvals: []):

Maintainer action: approve and run those workflows. Independent Windows unit tests and native launcher probes are in Testing below.

Visual Proof

N/A for rendered Orca UI — no Orca view, layout, or in-app control changes. Linked issues #14815, #14818, #14828, and #14837 have no screenshot or video attachments (the only extra #14828 file is a Discord message.txt, not an image), so none is copied here and none is invented.

This is still an OS-console / focus-steal interaction. Public before/after evidence is textual and process-level, not a tab-switchable screenshot pair:

Before (already public):

After (already public on this PR; re-verified on head b157fd3):

  • Bundled launcher PE subsystem 2 = IMAGE_SUBSYSTEM_WINDOWS_GUI
  • --neutral-json + child exit /b 7 + leaked echo: exit 7, stdout exactly {}\n (7B-7D-0A), stderr empty, 77ms
  • Silent Cursor/Grok path: exit 7, stdout empty, 180ms
  • Missing script: exit 0, stdout {}\n, 50ms
  • Prior public tree-kill probe: leftover descendants 0 — fix(windows): stop agent hooks from flashing console windows #14845 (comment)

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

Author-reported Windows 11 live sessions (not re-run in this compliance pass):

  • Fresh Claude session: 8 hook runs; closed stdin completed in at most 114 ms, deliberately open stdin completed in about 1.05 s; stdout was exactly {} plus newline, stderr was empty, all 11 managed commands used one command string with no args, and no launcher/curl process remained.
  • Fresh Cursor session: imported Claude PreToolUse returned valid neutral JSON without blocking; Cursor-native hooks exited with no stdout; all probes completed in 82–1145 ms with no stderr or orphaned process.
  • Fresh Grok/Codex session: the installed Grok hook completed with deliberately open stdin in about 1.06 s, with no stdout/stderr, PowerShell/conhost command, or orphaned process.
  • Exact Git Bash single-command invocation returned {} and exit 0 with zero active launchers/curl processes.
  • Unicode payload coverage included accented text, CJK, and emoji without corruption.

This compliance pass on detached b157fd3101a56206bddf06d2221b5f2b965a29a4 (Windows 11):

  • Focused pnpm exec vitest run --config config/vitest.config.ts on the 6 changed test files: 6 files, 120 passed
  • pnpm exec oxlint --deny-warnings on changed TypeScript/JavaScript files: exit 0
  • git diff --check origin/main...HEAD: clean
  • Existing native/windows-agent-hook-launcher/.build/orca-agent-hook.exe PE subsystem 2 (IMAGE_SUBSYSTEM_WINDOWS_GUI); live launcher probes as in Visual Proof
  • Full pnpm lint, pnpm typecheck, pnpm test, and pnpm build were not re-run here; those remain the hosted-CI gate after maintainer fork-workflow approval
  • oxfmt --check is not claimed: it also fails on unchanged src/main/wsl.ts in this worktree, so it is not treated as a PR-specific defect

AI Disclosure

Investigation and implementation were AI-assisted with Claude, Grok, and OpenAI Codex. The final patch, scope, tests, and live Windows evidence were reviewed and verified by me before submission.

Review

  • Security: uses absolute system executable paths, redirects standard streams, avoids workspace/PATH executable lookup, quotes the managed script path, and only migrates configs that already contain an Orca-managed command.
  • Cross-platform: the native launcher and config migration are guarded to Windows. macOS and Linux keep their existing POSIX hook paths. No renderer, keyboard, path-format, or native-module ABI behavior changes.
  • SSH / remote / folder workspaces: remote hook installation remains POSIX and unchanged. The launcher is only selected for local Windows execution; folder workspaces and git worktrees use the same managed user hook path. WSL receives only the existing Electron windowsHide spawn option on the Windows host side.
  • Agent compatibility: Claude/OpenClaude get protocol-valid neutral JSON; Cursor and Grok remain silent. Existing command matchers migrate legacy .cmd, .ps1, and .sh references without touching user-authored hooks.
  • Backwards compatibility: no RPC, stream, persisted-state, remote-wire, Git, or provider contract changes. Existing configs are upgraded in place and absent configs remain absent.
  • Performance: the launcher removes PowerShell startup from the hot path, uses async startup refresh I/O, and applies hard upper bounds to stdin and child lifetime.
  • UI / mobile: no rendered UI or mobile change.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author

  • X / Twitter: @EnricoPin

@Tauri-EPO Tauri-EPO changed the title fix(windows): hide agent hook consoles fix(windows): stop agent hooks from flashing console windows Aug 16, 2026
@coderabbitai

coderabbitai Bot commented Aug 16, 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: 6ad50a51-ed6d-4129-a12a-5ef7c4833fa0

📥 Commits

Reviewing files that changed from the base of the PR and between b157fd3 and ac78e99.

📒 Files selected for processing (7)
  • src/main/agent-hooks/managed-hook-config-refresh.ts
  • src/main/agent-hooks/managed-hook-script-refresh.test.ts
  • src/main/claude/claude-managed-script-refresh.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/hook-settings.ts
  • src/main/cursor/hook-service.ts
  • src/main/grok/hook-service.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/agent-hooks/managed-hook-script-refresh.test.ts
  • src/main/cursor/hook-service.ts
  • src/main/grok/hook-service.ts
  • src/main/agent-hooks/managed-hook-config-refresh.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The change adds a native Windows agent-hook launcher and packages it with Windows builds. The build script compiles both Windows launchers. TypeScript utilities install content-addressed launcher copies and construct quoted commands. Managed hook configuration refresh migrates commands with guarded atomic writes. Claude, Cursor, and Grok services use the launcher for Windows hooks. WSL and non-WSL hook execution hides spawned Windows processes. Tests cover installation, command generation, configuration migration, service integration, and process options.

Merge Risk: ⚪ Minimal · up to ac78e

The change replaces visible Windows hook execution with a windowless, bounded launcher and protocol-safe output; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the Windows agent-hook console-window fix, which is the primary change in the pull request.
Description check ✅ Passed The description covers the required change, rationale, linked issues, testing, visual proof, AI disclosure, review, and checklist, with only minor template sections omitted.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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: 3

🧹 Nitpick comments (5)
config/scripts/build-windows-cli-launcher.mjs (1)

29-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Update the error text to cover both binaries.

The script now compiles orca.exe and orca-agent-hook.exe. The message names only orca.exe.

♻️ Proposed wording change
-  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.'
+  )
src/main/agent-hooks/windows-agent-hook-launcher.ts (2)

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

Extract the duplicated candidate list.

resolveBundledLauncherPath and resolveBundledLauncherPathAsync build the same three candidate paths. Extract one getBundledLauncherCandidatePaths() function and let both resolvers consume it. This keeps the packaged and development lookup order in one place.

♻️ Proposed refactor
+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 = [ /* ... */ ]
+  const candidates = getBundledLauncherCandidatePaths()
   const sourcePath = candidates.find((candidate) => existsSync(candidate))

64-133: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale content-addressed launchers accumulate.

Each launcher build produces a new orca-agent-hook-<digest>.exe in ~/.orca/agent-hooks. Old copies are never removed. After several app updates the directory keeps every historical binary.

Consider removing orca-agent-hook-*.exe entries that do not match the current digest after a successful publish. Skip files that are still referenced by installed hook commands.

src/main/agent-hooks/windows-agent-hook-launcher.test.ts (1)

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

Add an idempotency test for repeated installs.

The suite installs the launcher once. The production code contains a content-comparison short circuit and a rename-race fallback. Neither path is exercised.

Add a test that calls installWindowsAgentHookLauncher(sourcePath) twice and asserts the same destination path and a single file in ~/.orca/agent-hooks. Consider also covering installWindowsAgentHookLauncherAsync.

src/main/agent-hooks/managed-hook-config-refresh.ts (1)

110-123: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Preserve user formatting if required. parseHooksJsonText uses JSON.parse, so comments and trailing commas are rejected. Valid JSON properties are retained, but reserialization normalizes indentation, whitespace, the trailing newline, and a leading BOM. If formatting preservation is required, update only the migrated fields instead of reserializing the entire file.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 288c0dd5-2bed-4cf2-a884-b962ddc90103

📥 Commits

Reviewing files that changed from the base of the PR and between 1f483c3 and 8a0e793.

📒 Files selected for processing (16)
  • config/electron-builder.config.cjs
  • config/scripts/build-windows-cli-launcher.mjs
  • native/windows-agent-hook-launcher/OrcaAgentHookLauncher.cs
  • src/main/agent-hooks/managed-hook-config-refresh.ts
  • src/main/agent-hooks/managed-hook-script-refresh.test.ts
  • src/main/agent-hooks/windows-agent-hook-launcher.test.ts
  • src/main/agent-hooks/windows-agent-hook-launcher.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-service.ts
  • src/main/claude/hook-settings.ts
  • src/main/cursor/hook-service.test.ts
  • src/main/cursor/hook-service.ts
  • src/main/grok/hook-service.test.ts
  • src/main/grok/hook-service.ts
  • src/main/hooks.test.ts
  • src/main/hooks.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.

Comment thread src/main/claude/hook-service.test.ts Resolved
@Tauri-EPO

Copy link
Copy Markdown
Contributor Author

Independent delivery audit (b157fd3)

Audited from a separate top-level worktree at detached b157fd3101a56206bddf06d2221b5f2b965a29a4. The named branch remains checked out in another worktree and was not modified.

Canonical for #14815

This PR is the canonical Windows hook fix: one GUI-subsystem launcher for Claude (--neutral-json → {}), Cursor, and Grok; migrates existing managed configs; windowsHide: true on local/WSL hook subprocesses; taskkill /T /F on timed-out trees. That covers both causes in #14815, Cursor's invalid-JSON block (#14818), Grok's console flash (#14828), and the conhost hang/orphan class (#14837).

#14825 is a Claude-only predecessor that still emits conhost.exe --headless + encoded PowerShell and does not emit protocol-valid {}. Prefer this PR; do not merge #14825 first.

CodeRabbit functional threads

All 3 review threads are resolved and marked addressed in b157fd3:

Follow-up CodeRabbit pass on 8a0e793..b157fd3 (run 3091d807-5a20-45c2-9239-37f16cea92c1) posted no new actionable comments. Remaining items are nitpicks (stale content-addressed copies; JSON whitespace rewrite).

Hosted CI

Cross-repo fork PR (Tauri-EPO/orca → stablyai/orca). gh pr checks 14845 reports none. statusCheckRollup is []. Commit statuses total_count: 0. Check runs total_count: 0. mergeStateStatus: UNSTABLE.

Workflow runs exist but never spawned jobs (fork-workflow approval, approvals: []):

Maintainer action: approve/run those workflows. Independent local gates are below.

Independent Windows validation (Win 11, this worktree)

  • pnpm exec vitest run --config config/vitest.config.ts on the 6 changed test files: 6 files, 120 passed, 2.27s
  • pnpm exec oxlint --deny-warnings on changed TS/JS: exit 0
  • git diff --check origin/main...HEAD: clean
  • node config/scripts/build-windows-cli-launcher.mjs: PE subsystem 2 = IMAGE_SUBSYSTEM_WINDOWS_GUI
  • Live launcher via Process.WaitForExit (PowerShell & does not wait for winexe):
    • --neutral-json + child exit /b 7 + leaked echo: exit 7, stdout exactly {}\n, stderr empty, 68ms
    • silent (Cursor/Grok): exit 7, stdout empty, 156ms
    • missing script: exit 0, {}\n, 34ms
    • start /b ping -n 30 + blocking ping: exit 0, 3350ms, {}\n, leftover ping count 0

No objective code defect found. Did not push, merge, or close. PR is 74 commits behind main and 2 ahead; GitHub still reports MERGEABLE.

@Tauri-EPO

Copy link
Copy Markdown
Contributor Author

Formal compliance (b157fd3101a56206bddf06d2221b5f2b965a29a4)

Audited detached head in worktree review-pr-14845. No product code was modified, pushed, or merged.

PR body

Updated to match .github/pull_request_template.md / CONTRIBUTING.md without inventing proof:

Body: #14845

CodeRabbit (thread-aware GraphQL)

All 3 review threads are resolved and marked addressed in b157fd3:

Follow-up run 3091d807-5a20-45c2-9239-37f16cea92c1 posted no new actionables. Remaining items are nitpicks (stale content-addressed copies; JSON whitespace rewrite).

Hosted CI — maintainer-only blocker

Fork PR; no check runs. mergeStateStatus: UNSTABLE. Approve/run:

This pass: vitest 6/120, oxlint exit 0, git diff --check clean, launcher PE subsystem 2, live {}\n/silent probes. Worktree left clean.

@Tauri-EPO

Copy link
Copy Markdown
Contributor Author

Follow-up from live Windows regression audit (�c78e99973): startup refresh now migrates an existing managed Claude statusLine.command together with lifecycle hooks in one guarded config write. This closes the gap where CLI-unavailable refresh replaced conhost.exe lifecycle entries but could leave the legacy encoded-PowerShell statusline until a later full install. User-authored statuslines remain outside the managed matcher. Added coverage for lifecycle + statusline migration without CLI presence. Validation: focused Vitest 6 files / 120 passed; targeted oxlint --deny-warnings; ypecheck:node; git diff --check. Existing Cursor agent processes cache hook commands in memory, so already-running sessions may keep their pre-update command until restarted; no process was terminated during this audit.

@Tauri-EPO

Copy link
Copy Markdown
Contributor Author

Closing. #14825 merged as 02ba70a and rewrote the same files this branch touches (claude/hook-settings.ts, claude/hook-service.ts, cursor/hook-service.ts, grok/hook-service.ts), so this is now a competing implementation behind main rather than a fix on top of it. #14815 and #14818 are closed by that merge.

I re-verified the other two linked issues against merged main rather than assume they survived:

If anything here is still wanted — the GUI-subsystem launcher, the process deadline, or the startup config migration — it should come as a small PR on top of main, one item at a time, once there is a reproduction showing it is needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment