Skip to content

Open source CapCut alternative.

TypeScript

fix(app): find the Codex CLI bundled in the ChatGPT app [rebuild]

David Le6350af12ea3a
diff --git a/site/src/cut/engine/serve.ts b/site/src/cut/engine/serve.ts
index 02c11125..8be6cc32 100644
--- a/site/src/cut/engine/serve.ts
+++ b/site/src/cut/engine/serve.ts
@@ -3,7 +3,7 @@ import { matchCutRoute, runCutRoute } from "../server/http/routes";
import { flattenCutUsers, migrateCutDataDir } from "../server/migrateDataDir";
import { sweepPhoneInbox } from "../server/phoneLink";
import { reconcileProjectDirs } from "../server/projects";
-import { ensureToolPath, resolveOnPath } from "../server/tool-path";
+import { ensureCodexPath, ensureToolPath, resolveOnPath } from "../server/tool-path";
import { enginePort } from "./config";
// Throws (and exits with a clear message) on a bad DONKEY_CUT_PORT rather than
@@ -54,6 +54,8 @@ async function start() {
const claude = await resolveOnPath("claude");
if (claude) process.env.DONKEY_CUT_CLAUDE = claude;
}
+ // Codex may live only inside the ChatGPT app's bundle, off every PATH.
+ await ensureCodexPath();
native.serve({
hostname: "127.0.0.1",
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index f59f548c..1edd0d34 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -208,6 +208,10 @@ async function runClaude(
}
}
+/** The Codex CLI the engine resolved at startup (tool-path.ts); bare
+ * `codex` when none was found, so the spawn fails as "not installed". */
+const codexCommand = () => process.env.DONKEY_CUT_CODEX ?? "codex";
+
/** GPT models through the Codex CLI — the user's ChatGPT login. */
async function runCodex(
emit: UIChunkWriter["write"],
@@ -237,7 +241,7 @@ async function runCodex(
await new Promise<void>((resolve, reject) => {
// stdin must be closed: `codex exec` otherwise waits on it for EOF.
- const proc = spawn("codex", args, { env: process.env, stdio: ["ignore", "pipe", "pipe"] });
+ const proc = spawn(codexCommand(), args, { env: process.env, stdio: ["ignore", "pipe", "pipe"] });
const onAbort = () => proc.kill("SIGTERM");
signal.addEventListener("abort", onAbort);
@@ -303,7 +307,7 @@ async function runCodex(
settled = true;
signal.removeEventListener("abort", onAbort);
reject(
- err.message.includes("ENOENT")
+ (err as NodeJS.ErrnoException).code === "ENOENT"
? new Error("Codex CLI not found — install it with: npm i -g @openai/codex")
: err
);
@@ -373,7 +377,7 @@ function probe(cmd: string, args: string[]): Promise<{ ok: boolean; note: string
// words the error `Executable not found in $PATH` with no "ENOENT".
const missing = err.code === "ENOENT";
const note = missing
- ? `${cmd} is not installed`
+ ? `${path.basename(cmd)} is not installed`
: (stderr || err.message).trim().split("\n")[0];
resolve({ ok: false, note, installed: !missing });
} else {
@@ -520,7 +524,7 @@ export const aiApi = {
if (!value) {
const [claude, codexLogin] = await Promise.all([
probe("claude", ["--version"]),
- probe("codex", ["login", "status"]),
+ probe(codexCommand(), ["login", "status"]),
]);
// The login probe running at all means codex is installed; only its
// ENOENT failure (carried through in codexLogin) marks it missing.
diff --git a/site/src/cut/server/http/next.ts b/site/src/cut/server/http/next.ts
index 0889720f..1e78ee08 100644
--- a/site/src/cut/server/http/next.ts
+++ b/site/src/cut/server/http/next.ts
@@ -2,7 +2,7 @@ import { hostedApiBlock } from "../local-only";
import { flattenCutUsers } from "../migrateDataDir";
import { sweepPhoneInbox } from "../phoneLink";
import { reconcileProjectDirs } from "../projects";
-import { ensureToolPath } from "../tool-path";
+import { ensureCodexPath } from "../tool-path";
import { matchCutRoute, runCutRoute } from "./routes";
let flattened = false;
@@ -26,9 +26,10 @@ export async function cutCatchAll(req: Request): Promise<Response> {
if (blocked) return blocked;
// The dev server spawns tools (yt-dlp, ffmpeg, …) in-process, so it needs
- // the same widened PATH the packaged engine builds at startup, and it runs
- // the same users/-dir flatten the engine runs before serving data routes.
- await ensureToolPath();
+ // the same widened PATH the packaged engine builds at startup, the same
+ // resolved Codex, and it runs the same users/-dir flatten the engine runs
+ // before serving data routes.
+ await ensureCodexPath();
flattenOnce();
const { pathname } = new URL(req.url);
diff --git a/site/src/cut/server/tool-path.test.ts b/site/src/cut/server/tool-path.test.ts
new file mode 100644
index 00000000..3fc35bc7
--- /dev/null
+++ b/site/src/cut/server/tool-path.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, test } from "bun:test";
+import path from "node:path";
+import { codexBundleCandidates, resolveCodex } from "./tool-path";
+
+const home = "/Users/someone";
+const bundled = codexBundleCandidates(home);
+
+describe("resolveCodex", () => {
+ test("lists the system and the user Applications bundles", () => {
+ expect(bundled).toEqual([
+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
+ path.join(home, "Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"),
+ ]);
+ });
+
+ test("a codex on PATH wins over the bundled copy", async () => {
+ const asked: string[] = [];
+ const resolved = await resolveCodex({
+ onPath: async (name) => (name === "codex" ? "/opt/homebrew/bin/codex" : null),
+ executable: async (p) => {
+ asked.push(p);
+ return true;
+ },
+ home,
+ });
+ expect(resolved).toBe("/opt/homebrew/bin/codex");
+ expect(asked).toEqual([]);
+ });
+
+ test("the bundled copy is used when PATH has none", async () => {
+ const resolved = await resolveCodex({
+ onPath: async () => null,
+ executable: async (p) => p === bundled[1],
+ home,
+ });
+ expect(resolved).toBe(bundled[1]);
+ });
+
+ test("nothing installed resolves to null", async () => {
+ const resolved = await resolveCodex({
+ onPath: async () => null,
+ executable: async () => false,
+ home,
+ });
+ expect(resolved).toBeNull();
+ });
+});
diff --git a/site/src/cut/server/tool-path.ts b/site/src/cut/server/tool-path.ts
index 6325017c..9a9dd03d 100644
--- a/site/src/cut/server/tool-path.ts
+++ b/site/src/cut/server/tool-path.ts
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
import os from "node:os";
import path from "node:path";
-import { exists, findOnPath } from "./util";
+import { exists, findOnPath, isExecutable } from "./util";
/** Directories a GUI-spawned process misses but user CLIs commonly live in. */
const COMMON_BIN_DIRS = [
@@ -72,3 +72,48 @@ export function ensureToolPath(): Promise<void> {
/** First executable named `name` on the (widened) PATH, or null. */
export const resolveOnPath = findOnPath;
+
+/** The ChatGPT desktop app ships a Codex CLI inside its bundle, off every PATH. */
+const CODEX_BUNDLE_SUBPATH = path.join(
+ "ChatGPT.app", "Contents", "Resources", "codex-cli", "CodexCLI.app", "Contents", "MacOS", "codex",
+);
+
+/** Where a bundled Codex can sit: the system and the user Applications folders. */
+export function codexBundleCandidates(home: string = os.homedir()): string[] {
+ return ["/Applications", path.join(home, "Applications")].map((dir) =>
+ path.join(dir, CODEX_BUNDLE_SUBPATH),
+ );
+}
+
+export interface CodexResolverDeps {
+ onPath: (name: string) => Promise<string | null>;
+ executable: (p: string) => Promise<boolean>;
+ home: string;
+}
+
+/** The Codex CLI to run: the first `codex` on the (widened) PATH, else the
+ * ChatGPT app's bundled copy, else null. */
+export async function resolveCodex(
+ deps: CodexResolverDeps = { onPath: findOnPath, executable: isExecutable, home: os.homedir() },
+): Promise<string | null> {
+ const onPath = await deps.onPath("codex");
+ if (onPath) return onPath;
+ for (const candidate of codexBundleCandidates(deps.home)) {
+ if (await deps.executable(candidate)) return candidate;
+ }
+ return null;
+}
+
+let codexResolved: Promise<void> | null = null;
+
+/** Resolve Codex once into DONKEY_CUT_CODEX, which the probe and the turn
+ * runner spawn. Widens PATH first. Missing is fine — the models probe reports it. */
+export function ensureCodexPath(): Promise<void> {
+ codexResolved ??= (async () => {
+ await ensureToolPath();
+ if (process.env.DONKEY_CUT_CODEX) return;
+ const codex = await resolveCodex();
+ if (codex) process.env.DONKEY_CUT_CODEX = codex;
+ })();
+ return codexResolved;
+}
diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.ts
index 75a327d4..b2630363 100644
--- a/site/src/cut/server/util.ts
+++ b/site/src/cut/server/util.ts
@@ -37,18 +37,23 @@ export async function findOnPath(name: string): Promise<string | null> {
for (const dir of (process.env.PATH ?? "").split(":")) {
if (!dir) continue;
const candidate = path.join(dir, name);
- try {
- const s = await stat(candidate); // follows symlinks
- if (!s.isFile()) continue;
- await access(candidate, constants.X_OK);
- return candidate;
- } catch {
- // absent or not executable — keep looking
- }
+ if (await isExecutable(candidate)) return candidate;
}
return null;
}
+/** Whether `p` is an executable file (symlinks followed). */
+export async function isExecutable(p: string): Promise<boolean> {
+ try {
+ const s = await stat(p);
+ if (!s.isFile()) return false;
+ await access(p, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
/**
* First variant of `base` (stem, stem-1, stem-2, …) whose resolved path does
* not already exist. Used to avoid clobbering when copying/saving media.