Skip to content

fix(agent-hooks): skip unavailable agent homes - #11442

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/find-pi-omp-home
Jul 30, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/find-pi-omp-home

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • install managed hooks only for positively detected, enabled agent CLIs across local, SSH, and WSL runtimes
  • fail closed on missing or unknown CLI presence, remove hooks for disabled agents, and guard overlapping settings reconciliations
  • avoid opening SSH SFTP or mutating remote and WSL homes when no supported agents are detected

Related work

This supersedes the current-architecture approach in #7474 and keeps installed-CLI hook gating focused in one PR.

It complements #10198, which remains separate and owns the Pi/OMP bare-shell home behavior. Together they address the related symptoms in #10196 without coupling independent changes.

Addresses #10196.

Verification

  • pnpm run typecheck
  • pnpm run lint
  • focused affected suite: 15 files, 1,064 passed, 1 skipped
  • git diff --check

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds managed-agent target metadata, command-token validation, platform-aware local CLI detection, structured installation statuses, and centralized hook registries. Local, remote, WSL, and SSH installation flows now preflight agent availability and apply agent allowlists. Startup, CLI persistence, IPC settings, runtime settings updates, and RPC handling now support asynchronous hook reconciliation with continuation checks and failure telemetry. Tests cover detection, selective installation, relay behavior, settings reconciliation, and telemetry.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description has Summary/Related work/Verification, but it omits required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections; include a no-visual-change screenshots note, checklist-style testing results, review notes, security audit, and any platform-specific notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main theme of skipping unavailable agent home handling, though it’s narrower than the full managed-hook changeset.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

Comment thread src/main/runtime/orca-runtime.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR tightens the managed-hook installation pipeline so hooks are only written for agent CLIs that are positively detected as present, and actively removes them when agents are disabled. It is the second of two coordinated changes addressing #10196.

  • CLI-gated installs: A new detectLocalManagedAgentCliPresence module probes the PATH (with Windows PATHEXT, home-relative overrides, and symlink handling) before running any installer; the same gate is added to SSH and WSL flows via preflight.detectAgents round-trips.
  • Disabled-agent removal: applyAgentStatusHooksEnabled now explicitly calls removeManagedAgentHooks for any agent in disabledTuiAgents after install, with a shouldContinue race guard to skip the removal if settings changed concurrently.
  • No-op guard and serialized reconciliation: haveSameDisabledTuiAgents prevents redundant async reconciliation when the disabled-agent set is reordered but unchanged; OrcaRuntimeService serializes paired-client reconciliations with a generation counter so only the latest settings win.

Confidence Score: 5/5

Safe to merge. All three reconciliation paths consistently detect CLIs before installing hooks, hydrate the shell PATH on packaged builds, and guard against concurrent settings changes.

The logic across local, SSH, and WSL hook installation paths is coherent and symmetric. Fail-closed semantics are exercised by dedicated tests. Previously flagged gaps are addressed. No incorrect filtering, dropped state, broken contracts, or auth boundary issues found.

Files Needing Attention: No files require special attention. The most complex new logic in managed-agent-hook-controls.ts and orca-runtime.ts both have targeted regression tests.

Important Files Changed

Filename Overview
src/main/agent-hooks/managed-agent-hook-controls.ts Core control plane refactored: installManagedAgentHooks now async with CLI-presence gating and fail-closed detection; applyAgentStatusHooksEnabled properly removes hooks for disabled agents with shouldContinue race guard.
src/main/agent-hooks/local-agent-cli-presence.ts New module: probes PATH for managed agent CLIs, handling deduplication, Windows PATHEXT, home-relative overrides, absolute-path overrides, and shell PATH hydration with a warn-and-fallback on error.
src/main/runtime/orca-runtime.ts Added reconcileManagedAgentHooks with generation-counter serialization; updateClientSettings now async and guards on haveSameDisabledTuiAgents to avoid no-op reconciliation.
src/main/ssh/ssh-relay-session.ts installManagedHooksOnRemote moved to fire-and-forget after PTY registration; preflight.detectAgents gates hook installs on detected agent CLIs.
src/main/agent-hooks/wsl-hook-fs-adapter.ts installWslGuestHooks now calls preflight.detectAgents before mutating the WSL guest home; fails closed on detection error.
src/relay/managed-hook-installer.ts readAgents validates the agents allowlist; returns [] (fail-closed) when agents key is absent.
src/shared/managed-agent-command-token.ts New module: shell-safe command tokenizer and isSafeOverrideExecutableToken for injection filtering.
src/main/ipc/settings.ts Settings handler triggers hook reconciliation on disabledTuiAgents changes using haveSameDisabledTuiAgents to skip no-ops.
src/shared/tui-agent-selection.ts Added haveSameDisabledTuiAgents for set-equality comparison of normalized disabled-agent lists.
src/main/agent-hooks/managed-hook-detection-commands.ts New module: builds detection command list for preflight.detectAgents RPC; maps detected TUI IDs back to AgentHookTarget.

