Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(cli): detect the installed Codex CLI / ChatGPT desktop app in setup notes (#1443)

suantea (asuan_suan)79b03e962753
diff --git a/cli/src/__snapshots__/tools.test.ts.snap b/cli/src/__snapshots__/tools.test.ts.snap
index 3b8a912e..0914ea12 100644
--- a/cli/src/__snapshots__/tools.test.ts.snap
+++ b/cli/src/__snapshots__/tools.test.ts.snap
@@ -137,6 +137,8 @@ requires_openai_auth = false
},
],
"notes": [
+ "No Codex CLI detected on this machine.",
+ "Install the CLI with: npm install -g @openai/codex",
"Export FREELLMAPI_API_KEY before running codex; the key is not written to config.toml.",
"Selected fast-coder with a 131072 token context window.",
],
@@ -165,6 +167,8 @@ model_provider = "freellmapi"
},
],
"notes": [
+ "No Codex CLI detected on this machine.",
+ "Install the CLI with: npm install -g @openai/codex",
"Export FREELLMAPI_API_KEY before running codex; the key is not written to config.toml.",
"Activate this profile with: codex --profile work",
"Selected fast-coder with a 131072 token context window.",
diff --git a/cli/src/detect.test.ts b/cli/src/detect.test.ts
new file mode 100644
index 00000000..d701c7d1
--- /dev/null
+++ b/cli/src/detect.test.ts
@@ -0,0 +1,78 @@
+import fs from 'node:fs';
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import {
+ clientNotes,
+ desktopAppPath,
+ detectChatGptClient,
+} from './detect.js';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+});
+
+describe('desktopAppPath', () => {
+ it('points at /Applications/ChatGPT.app on macOS only', () => {
+ expect(desktopAppPath('darwin')).toBe('/Applications/ChatGPT.app');
+ expect(desktopAppPath('linux')).toBeUndefined();
+ expect(desktopAppPath('win32')).toBeUndefined();
+ });
+});
+
+describe('detectChatGptClient', () => {
+ it('detects the CLI when a codex binary is on PATH', () => {
+ vi.stubEnv('PATH', '/opt/tools/bin');
+ vi.spyOn(fs, 'accessSync').mockImplementation(() => {});
+ vi.spyOn(fs, 'statSync').mockReturnValue({ isFile: () => true } as fs.Stats);
+ vi.spyOn(fs, 'existsSync').mockReturnValue(false);
+ const found = detectChatGptClient('linux');
+ expect(found).toEqual({ kind: 'cli', cliPath: '/opt/tools/bin/codex' });
+ });
+
+ it('ignores PATH directories that merely shadow the binary name', () => {
+ vi.stubEnv('PATH', '/opt/shadow');
+ vi.spyOn(fs, 'accessSync').mockImplementation(() => {});
+ vi.spyOn(fs, 'statSync').mockReturnValue({ isFile: () => false } as fs.Stats);
+ vi.spyOn(fs, 'existsSync').mockReturnValue(false);
+ expect(detectChatGptClient('linux')).toBeUndefined();
+ });
+
+ it('detects the desktop app alone on macOS', () => {
+ vi.stubEnv('PATH', '');
+ vi.spyOn(fs, 'existsSync').mockReturnValue(true);
+ const found = detectChatGptClient('darwin');
+ expect(found).toEqual({ kind: 'desktop', desktopPath: '/Applications/ChatGPT.app' });
+ });
+
+ it('reports both when the CLI and the desktop app coexist', () => {
+ vi.stubEnv('PATH', '/usr/bin');
+ vi.spyOn(fs, 'accessSync').mockImplementation(() => {});
+ vi.spyOn(fs, 'statSync').mockReturnValue({ isFile: () => true } as fs.Stats);
+ vi.spyOn(fs, 'existsSync').mockReturnValue(true);
+ const found = detectChatGptClient('darwin');
+ expect(found?.kind).toBe('both');
+ });
+
+ it('returns undefined when nothing is installed', () => {
+ vi.stubEnv('PATH', '');
+ vi.spyOn(fs, 'existsSync').mockReturnValue(false);
+ expect(detectChatGptClient('darwin')).toBeUndefined();
+ });
+});
+
+describe('clientNotes', () => {
+ it('offers the install command when no client exists', () => {
+ const notes = clientNotes(undefined);
+ expect(notes.join('\n')).toContain('npm install -g @openai/codex');
+ });
+
+ it('points a desktop-only install at the Codex CLI', () => {
+ const notes = clientNotes({ kind: 'desktop', desktopPath: '/Applications/ChatGPT.app' });
+ expect(notes.join('\n')).toContain('this setup configures the Codex CLI');
+ });
+
+ it('names the CLI path when it is detected', () => {
+ const notes = clientNotes({ kind: 'cli', cliPath: '/usr/local/bin/codex' });
+ expect(notes.join('\n')).toContain('/usr/local/bin/codex');
+ });
+});
diff --git a/cli/src/detect.ts b/cli/src/detect.ts
new file mode 100644
index 00000000..709178c0
--- /dev/null
+++ b/cli/src/detect.ts
@@ -0,0 +1,83 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+// Client detection for the Codex CLI integration. `setup-codex` only WRITES a
+// config; this module tells the user WHICH client they actually have so the
+// setup note can say something true about their machine instead of a generic
+// "install X" line. Purely filesystem/PATH based — no network, no spawning
+// processes — so it stays fast and testable.
+
+export interface DetectedClient {
+ /** `cli` — the `codex` binary is on PATH; `desktop` — the ChatGPT desktop
+ * app is installed (macOS); `both` — self-explanatory. */
+ kind: 'cli' | 'desktop' | 'both';
+ /** Absolute path of the first `codex` binary found on PATH, when present. */
+ cliPath?: string;
+ /** Absolute path of the ChatGPT.app bundle, when present. */
+ desktopPath?: string;
+}
+
+/** Where the ChatGPT desktop app lives per platform. Only macOS ships a
+ * well-known .app bundle; Windows/Linux register no stable path we can
+ * probe cheaply, so those return nothing (a UI integration there would need
+ * registry/freedesktop lookups — out of scope). */
+export function desktopAppPath(platform: string = process.platform): string | undefined {
+ if (platform !== 'darwin') return undefined;
+ return '/Applications/ChatGPT.app';
+}
+
+function executableOnPath(name: string): string | undefined {
+ const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean);
+ for (const dir of dirs) {
+ const candidate = path.join(dir, name);
+ try {
+ fs.accessSync(candidate, fs.constants.X_OK);
+ // Directories on PATH shadow real binaries (a common nvm artifact);
+ // only a regular file counts.
+ if (fs.statSync(candidate).isFile()) return candidate;
+ } catch {
+ // Not here; keep scanning.
+ }
+ }
+ return undefined;
+}
+
+/** Detects the `codex` CLI on PATH and the ChatGPT desktop app on macOS.
+ * Only the `codex` binary is probed: the CLI still ships and runs as
+ * `codex`, and that is the only surface `setup-codex` configures. */
+export function detectChatGptClient(
+ platform: string = process.platform,
+): DetectedClient | undefined {
+ const cliPath = executableOnPath('codex');
+ const appPath = desktopAppPath(platform);
+ const hasDesktop = appPath !== undefined && fs.existsSync(appPath);
+ if (cliPath && hasDesktop) return { kind: 'both', cliPath, desktopPath: appPath };
+ if (cliPath) return { kind: 'cli', cliPath };
+ if (hasDesktop) return { kind: 'desktop', desktopPath: appPath };
+ return undefined;
+}
+
+/** Human-readable guidance appended to `setup-codex` output. This setup only
+ * writes the Codex CLI config, so the desktop app is reported but never
+ * configured. */
+export function clientNotes(client: DetectedClient | undefined): string[] {
+ if (!client) {
+ return [
+ 'No Codex CLI detected on this machine.',
+ 'Install the CLI with: npm install -g @openai/codex',
+ ];
+ }
+ if (client.kind === 'desktop') {
+ return [
+ `ChatGPT desktop app detected at ${client.desktopPath}; this setup configures the Codex CLI.`,
+ 'The generated configuration targets the Codex CLI — install it with: npm install -g @openai/codex',
+ ];
+ }
+ if (client.kind === 'both') {
+ return [
+ `Codex CLI detected at ${client.cliPath}; the configuration above applies to it.`,
+ 'ChatGPT desktop app also detected; it is not configured by this setup.',
+ ];
+ }
+ return [`Codex CLI detected at ${client.cliPath}; the configuration above applies to it.`];
+}
diff --git a/cli/src/index.ts b/cli/src/index.ts
index d872c88b..e765259c 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -7,6 +7,7 @@ import spawn from 'cross-spawn';
import { Writable } from 'node:stream';
import { fileURLToPath } from 'node:url';
import { applyGeneratedFiles, printDryRunDiff } from './config-files.js';
+import { detectChatGptClient } from './detect.js';
import { getTool, tools } from './tools.js';
import { resolveLaunchModel, type ResolvedModel } from './models.js';
import { DOCTOR_TOOLS, diagnose, exitCodeFor, formatReport, type ToolReport } from './doctor.js';
@@ -271,7 +272,7 @@ function help(): string {
' doctor [tool…] Check whether a tool\'s requests actually reach this gateway',
' (--timeout MS raises the probe wait on a slow link)',
' launch Run Claude Code with credentials injected into the child environment',
- ' launch-codex Run Codex with provider overrides and injected credentials',
+ ' launch-codex Run Codex CLI with provider overrides and injected credentials',
' list List supported coding agents',
' keys Add, list, remove, or test provider keys (keys --help)',
'',
@@ -297,6 +298,7 @@ async function setup(command: string, options: CliOptions): Promise<void> {
models: rosters.available,
homeDir: os.homedir(),
requestedModelId,
+ detectedClient: detectChatGptClient(),
};
const generation = tool.generate(context);
diff --git a/cli/src/tools.test.ts b/cli/src/tools.test.ts
index 1873a579..7024978e 100644
--- a/cli/src/tools.test.ts
+++ b/cli/src/tools.test.ts
@@ -4,6 +4,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { tools } from './tools.js';
import type { GenerateContext } from './types.js';
+// Pinning ctx.detectedClient is not enough: tools.ts falls back to a live
+// detectChatGptClient() when it is undefined, so a runner with `codex` on
+// PATH (or ChatGPT.app installed) would still shift the golden notes. Mock
+// the module outright — undefined keeps the snapshots host-independent.
+vi.mock('./detect.js', () => ({
+ detectChatGptClient: () => undefined,
+ clientNotes: () => [
+ 'No Codex CLI detected on this machine.',
+ 'Install the CLI with: npm install -g @openai/codex',
+ ],
+}));
+
// CI runners export XDG_CONFIG_HOME (and could export MIMOCODE_HOME / DSH_HOME),
// which the XDG-aware generators honour over ctx.homeDir. Pin them so golden
// output is stable everywhere.
@@ -25,11 +37,15 @@ afterEach(() => {
vi.unstubAllEnvs();
});
+// Golden snapshots must not depend on the host: pin the client detection the
+// same way the XDG env vars above are pinned (a machine with `codex` on PATH
+// or ChatGPT.app installed would otherwise produce different notes than CI).
const context: GenerateContext = {
url: 'http://localhost:3000',
apiKey: 'freellmapi-test-key',
profile: 'default',
homeDir: '/home/tester',
+ detectedClient: undefined,
models: [
{
id: 'fast-coder',
diff --git a/cli/src/tools.ts b/cli/src/tools.ts
index 1aa29074..0a996171 100644
--- a/cli/src/tools.ts
+++ b/cli/src/tools.ts
@@ -1,4 +1,5 @@
import path from 'node:path';
+import { clientNotes, detectChatGptClient } from './detect.js';
import type {
CatalogModel,
GenerateContext,
@@ -125,6 +126,7 @@ function codex(ctx: GenerateContext): Generation {
content: content.join('\n'),
}],
notes: [
+ ...clientNotes(ctx.detectedClient ?? detectChatGptClient()),
'Export FREELLMAPI_API_KEY before running codex; the key is not written to config.toml.',
...(ctx.profile === 'default'
? []
diff --git a/cli/src/types.ts b/cli/src/types.ts
index c8196a6d..1a4723bd 100644
--- a/cli/src/types.ts
+++ b/cli/src/types.ts
@@ -1,3 +1,5 @@
+import type { DetectedClient } from './detect.js';
+
export interface CatalogModel {
id: string;
name?: string;
@@ -32,6 +34,11 @@ export interface GenerateContext {
/** An explicit `--model`. Overrides each generator's default-model
* heuristic; validated against the unfiltered catalog by the caller. */
requestedModelId?: string;
+ /** Result of `detectChatGptClient()`. Injected by the CLI entry point;
+ * when the property is absent generators probe the real machine, which
+ * golden-output tests must avoid (the snapshot must not depend on the
+ * host's installed clients). */
+ detectedClient?: DetectedClient;
}
export interface Generation {