Repository navigation
fix(agent-hooks): skip unavailable agent homes - #11442
Conversation
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
Greptile SummaryThis 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.
Confidence Score: 5/5Safe 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.
|
| 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
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (4)
src/main/agent-hooks/local-agent-cli-presence.ts (1)
169-174: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winParallelize PATH candidate probing.
Each candidate is probed sequentially (
awaitinside aforloop), andprobePathCandidateitself 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 winAdd coverage for the detection-failure (fail-closed) path.
No test exercises
detectLocalManagedAgentCliPresencerejecting, which is the branch that producescli_presence_unknown/agent_disabledskip 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 winConsider 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 valueRemove 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
📒 Files selected for processing (36)
config/tsconfig.cli.jsonsrc/cli/handlers/agent-hooks.tssrc/main/agent-hooks/install-telemetry.test.tssrc/main/agent-hooks/install-telemetry.tssrc/main/agent-hooks/local-agent-cli-presence.test.tssrc/main/agent-hooks/local-agent-cli-presence.tssrc/main/agent-hooks/managed-agent-hook-controls.test.tssrc/main/agent-hooks/managed-agent-hook-controls.tssrc/main/agent-hooks/managed-agent-hook-registry.tssrc/main/agent-hooks/managed-hook-detection-commands.test.tssrc/main/agent-hooks/managed-hook-detection-commands.tssrc/main/agent-hooks/managed-hook-local-filesystem.test.tssrc/main/agent-hooks/managed-hook-runtime.tssrc/main/agent-hooks/remote-hook-service-installers.test.tssrc/main/agent-hooks/remote-managed-hook-installers.tssrc/main/agent-hooks/wsl-hook-fs-adapter.tssrc/main/agent-hooks/wsl-hook-relay-deps.tssrc/main/agent-hooks/wsl-hook-relay-live.integration.test.tssrc/main/agent-hooks/wsl-hook-relay-manager.test.tssrc/main/agent-hooks/wsl-hook-relay-manager.tssrc/main/agent-hooks/wsl-hook-relay-state-key.tssrc/main/index.tssrc/main/ipc/settings.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/client-ui.tssrc/main/ssh/ssh-relay-session-managed-hooks.test.tssrc/main/ssh/ssh-relay-session.test.tssrc/main/ssh/ssh-relay-session.tssrc/relay/managed-hook-installer.test.tssrc/relay/managed-hook-installer.tssrc/relay/wsl-agent-hook-relay.tssrc/shared/agent-hook-relay.tssrc/shared/agent-hook-types.tssrc/shared/managed-agent-command-token.tssrc/shared/managed-agent-hook-targets.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/ipc/settings.test.ts (1)
131-150: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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
applyAgentStatusHooksEnabledMockis 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
📒 Files selected for processing (8)
src/main/agent-hooks/local-agent-cli-presence.test.tssrc/main/agent-hooks/local-agent-cli-presence.tssrc/main/ipc/settings.test.tssrc/main/ipc/settings.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/shared/tui-agent-selection.test.tssrc/shared/tui-agent-selection.ts
There was a problem hiding this comment.
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 winReconcile hooks after
updateClientSettingscommits
this.reconcileManagedAgentHooks()catches hook-install failures and queues a stable reconciliation tail, butupdateClientSettings()awaits the same promise without catching failures. Sincestore.updateSettings()already commits before the await, wrap the reconciliation incatch/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 winVerify
shouldContinuesemantics; strengthen the "reads current settings" assertion.Two concerns with this test:
firstOptions?.shouldContinue?.('claude')is asserted to betrueat a point where the live settings (disabledTuiAgents) have already been mutated to[]by the secondupdateClientSettingscall. WhethershouldContinueis 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 insrc/main/runtime/orca-runtime.ts, which isn't included in this file set. Please confirm this assertion matches the intended semantics.- The final assertion (
toHaveBeenLastCalledWith(..., { disabledTuiAgents: [] }, ...)) only checks that the queued call's settings match whatseconditself requested — this is true whether the implementation captures a snapshot at enqueue time or re-readsgetSettings()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 betweensecond's enqueue andfirst's resolution, then asserting the queued run reflects that latest state rather thansecond'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
📒 Files selected for processing (11)
src/main/agent-hooks/local-agent-cli-presence.test.tssrc/main/agent-hooks/local-agent-cli-presence.tssrc/main/agent-hooks/managed-agent-hook-controls.test.tssrc/main/index.tssrc/main/ipc/settings.test.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/relay/managed-hook-installer.test.tssrc/relay/managed-hook-installer.tssrc/shared/agent-hook-relay.tssrc/shared/managed-agent-command-token.test.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)
1747-1750: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPin the platform for the
shouldHydrateShellPathassertion.The assertion
shouldHydrateShellPath: process.platform !== 'win32're-evaluatesprocess.platformat 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 existingsetPlatform('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')expectingshouldHydrateShellPath: false.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f8fc6bb0-5697-472b-82bc-7a48843cb500
📒 Files selected for processing (2)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.ts
Electron validationValidated the final branch in a fresh isolated Orca dev profile over CDP.
Agents settingsUnavailable-agent separationScope 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. |
Docker SSH validationValidated the exact final SHA
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. |
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).
* 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]>
* 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
…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]>



Summary
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 typecheckpnpm run lintgit diff --check