Reviews (6): Last reviewed commit: "fix(agent-hooks): hydrate PATH for paire..." | Re-trigger Greptile

@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: 5

🧹 Nitpick comments (4)
src/main/agent-hooks/local-agent-cli-presence.ts (1)

169-174: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Parallelize PATH candidate probing.

Each candidate is probed sequentially (await inside a for loop), and probePathCandidate itself sequentially scans every PATH directory/extension. Since most target CLIs won't be installed for a given user (the exact scenario this PR targets), most candidates will run a full sequential PATH scan, adding up across ~14 agents on every install/reconciliation.

⚡ Proposed fix: probe candidates concurrently
-  const found = new Set<string>()
-  for (const candidate of candidates) {
-    if (await probePathCandidate(candidate, dirs, platform, fileProbe, options.pathExt)) {
-      found.add(candidate)
-    }
-  }
+  const found = new Set<string>()
+  await Promise.all(
+    [...candidates].map(async (candidate) => {
+      if (await probePathCandidate(candidate, dirs, platform, fileProbe, options.pathExt)) {
+        found.add(candidate)
+      }
+    })
+  )
src/main/agent-hooks/managed-agent-hook-controls.test.ts (1)

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

Add coverage for the detection-failure (fail-closed) path.

No test exercises detectLocalManagedAgentCliPresence rejecting, which is the branch that produces cli_presence_unknown/agent_disabled skip statuses for every agent — a core "fail closed" guarantee this PR introduces.

✅ Suggested additional test
it('fails closed and skips every agent when detection throws', async () => {
  mocks.detect.mockRejectedValue(new Error('probe failed'))

  const results = await installManagedAgentHooks({
    agentCmdOverrides: {},
    disabledTuiAgents: ['claude']
  })

  expect(mocks.installClaude).not.toHaveBeenCalled()
  expect(mocks.installCodex).not.toHaveBeenCalled()
  expect(results).toEqual([
    expect.objectContaining({ agent: 'claude', state: 'skipped', skipReason: 'agent_disabled' }),
    expect.objectContaining({ agent: 'codex', state: 'skipped', skipReason: 'cli_presence_unknown' })
  ])
})
src/shared/managed-agent-command-token.ts (1)

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

Consider dedicated unit tests for this token-parsing module.

This module handles security-sensitive parsing (quoting, escaping, path-safety checks) that gates command strings used in detection/install flows, but it has no direct test file — coverage is only incidental via managed-hook-detection-commands.test.ts. Direct tests for quote/escape edge cases, .. traversal, and metacharacter rejection would harden this boundary.

src/main/agent-hooks/install-telemetry.test.ts (1)

19-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove duplicated tuple type element.

The cast type [string, { agent: string; error_message: string }, { agent: string; error_message: string }] duplicates the second element; only two values are destructured (eventName, props).

🧹 Suggested cleanup
     const [eventName, props] = trackMock.mock.calls[0] as [
       string,
-      { agent: string; error_message: string },
       { agent: string; error_message: string }
     ]

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 207b6729-5992-4caf-970e-9af5de76aa7e

📥 Commits

Reviewing files that changed from the base of the PR and between 5e00a30 and 604dcf4.

📒 Files selected for processing (36)
  • config/tsconfig.cli.json
  • src/cli/handlers/agent-hooks.ts
  • src/main/agent-hooks/install-telemetry.test.ts
  • src/main/agent-hooks/install-telemetry.ts
  • src/main/agent-hooks/local-agent-cli-presence.test.ts
  • src/main/agent-hooks/local-agent-cli-presence.ts
  • src/main/agent-hooks/managed-agent-hook-controls.test.ts
  • src/main/agent-hooks/managed-agent-hook-controls.ts
  • src/main/agent-hooks/managed-agent-hook-registry.ts
  • src/main/agent-hooks/managed-hook-detection-commands.test.ts
  • src/main/agent-hooks/managed-hook-detection-commands.ts
  • src/main/agent-hooks/managed-hook-local-filesystem.test.ts
  • src/main/agent-hooks/managed-hook-runtime.ts
  • src/main/agent-hooks/remote-hook-service-installers.test.ts
  • src/main/agent-hooks/remote-managed-hook-installers.ts
  • src/main/agent-hooks/wsl-hook-fs-adapter.ts
  • src/main/agent-hooks/wsl-hook-relay-deps.ts
  • src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.ts
  • src/main/agent-hooks/wsl-hook-relay-state-key.ts
  • src/main/index.ts
  • src/main/ipc/settings.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/client-ui.ts
  • src/main/ssh/ssh-relay-session-managed-hooks.test.ts
  • src/main/ssh/ssh-relay-session.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/managed-hook-installer.test.ts
  • src/relay/managed-hook-installer.ts
  • src/relay/wsl-agent-hook-relay.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/agent-hook-types.ts
  • src/shared/managed-agent-command-token.ts
  • src/shared/managed-agent-hook-targets.ts

