From 0b52d593b81bcdb9128eef858c34ae3be6c20f79 Mon Sep 17 00:00:00 2001 From: Lesley Murfin Date: Mon, 22 Jun 2026 19:49:21 -0600 Subject: [PATCH] Detect agents in the serve user's package-manager bins; don't pin empty remote-detect results (#6029) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Detect agents in the serve user's package-manager bins; don't pin empty remote-detect results Two defects prevent the desktop client from detecting agents installed on a remote `orca serve`: D1 (src/relay/relay-command-env.ts): the relay probes agents with a login shell (`/bin/sh -lc`), which sources ~/.profile but not the interactive ~/.bashrc that real PTY sessions source. Per-user package-manager bins added to PATH only in ~/.bashrc are therefore invisible to detection. Resolve the serve user's package-manager bins from $HOME (.local/bin, .npm-global/bin, .cargo/bin, .bun/bin, go/bin, .deno/bin, .local/share/pnpm), honor npm_config_prefix, append to the POSIX fallback set, dedupe against inherited PATH; win32 unchanged. D2 (src/renderer/src/store/slices/detected-agents.ts): an empty detection result ([], truthy in JS) was pinned by the `if (existing)` short-circuit, so detection never retried after the server env was fixed. Changed to `if (existing?.length)`; in-flight dedup still prevents re-detect storms; failures stay uncached. No new transport, no PowerShell/bash bridge. D1 and D2 are independent. Co-Authored-By: Claude Opus 4.8 (1M context) * Also patch the runtime (orca serve) detection path against the empty-pin bug The D2 fix guarded only ensureRemoteDetectedAgents (the SSH path). The desktop client's headline scenario — pairing to a remote `orca serve` — routes through ensureRuntimeDetectedAgents (kind: 'runtime'), which had the identical bug: an empty detection result ([], truthy in JS) was pinned by the `if (existing)` short-circuit, so a later install / PATH fix was never picked up without a reconnect. Change the runtime guard to `if (existing?.length)`, mirroring the remote path. In-flight dedup still collapses concurrent re-detects; failed requests stay uncached. Add a runtime regression test proving detection re-runs after an empty result (fails on the pre-fix guard). Co-Authored-By: Claude Opus 4.8 (1M context) * Honor package-manager relocation env vars in relay PATH detection Extend the existing npm_config_prefix precedence to cargo, bun, deno, go, and pnpm so relocated installs (CARGO_HOME, BUN_INSTALL, DENO_INSTALL, GOBIN/GOPATH, PNPM_HOME/XDG_DATA_HOME) are detected, falling back to the $HOME defaults. Mirrors the remote-node probe's NVM_DIR handling (#6037). Co-Authored-By: Claude Opus 4.8 (1M context) * Tighten remote agent detection retries Co-authored-by: Orca --------- Co-authored-by: Claude Opus 4.8 (1M context) Co-authored-by: LesleyMurfin <260182349+LesleyMurfin@users.noreply.github.com> Co-authored-by: Jinwoo-H Co-authored-by: Orca --- src/relay/relay-command-env.test.ts | 210 +++++++++++++++++- src/relay/relay-command-env.ts | 125 ++++++++++- .../src/hooks/useDetectedAgents.test.tsx | 161 ++++++++++++++ src/renderer/src/hooks/useDetectedAgents.ts | 21 +- .../src/store/slices/detected-agents.test.ts | 56 +++++ .../src/store/slices/detected-agents.ts | 10 +- 6 files changed, 576 insertions(+), 7 deletions(-) create mode 100644 src/renderer/src/hooks/useDetectedAgents.test.tsx diff --git a/src/relay/relay-command-env.test.ts b/src/relay/relay-command-env.test.ts index 3a53eae35..89602d81a 100644 --- a/src/relay/relay-command-env.test.ts +++ b/src/relay/relay-command-env.test.ts @@ -1,6 +1,11 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import { homedir } from 'os' import { buildRelayCommandEnv } from './relay-command-env' +// homedir() is the fallback when the relay env carries no HOME; mock it so the +// fallback path is deterministic and the "no resolvable home" branch is reachable. +vi.mock('os', () => ({ homedir: vi.fn(() => '/home/fallback') })) + describe('buildRelayCommandEnv', () => { it('adds POSIX git locations when the relay starts with an empty PATH', () => { const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '' }, 'linux') @@ -19,4 +24,207 @@ describe('buildRelayCommandEnv', () => { expect.arrayContaining(['C:\\Tools', 'C:\\Program Files\\Git\\cmd']) ) }) + + it('adds per-user package-manager bins resolved from HOME on POSIX', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '/usr/bin' }, 'linux') + + expect(env.PATH?.split(':')).toEqual( + expect.arrayContaining([ + '/home/me/.local/bin', + '/home/me/.npm-global/bin', + '/home/me/.cargo/bin', + '/home/me/.bun/bin', + '/home/me/go/bin', + '/home/me/.deno/bin', + '/home/me/.local/share/pnpm' + ]) + ) + }) + + it('honors a relocated npm global prefix via npm_config_prefix', () => { + const env = buildRelayCommandEnv( + { HOME: '/home/me', PATH: '', npm_config_prefix: '/opt/npm' }, + 'linux' + ) + + expect(env.PATH?.split(':')).toContain('/opt/npm/bin') + }) + + it('honors a relocated cargo home via CARGO_HOME', () => { + const env = buildRelayCommandEnv( + { HOME: '/home/me', PATH: '', CARGO_HOME: '/opt/cargo' }, + 'linux' + ) + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/cargo/bin') + expect(segments).not.toContain('/home/me/.cargo/bin') + }) + + it('honors a relocated bun install via BUN_INSTALL', () => { + const env = buildRelayCommandEnv( + { HOME: '/home/me', PATH: '', BUN_INSTALL: '/opt/bun' }, + 'linux' + ) + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/bun/bin') + expect(segments).not.toContain('/home/me/.bun/bin') + }) + + it('honors a relocated deno install via DENO_INSTALL', () => { + const env = buildRelayCommandEnv( + { HOME: '/home/me', PATH: '', DENO_INSTALL: '/opt/deno' }, + 'linux' + ) + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/deno/bin') + expect(segments).not.toContain('/home/me/.deno/bin') + }) + + it('uses GOBIN directly for the go bin directory', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '', GOBIN: '/opt/go/bin' }, 'linux') + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/go/bin') + expect(segments).not.toContain('/home/me/go/bin') + }) + + it('honors GOPATH for the go bin directory when GOBIN is unset', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '', GOPATH: '/opt/gopath' }, 'linux') + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/gopath/bin') + expect(segments).not.toContain('/home/me/go/bin') + }) + + it('honors PNPM_HOME for the pnpm global bin directory', () => { + const env = buildRelayCommandEnv( + { HOME: '/home/me', PATH: '', PNPM_HOME: '/opt/pnpm' }, + 'linux' + ) + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/pnpm') + expect(segments).not.toContain('/home/me/.local/share/pnpm') + }) + + it('honors XDG_DATA_HOME for pnpm when PNPM_HOME is unset', () => { + const env = buildRelayCommandEnv( + { HOME: '/home/me', PATH: '', XDG_DATA_HOME: '/opt/xdg' }, + 'linux' + ) + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toContain('/opt/xdg/pnpm') + expect(segments).not.toContain('/home/me/.local/share/pnpm') + }) + + it('adds the macOS pnpm home for Darwin relay envs', () => { + const env = buildRelayCommandEnv({ HOME: '/Users/me', PATH: '' }, 'darwin') + + expect(env.PATH?.split(':')).toContain('/Users/me/Library/pnpm') + }) + + it('does not leak POSIX user bins into a Windows relay env', () => { + const env = buildRelayCommandEnv({ Path: 'C:\\Tools', HOME: '/home/me' }, 'win32') + + expect(env.Path).not.toContain('/home/me/.local/bin') + expect(env.Path).not.toContain('.npm-global') + }) + + it('adds Windows user package-manager bins to a Windows relay env', () => { + const env = buildRelayCommandEnv( + { + Path: 'C:\\Tools', + APPDATA: 'C:\\Users\\me\\AppData\\Roaming', + LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local', + USERPROFILE: 'C:\\Users\\me', + PNPM_HOME: 'C:\\Users\\me\\AppData\\Local\\pnpm-home' + }, + 'win32' + ) + const segments = env.Path?.split(';') ?? [] + + expect(segments).toEqual( + expect.arrayContaining([ + 'C:\\Users\\me\\AppData\\Roaming\\npm', + 'C:\\Users\\me\\AppData\\Local\\pnpm', + 'C:\\Users\\me\\.cargo\\bin', + 'C:\\Users\\me\\.bun\\bin', + 'C:\\Users\\me\\go\\bin', + 'C:\\Users\\me\\.deno\\bin', + 'C:\\Users\\me\\AppData\\Local\\pnpm-home' + ]) + ) + }) + + it('honors relocated Windows package-manager env vars', () => { + const env = buildRelayCommandEnv( + { + Path: 'C:\\Tools', + CARGO_HOME: 'D:\\cargo', + BUN_INSTALL: 'D:\\bun', + DENO_INSTALL: 'D:\\deno', + GOBIN: 'D:\\go\\bin', + PNPM_HOME: 'D:\\pnpm' + }, + 'win32' + ) + const segments = env.Path?.split(';') ?? [] + + expect(segments).toEqual( + expect.arrayContaining([ + 'D:\\cargo\\bin', + 'D:\\bun\\bin', + 'D:\\deno\\bin', + 'D:\\go\\bin', + 'D:\\pnpm' + ]) + ) + }) + + it('deduplicates a user bin already present in the inherited PATH', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '/home/me/.local/bin' }, 'linux') + const segments = env.PATH?.split(':') ?? [] + + expect(segments.filter((s) => s === '/home/me/.local/bin')).toHaveLength(1) + }) + + it('falls back to homedir() for user bins when the relay env carries no HOME', () => { + const env = buildRelayCommandEnv({ PATH: '/usr/bin' }, 'linux') + + expect(env.PATH?.split(':')).toContain('/home/fallback/.local/bin') + expect(env.PATH).not.toContain('undefined') + }) + + it('adds only POSIX fallbacks when no home directory can be resolved', () => { + vi.mocked(homedir).mockReturnValueOnce('') + const env = buildRelayCommandEnv({ PATH: '' }, 'linux') + const segments = env.PATH?.split(':') ?? [] + + expect(segments).toEqual(expect.arrayContaining(['/usr/local/bin', '/usr/bin', '/bin'])) + expect(segments.some((s) => s.includes('.local/bin'))).toBe(false) + }) + + it('keeps inherited PATH entries ahead of the appended fallbacks', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '/custom/bin' }, 'linux') + const segments = env.PATH?.split(':') ?? [] + + expect(segments.indexOf('/custom/bin')).toBeLessThan(segments.indexOf('/usr/bin')) + }) + + it('orders the static POSIX fallbacks ahead of the resolved user bins', () => { + const env = buildRelayCommandEnv({ HOME: '/home/me', PATH: '' }, 'linux') + const segments = env.PATH?.split(':') ?? [] + + expect(segments.indexOf('/usr/bin')).toBeLessThan(segments.indexOf('/home/me/.local/bin')) + }) + + it('treats an empty-string HOME as absent and falls back to homedir()', () => { + const env = buildRelayCommandEnv({ HOME: '', PATH: '/usr/bin' }, 'linux') + + expect(env.PATH?.split(':')).toContain('/home/fallback/.local/bin') + }) }) diff --git a/src/relay/relay-command-env.ts b/src/relay/relay-command-env.ts index 2939e660f..be8e030b2 100644 --- a/src/relay/relay-command-env.ts +++ b/src/relay/relay-command-env.ts @@ -1,3 +1,6 @@ +import { homedir } from 'os' +import { posix, win32 } from 'path' + const POSIX_RELAY_PATH_FALLBACKS = ['/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin'] const WINDOWS_RELAY_PATH_FALLBACKS = [ 'C:\\Program Files\\Git\\cmd', @@ -6,6 +9,119 @@ const WINDOWS_RELAY_PATH_FALLBACKS = [ 'C:\\Windows' ] +// Why: the login-shell probe (`/bin/sh -lc`) sources ~/.profile but not the +// interactive ~/.bashrc, so per-user package-manager bins are invisible to +// detection even though the user can run those agents. Add them to PATH so the +// relay sees what interactive PTY sessions do; prefer each tool's documented +// relocation env var over the $HOME default so relocated installs stay covered. +function getPosixUserInstallBinFallbacks( + baseEnv: NodeJS.ProcessEnv, + platform: NodeJS.Platform +): string[] { + const home = baseEnv.HOME || homedir() + const bins: string[] = [] + if (baseEnv.PNPM_HOME) { + bins.push(baseEnv.PNPM_HOME) + } + if (home) { + bins.push(posix.join(home, '.local', 'bin'), posix.join(home, '.npm-global', 'bin')) + if (platform === 'darwin') { + bins.push(posix.join(home, 'Library', 'pnpm')) + } + } + const cargoBin = baseEnv.CARGO_HOME + ? posix.join(baseEnv.CARGO_HOME, 'bin') + : home + ? posix.join(home, '.cargo', 'bin') + : null + if (cargoBin) { + bins.push(cargoBin) + } + const bunBin = baseEnv.BUN_INSTALL + ? posix.join(baseEnv.BUN_INSTALL, 'bin') + : home + ? posix.join(home, '.bun', 'bin') + : null + if (bunBin) { + bins.push(bunBin) + } + const denoBin = baseEnv.DENO_INSTALL + ? posix.join(baseEnv.DENO_INSTALL, 'bin') + : home + ? posix.join(home, '.deno', 'bin') + : null + if (denoBin) { + bins.push(denoBin) + } + // GOBIN is the bin dir itself; otherwise go installs into $GOPATH/bin (default ~/go/bin). + const goBin = baseEnv.GOBIN + ? baseEnv.GOBIN + : baseEnv.GOPATH + ? posix.join(baseEnv.GOPATH, 'bin') + : home + ? posix.join(home, 'go', 'bin') + : null + if (goBin) { + bins.push(goBin) + } + // pnpm/PNPM_HOME point at the global-bin dir directly; the default lives under + // XDG_DATA_HOME (default ~/.local/share). + const pnpmHome = baseEnv.PNPM_HOME + ? null + : baseEnv.XDG_DATA_HOME + ? posix.join(baseEnv.XDG_DATA_HOME, 'pnpm') + : home + ? posix.join(home, '.local', 'share', 'pnpm') + : null + if (pnpmHome) { + bins.push(pnpmHome) + } + const npmPrefix = baseEnv.npm_config_prefix + if (npmPrefix) { + bins.push(posix.join(npmPrefix, 'bin')) + } + return bins +} + +function getWindowsUserInstallBinFallbacks(baseEnv: NodeJS.ProcessEnv): string[] { + const bins = baseEnv.PNPM_HOME ? [baseEnv.PNPM_HOME] : [] + if (baseEnv.APPDATA) { + bins.push(win32.join(baseEnv.APPDATA, 'npm')) + } + if (baseEnv.LOCALAPPDATA) { + bins.push(win32.join(baseEnv.LOCALAPPDATA, 'pnpm')) + } + if (baseEnv.CARGO_HOME) { + bins.push(win32.join(baseEnv.CARGO_HOME, 'bin')) + } + if (baseEnv.BUN_INSTALL) { + bins.push(win32.join(baseEnv.BUN_INSTALL, 'bin')) + } + if (baseEnv.DENO_INSTALL) { + bins.push(win32.join(baseEnv.DENO_INSTALL, 'bin')) + } + if (baseEnv.GOBIN) { + bins.push(baseEnv.GOBIN) + } else if (baseEnv.GOPATH) { + bins.push(win32.join(baseEnv.GOPATH, 'bin')) + } + if (baseEnv.USERPROFILE) { + if (!baseEnv.CARGO_HOME) { + bins.push(win32.join(baseEnv.USERPROFILE, '.cargo', 'bin')) + } + if (!baseEnv.BUN_INSTALL) { + bins.push(win32.join(baseEnv.USERPROFILE, '.bun', 'bin')) + } + if (!baseEnv.GOBIN && !baseEnv.GOPATH) { + bins.push(win32.join(baseEnv.USERPROFILE, 'go', 'bin')) + } + if (!baseEnv.DENO_INSTALL) { + bins.push(win32.join(baseEnv.USERPROFILE, '.deno', 'bin')) + } + } + return bins +} + function getPathKey(env: NodeJS.ProcessEnv): 'PATH' | 'Path' { return env.Path !== undefined && env.PATH === undefined ? 'Path' : 'PATH' } @@ -14,8 +130,11 @@ function getPathDelimiter(platform: NodeJS.Platform): string { return platform === 'win32' ? ';' : ':' } -function getFallbackSegments(platform: NodeJS.Platform): string[] { - return platform === 'win32' ? WINDOWS_RELAY_PATH_FALLBACKS : POSIX_RELAY_PATH_FALLBACKS +function getFallbackSegments(platform: NodeJS.Platform, baseEnv: NodeJS.ProcessEnv): string[] { + if (platform === 'win32') { + return [...WINDOWS_RELAY_PATH_FALLBACKS, ...getWindowsUserInstallBinFallbacks(baseEnv)] + } + return [...POSIX_RELAY_PATH_FALLBACKS, ...getPosixUserInstallBinFallbacks(baseEnv, platform)] } export function buildRelayCommandEnv( @@ -26,7 +145,7 @@ export function buildRelayCommandEnv( const delimiter = getPathDelimiter(platform) const segments = new Set((baseEnv[key] ?? '').split(delimiter).filter(Boolean)) - for (const segment of getFallbackSegments(platform)) { + for (const segment of getFallbackSegments(platform, baseEnv)) { segments.add(segment) } diff --git a/src/renderer/src/hooks/useDetectedAgents.test.tsx b/src/renderer/src/hooks/useDetectedAgents.test.tsx new file mode 100644 index 000000000..7e9febda3 --- /dev/null +++ b/src/renderer/src/hooks/useDetectedAgents.test.tsx @@ -0,0 +1,161 @@ +// @vitest-environment happy-dom + +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { useDetectedAgents, type AgentDetectionTarget } from './useDetectedAgents' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../shared/protocol-version' + +const detectRemoteAgents = vi.fn() +const runtimeEnvironmentCall = vi.fn() +const initialAppState = useAppStore.getInitialState() +const roots: Root[] = [] + +function HookProbe({ target }: { target: AgentDetectionTarget }): null { + useDetectedAgents(target) + return null +} + +async function flushEffects(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +async function renderProbe(target: AgentDetectionTarget): Promise { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + roots.push(root) + await act(async () => { + root.render(createElement(HookProbe, { target })) + }) + await flushEffects() + return root +} + +beforeEach(() => { + useAppStore.setState(initialAppState, true) + detectRemoteAgents.mockReset().mockResolvedValue([]) + runtimeEnvironmentCall.mockReset().mockImplementation(({ method }: { method: string }) => { + const result = + method === 'status.get' + ? { + runtimeId: 'remote-runtime', + rendererGraphEpoch: 1, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + } + : [] + return Promise.resolve({ + id: method, + ok: true, + result, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + globalThis.window.api = { + preflight: { detectRemoteAgents }, + runtimeEnvironments: { call: runtimeEnvironmentCall } + } as unknown as Window['api'] +}) + +afterEach(async () => { + for (const root of roots) { + await act(async () => { + root.unmount() + }) + } + roots.length = 0 +}) + +describe('useDetectedAgents (ssh call site)', () => { + it('fires remote detection once on mount and does not thrash after an empty result', async () => { + const root = await renderProbe({ kind: 'ssh', connectionId: 'ssh-1' }) + + // The effect fires detection once; an empty [] is stored (not null), so the + // detectedIds===null guard prevents a re-detect loop on the same surface. + expect(detectRemoteAgents).toHaveBeenCalledTimes(1) + expect(useAppStore.getState().remoteDetectedAgentIds['ssh-1']).toEqual([]) + + // Re-rendering the same connection must not trigger another probe. + await act(async () => { + root.render(createElement(HookProbe, { target: { kind: 'ssh', connectionId: 'ssh-1' } })) + }) + await flushEffects() + + expect(detectRemoteAgents).toHaveBeenCalledTimes(1) + }) + + it('retries a cached empty SSH result when the launch surface is reopened', async () => { + const firstRoot = await renderProbe({ kind: 'ssh', connectionId: 'ssh-1' }) + + expect(detectRemoteAgents).toHaveBeenCalledTimes(1) + expect(useAppStore.getState().remoteDetectedAgentIds['ssh-1']).toEqual([]) + + await act(async () => { + firstRoot.unmount() + }) + roots.splice(roots.indexOf(firstRoot), 1) + detectRemoteAgents.mockResolvedValueOnce(['kilo']) + + await renderProbe({ kind: 'ssh', connectionId: 'ssh-1' }) + + expect(detectRemoteAgents).toHaveBeenCalledTimes(2) + expect(useAppStore.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['kilo']) + }) +}) + +describe('useDetectedAgents (runtime call site)', () => { + it('retries a cached empty runtime result when the launch surface is reopened', async () => { + let detectCalls = 0 + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + let result: unknown + if (method === 'status.get') { + result = { + runtimeId: 'remote-runtime', + rendererGraphEpoch: 1, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + } + } else { + detectCalls += 1 + result = detectCalls === 1 ? [] : ['kilo'] + } + return Promise.resolve({ + id: method, + ok: true, + result, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + + const firstRoot = await renderProbe({ kind: 'runtime', environmentId: 'env-1' }) + + expect(detectCalls).toBe(1) + expect(useAppStore.getState().runtimeDetectedAgentIds['env-1']).toEqual([]) + + await act(async () => { + firstRoot.unmount() + }) + roots.splice(roots.indexOf(firstRoot), 1) + + await renderProbe({ kind: 'runtime', environmentId: 'env-1' }) + + expect(detectCalls).toBe(2) + expect(useAppStore.getState().runtimeDetectedAgentIds['env-1']).toEqual(['kilo']) + }) +}) diff --git a/src/renderer/src/hooks/useDetectedAgents.ts b/src/renderer/src/hooks/useDetectedAgents.ts index 950e68939..d4be36d0e 100644 --- a/src/renderer/src/hooks/useDetectedAgents.ts +++ b/src/renderer/src/hooks/useDetectedAgents.ts @@ -1,4 +1,4 @@ -import { useEffect } from 'react' +import { useEffect, useRef } from 'react' import { useAppStore } from '@/store' import type { TuiAgent } from '../../../shared/types' @@ -50,6 +50,7 @@ export function useDetectedAgents( connectionId: AgentDetectionTarget | string | null | undefined = null ): UseDetectedAgentsResult { const target = normalizeAgentDetectionTarget(connectionId) + const retriedEmptyTargetRef = useRef(null) // Why: undefined means "store not yet hydrated" — we don't know if the // worktree is local or remote yet. This prevents flashing local agents for // remote worktrees during hydration. @@ -96,12 +97,30 @@ export function useDetectedAgents( if (isUnknown) { return } + const emptyRetryKey = + targetKind === 'ssh' && targetId + ? `ssh:${targetId}` + : targetKind === 'runtime' && targetId + ? `runtime:${targetId}` + : null if (targetKind === 'ssh' && targetId) { if (detectedIds === null) { + retriedEmptyTargetRef.current = emptyRetryKey + void ensureRemote(targetId) + } else if (detectedIds.length === 0 && retriedEmptyTargetRef.current !== emptyRetryKey) { + // Why: a newly opened remote launch surface should get one fresh probe + // after a prior empty result, but must not spin while the host has no agents. + retriedEmptyTargetRef.current = emptyRetryKey void ensureRemote(targetId) } } else if (targetKind === 'runtime' && targetId) { if (detectedIds === null) { + retriedEmptyTargetRef.current = emptyRetryKey + void ensureRuntime(targetId) + } else if (detectedIds.length === 0 && retriedEmptyTargetRef.current !== emptyRetryKey) { + // Why: remote `orca serve` users can install/fix PATH without reconnecting; + // retry once per mounted surface so the menu can pick that up. + retriedEmptyTargetRef.current = emptyRetryKey void ensureRuntime(targetId) } } else { diff --git a/src/renderer/src/store/slices/detected-agents.test.ts b/src/renderer/src/store/slices/detected-agents.test.ts index 6554ce392..0ef08fccd 100644 --- a/src/renderer/src/store/slices/detected-agents.test.ts +++ b/src/renderer/src/store/slices/detected-agents.test.ts @@ -451,6 +451,23 @@ describe('createDetectedAgentsSlice remote detection', () => { expect(detectRemoteAgents).toHaveBeenCalledTimes(1) }) + it('re-runs remote detection after an empty result instead of pinning it', async () => { + const store = createTestStore() + // An empty [] is truthy, so a prior "no agents found" must not be cached: + // a later install / PATH fix has to be picked up without a reconnect. + detectRemoteAgents.mockResolvedValueOnce([]) + + await expect(store.getState().ensureRemoteDetectedAgents('ssh-1')).resolves.toEqual([]) + expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual([]) + expect(detectRemoteAgents).toHaveBeenCalledTimes(1) + + detectRemoteAgents.mockResolvedValueOnce(['kilo']) + + await expect(store.getState().ensureRemoteDetectedAgents('ssh-1')).resolves.toEqual(['kilo']) + expect(detectRemoteAgents).toHaveBeenCalledTimes(2) + expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['kilo']) + }) + it('detects runtime environment agents through the owning runtime', async () => { const store = createTestStore() @@ -478,4 +495,43 @@ describe('createDetectedAgentsSlice remote detection', () => { timeoutMs: undefined }) }) + + it('re-runs runtime detection after an empty result instead of pinning it', async () => { + const store = createTestStore() + // An empty [] is truthy, so a prior "no agents found" must not be cached: + // a later install / PATH fix has to be picked up without a reconnect. This is + // the Orca-serve path (kind: 'runtime'), distinct from the SSH remote path. + let detectCalls = 0 + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + let result: unknown + if (method === 'status.get') { + result = { + runtimeId: 'remote-runtime', + rendererGraphEpoch: 1, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + } + } else { + detectCalls += 1 + result = detectCalls === 1 ? [] : ['kilo'] + } + return Promise.resolve({ + id: method, + ok: true, + result, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + + await expect(store.getState().ensureRuntimeDetectedAgents('env-1')).resolves.toEqual([]) + expect(store.getState().runtimeDetectedAgentIds['env-1']).toEqual([]) + + await expect(store.getState().ensureRuntimeDetectedAgents('env-1')).resolves.toEqual(['kilo']) + expect(store.getState().runtimeDetectedAgentIds['env-1']).toEqual(['kilo']) + expect(detectCalls).toBe(2) + }) }) diff --git a/src/renderer/src/store/slices/detected-agents.ts b/src/renderer/src/store/slices/detected-agents.ts index f84c42a49..4c6cdf372 100644 --- a/src/renderer/src/store/slices/detected-agents.ts +++ b/src/renderer/src/store/slices/detected-agents.ts @@ -185,7 +185,10 @@ export const createDetectedAgentsSlice: StateCreator { const existing = get().remoteDetectedAgentIds[connectionId] - if (existing) { + // Why: an empty result ([]) is truthy, so a prior "no agents found" detection + // must not be treated as cached — re-detect so a later install / PATH fix is + // picked up without a reconnect. Non-empty results still short-circuit. + if (existing?.length) { return Promise.resolve(existing) } const inflight = remoteDetectPromises.get(connectionId) @@ -242,7 +245,10 @@ export const createDetectedAgentsSlice: StateCreator { const existing = get().runtimeDetectedAgentIds[environmentId] - if (existing) { + // Why: an empty result ([]) is truthy, so a prior "no agents found" detection + // must not be treated as cached — re-detect so a later install / PATH fix is + // picked up without a reconnect. Non-empty results still short-circuit. + if (existing?.length) { return Promise.resolve(existing) } const inflight = runtimeDetectPromises.get(environmentId)