Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): run local codex sessions on the user's own ChatGPT subscription (#89077)

Shy Alter143d16fbabfa
diff --git a/products/desktop/apps/code/scripts/download-binaries.test.mjs b/products/desktop/apps/code/scripts/download-binaries.test.mjs
index 945370cc0eb5..4a4931d328d6 100644
--- a/products/desktop/apps/code/scripts/download-binaries.test.mjs
+++ b/products/desktop/apps/code/scripts/download-binaries.test.mjs
@@ -1,3 +1,4 @@
+import { execSync } from "node:child_process";
import { chmodSync, existsSync, renameSync } from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import { extract } from "tar";
@@ -13,6 +14,10 @@ vi.mock("node:timers/promises", () => {
const setTimeout = vi.fn(() => Promise.resolve());
return { setTimeout, default: { setTimeout } };
});
+vi.mock("node:child_process", () => {
+ const execSync = vi.fn();
+ return { execSync, default: { execSync } };
+});
vi.mock("node:stream/promises", () => {
const pipeline = vi.fn(() => Promise.resolve());
return { pipeline, default: { pipeline } };
@@ -172,6 +177,12 @@ describe("download binaries", () => {
}
expect(renameSync).toHaveBeenCalledWith(extractedPath, binaryPath);
expect(chmodSync).toHaveBeenCalledWith(binaryPath, 0o755);
+ if (process.platform === "darwin") {
+ expect(execSync).toHaveBeenCalledWith(
+ `codesign --force --sign - "${binaryPath}"`,
+ { stdio: "pipe" },
+ );
+ }
});
it.each([
diff --git a/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts b/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts
index 4c2f6e88c6b1..99052be9dac2 100644
--- a/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts
+++ b/products/desktop/apps/code/src/main/services/app-lifecycle/service.test.ts
@@ -9,6 +9,7 @@ const {
mockWatcherRegistry,
mockProcessTracking,
mockWorkspaceService,
+ mockCleanupAllCodexHomes,
mockTrackAppEvent,
mockShutdownPostHog,
mockShutdownOtelTransport,
@@ -31,6 +32,7 @@ const {
pendingCreationCount: 0,
waitForPendingCreations: vi.fn(() => Promise.resolve()),
},
+ mockCleanupAllCodexHomes: vi.fn(() => Promise.resolve()),
mockProcessTracking: {
getSnapshot: vi.fn(() =>
Promise.resolve({
@@ -97,6 +99,10 @@ vi.mock("@posthog/shared/analytics-events", () => ({
},
}));
+vi.mock("@posthog/workspace-server/services/agent/codex-home", () => ({
+ cleanupAllCodexHomes: mockCleanupAllCodexHomes,
+}));
+
describe("AppLifecycleService", () => {
let service: AppLifecycleService;
const originalProcessExit = process.exit;
@@ -115,6 +121,7 @@ describe("AppLifecycleService", () => {
mockWatcherRegistry as never,
mockProcessTracking as never,
mockWorkspaceService as never,
+ { appDataPath: "/app-data" } as never,
{ getBrowserWindow: () => mockBrowserWindow } as never,
);
});
@@ -175,6 +182,14 @@ describe("AppLifecycleService", () => {
});
describe("shutdown", () => {
+ it("cleans all app-owned Codex state", async () => {
+ const promise = service.shutdown();
+ await vi.runAllTimersAsync();
+ await promise;
+
+ expect(mockCleanupAllCodexHomes).toHaveBeenCalledWith("/app-data");
+ });
+
it("tracks app quit event", async () => {
const promise = service.shutdown();
await vi.runAllTimersAsync();
diff --git a/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts b/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts
index e94402ea18f5..3707a619c70c 100644
--- a/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts
+++ b/products/desktop/apps/code/src/main/services/app-lifecycle/service.ts
@@ -3,9 +3,14 @@ import {
type IAppLifecycle,
} from "@posthog/platform/app-lifecycle";
import { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";
+import {
+ type IStoragePaths,
+ STORAGE_PATHS_SERVICE,
+} from "@posthog/platform/storage-paths";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { DATABASE_SERVICE } from "@posthog/workspace-server/db/identifiers";
import type { DatabaseService } from "@posthog/workspace-server/db/service";
+import { cleanupAllCodexHomes } from "@posthog/workspace-server/services/agent/codex-home";
import { PROCESS_TRACKING_SERVICE } from "@posthog/workspace-server/services/process-tracking/identifiers";
import type { ProcessTrackingService } from "@posthog/workspace-server/services/process-tracking/process-tracking";
import { SUSPENSION_SERVICE } from "@posthog/workspace-server/services/suspension/identifiers";
@@ -49,6 +54,8 @@ export class AppLifecycleService {
private readonly processTracking: ProcessTrackingService,
@inject(WORKSPACE_SERVICE)
private readonly workspaceService: WorkspaceService,
+ @inject(STORAGE_PATHS_SERVICE)
+ private readonly storagePaths: IStoragePaths,
@inject(MAIN_WINDOW_SERVICE)
private readonly mainWindow: ElectronMainWindow,
) {}
@@ -262,6 +269,12 @@ export class AppLifecycleService {
log.warn("Failed to kill tracked processes", error);
}
+ try {
+ await cleanupAllCodexHomes(this.storagePaths.appDataPath);
+ } catch (error) {
+ log.warn("Failed to clean Codex state", error);
+ }
+
// Drain pending native callbacks (e.g. @parcel/watcher ThreadSafeFunction)
// so they fire while JS is still alive, not during FreeEnvironment teardown
await new Promise((resolve) => setImmediate(resolve));
diff --git a/products/desktop/apps/code/src/renderer/contributions/app-boot.contributions.ts b/products/desktop/apps/code/src/renderer/contributions/app-boot.contributions.ts
index 7ccb31aaaf3e..ace264aeed72 100644
--- a/products/desktop/apps/code/src/renderer/contributions/app-boot.contributions.ts
+++ b/products/desktop/apps/code/src/renderer/contributions/app-boot.contributions.ts
@@ -1,6 +1,9 @@
import type { Contribution } from "@posthog/di/contribution";
+import { CODEX_OWN_SUBSCRIPTION_FLAG } from "@posthog/shared";
+import { registerCodexSubscriptionAtBoot } from "@posthog/ui/features/settings/useCodexSubscription";
import {
initializePostHog,
+ posthogFeatureFlags,
registerAppVersion,
registerHostInfo,
} from "@posthog/ui/shell/posthogAnalyticsImpl";
@@ -33,6 +36,19 @@ export class AnalyticsBootContribution implements Contribution {
} catch (error) {
log.warn("Failed to register host info super properties", { error });
}
+ try {
+ const codexFlagEnabled =
+ posthogFeatureFlags.isEnabled(CODEX_OWN_SUBSCRIPTION_FLAG) ||
+ import.meta.env.DEV;
+ await registerCodexSubscriptionAtBoot(
+ () => trpcClient.agent.codexSubscriptionStatus.query(),
+ codexFlagEnabled,
+ );
+ } catch (error) {
+ log.warn("Failed to register codex subscription super properties", {
+ error,
+ });
+ }
})();
}
}
diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.json
index c94ee1ba7075..821eebedbbf6 100644
--- a/products/desktop/packages/agent/package.json
+++ b/products/desktop/packages/agent/package.json
@@ -84,6 +84,10 @@
"types": "./dist/adapters/claude/conversion/tool-use-to-acp.d.ts",
"import": "./dist/adapters/claude/conversion/tool-use-to-acp.js"
},
+ "./adapters/codex-app-server/subscription-login": {
+ "types": "./dist/adapters/codex-app-server/subscription-login.d.ts",
+ "import": "./dist/adapters/codex-app-server/subscription-login.js"
+ },
"./adapters/claude/session/jsonl-hydration": {
"types": "./dist/adapters/claude/session/jsonl-hydration.d.ts",
"import": "./dist/adapters/claude/session/jsonl-hydration.js"
diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.ts b/products/desktop/packages/agent/src/adapters/acp-connection.ts
index df2a460c930a..bb15ede42f24 100644
--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts
+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts
@@ -232,6 +232,7 @@ function createCodexConnection(config: AcpConnectionConfig): AcpConnection {
apiBaseUrl: codexOptions.apiBaseUrl,
apiKey: codexOptions.apiKey,
codexHome: codexOptions.codexHome,
+ useMachineAuth: codexOptions.useMachineAuth,
developerInstructions: codexOptions.developerInstructions,
httpHeaders: codexOptions.httpHeaders,
configOverrides: codexOptions.configOverrides,
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
index 3e607a0954e6..df23190013da 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
@@ -89,6 +89,7 @@ import {
APP_SERVER_METHODS,
APP_SERVER_NOTIFICATIONS,
APP_SERVER_REQUESTS,
+ CODEX_CLIENT_INFO,
} from "./protocol";
import {
type CodexSandboxPolicy,
@@ -341,11 +342,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
async initialize(request: InitializeRequest): Promise<InitializeResponse> {
await this.rpc.request(APP_SERVER_METHODS.INITIALIZE, {
- clientInfo: {
- name: "posthog-code",
- title: "PostHog",
- version: "0.1.0",
- },
+ clientInfo: CODEX_CLIENT_INFO,
// Opt into codex's experimental API so experimental turn/start fields are honored.
capabilities: { experimentalApi: true, requestAttestation: false },
});
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts
index 38e21191529e..651e4045ef26 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/protocol.ts
@@ -4,8 +4,18 @@
* newline-delimited JSON that omits the `"jsonrpc": "2.0"` header.
*/
+export const CODEX_CLIENT_INFO = {
+ name: "posthog-code",
+ title: "PostHog",
+ version: "0.1.0",
+} as const;
+
export const APP_SERVER_METHODS = {
INITIALIZE: "initialize",
+ ACCOUNT_READ: "account/read",
+ ACCOUNT_LOGIN_START: "account/login/start",
+ ACCOUNT_LOGIN_CANCEL: "account/login/cancel",
+ ACCOUNT_LOGOUT: "account/logout",
THREAD_START: "thread/start",
THREAD_RESUME: "thread/resume",
THREAD_FORK: "thread/fork",
@@ -23,6 +33,7 @@ export const APP_SERVER_METHODS = {
export const APP_SERVER_NOTIFICATIONS = {
INITIALIZED: "initialized",
+ ACCOUNT_LOGIN_COMPLETED: "account/login/completed",
THREAD_STARTED: "thread/started",
// Carries the active turn id — precondition for turn/steer + turn/interrupt.
TURN_STARTED: "turn/started",
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts
index a14d36ea6249..f9dc185599aa 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.test.ts
@@ -10,10 +10,15 @@ import {
const BINARY_PATH = "/bundle/codex";
const mockSpawn = vi.hoisted(() => vi.fn());
+const mockExecFileSync = vi.hoisted(() => vi.fn());
vi.mock("node:child_process", async (importOriginal) => {
const original = await importOriginal<typeof import("node:child_process")>();
- return { ...original, spawn: mockSpawn };
+ return {
+ ...original,
+ execFileSync: mockExecFileSync,
+ spawn: mockSpawn,
+ };
});
vi.mock("node:fs", async (importOriginal) => {
@@ -122,6 +127,25 @@ describe("buildAppServerArgs", () => {
},
);
+ it("uses the machine account without gateway or user integrations", () => {
+ const args = buildAppServerArgs({
+ binaryPath: "/bundle/codex",
+ useMachineAuth: true,
+ });
+
+ expect(args).toContain('model_provider="openai"');
+ expect(args).toContain('forced_login_method="chatgpt"');
+ expect(args).toContain('history.persistence="none"');
+ expect(args).toContain("mcp_servers={}");
+ expect(args).toContain("hooks={}");
+ expect(args).toContain("notify=[]");
+ expect(args).toContain('otel.exporter="none"');
+ expect(args).not.toContain('cli_auth_credentials_store="file"');
+ expect(args.some((arg) => arg.includes("POSTHOG_GATEWAY_API_KEY"))).toBe(
+ false,
+ );
+ });
+
it("keeps codex credential stores on files so the bundled binary never triggers keychain prompts", () => {
const args = buildAppServerArgs({ binaryPath: "/bundle/codex" });
@@ -238,6 +262,55 @@ describe("spawnCodexAppServerProcess", () => {
}
});
+ it("separates machine login variables from gateway login variables", () => {
+ const saved = {
+ access: process.env.CODEX_ACCESS_TOKEN,
+ gateway: process.env.POSTHOG_GATEWAY_API_KEY,
+ openai: process.env.OPENAI_API_KEY,
+ openaiBaseUrl: process.env.OPENAI_BASE_URL,
+ sqliteHome: process.env.CODEX_SQLITE_HOME,
+ };
+ process.env.CODEX_ACCESS_TOKEN = "old-access-token";
+ process.env.POSTHOG_GATEWAY_API_KEY = "old-gateway-key";
+ process.env.OPENAI_API_KEY = "old-openai-key";
+ process.env.OPENAI_BASE_URL = "https://api.openai.example/v1";
+ mockSpawn.mockReturnValue(fakeChild() as never);
+ try {
+ spawnCodexAppServerProcess({
+ binaryPath: BINARY_PATH,
+ codexHome: "/appdata/codex/run-1",
+ useMachineAuth: true,
+ logger: silentLogger,
+ });
+ const subscriptionEnv = mockSpawn.mock.lastCall?.[2]
+ .env as NodeJS.ProcessEnv;
+ expect(subscriptionEnv.POSTHOG_GATEWAY_API_KEY).toBeUndefined();
+ expect(subscriptionEnv.OPENAI_API_KEY).toBeUndefined();
+ expect(subscriptionEnv.CODEX_ACCESS_TOKEN).toBeUndefined();
+ expect(subscriptionEnv.CODEX_SQLITE_HOME).toBe("/appdata/codex/run-1");
+
+ spawnCodexAppServerProcess({
+ binaryPath: BINARY_PATH,
+ apiKey: "phk",
+ codexHome: "/appdata/codex/run-2",
+ logger: silentLogger,
+ });
+ const gatewayEnv = mockSpawn.mock.lastCall?.[2].env as NodeJS.ProcessEnv;
+ expect(gatewayEnv.POSTHOG_GATEWAY_API_KEY).toBe("phk");
+ expect(gatewayEnv.OPENAI_API_KEY).toBeUndefined();
+ expect(gatewayEnv.OPENAI_BASE_URL).toBeUndefined();
+ expect(gatewayEnv.CODEX_ACCESS_TOKEN).toBeUndefined();
+ expect(gatewayEnv.CODEX_HOME).toBe("/appdata/codex/run-2");
+ expect(gatewayEnv.CODEX_SQLITE_HOME).toBe("/appdata/codex/run-2");
+ } finally {
+ restoreEnv("CODEX_ACCESS_TOKEN", saved.access);
+ restoreEnv("POSTHOG_GATEWAY_API_KEY", saved.gateway);
+ restoreEnv("OPENAI_API_KEY", saved.openai);
+ restoreEnv("OPENAI_BASE_URL", saved.openaiBaseUrl);
+ restoreEnv("CODEX_SQLITE_HOME", saved.sqliteHome);
+ }
+ });
+
// Codex snapshots process.env at spawn time, so the per-session mount must
// win over conflicting global values, and a session without a publish token
// (impersonation) must not inherit another session's.
@@ -273,6 +346,51 @@ describe("spawnCodexAppServerProcess", () => {
restoreEnv("POSTHOG_PERSONAL_API_KEY", saved.personalKey);
}
});
+
+ it("kills descendant processes before the Codex process on Unix", () => {
+ const child = fakeChild();
+ const killProcess = vi.spyOn(process, "kill").mockReturnValue(true);
+ mockSpawn.mockReturnValue(child as never);
+ mockExecFileSync.mockReturnValue(
+ "4242 100\n5000 4242\n6000 5000\n5001 4242\n",
+ );
+
+ try {
+ const spawned = spawnCodexAppServerProcess({
+ binaryPath: BINARY_PATH,
+ logger: silentLogger,
+ });
+
+ spawned.kill();
+
+ expect(killProcess.mock.calls).toEqual([
+ [6000, "SIGTERM"],
+ [5000, "SIGTERM"],
+ [5001, "SIGTERM"],
+ [4242, "SIGTERM"],
+ ]);
+ expect(child.kill).not.toHaveBeenCalled();
+ } finally {
+ killProcess.mockRestore();
+ }
+ });
+
+ it("falls back to the direct child when process discovery fails", () => {
+ const child = fakeChild();
+ mockSpawn.mockReturnValue(child as never);
+ mockExecFileSync.mockImplementation(() => {
+ throw new Error("ps failed");
+ });
+
+ const spawned = spawnCodexAppServerProcess({
+ binaryPath: BINARY_PATH,
+ logger: silentLogger,
+ });
+
+ spawned.kill();
+
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ });
});
function restoreEnv(key: string, value: string | undefined): void {
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
index 8bbc985b7eb6..d217b74c6941 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/spawn.ts
@@ -1,4 +1,4 @@
-import { type ChildProcess, spawn } from "node:child_process";
+import { type ChildProcess, execFileSync, spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { delimiter, dirname } from "node:path";
import type { Readable, Writable } from "node:stream";
@@ -32,6 +32,7 @@ export interface CodexOptions {
*/
binaryPath?: string;
codexHome?: string;
+ useMachineAuth?: boolean;
/** Extra codex `-c key=value` config overrides. */
configOverrides?: Record<string, string | number>;
/**
@@ -49,12 +50,8 @@ export interface CodexAppServerProcessOptions {
cwd?: string;
apiBaseUrl?: string;
apiKey?: string;
- /**
- * Private CODEX_HOME for this run (skills + config). Without it codex falls
- * back to the user's ~/.codex, whose ambient plugins/MCP servers can stall
- * every turn (a broken plugin MCP blocks turn/start for its full timeout).
- */
codexHome?: string;
+ useMachineAuth?: boolean;
/** Guidance appended to Codex's base prompt via `developer_instructions`. */
developerInstructions?: string;
/**
@@ -81,6 +78,42 @@ export interface CodexAppServerProcess {
kill: () => void;
}
+function getUnixProcessTreePids(rootPid: number): number[] | undefined {
+ let processTable: string;
+ try {
+ processTable = execFileSync("ps", ["-ax", "-o", "pid=,ppid="], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ } catch {
+ return undefined;
+ }
+
+ const childrenByParent = new Map<number, number[]>();
+ for (const line of processTable.split("\n")) {
+ const [pidText, parentPidText] = line.trim().split(/\s+/);
+ const pid = Number.parseInt(pidText, 10);
+ const parentPid = Number.parseInt(parentPidText, 10);
+ if (Number.isNaN(pid) || Number.isNaN(parentPid)) continue;
+ const children = childrenByParent.get(parentPid) ?? [];
+ children.push(pid);
+ childrenByParent.set(parentPid, children);
+ }
+
+ const processTreePids: number[] = [];
+ const visited = new Set<number>();
+ const addProcessTree = (pid: number): void => {
+ if (visited.has(pid)) return;
+ visited.add(pid);
+ for (const childPid of childrenByParent.get(pid) ?? []) {
+ addProcessTree(childPid);
+ }
+ processTreePids.push(pid);
+ };
+ addProcessTree(rootPid);
+ return processTreePids;
+}
+
/** Serialize a string map as a TOML basic string (escapes `\` and `"`). */
function tomlBasicString(value: string): string {
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
@@ -108,15 +141,24 @@ export function buildAppServerArgs(
// servers PostHog injects, so disable the plugin system outright.
args.push("-c", "features.plugins=false");
- // Codex defaults to the OS keychain for CLI auth, MCP OAuth tokens, and its
- // secrets encryption key — on macOS that means permission prompts for our
- // bundled binary (keychain ACLs are signature-bound, so grants to a user's
- // standalone codex don't cover ours and don't stick across releases). Model
- // auth is injected via POSTHOG_GATEWAY_API_KEY, so codex's own credential
- // stores are unused: keep them on plain files inside the private CODEX_HOME
- // and never touch the keychain.
- args.push("-c", `cli_auth_credentials_store="file"`);
- args.push("-c", `mcp_oauth_credentials_store="file"`);
+ // PostHog owns these integrations. Do not run user hooks or send task data
+ // to telemetry exporters from the user's Codex config.
+ args.push("-c", "mcp_servers={}");
+ args.push("-c", "hooks={}");
+ args.push("-c", "notify=[]");
+ args.push("-c", `otel.exporter="none"`);
+ args.push("-c", `otel.metrics_exporter="none"`);
+ args.push("-c", `otel.trace_exporter="none"`);
+ args.push("-c", "otel.log_user_prompt=false");
+
+ if (options.useMachineAuth) {
+ args.push("-c", `model_provider="openai"`);
+ args.push("-c", `forced_login_method="chatgpt"`);
+ args.push("-c", `history.persistence="none"`);
+ } else {
+ args.push("-c", `cli_auth_credentials_store="file"`);
+ args.push("-c", `mcp_oauth_credentials_store="file"`);
+ }
// OS sandbox gated on platform (= availability): macOS Seatbelt → workspace-write
// (keeps the sandbox engaged so a per-turn readOnly can tighten it and block
@@ -210,11 +252,23 @@ export function spawnCodexAppServerProcess(
const env: NodeJS.ProcessEnv = { ...process.env };
delete env.ELECTRON_RUN_AS_NODE;
delete env.ELECTRON_NO_ASAR;
+ delete env.POSTHOG_GATEWAY_API_KEY;
+ // Codex hands its environment to every shell the exec tools run, so an
+ // ambient provider key would be readable by any script the agent executes.
+ // Neither auth mode needs them: gateway mode pins model_provider to the
+ // PostHog provider (env_key=POSTHOG_GATEWAY_API_KEY), machine auth uses the
+ // ChatGPT login state.
+ delete env.CODEX_ACCESS_TOKEN;
+ delete env.CODEX_API_KEY;
+ delete env.OPENAI_API_KEY;
+ delete env.OPENAI_API_BASE;
+ delete env.OPENAI_BASE_URL;
if (options.apiKey) {
env.POSTHOG_GATEWAY_API_KEY = options.apiKey;
}
if (options.codexHome) {
- env.CODEX_HOME = options.codexHome;
+ if (!options.useMachineAuth) env.CODEX_HOME = options.codexHome;
+ env.CODEX_SQLITE_HOME = options.codexHome;
}
applyContextWikiEnv(env, options.contextWiki);
env.PATH = `${dirname(options.binaryPath)}${delimiter}${env.PATH ?? ""}`;
@@ -271,6 +325,17 @@ export function spawnCodexAppServerProcess(
child.stdin?.destroy();
child.stdout?.destroy();
child.stderr?.destroy();
+ if (process.platform !== "win32" && child.pid) {
+ const processTreePids = getUnixProcessTreePids(child.pid);
+ if (processTreePids) {
+ for (const pid of processTreePids) {
+ try {
+ process.kill(pid, "SIGTERM");
+ } catch {}
+ }
+ return;
+ }
+ }
child.kill("SIGTERM");
},
};
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.test.ts
new file mode 100644
index 000000000000..2df4dcc81ae8
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.test.ts
@@ -0,0 +1,128 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { APP_SERVER_METHODS, APP_SERVER_NOTIFICATIONS } from "./protocol";
+
+const state = vi.hoisted(() => ({
+ account: null as { type: string } | null,
+ failLogout: false,
+ kill: vi.fn(),
+ onExit: undefined as (() => void) | undefined,
+ onNotification: undefined as
+ | ((method: string, params: unknown) => void)
+ | undefined,
+ requests: [] as string[],
+ spawnOptions: undefined as { useMachineAuth?: boolean } | undefined,
+}));
+
+vi.mock("./spawn", async () => {
+ const { PassThrough } = await import("node:stream");
+ return {
+ spawnCodexAppServerProcess: (options: { useMachineAuth?: boolean }) => {
+ state.spawnOptions = options;
+ return {
+ process: {
+ once: (_event: string, callback: () => void) => {
+ state.onExit = callback;
+ },
+ },
+ stdout: new PassThrough(),
+ stdin: new PassThrough(),
+ kill: state.kill,
+ };
+ },
+ };
+});
+
+vi.mock("./app-server-client", () => ({
+ AppServerClient: class {
+ constructor(
+ _streams: unknown,
+ handlers: {
+ onNotification?: (method: string, params: unknown) => void;
+ },
+ ) {
+ state.onNotification = handlers.onNotification;
+ }
+
+ async request(method: string): Promise<unknown> {
+ state.requests.push(method);
+ if (method === APP_SERVER_METHODS.ACCOUNT_READ) {
+ return { account: state.account };
+ }
+ if (method === APP_SERVER_METHODS.ACCOUNT_LOGIN_START) {
+ return {
+ authUrl: "https://chatgpt.com/login",
+ loginId: "login-1",
+ };
+ }
+ if (method === APP_SERVER_METHODS.ACCOUNT_LOGOUT && state.failLogout) {
+ throw new Error("Logout failed");
+ }
+ return {};
+ }
+
+ notify(): void {}
+
+ async close(): Promise<void> {}
+ },
+}));
+
+import {
+ hasCodexChatgptLogin,
+ signOutCodexChatgpt,
+ startCodexChatgptLogin,
+} from "./subscription-login";
+
+const options = { binaryPath: "/bundle/codex" };
+
+beforeEach(() => {
+ state.account = null;
+ state.failLogout = false;
+ state.kill.mockClear();
+ state.onExit = undefined;
+ state.onNotification = undefined;
+ state.requests = [];
+ state.spawnOptions = undefined;
+});
+
+describe("Codex account", () => {
+ it("uses the normal machine login and accepts only ChatGPT accounts", async () => {
+ state.account = { type: "chatgpt" };
+
+ await expect(hasCodexChatgptLogin(options)).resolves.toBe(true);
+ expect(state.spawnOptions?.useMachineAuth).toBe(true);
+
+ state.account = { type: "apiKey" };
+ await expect(hasCodexChatgptLogin(options)).resolves.toBe(false);
+ });
+
+ it("finishes login from the app-server notification", async () => {
+ const login = await startCodexChatgptLogin(options);
+
+ expect(login.authUrl).toBe("https://chatgpt.com/login");
+ state.onNotification?.(APP_SERVER_NOTIFICATIONS.ACCOUNT_LOGIN_COMPLETED, {
+ loginId: "login-1",
+ success: true,
+ });
+
+ await expect(login.completed).resolves.toBe(true);
+ expect(state.requests).toEqual([
+ APP_SERVER_METHODS.INITIALIZE,
+ APP_SERVER_METHODS.ACCOUNT_LOGIN_START,
+ ]);
+ });
+
+ it("cancels the active Codex login", async () => {
+ const login = await startCodexChatgptLogin(options);
+
+ await login.cancel();
+
+ await expect(login.completed).resolves.toBe(false);
+ expect(state.requests).toContain(APP_SERVER_METHODS.ACCOUNT_LOGIN_CANCEL);
+ });
+
+ it("reports a logout failure", async () => {
+ state.failLogout = true;
+
+ await expect(signOutCodexChatgpt(options)).rejects.toThrow("Logout failed");
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.ts
new file mode 100644
index 000000000000..702e2bd2bc4d
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/subscription-login.ts
@@ -0,0 +1,185 @@
+import type { ProcessSpawnedCallback } from "../../types";
+import type { Logger } from "../../utils/logger";
+import {
+ nodeReadableToWebReadable,
+ nodeWritableToWebWritable,
+} from "../../utils/streams";
+import { AppServerClient, type AppServerRpc } from "./app-server-client";
+import {
+ APP_SERVER_METHODS,
+ APP_SERVER_NOTIFICATIONS,
+ CODEX_CLIENT_INFO,
+} from "./protocol";
+import {
+ type CodexAppServerProcess,
+ spawnCodexAppServerProcess,
+} from "./spawn";
+
+const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
+const REQUEST_TIMEOUT_MS = 10_000;
+
+interface CodexAccountOptions {
+ binaryPath: string;
+ logger?: Logger;
+ processCallbacks?: ProcessSpawnedCallback;
+}
+
+interface CodexAccountClient {
+ process: CodexAppServerProcess;
+ rpc: AppServerRpc;
+ close: () => void;
+}
+
+export interface CodexLoginSession {
+ authUrl: string;
+ completed: Promise<boolean>;
+ cancel: () => Promise<void>;
+}
+
+export async function hasCodexChatgptLogin(
+ options: CodexAccountOptions,
+): Promise<boolean> {
+ const client = openCodexAccountClient(options);
+ try {
+ await initialize(client.rpc);
+ const result = await requestWithTimeout<{
+ account?: { type?: string } | null;
+ }>(client.rpc, APP_SERVER_METHODS.ACCOUNT_READ, { refreshToken: false });
+ return result.account?.type === "chatgpt";
+ } finally {
+ client.close();
+ }
+}
+
+export async function signOutCodexChatgpt(
+ options: CodexAccountOptions,
+): Promise<void> {
+ const client = openCodexAccountClient(options);
+ try {
+ await initialize(client.rpc);
+ await requestWithTimeout(client.rpc, APP_SERVER_METHODS.ACCOUNT_LOGOUT, {});
+ } finally {
+ client.close();
+ }
+}
+
+export async function startCodexChatgptLogin(
+ options: CodexAccountOptions,
+): Promise<CodexLoginSession> {
+ let loginId: string | undefined;
+ let settled = false;
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ let resolveCompleted: (value: boolean) => void = () => {};
+
+ const completed = new Promise<boolean>((resolve) => {
+ resolveCompleted = resolve;
+ });
+ const client = openCodexAccountClient(options, (method, params) => {
+ if (method !== APP_SERVER_NOTIFICATIONS.ACCOUNT_LOGIN_COMPLETED) return;
+ if (params === null || typeof params !== "object") return;
+ const completedLoginId = Reflect.get(params, "loginId");
+ const success = Reflect.get(params, "success");
+ if (typeof completedLoginId !== "string" || typeof success !== "boolean") {
+ return;
+ }
+ if (loginId !== undefined && completedLoginId !== loginId) return;
+ finish(success);
+ });
+
+ function finish(success: boolean): void {
+ if (settled) return;
+ settled = true;
+ if (timeout) clearTimeout(timeout);
+ resolveCompleted(success);
+ client.close();
+ }
+
+ client.process.process.once("exit", () => finish(false));
+
+ try {
+ await initialize(client.rpc);
+ const login = await requestWithTimeout<{
+ authUrl: string;
+ loginId: string;
+ }>(client.rpc, APP_SERVER_METHODS.ACCOUNT_LOGIN_START, {
+ type: "chatgpt",
+ useHostedLoginSuccessPage: true,
+ appBrand: "chatgpt",
+ });
+ loginId = login.loginId;
+ if (!settled) timeout = setTimeout(() => finish(false), LOGIN_TIMEOUT_MS);
+
+ return {
+ authUrl: login.authUrl,
+ completed,
+ cancel: async (): Promise<void> => {
+ if (settled) return;
+ await requestWithTimeout(
+ client.rpc,
+ APP_SERVER_METHODS.ACCOUNT_LOGIN_CANCEL,
+ { loginId },
+ ).catch(() => undefined);
+ finish(false);
+ },
+ };
+ } catch (error) {
+ finish(false);
+ throw error;
+ }
+}
+
+function openCodexAccountClient(
+ options: CodexAccountOptions,
+ onNotification?: (method: string, params: unknown) => void,
+): CodexAccountClient {
+ const process = spawnCodexAppServerProcess({
+ binaryPath: options.binaryPath,
+ logger: options.logger,
+ processCallbacks: options.processCallbacks,
+ useMachineAuth: true,
+ });
+ const rpc = new AppServerClient(
+ {
+ readable: nodeReadableToWebReadable(process.stdout),
+ writable: nodeWritableToWebWritable(process.stdin),
+ },
+ { logger: options.logger, onNotification },
+ );
+ let closed = false;
+ return {
+ process,
+ rpc,
+ close: (): void => {
+ if (closed) return;
+ closed = true;
+ void rpc.close();
+ process.kill();
+ },
+ };
+}
+
+async function initialize(rpc: AppServerRpc): Promise<void> {
+ await requestWithTimeout(rpc, APP_SERVER_METHODS.INITIALIZE, {
+ clientInfo: CODEX_CLIENT_INFO,
+ });
+ rpc.notify(APP_SERVER_NOTIFICATIONS.INITIALIZED, {});
+}
+
+async function requestWithTimeout<T = unknown>(
+ rpc: AppServerRpc,
+ method: string,
+ params: unknown,
+): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error("The Codex account request timed out.")),
+ REQUEST_TIMEOUT_MS,
+ );
+ });
+ try {
+ return await Promise.race([rpc.request<T>(method, params), timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
diff --git a/products/desktop/packages/agent/src/agent.test.ts b/products/desktop/packages/agent/src/agent.test.ts
index 65575c370ce0..cf9666ce6643 100644
--- a/products/desktop/packages/agent/src/agent.test.ts
+++ b/products/desktop/packages/agent/src/agent.test.ts
@@ -68,6 +68,35 @@ describe("Agent", () => {
);
});
+ it("uses machine authentication for a ChatGPT subscription", async () => {
+ const agent = new Agent({ skipLogPersistence: true });
+
+ await agent.run("task-1", "run-1", {
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
+ repositoryPath: "/tmp/repo",
+ });
+
+ const [[config]] = createAcpConnectionMock.mock.calls as unknown as [
+ [AcpConnectionConfig],
+ ];
+ expect(config.codexOptions).toEqual(
+ expect.objectContaining({ useMachineAuth: true }),
+ );
+ });
+
+ it("stops before starting Codex without authentication", async () => {
+ const agent = new Agent({ skipLogPersistence: true });
+
+ await expect(
+ agent.run("task-1", "run-1", {
+ adapter: "codex",
+ codexModelAccess: "posthog-gateway",
+ }),
+ ).rejects.toThrow("Codex authentication is not ready");
+ expect(createAcpConnectionMock).not.toHaveBeenCalled();
+ });
+
it("scopes local Claude sessions to the selected project", async () => {
const agent = new Agent({
posthog: {
diff --git a/products/desktop/packages/agent/src/agent.ts b/products/desktop/packages/agent/src/agent.ts
index 543023f79372..6ca4fb5d798f 100644
--- a/products/desktop/packages/agent/src/agent.ts
+++ b/products/desktop/packages/agent/src/agent.ts
@@ -117,12 +117,44 @@ export class Agent {
task_execution_environment: "local" as const,
};
+ const codexSubscription =
+ options.adapter === "codex" &&
+ options.codexModelAccess === "own-subscription";
+
+ if (options.adapter === "codex" && !codexSubscription && !gatewayConfig) {
+ throw new Error(
+ "Codex authentication is not ready. In Settings, select PostHog credits or connect your ChatGPT subscription, then try again.",
+ );
+ }
+
+ const codexGatewayAuth =
+ !codexSubscription && gatewayConfig
+ ? {
+ apiBaseUrl: `${gatewayConfig.gatewayUrl}/v1`,
+ apiKey: gatewayConfig.apiKey,
+ httpHeaders: {
+ ...buildPosthogPropertyHeaderRecord(
+ taskId ? { ...attribution, $ai_session_id: taskId } : {},
+ ),
+ ...buildPosthogUserHeaderRecord(userNode),
+ },
+ }
+ : undefined;
+
let codexModels: ModelInfo[] | undefined;
let sanitizedModel =
options.model && !isBlockedModelId(options.model)
? options.model
: undefined;
- if (options.adapter === "codex" && gatewayConfig) {
+ if (codexSubscription) {
+ const looksOpenAi =
+ sanitizedModel?.startsWith("gpt-") ||
+ sanitizedModel?.startsWith("openai/") ||
+ sanitizedModel?.includes("codex");
+ if (!looksOpenAi) {
+ sanitizedModel = DEFAULT_CODEX_MODEL;
+ }
+ } else if (options.adapter === "codex" && gatewayConfig) {
const models = await fetchModelsList({
gatewayUrl: gatewayConfig.gatewayUrl,
authToken: gatewayConfig.apiKey,
@@ -191,25 +223,16 @@ export class Agent {
claudeGatewayEnv,
contextWiki: options.contextWiki,
codexOptions:
- options.adapter === "codex" && gatewayConfig
+ options.adapter === "codex" && (codexSubscription || gatewayConfig)
? {
cwd: options.repositoryPath,
- apiBaseUrl: `${gatewayConfig.gatewayUrl}/v1`,
- apiKey: gatewayConfig.apiKey,
+ ...codexGatewayAuth,
binaryPath: options.codexBinaryPath,
codexHome: options.codexHome,
+ useMachineAuth: codexSubscription,
model: sanitizedModel,
reasoningEffort: options.reasoningEffort,
developerInstructions: options.developerInstructions,
- httpHeaders: taskId
- ? {
- ...buildPosthogPropertyHeaderRecord({
- ...attribution,
- $ai_session_id: taskId,
- }),
- ...buildPosthogUserHeaderRecord(userNode),
- }
- : buildPosthogUserHeaderRecord(userNode),
additionalDirectories: options.additionalDirectories,
}
: undefined,
diff --git a/products/desktop/packages/agent/src/types.ts b/products/desktop/packages/agent/src/types.ts
index 3a8337693f8b..035ddcf07689 100644
--- a/products/desktop/packages/agent/src/types.ts
+++ b/products/desktop/packages/agent/src/types.ts
@@ -1,4 +1,8 @@
-import type { Adapter, PostHogAPIConfig } from "@posthog/shared";
+import type {
+ Adapter,
+ CodexModelAccess,
+ PostHogAPIConfig,
+} from "@posthog/shared";
import type { EffortLevel } from "@posthog/shared/domain-types";
export type {
@@ -65,6 +69,7 @@ export interface TaskExecutionOptions {
adapter?: Adapter;
model?: string;
gatewayUrl?: string;
+ codexModelAccess?: CodexModelAccess;
codexBinaryPath?: string;
codexHome?: string;
reasoningEffort?: EffortLevel;
diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.ts
index e067b2c54793..1e5639c952a8 100644
--- a/products/desktop/packages/agent/tsup.config.ts
+++ b/products/desktop/packages/agent/tsup.config.ts
@@ -171,6 +171,7 @@ export default defineConfig([
"src/adapters/claude/session/models.ts",
"src/adapters/codex-app-server/models.ts",
"src/adapters/codex-app-server/local-tools-mcp-server.ts",
+ "src/adapters/codex-app-server/subscription-login.ts",
"src/adapters/claude/mcp/tool-metadata.ts",
"src/adapters/reasoning-effort.ts",
"src/execution-mode.ts",
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index f7b357281092..3b4d0eacd7fd 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -24,6 +24,7 @@ import {
type AgentSession,
type BedrockGatewayVariant,
type CloudRegion,
+ type CodexModelAccess,
classifyGatewayLimitError,
type ExecutionMode,
flattenSelectOptions,
@@ -498,6 +499,7 @@ export interface SessionServiceDeps {
spokenNotifications?: boolean;
spokenNarrationEnabled?: boolean;
bedrockGatewayVariant?: BedrockGatewayVariant;
+ codexModelAccess?: CodexModelAccess;
};
usageLimit: { show: (...args: any[]) => any };
readonly addDirectoryDialog: { open: boolean };
@@ -536,6 +538,7 @@ export interface ConnectParams {
initialPrompt?: ContentBlock[];
executionMode?: ExecutionMode;
adapter?: Adapter;
+ codexModelAccess?: CodexModelAccess;
model?: string;
reasoningLevel?: string;
contextWindow?: "200k" | "1m";
@@ -1924,6 +1927,7 @@ export class SessionService {
private stampRunConfig(session: AgentSession, params: ConnectParams): void {
session.adapter = params.adapter;
+ session.codexModelAccess = params.codexModelAccess;
session.model = params.model;
session.executionMode = params.executionMode;
session.reasoningLevel = params.reasoningLevel;
@@ -1941,6 +1945,7 @@ export class SessionService {
initialPrompt,
executionMode,
adapter,
+ codexModelAccess,
model,
reasoningLevel,
contextWindow,
@@ -2060,6 +2065,7 @@ export class SessionService {
importedSessionId,
contextWindow,
fastMode,
+ codexModelAccess,
);
}
} catch (error) {
@@ -2279,12 +2285,14 @@ export class SessionService {
rtkEnabledLocal,
spokenNarrationEnabled,
bedrockGatewayVariant,
+ codexModelAccess,
} = this.d.settings;
const result = await this.d.trpc.agent.reconnect.mutate({
taskId,
taskRunId,
repoPath,
rtkEnabled: rtkEnabledLocal,
+ codexModelAccess,
spokenNarration: spokenNarrationEnabled === true,
bedrockGatewayVariant,
apiHost: auth.apiHost,
@@ -2620,6 +2628,7 @@ export class SessionService {
importedSessionId?: string,
contextWindow?: "200k" | "1m",
fastMode?: boolean,
+ codexModelAccess?: CodexModelAccess,
): Promise<void> {
const { client } = auth;
if (!client) {
@@ -2636,7 +2645,10 @@ export class SessionService {
rtkEnabledLocal,
spokenNarrationEnabled,
bedrockGatewayVariant,
+ codexModelAccess: settingsCodexModelAccess,
} = this.d.settings;
+ const resolvedCodexModelAccess =
+ codexModelAccess ?? settingsCodexModelAccess;
const preferredModel = model ?? this.d.DEFAULT_GATEWAY_MODEL;
const result = await this.d.trpc.agent.start.mutate({
taskId,
@@ -2646,6 +2658,7 @@ export class SessionService {
projectId: auth.projectId,
permissionMode: executionMode,
adapter,
+ codexModelAccess: resolvedCodexModelAccess,
customInstructions: startCustomInstructions || undefined,
rtkEnabled: rtkEnabledLocal,
spokenNarration: spokenNarrationEnabled === true,
@@ -2663,6 +2676,7 @@ export class SessionService {
session.channel = result.channel;
session.status = "connected";
session.adapter = adapter;
+ session.codexModelAccess = resolvedCodexModelAccess;
session.model = model;
session.executionMode = executionMode;
session.reasoningLevel = reasoningLevel;
@@ -6054,6 +6068,7 @@ export class SessionService {
reasoningLevel,
contextWindow,
fastMode,
+ codexModelAccess,
} = session;
await this.teardownSession(session.taskRunId);
const authStatus = await this.getAuthCredentialsStatus();
@@ -6078,6 +6093,7 @@ export class SessionService {
undefined,
contextWindow,
fastMode,
+ codexModelAccess,
);
return;
}
diff --git a/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts
index c760f5a74cc5..77830a97bbd1 100644
--- a/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts
@@ -124,7 +124,8 @@ describe("SessionService.clearSessionError retry config", () => {
it("recreates the session with the original run configuration", async () => {
const session = makeSession({
model: "claude-fable-5",
- adapter: "claude",
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
executionMode: "auto",
reasoningLevel: "high",
contextWindow: "1m",
@@ -140,13 +141,14 @@ describe("SessionService.clearSessionError retry config", () => {
"/repo",
{ client: {} },
session.initialPrompt,
- "auto", // executionMode
- "claude", // adapter
- "claude-fable-5", // model
- "high", // reasoningLevel
- undefined, // importedSessionId
- "1m", // contextWindow
- true, // fastMode
+ "auto",
+ "codex",
+ "claude-fable-5",
+ "high",
+ undefined,
+ "1m",
+ true,
+ "own-subscription",
);
});
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
index f3e6f52ae4f8..25b10360c7b9 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -1436,7 +1436,7 @@ describe("TaskCreationSaga", () => {
});
it.each(["local", "worktree"] as const)(
- "forwards context window and fast mode to the agent session for workspaceMode=%s",
+ "forwards run configuration to the agent session for workspaceMode=%s",
async (workspaceMode) => {
const createTaskMock = vi.fn().mockResolvedValue(createTask());
mockHost.addFolder.mockResolvedValue({ id: "folder-1", path: "/repo" });
@@ -1448,13 +1448,20 @@ describe("TaskCreationSaga", () => {
content: "Ship the fix",
repoPath: "/repo",
workspaceMode,
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
contextWindow: "1m",
fastMode: true,
});
expect(result.success).toBe(true);
expect(sessionService.connectToTask).toHaveBeenCalledWith(
- expect.objectContaining({ contextWindow: "1m", fastMode: true }),
+ expect.objectContaining({
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
+ contextWindow: "1m",
+ fastMode: true,
+ }),
);
},
);
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index e8240efab6d2..dc19394d35df 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -576,6 +576,8 @@ export class TaskCreationSaga extends Saga<
if (input.executionMode)
connectParams.executionMode = input.executionMode;
if (input.adapter) connectParams.adapter = input.adapter;
+ if (input.codexModelAccess)
+ connectParams.codexModelAccess = input.codexModelAccess;
if (input.model) connectParams.model = input.model;
if (input.reasoningLevel)
connectParams.reasoningLevel = input.reasoningLevel;
diff --git a/products/desktop/packages/core/src/task-detail/taskInput.test.ts b/products/desktop/packages/core/src/task-detail/taskInput.test.ts
index 1b4c8f0aba0a..780a262ce765 100644
--- a/products/desktop/packages/core/src/task-detail/taskInput.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskInput.test.ts
@@ -38,6 +38,16 @@ describe("prepareTaskInput", () => {
expect(input.runtime).toBe("pi");
});
+ it("preserves the selected Codex model access", () => {
+ const input = prepareTaskInput("do the thing", [], {
+ workspaceMode: "local",
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
+ });
+
+ expect(input.codexModelAccess).toBe("own-subscription");
+ });
+
it("drops customInstructions for cloud when none is set", () => {
const input = prepareTaskInput("do the thing", [], {
workspaceMode: "cloud",
diff --git a/products/desktop/packages/core/src/task-detail/taskInput.ts b/products/desktop/packages/core/src/task-detail/taskInput.ts
index b17b6c73a224..a8c300ecc857 100644
--- a/products/desktop/packages/core/src/task-detail/taskInput.ts
+++ b/products/desktop/packages/core/src/task-detail/taskInput.ts
@@ -3,6 +3,7 @@ import type {
Adapter,
AgentRuntime,
CloudMcpServerRelayDesignation,
+ CodexModelAccess,
McpServerConnection,
TaskCreationInput,
WorkspaceMode,
@@ -21,6 +22,7 @@ export interface PrepareTaskInputOptions {
reuseExistingWorktree?: boolean;
executionMode?: ExecutionMode;
adapter?: Adapter;
+ codexModelAccess?: CodexModelAccess;
runtime?: AgentRuntime;
model?: string;
reasoningLevel?: string;
@@ -67,6 +69,7 @@ export function prepareTaskInput(
reuseExistingWorktree: options.reuseExistingWorktree,
executionMode: options.executionMode,
adapter: options.adapter,
+ codexModelAccess: options.codexModelAccess,
runtime: options.runtime ?? "acp",
model: options.model,
reasoningLevel: options.reasoningLevel,
diff --git a/products/desktop/packages/host-router/src/routers/agent.router.ts b/products/desktop/packages/host-router/src/routers/agent.router.ts
index 9d8a43f16432..f7678de317f2 100644
--- a/products/desktop/packages/host-router/src/routers/agent.router.ts
+++ b/products/desktop/packages/host-router/src/routers/agent.router.ts
@@ -9,6 +9,8 @@ import {
cancelPermissionInput,
cancelPromptInput,
cancelSessionInput,
+ codexSubscriptionLoginOutput,
+ codexSubscriptionStatusOutput,
getPiModelCatalogInput,
getPiModelCatalogOutput,
getPreviewConfigOptionsInput,
@@ -84,6 +86,26 @@ export const agentRouter = router({
ctx.container.get<AgentService>(AGENT_SERVICE).getRtkStatus(),
),
+ codexSubscriptionStatus: publicProcedure
+ .output(codexSubscriptionStatusOutput)
+ .query(({ ctx }) =>
+ ctx.container
+ .get<AgentService>(AGENT_SERVICE)
+ .getCodexSubscriptionStatus(),
+ ),
+
+ codexSubscriptionLoginStart: publicProcedure
+ .output(codexSubscriptionLoginOutput)
+ .mutation(({ ctx }) =>
+ ctx.container
+ .get<AgentService>(AGENT_SERVICE)
+ .startCodexSubscriptionLogin(),
+ ),
+
+ codexSubscriptionSignOut: publicProcedure.mutation(({ ctx }) =>
+ ctx.container.get<AgentService>(AGENT_SERVICE).signOutCodexSubscription(),
+ ),
+
reconnect: publicProcedure
.input(reconnectSessionInput)
.output(sessionResponseSchema.nullable())
diff --git a/products/desktop/packages/shared/src/adapter.ts b/products/desktop/packages/shared/src/adapter.ts
index 66de614a717b..66f9816e68c4 100644
--- a/products/desktop/packages/shared/src/adapter.ts
+++ b/products/desktop/packages/shared/src/adapter.ts
@@ -1 +1,3 @@
export type Adapter = "claude" | "codex";
+
+export type CodexModelAccess = "posthog-gateway" | "own-subscription";
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 20b355d5cee3..f21a64433b36 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -100,6 +100,7 @@ export interface TaskCreateProperties {
/** Worktree mode: repo has a non-empty .worktreeinclude file */
uses_worktree_include?: boolean;
adapter?: Adapter;
+ codex_model_access?: "posthog-gateway" | "own-subscription";
}
export interface TaskViewProperties {
@@ -1438,6 +1439,8 @@ export const ANALYTICS_EVENTS = {
SETTING_CHANGED: "Setting changed",
CUSTOM_SOUND_ADDED: "Custom sound added",
CUSTOM_SOUND_RECORDING_SILENT: "Custom sound recording silent",
+ CODEX_SUBSCRIPTION_CONNECTED: "Codex subscription connected",
+ CODEX_SUBSCRIPTION_SIGNED_OUT: "Codex subscription signed out",
// Feedback events
TASK_FEEDBACK: "Task feedback",
@@ -1629,6 +1632,8 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.SETTING_CHANGED]: SettingChangedProperties;
[ANALYTICS_EVENTS.CUSTOM_SOUND_ADDED]: CustomSoundAddedProperties;
[ANALYTICS_EVENTS.CUSTOM_SOUND_RECORDING_SILENT]: never;
+ [ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_CONNECTED]: never;
+ [ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_SIGNED_OUT]: never;
// Feedback events
[ANALYTICS_EVENTS.TASK_FEEDBACK]: TaskFeedbackProperties;
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 61be9bedd6bc..1ef364860d8d 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -34,6 +34,8 @@ export const KIMI_MODEL_FLAG = "tasks-kimi-k3";
export const FAST_MODE_FLAG = "posthog-desktop-fast-mode";
/** Spoken narration (agent speaks via the `speak` tool). Gated for a staged rollout. */
export const SPOKEN_NARRATION_FLAG = "posthog-code-spoken-narration";
+export const CODEX_OWN_SUBSCRIPTION_FLAG =
+ "posthog-code-codex-own-subscription";
// Gates importing and relaying local MCP servers into cloud task runs.
export const LOCAL_MCP_IMPORT_FLAG = "posthog-code-local-mcp-import";
/**
diff --git a/products/desktop/packages/shared/src/sessions.ts b/products/desktop/packages/shared/src/sessions.ts
index f987fae5a8cb..43fb5f2918a7 100644
--- a/products/desktop/packages/shared/src/sessions.ts
+++ b/products/desktop/packages/shared/src/sessions.ts
@@ -6,7 +6,7 @@ import type {
SessionConfigSelectOption,
SessionConfigSelectOptions,
} from "@agentclientprotocol/sdk";
-import type { Adapter } from "./adapter";
+import type { Adapter, CodexModelAccess } from "./adapter";
import type { SkillButtonId } from "./analytics-events";
import type { TaskRunArtifact, TaskRunStatus } from "./domain-types";
import type { ExecutionMode } from "./exec-types";
@@ -77,6 +77,7 @@ export interface AgentSession {
processedLineCount?: number;
framework?: "claude";
adapter?: Adapter;
+ codexModelAccess?: CodexModelAccess;
model?: string;
executionMode?: ExecutionMode;
reasoningLevel?: string;
diff --git a/products/desktop/packages/shared/src/task-creation-domain.ts b/products/desktop/packages/shared/src/task-creation-domain.ts
index 0f7956e7892a..6e509d818adf 100644
--- a/products/desktop/packages/shared/src/task-creation-domain.ts
+++ b/products/desktop/packages/shared/src/task-creation-domain.ts
@@ -1,4 +1,4 @@
-import type { Adapter } from "./adapter";
+import type { Adapter, CodexModelAccess } from "./adapter";
import type { AgentRuntime } from "./agent-runtime";
import type { CloudRunSource, PrAuthorshipMode } from "./cloud";
import type { Task } from "./domain-types";
@@ -37,6 +37,7 @@ export interface TaskCreationInput {
githubUserIntegrationId?: string;
executionMode?: ExecutionMode;
adapter?: Adapter;
+ codexModelAccess?: CodexModelAccess;
runtime?: AgentRuntime;
model?: string;
reasoningLevel?: string;
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
index a77dcbfbc2e4..116d28c5d3f5 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -394,6 +394,7 @@ export const ChannelHomeComposer = forwardRef<
<WorkspaceModeSelect
value={workspaceMode}
onChange={setWorkspaceMode}
+ adapter={runtime === "pi" ? undefined : adapter}
overrideModes={["local", "cloud"]}
selectedCloudEnvironmentId={selectedCloudEnvId}
onCloudEnvironmentChange={setSelectedCloudEnvId}
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index e0a6f016ed8b..4f369dcad6be 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -271,6 +271,7 @@ const mockFeatureFlags = vi.hoisted(() => ({
const mockSettingsState = vi.hoisted(() => ({
customInstructions: "",
+ codexModelAccess: "posthog-gateway" as "posthog-gateway" | "own-subscription",
spokenNotifications: false,
syncCustomInstructionsFromFile: false,
syncedCustomInstructions: null as {
@@ -485,6 +486,7 @@ describe("SessionService", () => {
mockHasSessionPromptEventForTaskRun.mockReturnValue(false);
resetSessionService();
mockSettingsState.customInstructions = "";
+ mockSettingsState.codexModelAccess = "posthog-gateway";
mockSettingsState.spokenNotifications = false;
mockFeatureFlags.isEnabled.mockReturnValue(false);
mockSettingsState.syncCustomInstructionsFromFile = false;
@@ -870,6 +872,40 @@ describe("SessionService", () => {
);
});
+ it("starts Codex with the access selected for the task", async () => {
+ const service = getSessionService();
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);
+ mockBuildAuthenticatedClient.mockReturnValue({
+ ...mockAuthenticatedClient,
+ createTaskRun: vi.fn().mockResolvedValue({ id: "run-789" }),
+ appendTaskRunLog: vi.fn(),
+ });
+ mockTrpcAgent.start.mutate.mockResolvedValue({
+ channel: "test-channel",
+ configOptions: [],
+ });
+
+ await service.connectToTask({
+ task: createMockTask(),
+ repoPath: "/repo",
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
+ });
+
+ expect(mockTrpcAgent.start.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
+ }),
+ );
+ expect(mockSessionStoreSetters.setSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: "codex",
+ codexModelAccess: "own-subscription",
+ }),
+ );
+ });
+
it("deduplicates concurrent connection attempts", async () => {
const service = getSessionService();
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
index 5395ebddb434..01d07c375791 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
@@ -23,6 +23,7 @@ import {
BEDROCK_GATEWAY_VARIANTS,
BEDROCK_LLM_GATEWAY_FLAG,
type BedrockGatewayVariant,
+ CODEX_OWN_SUBSCRIPTION_FLAG,
SPOKEN_NARRATION_FLAG,
} from "@posthog/shared";
import {
@@ -151,21 +152,24 @@ function buildSessionServiceDeps(): SessionServiceDeps {
},
get settings() {
const state = useSettingsStore.getState();
+ const featureFlags = resolveService<FeatureFlags>(FEATURE_FLAGS);
+ const codexSubscriptionEnabled =
+ featureFlags.isEnabled(CODEX_OWN_SUBSCRIPTION_FLAG) ||
+ import.meta.env.DEV;
return {
...state,
customInstructions: getEffectiveCustomInstructions(state),
spokenNarrationEnabled: shouldEnableSpokenNarration(
state.spokenNotifications,
- resolveService<FeatureFlags>(FEATURE_FLAGS).isEnabled(
- SPOKEN_NARRATION_FLAG,
- ),
+ featureFlags.isEnabled(SPOKEN_NARRATION_FLAG),
import.meta.env.DEV,
),
bedrockGatewayVariant: resolveBedrockGatewayVariant(
- resolveService<FeatureFlags>(FEATURE_FLAGS).getVariant(
- BEDROCK_LLM_GATEWAY_FLAG,
- ),
+ featureFlags.getVariant(BEDROCK_LLM_GATEWAY_FLAG),
),
+ codexModelAccess: codexSubscriptionEnabled
+ ? state.codexModelAccess
+ : undefined,
};
},
usageLimit: {
diff --git a/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx
new file mode 100644
index 000000000000..a9d1ea9751a7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx
@@ -0,0 +1,166 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import { Button, Switch } from "@posthog/quill";
+import { ANALYTICS_EVENTS } from "@posthog/shared";
+import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";
+import {
+ applyCodexModelAccess,
+ shouldShowCodexSubscriptionControls,
+ useCodexSubscription,
+} from "@posthog/ui/features/settings/useCodexSubscription";
+import { toast } from "@posthog/ui/primitives/toast";
+import { track } from "@posthog/ui/shell/analytics";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { registerCodexSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { type ReactElement, useEffect, useState } from "react";
+
+const SIGN_IN_POLL_TIMEOUT_MS = 10 * 60_000 + 15_000;
+const SIGN_IN_LAUNCH_FEEDBACK_MS = 4_000;
+
+export function CodexSubscriptionSettings(): ReactElement | null {
+ const subscription = useCodexSubscription();
+ const hostTRPC = useHostTRPC();
+ const queryClient = useQueryClient();
+ const [awaitingLogin, setAwaitingLogin] = useState(false);
+ const [launching, setLaunching] = useState(false);
+
+ const statusQuery = hostTRPC.agent.codexSubscriptionStatus.queryOptions();
+ const { data: status } = useQuery({
+ ...statusQuery,
+ enabled: subscription.flagEnabled,
+ refetchInterval: (query) =>
+ awaitingLogin && query.state.data?.appLoggedIn !== true ? 2000 : false,
+ });
+ const loggedIn = status?.appLoggedIn === true;
+
+ useEffect(() => {
+ if (!awaitingLogin || !loggedIn) return;
+ setAwaitingLogin(false);
+ track(ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_CONNECTED);
+ applyCodexModelAccess("own-subscription", true);
+ registerCodexSubscription({ access: "own-subscription", connected: true });
+ }, [awaitingLogin, loggedIn]);
+
+ const login = useMutation({
+ ...hostTRPC.agent.codexSubscriptionLoginStart.mutationOptions(),
+ onSuccess: ({ authUrl }) => {
+ openExternalUrl(authUrl);
+ setAwaitingLogin(true);
+ setLaunching(true);
+ },
+ onError: (error) =>
+ toast.error("Couldn't start ChatGPT sign-in", {
+ description: error.message,
+ }),
+ });
+ useEffect(() => {
+ if (!launching) return;
+ const timer = setTimeout(
+ () => setLaunching(false),
+ SIGN_IN_LAUNCH_FEEDBACK_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [launching]);
+
+ useEffect(() => {
+ if (!awaitingLogin) return;
+ const timer = setTimeout(
+ () => setAwaitingLogin(false),
+ SIGN_IN_POLL_TIMEOUT_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [awaitingLogin]);
+ const connecting = login.isPending || launching;
+ const signOut = useMutation({
+ ...hostTRPC.agent.codexSubscriptionSignOut.mutationOptions(),
+ onSuccess: () => {
+ track(ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_SIGNED_OUT);
+ applyCodexModelAccess("posthog-gateway", false);
+ registerCodexSubscription({
+ access: "posthog-gateway",
+ connected: false,
+ });
+ },
+ onError: (error) =>
+ toast.error("Couldn't sign out of ChatGPT", {
+ description: error.message,
+ }),
+ onSettled: () => {
+ setAwaitingLogin(false);
+ void queryClient.invalidateQueries({ queryKey: statusQuery.queryKey });
+ },
+ });
+
+ const visible = shouldShowCodexSubscriptionControls({
+ flagEnabled: subscription.flagEnabled,
+ adapter: "codex",
+ });
+ if (!visible) {
+ return null;
+ }
+
+ if (!loggedIn) {
+ return (
+ <SettingsCardRow
+ label="ChatGPT account"
+ description={
+ awaitingLogin
+ ? "Finish signing in with your browser. This updates automatically"
+ : "Connect to run local and worktree Codex sessions on your ChatGPT plan"
+ }
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ loading={connecting}
+ disabled={connecting}
+ onClick={() => login.mutate()}
+ >
+ {connecting
+ ? "Opening browser..."
+ : awaitingLogin
+ ? "Try again"
+ : "Connect ChatGPT account"}
+ </Button>
+ </SettingsCardRow>
+ );
+ }
+
+ return (
+ <SettingsCardRow
+ label="Use your ChatGPT subscription"
+ description={
+ <span className="flex flex-col gap-1">
+ <span>
+ Local and worktree Codex sessions run on your ChatGPT plan instead
+ of PostHog credits. Cloud tasks always use PostHog credits
+ </span>
+ <span className="flex items-center gap-1.5">
+ <span
+ className="inline-block h-1.5 w-1.5 rounded-full bg-(--green-9)"
+ aria-hidden
+ />
+ ChatGPT account connected
+ <span aria-hidden>&middot;</span>
+ <button
+ type="button"
+ className="cursor-pointer hover:underline"
+ disabled={signOut.isPending}
+ onClick={() => signOut.mutate()}
+ >
+ Sign out
+ </button>
+ </span>
+ </span>
+ }
+ >
+ <Switch
+ size="sm"
+ checked={subscription.subscriptionOn}
+ onCheckedChange={(checked) =>
+ subscription.setSubscriptionOn(checked === true)
+ }
+ />
+ </SettingsCardRow>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/HarnessSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/HarnessSettings.tsx
index 832f4c6d6dc0..4d722cba7958 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/HarnessSettings.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/HarnessSettings.tsx
@@ -5,6 +5,7 @@ import {
SettingsCardRow,
SettingsSection,
} from "@posthog/ui/features/settings/components/SettingsCard";
+import { CodexSubscriptionSettings } from "@posthog/ui/features/settings/sections/CodexSubscriptionSettings";
import { PermissionsSettings } from "@posthog/ui/features/settings/sections/PermissionsSettings";
import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
import { Tooltip } from "@posthog/ui/primitives/Tooltip";
@@ -168,6 +169,7 @@ export function HarnessSettings() {
description="Configuration that lives with the Codex harness"
>
<SettingsCard>
+ <CodexSubscriptionSettings />
<SettingsCardRow
label="MCP servers"
description={
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
index 1abbb3694c20..1e60c1360576 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -10,6 +10,7 @@ import { clampAutoCompactPercent } from "@posthog/core/sessions/autoCompact";
import type {
Adapter,
AgentRuntime,
+ CodexModelAccess,
ExecutionMode,
WorkspaceMode,
} from "@posthog/shared";
@@ -279,12 +280,14 @@ interface SettingsStore {
// sessions, cloud covers cloud runs.
rtkEnabledLocal: boolean;
rtkEnabledCloud: boolean;
+ codexModelAccess: CodexModelAccess;
setAllowBypassPermissions: (enabled: boolean) => void;
setPreventSleepWhileRunning: (enabled: boolean) => void;
setDebugLogsCloudRuns: (enabled: boolean) => void;
setAutoPublishCloudRuns: (enabled: boolean) => void;
setRtkEnabledLocal: (enabled: boolean) => void;
setRtkEnabledCloud: (enabled: boolean) => void;
+ setCodexModelAccess: (mode: CodexModelAccess) => void;
// Terminal
terminalFont: TerminalFont;
@@ -541,6 +544,7 @@ export const useSettingsStore = create<SettingsStore>()(
autoPublishCloudRuns: true,
rtkEnabledLocal: true,
rtkEnabledCloud: true,
+ codexModelAccess: "posthog-gateway",
setAllowBypassPermissions: (enabled) =>
set({ allowBypassPermissions: enabled }),
setPreventSleepWhileRunning: (enabled) =>
@@ -550,6 +554,7 @@ export const useSettingsStore = create<SettingsStore>()(
set({ autoPublishCloudRuns: enabled }),
setRtkEnabledLocal: (enabled) => set({ rtkEnabledLocal: enabled }),
setRtkEnabledCloud: (enabled) => set({ rtkEnabledCloud: enabled }),
+ setCodexModelAccess: (mode) => set({ codexModelAccess: mode }),
// Terminal
terminalFont: "berkeley-mono",
@@ -699,6 +704,7 @@ export const useSettingsStore = create<SettingsStore>()(
autoPublishCloudRuns: state.autoPublishCloudRuns,
rtkEnabledLocal: state.rtkEnabledLocal,
rtkEnabledCloud: state.rtkEnabledCloud,
+ codexModelAccess: state.codexModelAccess,
// Terminal
terminalFont: state.terminalFont,
diff --git a/products/desktop/packages/ui/src/features/settings/useCodexSubscription.test.ts b/products/desktop/packages/ui/src/features/settings/useCodexSubscription.test.ts
new file mode 100644
index 000000000000..6a492845b128
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/useCodexSubscription.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vitest";
+import {
+ codexNeedsConnection,
+ effectiveCodexModelAccess,
+ shouldShowCodexSubscriptionControls,
+} from "./useCodexSubscription";
+
+const status = (appLoggedIn: boolean) => ({
+ appLoggedIn,
+});
+
+describe("codex subscription gating", () => {
+ it.each([
+ [
+ "flag off hides everything",
+ { flagEnabled: false, adapter: "codex" as const },
+ false,
+ ],
+ [
+ "claude harness hides everything",
+ { flagEnabled: true, adapter: "claude" as const },
+ false,
+ ],
+ [
+ "no adapter selected hides everything",
+ { flagEnabled: true, adapter: undefined },
+ false,
+ ],
+ [
+ "codex under the flag shows so a fresh ChatGPT user can reach sign-in",
+ { flagEnabled: true, adapter: "codex" as const },
+ true,
+ ],
+ ])("%s", (_name, input, expected) => {
+ expect(shouldShowCodexSubscriptionControls(input)).toBe(expected);
+ });
+
+ it.each([
+ [
+ "cloud tasks never bill the subscription",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loggedIn: true,
+ workspaceMode: "cloud" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "not signed in falls back to the gateway",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loggedIn: false,
+ workspaceMode: "local" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "flag off falls back to the gateway",
+ {
+ flagEnabled: false,
+ subscriptionOn: true,
+ loggedIn: true,
+ workspaceMode: "local" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "local on the subscription",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loggedIn: true,
+ workspaceMode: "local" as const,
+ },
+ "own-subscription",
+ ],
+ [
+ "worktree on the subscription",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loggedIn: true,
+ workspaceMode: "worktree" as const,
+ },
+ "own-subscription",
+ ],
+ ])("%s", (_name, input, expected) => {
+ expect(effectiveCodexModelAccess(input)).toBe(expected);
+ });
+
+ it.each([
+ [
+ "unknown status while loading is not treated as signed out",
+ { flagEnabled: true, subscriptionOn: true, status: undefined },
+ false,
+ ],
+ [
+ "confirmed signed out needs connection",
+ { flagEnabled: true, subscriptionOn: true, status: status(false) },
+ true,
+ ],
+ [
+ "signed in does not need connection",
+ { flagEnabled: true, subscriptionOn: true, status: status(true) },
+ false,
+ ],
+ [
+ "subscription off never needs connection",
+ { flagEnabled: true, subscriptionOn: false, status: status(false) },
+ false,
+ ],
+ [
+ "flag off never needs connection",
+ { flagEnabled: false, subscriptionOn: true, status: status(false) },
+ false,
+ ],
+ ])("%s", (_name, input, expected) => {
+ expect(codexNeedsConnection(input)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/useCodexSubscription.ts b/products/desktop/packages/ui/src/features/settings/useCodexSubscription.ts
new file mode 100644
index 000000000000..78d4c1e76ecb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/useCodexSubscription.ts
@@ -0,0 +1,134 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import {
+ type Adapter,
+ ANALYTICS_EVENTS,
+ CODEX_OWN_SUBSCRIPTION_FLAG,
+ type CodexModelAccess,
+} from "@posthog/shared";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { track } from "@posthog/ui/shell/analytics";
+import { registerCodexSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";
+import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";
+import { useQuery } from "@tanstack/react-query";
+
+export interface CodexSubscriptionStatus {
+ appLoggedIn: boolean;
+}
+
+export function shouldShowCodexSubscriptionControls(input: {
+ flagEnabled: boolean;
+ adapter: Adapter | undefined;
+}): boolean {
+ return input.flagEnabled && input.adapter === "codex";
+}
+
+export function codexNeedsConnection(input: {
+ flagEnabled: boolean;
+ subscriptionOn: boolean;
+ status: CodexSubscriptionStatus | undefined;
+}): boolean {
+ return (
+ input.flagEnabled &&
+ input.subscriptionOn &&
+ input.status?.appLoggedIn === false
+ );
+}
+
+export function effectiveCodexModelAccess(input: {
+ flagEnabled: boolean;
+ subscriptionOn: boolean;
+ loggedIn: boolean;
+ workspaceMode: "local" | "worktree" | "cloud";
+}): CodexModelAccess {
+ const usesOwnSubscription =
+ input.flagEnabled &&
+ input.subscriptionOn &&
+ input.loggedIn &&
+ input.workspaceMode !== "cloud";
+ return usesOwnSubscription ? "own-subscription" : "posthog-gateway";
+}
+
+export function applyCodexModelAccess(
+ next: CodexModelAccess,
+ connected: boolean,
+): void {
+ const prev = useSettingsStore.getState().codexModelAccess;
+ if (prev === next) return;
+ useSettingsStore.getState().setCodexModelAccess(next);
+ track(ANALYTICS_EVENTS.SETTING_CHANGED, {
+ setting_name: "codex_model_access",
+ new_value: next,
+ old_value: prev,
+ });
+ registerCodexSubscription({ access: next, connected });
+}
+
+export async function registerCodexSubscriptionAtBoot(
+ fetchStatus: () => Promise<CodexSubscriptionStatus>,
+ flagEnabled: boolean,
+): Promise<void> {
+ await settingsHydrated();
+ const status = await fetchStatus();
+ const access: CodexModelAccess = flagEnabled
+ ? useSettingsStore.getState().codexModelAccess
+ : "posthog-gateway";
+ registerCodexSubscription({
+ access,
+ connected: status.appLoggedIn,
+ });
+}
+
+function settingsHydrated(): Promise<void> {
+ if (useSettingsStore.getState()._hasHydrated) return Promise.resolve();
+ return new Promise((resolve) => {
+ const unsubscribe = useSettingsStore.subscribe((state) => {
+ if (state._hasHydrated) {
+ unsubscribe();
+ resolve();
+ }
+ });
+ });
+}
+
+export interface CodexSubscription {
+ flagEnabled: boolean;
+ subscriptionOn: boolean;
+ status: CodexSubscriptionStatus | undefined;
+ loggedIn: boolean;
+ needsConnection: boolean;
+ setSubscriptionOn: (on: boolean) => void;
+}
+
+export function useCodexSubscription(): CodexSubscription {
+ const flagEnabled =
+ useFeatureFlag(CODEX_OWN_SUBSCRIPTION_FLAG) || import.meta.env.DEV;
+ const codexModelAccess = useSettingsStore((s) => s.codexModelAccess);
+ const { localWorkspaces } = useHostCapabilities();
+ const hostTRPC = useHostTRPC();
+ const canQueryStatus = flagEnabled && localWorkspaces;
+ const { data: status } = useQuery({
+ ...hostTRPC.agent.codexSubscriptionStatus.queryOptions(),
+ enabled: canQueryStatus,
+ });
+
+ const subscriptionOn = codexModelAccess === "own-subscription";
+ const loggedIn = status?.appLoggedIn === true;
+
+ return {
+ flagEnabled,
+ subscriptionOn,
+ status,
+ loggedIn,
+ needsConnection: codexNeedsConnection({
+ flagEnabled,
+ subscriptionOn,
+ status,
+ }),
+ setSubscriptionOn: (on) =>
+ applyCodexModelAccess(
+ on ? "own-subscription" : "posthog-gateway",
+ loggedIn,
+ ),
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index a9ac6acd1818..93fb14675ca7 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -31,6 +31,7 @@ import {
import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";
import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";
import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+import { useCodexSubscription } from "@posthog/ui/features/settings/useCodexSubscription";
import { NEW_TASK_COMPOSER_FADE_MS } from "@posthog/ui/features/task-detail/newTaskComposerTransition";
import type { TaskInputReportAssociation } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";
import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";
@@ -366,6 +367,7 @@ export function TaskInput({
!!channelContextSource && !channelContextDismissed;
const adapter = lastUsedAdapter;
+ const codexSubscription = useCodexSubscription();
const prefillRequestKey = initialPromptKey ?? initialPrompt;
// Applying a prefilled prompt replaces whatever the composer had, so it must
@@ -497,6 +499,12 @@ export function TaskInput({
pinCloud: !!initialCloudRepository,
});
+ const showCodexNotConnectedNotice =
+ runtime !== "pi" &&
+ adapter === "codex" &&
+ workspaceMode !== "cloud" &&
+ codexSubscription.needsConnection;
+
const {
repositories: visibleCloudRepositories,
isPending: cloudRepositoriesLoading,
@@ -1295,6 +1303,7 @@ export function TaskInput({
<WorkspaceModeSelect
value={workspaceMode}
onChange={setWorkspaceMode}
+ adapter={runtime === "pi" ? undefined : adapter}
selectedCloudEnvironmentId={selectedCloudEnvId}
onCloudEnvironmentChange={setSelectedCloudEnvId}
selectedCustomImageId={selectedCustomImageId}
@@ -1581,6 +1590,19 @@ export function TaskInput({
if (canSubmit) void submitTask();
}}
/>
+ {showCodexNotConnectedNotice && (
+ <div className="mx-2 mt-1.5 text-[12px] text-gray-10">
+ Codex is set to use your ChatGPT plan, but no account is
+ connected. Sessions use PostHog credits.{" "}
+ <button
+ type="button"
+ className="underline"
+ onClick={() => openSettings("harness")}
+ >
+ Connect in Settings
+ </button>
+ </div>
+ )}
{activeReportAssociation && (
<div className="-mt-px mx-2 flex select-none items-center justify-between gap-2 rounded-b-md border border-blue-6 border-t-0 bg-blue-2 px-2 py-1 text-[12px] text-blue-11">
<span className="flex min-w-0 flex-1 items-center gap-1">
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
index 1b5a9b263939..0fe7ebb2749d 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/WorkspaceModeSelect.tsx
@@ -1,4 +1,11 @@
-import { ArrowsSplit, Cloud, Cube, Laptop, Plus } from "@phosphor-icons/react";
+import {
+ ArrowsSplit,
+ Cloud,
+ Cube,
+ Gear,
+ Laptop,
+ Plus,
+} from "@phosphor-icons/react";
import {
Button,
DropdownMenu,
@@ -14,8 +21,12 @@ import {
ItemTitle,
MenuLabel,
} from "@posthog/quill";
-import type { WorkspaceMode } from "@posthog/shared";
+import type { Adapter, WorkspaceMode } from "@posthog/shared";
import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+import {
+ shouldShowCodexSubscriptionControls,
+ useCodexSubscription,
+} from "@posthog/ui/features/settings/useCodexSubscription";
import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";
import { useCallback, useMemo, useState } from "react";
import { useSandboxCustomImages } from "../../settings/sections/environments/useSandboxCustomImages";
@@ -30,6 +41,7 @@ interface WorkspaceModeSelectProps {
size?: "1" | "2";
disabled?: boolean;
overrideModes?: WorkspaceMode[];
+ adapter?: Adapter;
selectedCloudEnvironmentId?: string | null;
onCloudEnvironmentChange?: (envId: string | null) => void;
selectedCustomImageId?: string | null;
@@ -63,6 +75,7 @@ export function WorkspaceModeSelect({
onChange,
disabled,
overrideModes,
+ adapter,
selectedCloudEnvironmentId,
onCloudEnvironmentChange,
selectedCustomImageId,
@@ -70,6 +83,7 @@ export function WorkspaceModeSelect({
}: WorkspaceModeSelectProps) {
const { localWorkspaces } = useHostCapabilities();
const cloudModeEnabled = useCloudModeEnabled();
+ const codexSubscription = useCodexSubscription();
const { environments } = useSandboxEnvironments();
const { images, customImagesEnabled } = useSandboxCustomImages();
@@ -148,6 +162,36 @@ export function WorkspaceModeSelect({
sideOffset={6}
className="w-auto min-w-[280px]"
>
+ {localModes.length > 0 && (
+ <div className="flex items-center justify-between px-2 py-1">
+ <MenuLabel className="p-0">Local</MenuLabel>
+ {shouldShowCodexSubscriptionControls({
+ flagEnabled: codexSubscription.flagEnabled,
+ adapter,
+ }) && (
+ <div className="flex items-center gap-1.5">
+ {codexSubscription.subscriptionOn &&
+ codexSubscription.loggedIn && (
+ <span className="text-[11px] text-muted-foreground">
+ Using Codex subscription
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={() => {
+ setMenuOpen(false);
+ openSettings("harness");
+ }}
+ aria-label="Subscription settings"
+ className="flex cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0.5 text-muted-foreground transition-colors hover:bg-fill-hover hover:text-foreground"
+ >
+ <Gear size={12} />
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+
<DropdownMenuGroup>
{localModes.map((item) => (
<DropdownMenuItem
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
index e3d401bfdc18..fd1ef8fdf5b6 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.ts
@@ -16,6 +16,7 @@ import {
type Adapter,
type AgentRuntime,
ANALYTICS_EVENTS,
+ type CodexModelAccess,
PROJECT_BLUEBIRD_FLAG,
type TaskCreationInput,
type WorkspaceMode,
@@ -28,6 +29,10 @@ import {
import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChannels";
import { useTaskRepositoryDraftStore } from "@posthog/ui/features/canvas/stores/taskRepositoryDraftStore";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import {
+ effectiveCodexModelAccess,
+ useCodexSubscription,
+} from "@posthog/ui/features/settings/useCodexSubscription";
import { waitForComposerExit } from "@posthog/ui/features/task-detail/newTaskComposerTransition";
import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";
import { navigateToTaskPending } from "@posthog/ui/router/navigationBridge";
@@ -135,6 +140,7 @@ async function trackTaskCreated(
input: TaskCreationInput,
selectedDirectory: string,
hostClient: HostTrpcClient,
+ codexModelAccess?: CodexModelAccess,
): Promise<void> {
try {
const workspaceMode = input.workspaceMode ?? "local";
@@ -175,6 +181,7 @@ async function trackTaskCreated(
uses_worktree_link: usesWorktreeLink,
uses_worktree_include: usesWorktreeInclude,
adapter: input.adapter,
+ codex_model_access: codexModelAccess,
});
} catch (error) {
log.warn("Failed to track Task created event", { error });
@@ -216,6 +223,7 @@ export function useTaskCreation({
const [isCreatingTask, setIsCreatingTask] = useState(false);
const [isExitingComposer, setIsExitingComposer] = useState(false);
const hostClient = useHostTRPCClient();
+ const codexSubscription = useCodexSubscription();
const trpc = useHostTRPC();
const queryClient = useQueryClient();
const defaultAdditionalDirectoriesQuery = useQuery(
@@ -401,6 +409,15 @@ export function useTaskCreation({
localMcpServers,
adapter,
);
+ const codexModelAccess =
+ runtime !== "pi" && adapter === "codex"
+ ? effectiveCodexModelAccess({
+ flagEnabled: codexSubscription.flagEnabled,
+ subscriptionOn: codexSubscription.subscriptionOn,
+ loggedIn: codexSubscription.loggedIn,
+ workspaceMode,
+ })
+ : undefined;
const input = prepareTaskInput(serializedContent, filePaths, {
// Repo-optional surfaces may still supply an explicit task folder or
// repository selection; otherwise creation falls back to scratch.
@@ -415,6 +432,7 @@ export function useTaskCreation({
reuseExistingWorktree,
executionMode,
adapter,
+ codexModelAccess,
runtime,
model,
reasoningLevel,
@@ -547,7 +565,12 @@ export function useTaskCreation({
if (allowNoRepo && channelId) {
useTaskRepositoryDraftStore.getState().clearDraft(channelId);
}
- void trackTaskCreated(input, selectedDirectory, hostClient);
+ void trackTaskCreated(
+ input,
+ selectedDirectory,
+ hostClient,
+ input.codexModelAccess,
+ );
// Repo-less channel tasks create no workspace row (the agent runs in
// a scratch dir surfaced as a synthetic workspace), so the normal
// workspace.create invalidation never fires. Refresh the workspace
@@ -682,6 +705,9 @@ export function useTaskCreation({
queryClient,
taskService,
tasks,
+ codexSubscription.flagEnabled,
+ codexSubscription.loggedIn,
+ codexSubscription.subscriptionOn,
],
);
diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.subscription-verify.test.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.subscription-verify.test.ts
new file mode 100644
index 000000000000..30b094711f53
--- /dev/null
+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.subscription-verify.test.ts
@@ -0,0 +1,124 @@
+import { setRootContainer } from "@posthog/di/container";
+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
+import { ANALYTICS_TRACKER, track } from "@posthog/ui/shell/analytics";
+import {
+ initializePostHog,
+ posthogAnalyticsTracker,
+ registerCodexSubscription,
+} from "@posthog/ui/shell/posthogAnalyticsImpl";
+import posthog from "posthog-js/dist/module.full.no-external";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type EnqueuedRequest = {
+ method: string;
+ url: string;
+ data: { event: string; properties: Record<string, unknown> };
+};
+
+function tapRequestQueue(): { enqueued: EnqueuedRequest[] } {
+ const enqueued: EnqueuedRequest[] = [];
+ const queue = (
+ posthog as unknown as {
+ _requestQueue: { enqueue: (r: EnqueuedRequest) => void };
+ }
+ )._requestQueue;
+ const realEnqueue = queue.enqueue.bind(queue);
+ queue.enqueue = (request: EnqueuedRequest) => {
+ enqueued.push(JSON.parse(JSON.stringify(request)) as EnqueuedRequest);
+ return realEnqueue(request);
+ };
+ return { enqueued };
+}
+
+function captureEventsOnWire(
+ enqueued: EnqueuedRequest[],
+): EnqueuedRequest["data"][] {
+ return enqueued
+ .filter((r) => r.method === "POST" && r.url.endsWith("/e/"))
+ .map((r) => r.data);
+}
+
+describe("subscription analytics evidence", () => {
+ beforeEach(() => {
+ vi.stubEnv("VITE_POSTHOG_API_KEY", "phc_test_key");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("1", { status: 200 })),
+ );
+ (window as unknown as { fetch: unknown }).fetch = globalThis.fetch;
+
+ initializePostHog();
+ posthog.sessionRecording?.stopRecording();
+
+ setRootContainer({
+ get: (id: unknown) => {
+ if (id === ANALYTICS_TRACKER) return posthogAnalyticsTracker;
+ throw new Error(`unbound ${String(id)}`);
+ },
+ getAll: () => [],
+ isBound: (id: unknown) => id === ANALYTICS_TRACKER,
+ bind: () => {
+ throw new Error("not needed");
+ },
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ });
+
+ it("registers the subscription state as SDK super properties", () => {
+ registerCodexSubscription({ access: "own-subscription", connected: true });
+
+ expect(posthog.get_property("codex_model_access" as never)).toBe(
+ "own-subscription",
+ );
+ expect(posthog.get_property("codex_subscription_connected" as never)).toBe(
+ true,
+ );
+ });
+
+ it("sends a session's run event with the subscription state attached", async () => {
+ const { enqueued } = tapRequestQueue();
+ registerCodexSubscription({ access: "own-subscription", connected: true });
+
+ track(ANALYTICS_EVENTS.TASK_RUN, {
+ task_id: "task-evidence-1",
+ execution_type: "local",
+ });
+ await Promise.resolve();
+
+ const events = captureEventsOnWire(enqueued);
+ const runEvents = events.filter(
+ (e) => e.event === ANALYTICS_EVENTS.TASK_RUN,
+ );
+ expect(runEvents).toHaveLength(1);
+ expect(runEvents[0]?.properties.codex_model_access).toBe(
+ "own-subscription",
+ );
+ expect(runEvents[0]?.properties.codex_subscription_connected).toBe(true);
+ expect(runEvents[0]?.properties.task_id).toBe("task-evidence-1");
+ });
+
+ it("gateway runs are tracked too, with their own billing value", async () => {
+ const { enqueued } = tapRequestQueue();
+ registerCodexSubscription({
+ access: "posthog-gateway",
+ connected: false,
+ });
+
+ track(ANALYTICS_EVENTS.TASK_RUN, {
+ task_id: "task-evidence-gw",
+ execution_type: "local",
+ });
+ await Promise.resolve();
+
+ const events = captureEventsOnWire(enqueued);
+ const runEvents = events.filter(
+ (e) => e.event === ANALYTICS_EVENTS.TASK_RUN,
+ );
+ expect(runEvents).toHaveLength(1);
+ expect(runEvents[0]?.properties.codex_model_access).toBe("posthog-gateway");
+ });
+});
diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
index 4ca9aa2cca40..d79204acfeea 100644
--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
@@ -33,12 +33,18 @@ export type HostInfoProperties = { platform: string; arch: string };
let isInitialized = false;
+export type CodexSubscriptionState = {
+ access: "posthog-gateway" | "own-subscription";
+ connected: boolean;
+};
+
// Cached so it can be re-applied after posthog.reset() clears super properties.
let registeredAppVersion: string | null = null;
let registeredHostInfo: HostInfoProperties | null = null;
+let registeredCodexSubscription: CodexSubscriptionState | null = null;
// posthog.reset() wipes super properties, so these are re-registered after each reset.
-function registerPersistentSuperProperties() {
+function registerPersistentSuperProperties(): void {
posthog.register({
team: "posthog-code",
...(registeredAppVersion !== null
@@ -47,6 +53,9 @@ function registerPersistentSuperProperties() {
...(registeredHostInfo !== null
? hostInfoProperties(registeredHostInfo)
: {}),
+ ...(registeredCodexSubscription !== null
+ ? codexSubscriptionProperties(registeredCodexSubscription)
+ : {}),
});
}
@@ -57,6 +66,28 @@ function hostInfoProperties({ platform, arch }: HostInfoProperties): {
return { os_platform: platform, os_arch: arch };
}
+function codexSubscriptionProperties({
+ access,
+ connected,
+}: CodexSubscriptionState): {
+ codex_model_access: string;
+ codex_subscription_connected: boolean;
+} {
+ return {
+ codex_model_access: access,
+ codex_subscription_connected: connected,
+ };
+}
+
+export function registerCodexSubscription(state: CodexSubscriptionState): void {
+ registeredCodexSubscription = state;
+ if (!isInitialized) {
+ return;
+ }
+
+ posthog.register(codexSubscriptionProperties(state));
+}
+
type PendingFlagListener = {
callback: () => void;
unsubscribe: (() => void) | null;
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index 2f96483a630f..552611f4eb78 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
@@ -150,6 +150,12 @@ vi.mock("./context-wiki", () => ({
prepareContextWiki: mockPrepareContextWiki,
}));
+vi.mock("./codex-home", () => ({
+ cleanupCodexHome: vi.fn().mockResolvedValue(undefined),
+ getCodexHomeDir: vi.fn(() => "/mock/codex-home"),
+ prepareCodexHome: vi.fn().mockResolvedValue("/mock/codex-home"),
+}));
+
vi.mock("node:fs", async (importOriginal) => {
const original = await importOriginal<typeof import("node:fs")>();
return {
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
index d963fa105ad2..47dbe83c016a 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -21,6 +21,12 @@ import {
} from "@posthog/agent";
import type { McpToolApprovals } from "@posthog/agent/adapters/claude/mcp/tool-metadata";
import { hydrateSessionJsonl } from "@posthog/agent/adapters/claude/session/jsonl-hydration";
+import {
+ type CodexLoginSession,
+ hasCodexChatgptLogin,
+ signOutCodexChatgpt,
+ startCodexChatgptLogin,
+} from "@posthog/agent/adapters/codex-app-server/subscription-login";
import {
getContextWindowOptions,
getFastModeOptions,
@@ -70,6 +76,7 @@ import {
type BedrockGatewayVariant,
buildCloudTaskConfigOptions,
type CloudRegion,
+ type CodexModelAccess,
type ExecutionMode,
isAuthError,
resolveCloudInitialPermissionMode,
@@ -88,7 +95,11 @@ import type { ProcessTrackingService } from "../process-tracking/process-trackin
import { loadSessionEnvOverrides } from "../session-env/loader";
import { isScratchPath } from "../workspace/scratch";
import type { AgentAuthAdapter, McpToolInstallations } from "./auth-adapter";
-import { cleanupCodexHome, prepareCodexHome } from "./codex-home";
+import {
+ cleanupCodexHome,
+ getCodexHomeDir,
+ prepareCodexHome,
+} from "./codex-home";
import { prepareContextWiki } from "./context-wiki";
import { discoverExternalPlugins } from "./discover-plugins";
import {
@@ -108,6 +119,7 @@ import type {
import {
AgentServiceEvent,
type AgentServiceEvents,
+ type CodexSubscriptionStatus,
type Credentials,
type EffortLevel,
type InterruptReason,
@@ -273,6 +285,7 @@ interface SessionConfig {
/** The agent's session ID (for resume - SDK session ID for Claude, Codex's session ID for Codex) */
sessionId?: string;
adapter?: Adapter;
+ codexModelAccess?: CodexModelAccess;
/** Permission mode to use for the session */
permissionMode?: string;
/** Custom instructions injected into the system prompt */
@@ -507,6 +520,59 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
return this.bundledResources.resolve(`.vite/build/codex-acp/${binary}`);
}
+ private codexLogin?: CodexLoginSession;
+ private codexAuthGeneration = 0;
+
+ async getCodexSubscriptionStatus(): Promise<CodexSubscriptionStatus> {
+ if (this.codexLogin) return { appLoggedIn: false };
+ return {
+ appLoggedIn: await hasCodexChatgptLogin({
+ binaryPath: this.getCodexBinaryPath(),
+ }),
+ };
+ }
+
+ async startCodexSubscriptionLogin(): Promise<{ authUrl: string }> {
+ await this.prepareCodexAccountChange();
+ const login = await startCodexChatgptLogin({
+ binaryPath: this.getCodexBinaryPath(),
+ });
+ this.codexLogin = login;
+ void login.completed.then((loggedIn) => {
+ if (this.codexLogin === login) this.codexLogin = undefined;
+ this.log.info("Codex subscription login finished", { loggedIn });
+ });
+ return { authUrl: login.authUrl };
+ }
+
+ async signOutCodexSubscription(): Promise<void> {
+ await this.prepareCodexAccountChange();
+ await signOutCodexChatgpt({
+ binaryPath: this.getCodexBinaryPath(),
+ });
+ }
+
+ private async prepareCodexAccountChange(): Promise<void> {
+ this.codexAuthGeneration += 1;
+ const currentLogin = this.codexLogin;
+ this.codexLogin = undefined;
+ await Promise.all([
+ currentLogin?.cancel(),
+ this.stopCodexSubscriptionSessions(),
+ ]);
+ }
+
+ private async stopCodexSubscriptionSessions(): Promise<void> {
+ const sessionIds = [...this.sessions.entries()]
+ .filter(
+ ([, session]) => session.config.codexModelAccess === "own-subscription",
+ )
+ .map(([taskRunId]) => taskRunId);
+ await Promise.all(
+ sessionIds.map((taskRunId) => this.cleanupSession(taskRunId)),
+ );
+ }
+
/**
* Respond to a pending permission request from the UI.
* This resolves the promise that the agent is waiting on.
@@ -878,27 +944,28 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
this.posthogPluginService.getPluginPath(),
"skills",
);
+ const codexSubscription =
+ adapter === "codex" && config.codexModelAccess === "own-subscription";
+ const codexAuthGeneration = this.codexAuthGeneration;
let codexHome: string | undefined;
if (adapter === "codex") {
- try {
+ if (codexSubscription) {
+ codexHome = getCodexHomeDir(this.storagePaths.appDataPath, taskRunId);
+ await fs.promises.mkdir(codexHome, { recursive: true });
+ } else {
codexHome = await prepareCodexHome({
appDataPath: this.storagePaths.appDataPath,
taskRunId,
bundledSkillsDir,
log: this.log,
});
- } catch (err) {
- // A skills-prep failure must not kill the session; Codex falls back
- // to its default home and the user's own ~/.agents/skills.
- this.log.warn("Failed to prepare codex home", {
- error: err instanceof Error ? err.message : String(err),
- });
}
}
const acpConnection = await agent.run(taskId, taskRunId, {
adapter,
+ codexModelAccess: codexSubscription ? "own-subscription" : undefined,
gatewayUrl: proxyUrl,
contextWiki: contextWiki ?? undefined,
codexBinaryPath:
@@ -1215,6 +1282,13 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
};
this.sessions.set(taskRunId, session);
+ if (
+ codexSubscription &&
+ codexAuthGeneration !== this.codexAuthGeneration
+ ) {
+ await this.cleanupSession(taskRunId);
+ throw new Error("The Codex account changed during task setup.");
+ }
this.recordActivity(taskRunId);
if (isRetry) {
@@ -1700,6 +1774,8 @@ For git operations while detached:
@preDestroy()
async cleanupAll(): Promise<void> {
+ await this.codexLogin?.cancel();
+ this.codexLogin = undefined;
for (const { handle } of this.idleTimeouts.values()) clearTimeout(handle);
this.idleTimeouts.clear();
const sessionIds = Array.from(this.sessions.keys());
@@ -2161,6 +2237,8 @@ For git operations while detached:
logUrl: "logUrl" in params ? params.logUrl : undefined,
sessionId: "sessionId" in params ? params.sessionId : undefined,
adapter: "adapter" in params ? params.adapter : undefined,
+ codexModelAccess:
+ "codexModelAccess" in params ? params.codexModelAccess : undefined,
permissionMode:
"permissionMode" in params ? params.permissionMode : undefined,
customInstructions:
diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
index 2736284bf28d..5282ebec6767 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts
@@ -20,6 +20,7 @@ vi.mock("node:os", async (importOriginal) => {
});
import {
+ cleanupAllCodexHomes,
cleanupCodexHome,
getCodexHomeDir,
prepareCodexHome,
@@ -221,6 +222,26 @@ describe("prepareCodexHome", () => {
expect(existsSync(rollout)).toBe(true);
});
+ it("cleanupAllCodexHomes cleans every run and keeps each thread rollout", async () => {
+ const codexHomesDir = path.join(appDataPath, "codex-home");
+ for (const runId of ["run-a", "run-b"]) {
+ const runDir = path.join(codexHomesDir, runId);
+ await mkdir(path.join(runDir, "sessions"), { recursive: true });
+ await writeFile(path.join(runDir, "state_5.sqlite"), "state");
+ await writeFile(path.join(runDir, "sessions", "rollout.jsonl"), "{}");
+ }
+
+ await cleanupAllCodexHomes(appDataPath);
+
+ for (const runId of ["run-a", "run-b"]) {
+ const runDir = path.join(codexHomesDir, runId);
+ expect(existsSync(path.join(runDir, "state_5.sqlite"))).toBe(false);
+ expect(existsSync(path.join(runDir, "sessions", "rollout.jsonl"))).toBe(
+ true,
+ );
+ }
+ });
+
// Windows needs elevated rights to create a directory symlink.
it.skipIf(process.platform === "win32")(
"cleanupCodexHome unlinks a run home that is a link instead of emptying its target",
diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
index dd88ea144e84..63f6c7658333 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts
@@ -57,6 +57,22 @@ export async function cleanupCodexHome(
}
}
+export async function cleanupAllCodexHomes(appDataPath: string): Promise<void> {
+ const codexHomesDir = path.join(appDataPath, "codex-home");
+ let taskRunIds: string[];
+ try {
+ taskRunIds = await fs.promises.readdir(codexHomesDir);
+ } catch {
+ return;
+ }
+
+ await Promise.all(
+ taskRunIds
+ .filter(isSafePathSegment)
+ .map((taskRunId) => cleanupCodexHome(appDataPath, taskRunId)),
+ );
+}
+
/**
* Builds a private CODEX_HOME for PostHog's own Codex sessions, so they
* load the bundled PostHog catalog and the user's `~/.claude/skills` — without
diff --git a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts b/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
index 230227a592a1..f48cfa277cae 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
@@ -42,6 +42,11 @@ export const sessionConfigSchema = z.object({
export type SessionConfig = z.infer<typeof sessionConfigSchema>;
+export const codexModelAccessSchema = z.enum([
+ "posthog-gateway",
+ "own-subscription",
+]);
+
// Sized for personalization synced from an AGENTS.md/CLAUDE.md file, which
// can be far larger than the 2000-char hand-typed settings field. Kept equal
// to OsService's truncation length (USER_AGENT_INSTRUCTIONS_MAX_LENGTH) or a
@@ -64,6 +69,7 @@ export const startSessionInput = z.object({
autoProgress: z.boolean().optional(),
runMode: z.enum(["local", "cloud"]).optional(),
adapter: z.enum(["claude", "codex"]).optional(),
+ codexModelAccess: codexModelAccessSchema.optional(),
additionalDirectories: z.array(z.string()).optional(),
customInstructions: customInstructionsField,
/**
@@ -254,6 +260,7 @@ export const reconnectSessionInput = z.object({
logUrl: z.string().optional(),
sessionId: z.string().optional(),
adapter: z.enum(["claude", "codex"]).optional(),
+ codexModelAccess: codexModelAccessSchema.optional(),
/** Additional directories Claude can access beyond cwd (for worktree support) */
additionalDirectories: z.array(z.string()).optional(),
permissionMode: z.string().optional(),
@@ -281,6 +288,18 @@ export const rtkStatusOutput = z.object({
export type RtkStatus = z.infer<typeof rtkStatusOutput>;
+export const codexSubscriptionStatusOutput = z.object({
+ appLoggedIn: z.boolean(),
+});
+
+export type CodexSubscriptionStatus = z.infer<
+ typeof codexSubscriptionStatusOutput
+>;
+
+export const codexSubscriptionLoginOutput = z.object({
+ authUrl: z.string(),
+});
+
// Set config option input (for Codex reasoning level, etc.)
export const setConfigOptionInput = z.object({
sessionId: z.string(),
diff --git a/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.test.ts b/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.test.ts
new file mode 100644
index 000000000000..cfc88b2f4e72
--- /dev/null
+++ b/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.test.ts
@@ -0,0 +1,95 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockExecFileSync = vi.hoisted(() => vi.fn());
+const mockPlatform = vi.hoisted(() => vi.fn(() => "darwin"));
+
+vi.mock("node:child_process", () => ({
+ execFileSync: mockExecFileSync,
+}));
+
+vi.mock("node:os", () => ({
+ platform: mockPlatform,
+}));
+
+import { killProcessTree } from "./process-utils";
+
+describe("killProcessTree", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mockExecFileSync.mockReset();
+ mockPlatform.mockReset();
+ mockPlatform.mockReturnValue("darwin");
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it("signals Unix descendants before their parent", async () => {
+ mockExecFileSync.mockReturnValue(
+ [
+ "4242 100 Thu Aug 28 04:00:00 2026",
+ "5000 4242 Thu Aug 28 04:00:01 2026",
+ "6000 5000 Thu Aug 28 04:00:02 2026",
+ "5001 4242 Thu Aug 28 04:00:03 2026",
+ ].join("\n"),
+ );
+ const killProcess = vi.spyOn(process, "kill").mockReturnValue(true);
+
+ killProcessTree(4242);
+
+ expect(killProcess.mock.calls).toEqual([
+ [6000, "SIGTERM"],
+ [5000, "SIGTERM"],
+ [5001, "SIGTERM"],
+ [4242, "SIGTERM"],
+ ]);
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(killProcess.mock.calls.slice(4)).toEqual([
+ [6000, "SIGKILL"],
+ [5000, "SIGKILL"],
+ [5001, "SIGKILL"],
+ [4242, "SIGKILL"],
+ ]);
+ });
+
+ it("does not force-stop a reused Unix PID", async () => {
+ mockExecFileSync
+ .mockReturnValueOnce(
+ [
+ "4242 100 Thu Aug 28 04:00:00 2026",
+ "5000 4242 Thu Aug 28 04:00:01 2026",
+ ].join("\n"),
+ )
+ .mockReturnValueOnce(
+ [
+ "4242 100 Thu Aug 28 04:00:00 2026",
+ "5000 100 Thu Aug 28 04:00:06 2026",
+ ].join("\n"),
+ );
+ const killProcess = vi.spyOn(process, "kill").mockReturnValue(true);
+
+ killProcessTree(4242);
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ expect(killProcess.mock.calls).toEqual([
+ [5000, "SIGTERM"],
+ [4242, "SIGTERM"],
+ [4242, "SIGKILL"],
+ ]);
+ });
+
+ it("uses taskkill for the complete process tree on Windows", () => {
+ mockPlatform.mockReturnValue("win32");
+
+ killProcessTree(4242);
+
+ expect(mockExecFileSync).toHaveBeenCalledWith(
+ "taskkill",
+ ["/PID", "4242", "/T", "/F"],
+ { stdio: "ignore" },
+ );
+ });
+});
diff --git a/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.ts b/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.ts
index 5cd9d4e68652..48beb07a612c 100644
--- a/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.ts
+++ b/products/desktop/packages/workspace-server/src/services/process-tracking/process-utils.ts
@@ -1,39 +1,96 @@
-import { execSync } from "node:child_process";
+import { execFileSync } from "node:child_process";
import { platform } from "node:os";
const SIGKILL_GRACE_MS = 5_000;
-/**
- * Kill a process and all its children by killing the process group.
- * On Unix, we use process.kill(-pid) to kill the entire process group.
- * On Windows, we use taskkill with /T flag to kill the process tree.
- */
+interface UnixProcess {
+ pid: number;
+ parentPid: number;
+ startedAt: string;
+}
+
+function readUnixProcessTable(): Map<number, UnixProcess> | undefined {
+ let processTable: string;
+ try {
+ processTable = execFileSync("ps", ["-ax", "-o", "pid=,ppid=,lstart="], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ } catch {
+ return undefined;
+ }
+
+ const processes = new Map<number, UnixProcess>();
+ for (const line of processTable.split("\n")) {
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/);
+ if (!match) continue;
+ const pid = Number.parseInt(match[1], 10);
+ const parentPid = Number.parseInt(match[2], 10);
+ processes.set(pid, { pid, parentPid, startedAt: match[3] });
+ }
+ return processes;
+}
+
+function getUnixProcessTree(rootPid: number): UnixProcess[] {
+ const processes = readUnixProcessTable();
+ if (!processes) {
+ return [{ pid: rootPid, parentPid: 0, startedAt: "" }];
+ }
+
+ const childrenByParent = new Map<number, number[]>();
+ for (const processInfo of processes.values()) {
+ const { pid, parentPid } = processInfo;
+ const children = childrenByParent.get(parentPid) ?? [];
+ children.push(pid);
+ childrenByParent.set(parentPid, children);
+ }
+
+ const processTree: UnixProcess[] = [];
+ const visited = new Set<number>();
+ const addProcessTree = (pid: number): void => {
+ if (visited.has(pid)) return;
+ visited.add(pid);
+ for (const childPid of childrenByParent.get(pid) ?? []) {
+ addProcessTree(childPid);
+ }
+ processTree.push(
+ processes.get(pid) ?? { pid, parentPid: 0, startedAt: "" },
+ );
+ };
+ addProcessTree(rootPid);
+ return processTree;
+}
+
export function killProcessTree(pid: number): void {
try {
if (platform() === "win32") {
- // Windows: use taskkill with /T to kill process tree
- execSync(`taskkill /PID ${pid} /T /F`, { stdio: "ignore" });
+ execFileSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
+ stdio: "ignore",
+ });
} else {
- // SIGTERM the process group first, fall back to individual process
+ const processTree = getUnixProcessTree(pid);
let sent = false;
- for (const target of [-pid, pid]) {
+ for (const processInfo of processTree) {
try {
- process.kill(target, "SIGTERM");
+ process.kill(processInfo.pid, "SIGTERM");
sent = true;
- break;
} catch {}
}
if (!sent) return;
- // Force kill after a grace period — unref so the timer doesn't delay app exit.
- // We skip the liveness check since isProcessAlive only tests the group leader;
- // orphaned children in the same group would be missed. The catch blocks
- // handle ESRCH if everything already exited.
setTimeout(() => {
- for (const target of [-pid, pid]) {
+ const currentProcesses = readUnixProcessTable();
+ if (!currentProcesses) return;
+ for (const processInfo of processTree) {
+ if (
+ currentProcesses.get(processInfo.pid)?.startedAt !==
+ processInfo.startedAt
+ ) {
+ continue;
+ }
try {
- process.kill(target, "SIGKILL");
+ process.kill(processInfo.pid, "SIGKILL");
} catch {}
}
}, SIGKILL_GRACE_MS).unref();