Comment thread src/main/index.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/relay/managed-hook-installer.ts Resolved

@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.

🧹 Nitpick comments (1)
src/main/ipc/settings.test.ts (1)

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

Add a positive reconciliation test.

This verifies only that reordered members do not reconcile. Add a companion case that changes the disabled-agent set and asserts applyAgentStatusHooksEnabledMock is called with the updated settings.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e3fa2569-7683-4d95-aaca-2ead10242748

📥 Commits

Reviewing files that changed from the base of the PR and between 604dcf4 and f24625c.

📒 Files selected for processing (8)
  • src/main/agent-hooks/local-agent-cli-presence.test.ts
  • src/main/agent-hooks/local-agent-cli-presence.ts
  • src/main/ipc/settings.test.ts
  • src/main/ipc/settings.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/tui-agent-selection.test.ts
  • src/shared/tui-agent-selection.ts

Comment thread src/main/runtime/orca-runtime.ts Resolved

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)

3373-3411: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reconcile hooks after updateClientSettings commits

this.reconcileManagedAgentHooks() catches hook-install failures and queues a stable reconciliation tail, but updateClientSettings() awaits the same promise without catching failures. Since store.updateSettings() already commits before the await, wrap the reconciliation in catch/fire-and-forget so a hook install error cannot make the persisted settings update report failure.

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)

1749-1787: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Verify shouldContinue semantics; strengthen the "reads current settings" assertion.

Two concerns with this test:

  1. firstOptions?.shouldContinue?.('claude') is asserted to be true at a point where the live settings (disabledTuiAgents) have already been mutated to [] by the second updateClientSettings call. Whether shouldContinue is meant to check a frozen snapshot from its own call (making this trivially true) or re-check against current/live settings (where the expected result is less obvious, since 'claude' is no longer disabled) depends on the implementation in src/main/runtime/orca-runtime.ts, which isn't included in this file set. Please confirm this assertion matches the intended semantics.
  2. The final assertion (toHaveBeenLastCalledWith(..., { disabledTuiAgents: [] }, ...)) only checks that the queued call's settings match what second itself requested — this is true whether the implementation captures a snapshot at enqueue time or re-reads getSettings() at dispatch time, since nothing else mutates settings in between. To truly validate "reads current settings" per the test title, consider interleaving a third settings change between second's enqueue and first's resolution, then asserting the queued run reflects that latest state rather than second's enqueue-time value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cc63a221-918e-4eaf-87dc-5981b307221d

📥 Commits

Reviewing files that changed from the base of the PR and between f24625c and a64cf4c.

📒 Files selected for processing (11)
  • src/main/agent-hooks/local-agent-cli-presence.test.ts
  • src/main/agent-hooks/local-agent-cli-presence.ts
  • src/main/agent-hooks/managed-agent-hook-controls.test.ts
  • src/main/index.ts
  • src/main/ipc/settings.test.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/relay/managed-hook-installer.test.ts
  • src/relay/managed-hook-installer.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/managed-agent-command-token.test.ts

@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.

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)

1747-1750: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Pin the platform for the shouldHydrateShellPath assertion.

The assertion shouldHydrateShellPath: process.platform !== 'win32' re-evaluates process.platform at assertion time, so it will always match whatever the implementation computes from the same expression — the test can't catch a regression where the implementation flips the condition unless CI happens to run on Windows. Consider using the existing setPlatform('win32')/setPlatform('darwin') helpers (used elsewhere in this file) to deterministically exercise both branches.

