Skip to content

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

πŸ› fix(desktop): detect Windows npm .cmd shims for CLI agents (claude/codex/…) (#14720)

Arvin Xua40fe91fa461
diff --git a/apps/desktop/src/main/modules/toolDetectors/__tests__/cliAgentDetectors.test.ts b/apps/desktop/src/main/modules/toolDetectors/__tests__/cliAgentDetectors.test.ts
new file mode 100644
index 00000000000..b28a371e09a
--- /dev/null
+++ b/apps/desktop/src/main/modules/toolDetectors/__tests__/cliAgentDetectors.test.ts
@@ -0,0 +1,185 @@
+import * as childProcess from 'node:child_process';
+import * as os from 'node:os';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mocks must be set up before importing the module under test, because the
+// module captures `promisify(execFile)` / `promisify(exec)` at import time.
+vi.mock('node:os', async () => {
+ const actual = await vi.importActual<typeof os>('node:os');
+ return { ...actual, platform: vi.fn(() => actual.platform()) };
+});
+
+vi.mock('node:child_process', () => ({
+ exec: vi.fn(),
+ execFile: vi.fn(),
+}));
+
+const platformMock = vi.mocked(os.platform);
+const execFileMock = vi.mocked(childProcess.execFile);
+const execMock = vi.mocked(childProcess.exec);
+
+const noErr = null;
+const callExecFile = (stdout: string, stderr = '') => {
+ execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {
+ // promisify-wrapped: the callback is always the last positional arg.
+ const callback = typeof opts === 'function' ? opts : cb;
+ callback(noErr, { stdout, stderr });
+ return {} as any;
+ }) as any);
+};
+const callExecFileError = (err: Error) => {
+ execFileMock.mockImplementationOnce(((file: string, args: any, opts: any, cb: any) => {
+ const callback = typeof opts === 'function' ? opts : cb;
+ callback(err, { stdout: '', stderr: '' });
+ return {} as any;
+ }) as any);
+};
+const callExec = (stdout: string, stderr = '') => {
+ execMock.mockImplementationOnce(((cmd: string, opts: any, cb: any) => {
+ const callback = typeof opts === 'function' ? opts : cb;
+ callback(noErr, { stdout, stderr });
+ return {} as any;
+ }) as any);
+};
+
+describe('cliAgentDetectors', () => {
+ beforeEach(() => {
+ execFileMock.mockReset();
+ execMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.resetModules();
+ });
+
+ describe('on Windows with an npm-installed `claude.cmd` shim', () => {
+ beforeEach(() => {
+ platformMock.mockReturnValue('win32');
+ });
+
+ it('resolves `claude` to the .cmd path via `where`, then runs it through the shell', async () => {
+ // 1) `where claude` β†’ resolves to the .cmd shim under %APPDATA%\npm
+ callExecFile('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd\r\n');
+ // 2) `cmd /c "...\\claude.cmd" --version` β†’ keyword match
+ callExec('1.2.3 (Claude Code)');
+
+ const { claudeCodeDetector } = await import('../cliAgentDetectors');
+ const status = await claudeCodeDetector.detect();
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd');
+ expect(status.version).toBe('1.2.3 (Claude Code)');
+
+ // The validation call must go via `exec` (shell), NOT `execFile`, so
+ // cmd.exe can actually interpret the .cmd shim.
+ expect(execMock).toHaveBeenCalledTimes(1);
+ const execCall = execMock.mock.calls[0]!;
+ expect(execCall[0]).toBe('"C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.cmd" --version');
+ });
+
+ it('returns unavailable when `where` finds nothing', async () => {
+ callExecFileError(new Error('not found'));
+
+ const { claudeCodeDetector } = await import('../cliAgentDetectors');
+ const status = await claudeCodeDetector.detect();
+
+ expect(status.available).toBe(false);
+ // We should NOT proceed to invoke anything after a failed resolve.
+ expect(execMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects custom commands containing shell metacharacters', async () => {
+ const { detectHeterogeneousCliCommand } = await import('../cliAgentDetectors');
+ const status = await detectHeterogeneousCliCommand('claude-code', 'claude & calc.exe');
+
+ expect(status.available).toBe(false);
+ expect(execFileMock).not.toHaveBeenCalled();
+ expect(execMock).not.toHaveBeenCalled();
+ });
+
+ it('fails detection when version output does not match the expected keyword', async () => {
+ callExecFile('C:\\some\\other\\claude.cmd\r\n');
+ callExec('this is some other binary v1.0');
+
+ const { claudeCodeDetector } = await import('../cliAgentDetectors');
+ const status = await claudeCodeDetector.detect();
+
+ expect(status.available).toBe(false);
+ });
+
+ it('prefers a .cmd shim when `where` returns multiple PATHEXT matches (codex case)', async () => {
+ // npm drops a Unix shell-script wrapper (extensionless) alongside the
+ // Windows `.cmd` / `.ps1` shims. `where` lists every PATHEXT match;
+ // taking the first line would land us on the unrunnable wrapper.
+ callExecFile(
+ [
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex',
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd',
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.ps1',
+ ].join('\r\n'),
+ );
+ callExec('codex 0.130.0');
+
+ const { codexDetector } = await import('../cliAgentDetectors');
+ const status = await codexDetector.detect();
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe('C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd');
+ expect(execMock.mock.calls[0]![0]).toBe(
+ '"C:\\Users\\Hanam\\AppData\\Roaming\\npm\\codex.cmd" --version',
+ );
+ });
+
+ it('prefers .exe over .cmd when both are present', async () => {
+ callExecFile(['C:\\tools\\foo.exe', 'C:\\tools\\foo.cmd'].join('\r\n'));
+ callExecFile('claude code 1.0.0');
+
+ const { claudeCodeDetector } = await import('../cliAgentDetectors');
+ const status = await claudeCodeDetector.detect();
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe('C:\\tools\\foo.exe');
+ // .exe runs directly via execFile β€” no shell.
+ expect(execMock).not.toHaveBeenCalled();
+ expect(execFileMock).toHaveBeenCalledTimes(2);
+ expect(execFileMock.mock.calls[1]![0]).toBe('C:\\tools\\foo.exe');
+ });
+
+ it('reports unavailable when `where` only returns unrunnable matches (.ps1 / extensionless)', async () => {
+ callExecFile(
+ [
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude',
+ 'C:\\Users\\Hanam\\AppData\\Roaming\\npm\\claude.ps1',
+ ].join('\r\n'),
+ );
+
+ const { claudeCodeDetector } = await import('../cliAgentDetectors');
+ const status = await claudeCodeDetector.detect();
+
+ expect(status.available).toBe(false);
+ // Must not attempt to invoke the unrunnable matches.
+ expect(execMock).not.toHaveBeenCalled();
+ expect(execFileMock).toHaveBeenCalledTimes(1); // just `where`
+ });
+ });
+
+ describe('on macOS / Linux with a Unix-style claude binary', () => {
+ beforeEach(() => {
+ platformMock.mockReturnValue('darwin');
+ });
+
+ it('runs the binary directly via execFile (no shell)', async () => {
+ callExecFile('/usr/local/bin/claude\n');
+ callExecFile('1.2.3 (Claude Code)');
+
+ const { claudeCodeDetector } = await import('../cliAgentDetectors');
+ const status = await claudeCodeDetector.detect();
+
+ expect(status.available).toBe(true);
+ expect(status.path).toBe('/usr/local/bin/claude');
+ expect(execMock).not.toHaveBeenCalled();
+ expect(execFileMock).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts b/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts
index 79d7e920015..8556bacc132 100644
--- a/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts
+++ b/apps/desktop/src/main/modules/toolDetectors/cliAgentDetectors.ts
@@ -1,11 +1,13 @@
-import { execFile } from 'node:child_process';
+import { exec, execFile } from 'node:child_process';
import { platform } from 'node:os';
+import path from 'node:path';
import { promisify } from 'node:util';
import type { IToolDetector, ToolStatus } from '@/core/infrastructure/ToolDetectorManager';
import { createCommandDetector } from '@/core/infrastructure/ToolDetectorManager';
const execFilePromise = promisify(execFile);
+const execPromise = promisify(exec);
type HeterogeneousCliAgentType = 'claude-code' | 'codex';
@@ -17,17 +19,54 @@ interface ValidatedDetectorOptions {
validateKeywords: string[];
}
+const isWindows = () => platform() === 'win32';
+
+// Reject anything that could break out of the `cmd /c "<path>" --version`
+// shell line we build for Windows .cmd shims (see `detectValidatedCommand`).
+// User-supplied custom commands flow through here via `detectHeterogeneousCliCommand`.
+const WINDOWS_SHELL_METAS = /[&|;<>^`!"]/;
+
+// Extensions we can actually execute on Windows, in preference order:
+// `.exe` runs directly via `execFile`, `.cmd` / `.bat` runs via `cmd.exe`.
+// `.ps1` and extensionless wrappers (npm sometimes drops a Unix shell script
+// next to the `.cmd` shim) are deliberately excluded β€” we can't run them.
+const WINDOWS_RUNNABLE_EXTS = ['.exe', '.cmd', '.bat'] as const;
+
+const pickWindowsRunnable = (lines: string[]): string | undefined => {
+ for (const ext of WINDOWS_RUNNABLE_EXTS) {
+ const match = lines.find((line) => line.toLowerCase().endsWith(ext));
+ if (match) return match;
+ }
+ return undefined;
+};
+
const resolveCommandPath = async (command: string): Promise<string | undefined> => {
const trimmedCommand = command.trim();
if (!trimmedCommand) return;
- const whichCommand = platform() === 'win32' ? 'where' : 'which';
+ if (path.isAbsolute(trimmedCommand) || trimmedCommand.includes(path.sep)) {
+ return trimmedCommand;
+ }
+
+ const whichCommand = isWindows() ? 'where' : 'which';
try {
const { stdout } = await execFilePromise(whichCommand, [trimmedCommand], { timeout: 3000 });
- return stdout.trim().split(/\r?\n/)[0] || trimmedCommand;
+ const lines = stdout
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean);
+ if (lines.length === 0) return undefined;
+
+ // Windows `where` lists every PATHEXT match (e.g. for `codex` npm ships
+ // a Unix shell wrapper alongside `codex.cmd` and `codex.ps1`). Picking
+ // the first line can land us on something we can't execute, so prefer a
+ // runnable extension and bail otherwise.
+ if (isWindows()) return pickWindowsRunnable(lines);
+
+ return lines[0];
} catch {
- return trimmedCommand;
+ return undefined;
}
};
@@ -37,14 +76,27 @@ const detectValidatedCommand = async (
): Promise<ToolStatus> => {
const trimmedCommand = command.trim();
if (!trimmedCommand) return { available: false };
+ if (isWindows() && WINDOWS_SHELL_METAS.test(trimmedCommand)) return { available: false };
const { validateFlag = '--version', validateKeywords } = options;
+ // Resolve via where/which BEFORE invoking. On Windows this is what discovers
+ // npm-installed shims like `claude.cmd` under %APPDATA%\npm β€” `execFile`
+ // alone won't apply PATHEXT and can't run .cmd files directly.
+ const resolvedPath = await resolveCommandPath(trimmedCommand);
+ if (!resolvedPath) return { available: false };
+
try {
- const { stderr, stdout } = await execFilePromise(trimmedCommand, [validateFlag], {
- timeout: 5000,
- windowsHide: true,
- });
+ const needsShell = isWindows() && /\.(?:cmd|bat)$/i.test(resolvedPath);
+ const { stderr, stdout } = needsShell
+ ? await execPromise(`"${resolvedPath}" ${validateFlag}`, {
+ timeout: 5000,
+ windowsHide: true,
+ })
+ : await execFilePromise(resolvedPath, [validateFlag], {
+ timeout: 5000,
+ windowsHide: true,
+ });
const output = `${stdout}\n${stderr}`.trim();
const loweredOutput = output.toLowerCase();
@@ -54,7 +106,7 @@ const detectValidatedCommand = async (
return {
available: true,
- path: await resolveCommandPath(trimmedCommand),
+ path: resolvedPath,
version: output.split(/\r?\n/)[0],
};
} catch {