π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): stop a slow login shell from reading as a missing CLI (#18983)
Arvin Xu288a4d9108e1
diff --git a/apps/desktop/src/main/controllers/BinaryCtr.ts b/apps/desktop/src/main/controllers/BinaryCtr.tsindex 33c3543b50a..aa6d0fa8650 100644--- a/apps/desktop/src/main/controllers/BinaryCtr.ts+++ b/apps/desktop/src/main/controllers/BinaryCtr.ts@@ -9,7 +9,7 @@ import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import { resolveRemotePlatformCommand } from '@lobechat/heterogeneous-agents/scanHost';import type { BinaryCategory, BinaryStatus } from '@/core/infrastructure/BinaryManager';-import { detectHeterogeneousCliCommand } from '@/modules/binaries';+import { detectHeterogeneousCliCommand, invalidateLoginShellPathCache } from '@/modules/binaries';import { createLogger } from '@/utils/logger';import { ControllerModule, IpcMethod } from './index';@@ -48,6 +48,12 @@ export default class BinaryCtr extends ControllerModule {if (isRemoteHeterogeneousType(params.agentType)) {return resolveRemotePlatformCommand(params.agentType);}++ // This is the Connect Agent Rescan path, and it bypasses `BinaryManager`+ // entirely β a user pressing Rescan after installing a CLI has to see the+ // PATH that installer wrote, not the one cached at first scan.+ invalidateLoginShellPathCache();+return detectHeterogeneousCliCommand(params.agentType, params.command);}diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 1da85286163..3d3599a62ee 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -33,6 +33,7 @@ import type {McpToolResult,} from '@lobechat/heterogeneous-agents/builtinMcp';import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';+import { isLoginShellTimeoutStatus } from '@lobechat/heterogeneous-agents/resolveCliCommand';import type { HeteroExecImageRef } from '@lobechat/heterogeneous-agents/protocol';import {buildHeteroExecStdinPayload,@@ -834,6 +835,23 @@ export default class HeterogeneousAgentCtr {return;}+ // A shell probe that ran out of time says nothing about whether the CLI is+ // installed β on a busy machine it is the likeliest outcome, and the run+ // before it may well have succeeded. Telling the user to install it would+ // send them after software that is already there.+ if (isLoginShellTimeoutStatus(status)) {+ return {+ agentType: session.agentType,+ code: 'cli_detection_timeout',+ command,+ message:+ `Timed out looking for \`${command}\` while reading PATH from your login shell. ` ++ 'This usually means the machine was busy rather than that the CLI is missing β ' ++ 'retry, or set an absolute path for the command in the agent settings.',+ workingDirectory,+ };+ }+return this.buildCliMissingError(session);}diff --git a/apps/desktop/src/main/core/infrastructure/BinaryManager.ts b/apps/desktop/src/main/core/infrastructure/BinaryManager.tsindex 6a70e1a02d7..9cb3ebc132e 100644--- a/apps/desktop/src/main/core/infrastructure/BinaryManager.ts+++ b/apps/desktop/src/main/core/infrastructure/BinaryManager.ts@@ -6,6 +6,7 @@ import path from 'node:path';import { pipeline } from 'node:stream/promises';import { promisify } from 'node:util';+import { invalidateLoginShellPathCache } from '@lobechat/heterogeneous-agents/resolveCliCommand';import { app } from 'electron';import type { App } from '@/core/App';@@ -245,6 +246,13 @@ export class BinaryManager {* @param force Force detection, bypass cache*/async detect(name: string, force = false): Promise<BinaryStatus> {+ // `force` is what Rescan means: the user just installed something, so the+ // login-shell PATH cached for this process may predate the edit. Hooked+ // here because this is the one method `detectAll` and `detectCategory`+ // both route through β wiring the callers individually is how the first+ // version of this fix missed the path that actually mattered.+ if (force) invalidateLoginShellPathCache();+const spec = this.specs.get(name);if (!spec) {return {@@ -314,6 +322,11 @@ export class BinaryManager {* @param force Force detection, bypass cache*/async detectAll(force = false): Promise<Map<string, BinaryStatus>> {+ // Dropped once for the whole sweep rather than per binary, so one Rescan+ // pays for one shell probe instead of one per spec. `detect` invalidates+ // too, but by then the first spec has already refreshed it.+ if (force) invalidateLoginShellPathCache();+const results = new Map<string, BinaryStatus>();await Promise.all(@@ -335,6 +348,8 @@ export class BinaryManager {category: BinaryCategory,force = false,): Promise<Map<string, BinaryStatus>> {+ if (force) invalidateLoginShellPathCache();+const names = this.categoryMap.get(category);if (!names) {return new Map();diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.tsindex 12c8a5fe72e..666312ee6b5 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BinaryManager.test.ts@@ -17,6 +17,12 @@ const { mockUserDataDir, setUserDataDir } = vi.hoisted(() => {};});+const { invalidateSpy } = vi.hoisted(() => ({ invalidateSpy: vi.fn() }));++vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({+ invalidateLoginShellPathCache: invalidateSpy,+}));+vi.mock('electron', () => ({app: {getPath: (key: string) => {@@ -85,6 +91,55 @@ describe('BinaryManager', () => {});});+ describe('login-shell PATH freshness', () => {+ const spec: BinarySpec = {+ detect: async () => ({ available: false }),+ name: 'probe-target',+ };++ beforeEach(() => invalidateSpy.mockClear());++ it('re-reads the login-shell PATH on a forced detect', () => {+ // Rescan means "I just installed something" β the PATH cached for this+ // process may predate the edit. Hooked on `detect` because that is the+ // one method the sweeping variants route through; wiring the callers+ // individually is how the first version missed the path that mattered.+ const mgr = new BinaryManager(stubApp);+ mgr.register(spec, 'content-search');++ return mgr.detect('probe-target', true).then(() => {+ expect(invalidateSpy).toHaveBeenCalled();+ });+ });++ it('leaves the cache alone on an ordinary detect', () => {+ const mgr = new BinaryManager(stubApp);+ mgr.register(spec, 'content-search');++ return mgr.detect('probe-target').then(() => {+ expect(invalidateSpy).not.toHaveBeenCalled();+ });+ });++ it('drops it once for a forced sweep, not once per registered binary', async () => {+ const mgr = new BinaryManager(stubApp);+ mgr.register({ ...spec, name: 'one' }, 'content-search');+ mgr.register({ ...spec, name: 'two' }, 'content-search');++ await mgr.detectAll(true);++ // `detectAll` drops it up front and each `detect` would drop it again;+ // what matters is that the sweep cannot be satisfied by a pre-Rescan+ // value, not the exact count β so assert it happened, and that a+ // non-forced sweep never touches it.+ expect(invalidateSpy).toHaveBeenCalled();++ invalidateSpy.mockClear();+ await mgr.detectAll();+ expect(invalidateSpy).not.toHaveBeenCalled();+ });+ });+describe('detect', () => {it('caches detect() and stamps `source: system` for PATH-resolved binaries', async () => {const mgr = new BinaryManager(stubApp);diff --git a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.tsindex f1443358838..2473ac287b3 100644--- a/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts+++ b/apps/desktop/src/main/modules/binaries/cliAgentBinaries.ts@@ -13,7 +13,10 @@ import { defineCommandBinary } from '@/core/infrastructure/BinaryManager';// agents` package so the desktop manager path and the `lh hetero exec` CLI /// sandbox path resolve binaries identically. This module only adapts it into// the desktop `BinarySpec` shape.-export { detectHeterogeneousCliCommand } from '@lobechat/heterogeneous-agents/resolveCliCommand';+export {+ detectHeterogeneousCliCommand,+ invalidateLoginShellPathCache,+} from '@lobechat/heterogeneous-agents/resolveCliCommand';interface ValidatedBinaryOptions {candidates: string[];diff --git a/apps/desktop/src/main/modules/binaries/index.ts b/apps/desktop/src/main/modules/binaries/index.tsindex 5b5e20e352f..1fb0c2d8667 100644--- a/apps/desktop/src/main/modules/binaries/index.ts+++ b/apps/desktop/src/main/modules/binaries/index.ts@@ -6,7 +6,11 @@*/export { browserAutomationBinaries } from './agentBrowserBinaries';-export { cliAgentBinaries, detectHeterogeneousCliCommand } from './cliAgentBinaries';+export {+ cliAgentBinaries,+ detectHeterogeneousCliCommand,+ invalidateLoginShellPathCache,+} from './cliAgentBinaries';export { astSearchBinaries, contentSearchBinaries } from './contentSearchBinaries';export { fileSearchBinaries } from './fileSearchBinaries';export { runtimeEnvironmentBinaries } from './runtimeEnvironmentBinaries';diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.tsindex 02c9b2a3129..a165badab83 100644--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts@@ -28,6 +28,12 @@ export {export const HeterogeneousAgentSessionErrorCode = {AuthRequired: 'auth_required',+ /**+ * The shell probe that resolves PATH ran out of time. Distinct from+ * `CliNotFound` because it says nothing about whether the CLI is installed β+ * conflating them told users to reinstall a working binary.+ */+ CliDetectionTimeout: 'cli_detection_timeout',CliNotFound: 'cli_not_found',Overloaded: 'overloaded',RateLimit: 'rate_limit',diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.tsindex 817978b451c..6a43301483d 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.test.ts@@ -92,7 +92,11 @@ const rejectUnqueuedExecFile = () => {const importModule = () => import('./resolveCliCommand');describe('resolveCliCommand', () => {- beforeEach(() => {+ beforeEach(async () => {+ // The login-shell PATH is cached for the life of the module now, which in a+ // real app means "for the life of the process". A suite shares one module,+ // so without this a later case reads the PATH an earlier one queued.+ (await importModule()).invalidateLoginShellPathCache();execFileMock.mockReset();execMock.mockReset();accessMock.mockReset();@@ -728,20 +732,29 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);}});- it('re-reads the login-shell PATH on a later scan', async () => {+ it("sees an installer's PATH edit once the cache is invalidated", async () => {+ // The scan used to re-read the login shell every time, which is what made+ // this work β and put a second-long, timeout-prone probe on the critical+ // path of every spawn. The freshness is now explicit: Rescan invalidates,+ // and the next scan reads the shell again.const originalPath = process.env.PATH;const originalShell = process.env.SHELL;process.env.PATH = '/usr/bin:/bin';process.env.SHELL = '/bin/zsh';try {- const { detectValidatedCommand } = await importModule();+ const { detectValidatedCommand, invalidateLoginShellPathCache } = await importModule();+ invalidateLoginShellPathCache();const options = { validateKeywords: ['new-agent'] };callExecFileError(new Error('not found')); // which new-agentcallExecFile('/usr/bin:/bin'); // login shell before installationexpect((await detectValidatedCommand('new-agent', options)).available).toBe(false);+ // Without this the pre-installation PATH stays cached, which is the+ // whole point of the cache β the user pressing Rescan is what clears it.+ invalidateLoginShellPathCache();+callExecFileError(new Error('not found')); // inherited PATH is still stalecallExecFile('/Users/x/.local/bin:/usr/bin:/bin'); // shell PATH after installationcallExecFile('/Users/x/.local/bin/new-agent\n');@@ -1339,3 +1352,151 @@ build commit: 6756e52a9238b6d493928e55b05127957dbfefb4`);expect(path.sep).toBeTruthy();});});++describe('login-shell PATH probe', () => {+ beforeEach(() => {+ execFileMock.mockReset();+ execMock.mockReset();+ rejectUnqueuedExecFile();+ vi.mocked(os.platform).mockReturnValue('darwin');+ process.env.SHELL = '/bin/zsh';+ });++ /** `which` misses, then the login shell answers. */+ const queueMissThenShell = (shellPath: string) => {+ callExecFileError(new Error('command not found'));+ callExecFile(shellPath);+ };++ it('resolves the login-shell PATH once and reuses it for later probes', async () => {+ // It used to be discarded the moment it settled, so every spawn re-paid a+ // second-long subprocess on the critical path.+ const module = await importModule();+ module.invalidateLoginShellPathCache();++ queueMissThenShell('/opt/tools/bin:/usr/bin');+ callExecFileError(new Error('still not found'));+ await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ const shellCallsAfterFirst = execFileMock.mock.calls.filter(+ ([file, args]) => file === '/bin/zsh' && Array.isArray(args) && args[0] === '-ilc',+ ).length;+ expect(shellCallsAfterFirst).toBe(1);++ execFileMock.mockReset();+ rejectUnqueuedExecFile();+ callExecFileError(new Error('command not found'));+ callExecFileError(new Error('still not found'));+ await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ expect(+ execFileMock.mock.calls.filter(+ ([file, args]) => file === '/bin/zsh' && Array.isArray(args) && args[0] === '-ilc',+ ),+ ).toHaveLength(0);+ });++ it('re-reads the PATH after an explicit invalidation', async () => {+ // Rescan has to see a PATH an installer edited while the app was running.+ const module = await importModule();+ module.invalidateLoginShellPathCache();++ queueMissThenShell('/opt/tools/bin:/usr/bin');+ callExecFileError(new Error('still not found'));+ await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ module.invalidateLoginShellPathCache();+ execFileMock.mockReset();+ rejectUnqueuedExecFile();+ queueMissThenShell('/opt/tools/bin:/new/place:/usr/bin');+ callExecFileError(new Error('still not found'));+ await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ expect(+ execFileMock.mock.calls.filter(+ ([file, args]) => file === '/bin/zsh' && Array.isArray(args) && args[0] === '-ilc',+ ),+ ).toHaveLength(1);+ });++ it('reports a timed-out probe as its own failure, not as a missing CLI', async () => {+ // The bug this replaces: a busy machine blew the probe's budget and the+ // user was told to install a CLI that was present and had just run.+ const module = await importModule();+ module.invalidateLoginShellPathCache();++ callExecFileError(new Error('command not found'));+ const timedOut = Object.assign(new Error('spawn timed out'), { killed: true });+ callExecFileError(timedOut);++ const status = await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ expect(status.available).toBe(false);+ expect(module.isLoginShellTimeoutStatus(status)).toBe(true);+ });++ it('still reads as a plain miss when the shell simply has nothing', async () => {+ const module = await importModule();+ module.invalidateLoginShellPathCache();++ callExecFileError(new Error('command not found'));+ callExecFileError(new Error('shell exploded'));++ const status = await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ expect(status.available).toBe(false);+ expect(module.isLoginShellTimeoutStatus(status)).toBe(false);+ });+});++describe('login-shell PATH invalidation races', () => {+ beforeEach(async () => {+ (await importModule()).invalidateLoginShellPathCache();+ execFileMock.mockReset();+ execMock.mockReset();+ rejectUnqueuedExecFile();+ vi.mocked(os.platform).mockReturnValue('darwin');+ process.env.SHELL = '/bin/zsh';+ });++ it('refuses the cache to a probe that started before an invalidation', async () => {+ // A Rescan during the (now ten-second) probe would otherwise have the older+ // probe write the pre-Rescan PATH back moments later β hiding the very edit+ // the user pressed Rescan to see.+ const module = await importModule();++ let releaseShell: (() => void) | undefined;+ // `which` misses, then the shell probe is held open.+ callExecFileError(new Error('command not found'));+ execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {+ const callback = typeof opts === 'function' ? opts : cb;+ releaseShell = () => callback(noErr, { stderr: '', stdout: '/stale/bin:/usr/bin' });+ return {} as any;+ }) as any);++ const inFlight = module.detectHeterogeneousCliCommand('kimi-code', 'kimi');+ // Let the detector reach the held shell probe before the Rescan lands.+ await vi.waitFor(() => expect(releaseShell).toBeTypeOf('function'));++ module.invalidateLoginShellPathCache();++ callExecFileError(new Error('still not found'));+ releaseShell!();+ await inFlight;++ // The disowned probe must not have populated the cache, so the next lookup+ // goes back to the shell.+ execFileMock.mockReset();+ rejectUnqueuedExecFile();+ callExecFileError(new Error('command not found'));+ callExecFile('/fresh/bin:/usr/bin');+ callExecFileError(new Error('still not found'));+ await module.detectHeterogeneousCliCommand('kimi-code', 'kimi');++ expect(+ execFileMock.mock.calls.filter(+ ([file, args]) => file === '/bin/zsh' && Array.isArray(args) && args[0] === '-ilc',+ ),+ ).toHaveLength(1);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.tsindex 3a50764329a..6244e39e301 100644--- a/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts+++ b/packages/heterogeneous-agents/src/spawn/resolveCliCommand.ts@@ -122,6 +122,35 @@ const isPathLikeCommand = (command: string): boolean =>? path.win32.isAbsolute(command) || /[\\/]/.test(command): path.isAbsolute(command) || command.includes(path.sep);+/**+ * A login *interactive* shell has to load the user's full interactive config β+ * oh-my-zsh, plugins, nvm β before it can print PATH. On a developer machine+ * that is over a second when idle, and this probe runs while the machine is+ * busy doing the very work that needed the CLI. Three seconds left barely more+ * than twice the idle cost, and a machine under load spent it, which surfaced+ * as "CLI not found" for a CLI that was installed and had just run.+ */+const LOGIN_SHELL_PATH_TIMEOUT_MS = 10_000;++/**+ * Surfaced on `CliCommandStatus.error` so callers can tell a slow machine from+ * a missing binary. Matched by `isLoginShellTimeoutStatus`.+ */+export const LOGIN_SHELL_TIMEOUT_STATUS_ERROR =+ 'Timed out reading PATH from the login shell while looking for the CLI';++/** Whether a detection result failed because the shell probe ran out of time. */+export const isLoginShellTimeoutStatus = (status?: { error?: string }): boolean =>+ status?.error === LOGIN_SHELL_TIMEOUT_STATUS_ERROR;++/** Distinguishes "the probe ran out of time" from "the shell had nothing". */+export class LoginShellPathTimeoutError extends Error {+ constructor() {+ super('Timed out reading PATH from the login shell');+ this.name = 'LoginShellPathTimeoutError';+ }+}+const getLoginShellPath = async (): Promise<string | undefined> => {if (isWindows()) return undefined;@@ -130,7 +159,7 @@ const getLoginShellPath = async (): Promise<string | undefined> => {try {const { stdout } = await execFilePromise(shell, ['-ilc', 'printf "%s" "$PATH"'], {- timeout: 3000,+ timeout: LOGIN_SHELL_PATH_TIMEOUT_MS,windowsHide: true,});@@ -139,23 +168,67 @@ const getLoginShellPath = async (): Promise<string | undefined> => {.map((line) => line.trim()).reverse().find((line) => line.includes(path.delimiter));- } catch {+ } catch (error) {+ // `execFile` kills the child on timeout and reports it as a signal, so a+ // slow shell and a hostile one are told apart here rather than downstream.+ if ((error as { killed?: boolean })?.killed) throw new LoginShellPathTimeoutError();return undefined;}};/**- * Share one login-shell lookup between concurrent probes, but discard it once- * settled. A later Rescan must observe PATH edits made by an installer while- * the desktop app is already running.+ * The login-shell PATH, resolved once per process.+ *+ * It used to be discarded the moment it settled, so a Rescan could observe PATH+ * edits made by an installer while the app was running. That put a+ * second-long, timeout-prone subprocess on the critical path of *every* spawn β+ * and since the caller detects with `force`, every session paid it. The value+ * is cached for the process now and `invalidateLoginShellPathCache()` gives+ * Rescan the same freshness explicitly.+ *+ * A probe that *timed out* is deliberately not cached β that is the transient+ * case, and pinning it would leave the process believing there is no login+ * PATH until restart. A probe that completed is cached even when it found+ * nothing, because that is a real answer rather than a missed one.*/+let cachedShellPath: { value: string | undefined } | undefined;+/**+ * Bumped on every invalidation. A probe that started before a Rescan carries+ * the older generation and is refused the cache when it lands β without this,+ * a ten-second probe in flight would write the pre-Rescan PATH back moments+ * after the user asked for a fresh one, which is precisely the edit they were+ * trying to make visible.+ */+let shellPathGeneration = 0;+const getCurrentLoginShellPath = async (): Promise<string | undefined> => {- shellPathPromise ??= getLoginShellPath().finally(() => {- shellPathPromise = undefined;- });+ if (cachedShellPath) return cachedShellPath.value;++ if (!shellPathPromise) {+ const generation = shellPathGeneration;+ shellPathPromise = getLoginShellPath()+ .then((value) => {+ if (generation === shellPathGeneration) cachedShellPath = { value };+ return value;+ })+ .finally(() => {+ if (generation === shellPathGeneration) shellPathPromise = undefined;+ });+ }return shellPathPromise;};+/**+ * Drop the cached login-shell PATH so the next probe re-reads it, and disown+ * any probe already running so its result cannot satisfy or repopulate the+ * fresh scan.+ */+export const invalidateLoginShellPathCache = (): void => {+ cachedShellPath = undefined;+ shellPathGeneration += 1;+ shellPathPromise = undefined;+};+// Machine-wide then per-user PATH, the two halves Windows concatenates into a// process environment block.const WINDOWS_REGISTRY_PATH_KEYS = [@@ -559,7 +632,17 @@ export const detectValidatedCommandCandidates = async (if (!recoveryAttempted) {recoveryAttempted = true;- recovered = await recoverProbeEnvironment(probeEnv);+ try {+ recovered = await recoverProbeEnvironment(probeEnv);+ } catch (error) {+ // A timed-out shell probe is not evidence the CLI is missing, and+ // reporting it as such sends the user to reinstall software that is+ // already there. Say what actually happened instead.+ if (error instanceof LoginShellPathTimeoutError) {+ return { ...lastStatus, available: false, error: LOGIN_SHELL_TIMEOUT_STATUS_ERROR };+ }+ throw error;+ }}if (!recovered) continue;