♻️ Suggested fix
   it('reconciles hooks only when paired-client hook settings change', async () => {
     electronMocks.app.isPackaged = true
+    setPlatform('darwin')
     let settings = {

and add a second assertion (or separate test) with setPlatform('win32') expecting shouldHydrateShellPath: false.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f8fc6bb0-5697-472b-82bc-7a48843cb500

📥 Commits

Reviewing files that changed from the base of the PR and between a64cf4c and 9254946.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron validation

Validated the final branch in a fresh isolated Orca dev profile over CDP.

  • instance: merrow @ brennanb2025/find-pi-omp-home
  • worktree: /Users/brennanbenson/orca/workspaces/orca/merrow
  • exercised the real Settings button and Agents navigation
  • visible result: Agent status hooks are enabled, 7 installed agents are detected, and Pi is separated under Available to install
  • backing state matched the UI: detected agents were claude, claude-agent-teams, codex, omp, gemini, antigravity, and grok; disabled agents were empty

Agents settings

Agents settings showing the Agent status hooks control and detected-agent count

Unavailable-agent separation

Available to install section showing Pi outside the detected installed-agent set

Scope note: I did not toggle hook installation or agent enabled state during the Electron pass because that would intentionally modify host agent config files. Mutation behavior remains covered by the focused tests and green CI.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Docker SSH validation

Validated the exact final SHA 9254946b3e56fb08e4a5a9fa519fbb59a71d08d3 against a disposable Debian Bookworm ARM64 SSH host through the real Electron → SSH relay path.

  • No supported CLI: no agent config or ~/.orca/agent-hooks/*-hook.sh files were created.
  • Exactly one supported CLI (claude): only ~/.claude/settings.json and executable ~/.orca/agent-hooks/claude-hook.sh were installed; no other agent homes were touched.
  • Relay allowlist: omitted agents was a no-op (0 installers, 0 errors); an invalid agent was rejected with invalid_managed_hook_agents; existing managed-file hashes stayed unchanged.
  • Real remote PTY: Orca injected the hook endpoint/token/pane environment. The installed Claude hook posted both working and done events with the expected connection, worktree, and pane identities; the renderer store and live activity row matched.
  • Real remote Git operation: the same Orca PTY created a branch, linked worktree, and file successfully on the SSH host.
  • Logs: no hook, relay, or daemon errors.
  • Focused regression suite: 8 files, 56 tests passed.
  • Build/CI: pnpm build:relay passed for every relay target; GitHub reports 43 successful checks, four expected skips, and no merge conflict.

Live Claude working event from the installed hook on the disposable Docker SSH host

This covers the highest-risk runtime boundary for this PR: positive CLI detection, selective remote mutation, relay authorization, hook delivery, and UI receipt on an actual SSH session. Pi/OMP bare-shell HOME behavior remains intentionally owned by #10198 rather than this hook-installation PR.

Verdict: land.

@brennanb2025
brennanb2025 merged commit f8b553b into main Jul 30, 2026
47 checks passed
bbingz added a commit to bbingz/orca that referenced this pull request Aug 11, 2026
Omit/empty agents no longer means install every remote managed hook.
Closes the remaining hole after stablyai#11442 that recreated uninstalled
agent config homes via the relay/SSH/WSL install path (stablyai#11641).
brennanb2025 added a commit that referenced this pull request Aug 13, 2026
* fix(agent-hooks): fail closed without detected agent allowlist

Omit/empty agents no longer means install every remote managed hook.
Closes the remaining hole after #11442 that recreated uninstalled
agent config homes via the relay/SSH/WSL install path (#11641).

* test(agent-hooks): pin installManagedHooks fail-closed gate

The leaf guard already had a regression test, but the early return in
installManagedHooks was invisible to the suite: reverting it left every
agent-hooks and relay test green, because the leaf guard makes the summary
identical and the only delta is side effects (GROK_HOME login-shell probe,
host-identity read, ~/.orca mkdir + install lock).

---------

Co-authored-by: Brennan Benson <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(agent-hooks): skip unavailable agent homes

* refactor(agent-hooks): separate Pi and OMP home fix

* test(agent-hooks): update merged protocol harnesses

* fix(agent-hooks): avoid redundant reconciliation

* fix(agent-hooks): harden reconciliation and detection

* test(agent-hooks): cover settings reconciliation

* fix(agent-hooks): hydrate PATH for paired clients
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#11676)

* fix(agent-hooks): fail closed without detected agent allowlist

Omit/empty agents no longer means install every remote managed hook.
Closes the remaining hole after stablyai#11442 that recreated uninstalled
agent config homes via the relay/SSH/WSL install path (stablyai#11641).

* test(agent-hooks): pin installManagedHooks fail-closed gate

The leaf guard already had a regression test, but the early return in
installManagedHooks was invisible to the suite: reverting it left every
agent-hooks and relay test green, because the leaf guard makes the summary
identical and the only delta is side effects (GROK_HOME login-shell probe,
host-identity read, ~/.orca mkdir + install lock).

---------

Co-authored-by: Brennan Benson <[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

Development

Successfully merging this pull request may close these issues.

1 participant