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 claude sessions on the user's own Claude subscription (#90933)

Shy Alter1e6a94851cdb
diff --git a/products/desktop/apps/code/src/main/utils/env.ts b/products/desktop/apps/code/src/main/utils/env.ts
index 9b6011e41e38..e95c03e5d03a 100644
--- a/products/desktop/apps/code/src/main/utils/env.ts
+++ b/products/desktop/apps/code/src/main/utils/env.ts
@@ -1,5 +1,6 @@
import { mkdirSync } from "node:fs";
import path from "node:path";
+import { setMachineClaudeConfigDir } from "@posthog/agent/adapters/claude/machine-auth";
function requireEnv(name: string): string {
const value = process.env[name];
@@ -30,7 +31,10 @@ export function getAppVersion(): string {
export function ensureClaudeConfigDir(): void {
const existing = process.env.CLAUDE_CONFIG_DIR;
- if (existing) return;
+ setMachineClaudeConfigDir(existing);
+ if (existing) {
+ return;
+ }
const claudeDir = path.join(getUserDataDir(), "claude");
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 ace264aeed72..66aeafb18bb5 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,13 @@
import type { Contribution } from "@posthog/di/contribution";
-import { CODEX_OWN_SUBSCRIPTION_FLAG } from "@posthog/shared";
-import { registerCodexSubscriptionAtBoot } from "@posthog/ui/features/settings/useCodexSubscription";
+import {
+ type Adapter,
+ CLAUDE_OWN_SUBSCRIPTION_FLAG,
+ CODEX_OWN_SUBSCRIPTION_FLAG,
+} from "@posthog/shared";
+import {
+ registerSubscriptionAtBoot,
+ type SubscriptionStatus,
+} from "@posthog/ui/features/settings/adapterSubscription";
import {
initializePostHog,
posthogFeatureFlags,
@@ -13,6 +20,23 @@ import { injectable } from "inversify";
const log = logger.scope("app-boot");
+const SUBSCRIPTION_BOOT: {
+ adapter: Adapter;
+ flag: string;
+ fetchStatus: () => Promise<SubscriptionStatus>;
+}[] = [
+ {
+ adapter: "codex",
+ flag: CODEX_OWN_SUBSCRIPTION_FLAG,
+ fetchStatus: () => trpcClient.agent.codexSubscriptionStatus.query(),
+ },
+ {
+ adapter: "claude",
+ flag: CLAUDE_OWN_SUBSCRIPTION_FLAG,
+ fetchStatus: () => trpcClient.agent.claudeSubscriptionStatus.query(),
+ },
+];
+
@injectable()
export class AnalyticsBootContribution implements Contribution {
start(): void {
@@ -36,18 +60,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,
- });
+ for (const { adapter, flag, fetchStatus } of SUBSCRIPTION_BOOT) {
+ try {
+ await registerSubscriptionAtBoot(
+ adapter,
+ fetchStatus,
+ posthogFeatureFlags.isEnabled(flag) || import.meta.env.DEV,
+ );
+ } catch (error) {
+ log.warn(
+ `Failed to register ${adapter} subscription super properties`,
+ { error },
+ );
+ }
}
})();
}
diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.json
index ed12be0ce60e..b8318c08ed75 100644
--- a/products/desktop/packages/agent/package.json
+++ b/products/desktop/packages/agent/package.json
@@ -88,6 +88,14 @@
"types": "./dist/adapters/codex-app-server/subscription-login.d.ts",
"import": "./dist/adapters/codex-app-server/subscription-login.js"
},
+ "./adapters/claude/machine-auth": {
+ "types": "./dist/adapters/claude/machine-auth.d.ts",
+ "import": "./dist/adapters/claude/machine-auth.js"
+ },
+ "./adapters/claude/subscription-login": {
+ "types": "./dist/adapters/claude/subscription-login.d.ts",
+ "import": "./dist/adapters/claude/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 bb15ede42f24..b1a86cc73426 100644
--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts
+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts
@@ -14,6 +14,7 @@ import {
type StreamPair,
} from "../utils/streams";
import { ClaudeAcpAgent } from "./claude/claude-agent";
+import type { MachineClaudeAuth } from "./claude/machine-auth";
import type { GatewayEnv } from "./claude/session/options";
import { nativeCodexBinaryPath } from "./codex-app-server/binary-path";
import { CodexAppServerAgent } from "./codex-app-server/codex-app-server-agent";
@@ -38,6 +39,7 @@ export type AcpConnectionConfig = {
enricherEnabled?: boolean;
/** Explicit gateway config for the Claude adapter — prevents global process.env mutation. */
claudeGatewayEnv?: GatewayEnv;
+ claudeMachineAuth?: MachineClaudeAuth;
/** Per-session context wiki mount — prevents global process.env mutation. */
contextWiki?: ContextWikiEnv;
};
@@ -125,6 +127,7 @@ function createClaudeConnection(config: AcpConnectionConfig): AcpConnection {
onStructuredOutput: config.onStructuredOutput,
posthogApiConfig: resolveEnricherApiConfig(config),
gatewayEnv: config.claudeGatewayEnv,
+ machineAuth: config.claudeMachineAuth,
contextWiki: config.contextWiki,
});
return agent;
diff --git a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts b/products/desktop/packages/agent/src/adapters/base-acp-agent.ts
index d01e5ac8dcba..0e89ef5dc86a 100644
--- a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/base-acp-agent.ts
@@ -16,7 +16,7 @@ import type {
WriteTextFileRequest,
WriteTextFileResponse,
} from "@agentclientprotocol/sdk";
-import { restrictedModelMeta } from "@posthog/shared";
+import { isAnthropicModelId, restrictedModelMeta } from "@posthog/shared";
import {
compareModelsForPicker,
DEFAULT_GATEWAY_MODEL,
@@ -140,6 +140,10 @@ export abstract class BaseAcpAgent implements Agent {
throw new Error("Method not implemented.");
}
+ protected usesMachineAuth(): boolean {
+ return false;
+ }
+
async getModelConfigOptions(
currentModelOverride?: string,
gatewayUrl?: string,
@@ -191,6 +195,21 @@ export abstract class BaseAcpAgent implements Agent {
let currentModelId = currentModelOverride ?? DEFAULT_GATEWAY_MODEL;
+ if (
+ this.usesMachineAuth() &&
+ currentModelId !== DEFAULT_GATEWAY_MODEL &&
+ !isAnthropicModelId(currentModelId)
+ ) {
+ this.logger.warn(
+ "Saved model is not available without the gateway; falling back to default",
+ {
+ requestedModel: currentModelId,
+ fallbackModel: DEFAULT_GATEWAY_MODEL,
+ },
+ );
+ currentModelId = DEFAULT_GATEWAY_MODEL;
+ }
+
if (!options.some((opt) => opt.value === currentModelId)) {
if (!isClaudeAdapterModelId(currentModelId)) {
// A model the Claude adapter can't drive reached it, which means the adapter and model
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 7b577b2776b5..16a4863e93a7 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -109,6 +109,7 @@ import {
taskStateToPlanEntries,
} from "./conversion/task-state";
import type { EnrichedReadCache } from "./hooks";
+import type { MachineClaudeAuth } from "./machine-auth";
import { createLocalToolsMcpServer } from "./mcp/local-tools";
import {
clearMcpToolMetadataCache,
@@ -342,11 +343,16 @@ export interface ClaudeAcpAgentOptions {
posthogApiConfig?: PostHogAPIConfig;
/** Explicit gateway config — avoids global process.env mutation across concurrent sessions. */
gatewayEnv?: GatewayEnv;
+ machineAuth?: MachineClaudeAuth;
/** Per-session context wiki mount — avoids global process.env mutation across concurrent sessions. */
contextWiki?: ContextWikiEnv;
}
export class ClaudeAcpAgent extends BaseAcpAgent {
+ protected override usesMachineAuth(): boolean {
+ return !!this.options?.machineAuth;
+ }
+
readonly adapterName = "claude";
declare session: Session;
toolUseCache: ToolUseCache;
@@ -1915,7 +1921,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
abortController: newAbortController,
// `rest.model` is the creation-time value; the user may have switched
// models since, so re-root the new Query on the live session model.
- ...rerootedModelOptions(session.modelId, rest.fallbackModel),
+ ...rerootedModelOptions(
+ session.modelId,
+ rest.fallbackModel,
+ !!this.options?.machineAuth,
+ ),
};
const newInput = new Pushable<SDKUserMessage>();
@@ -2139,7 +2149,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
abortController,
// `rest.model` is the creation-time value; the user may have
// switched models since, so answer on the live session model.
- ...rerootedModelOptions(this.session.modelId, rest.fallbackModel),
+ ...rerootedModelOptions(
+ this.session.modelId,
+ rest.fallbackModel,
+ !!this.options?.machineAuth,
+ ),
};
const oneShot = query({
@@ -2249,7 +2263,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
abortController: newAbortController,
// `rest.model` is the creation-time value; the user may have switched
// models since, so re-root the new Query on the live session model.
- ...rerootedModelOptions(prev.modelId, rest.fallbackModel),
+ ...rerootedModelOptions(
+ prev.modelId,
+ rest.fallbackModel,
+ !!this.options?.machineAuth,
+ ),
};
const newInput = new Pushable<SDKUserMessage>();
@@ -2640,7 +2658,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
const input = new Pushable<SDKUserMessage>();
- const settingsManager = new SettingsManager(cwd);
+ const settingsManager = new SettingsManager(
+ cwd,
+ !!this.options?.machineAuth,
+ );
await settingsManager.initialize();
// The session's explicit pick outranks the shared claude settings file:
@@ -2781,6 +2802,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
taskState,
getCurrentModelId: () => this.session?.modelId,
gatewayEnv: this.options?.gatewayEnv,
+ machineAuth: this.options?.machineAuth,
bedrockGatewayVariant,
contextWiki: this.options?.contextWiki,
onTaskStateChange: async () => {
diff --git a/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts b/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
new file mode 100644
index 000000000000..4acf116e7206
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
@@ -0,0 +1,66 @@
+import * as os from "node:os";
+import * as path from "node:path";
+
+export interface MachineClaudeAuth {
+ configDir?: string;
+}
+
+export const MACHINE_AUTH_STRIPPED_KEYS = [
+ "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_AUTH_TOKEN",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_CUSTOM_HEADERS",
+ "OPENAI_BASE_URL",
+ "OPENAI_API_KEY",
+ "CLAUDE_CODE_USE_BEDROCK",
+ "CLAUDE_CODE_USE_VERTEX",
+ "CLAUDE_CODE_USE_FOUNDRY",
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
+ "CLAUDE_CODE_USE_MANTLE",
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
+ "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
+ "CLAUDE_CODE_PROPAGATE_TRACEPARENT",
+ "OTEL_TRACES_EXPORTER",
+ "OTEL_EXPORTER_OTLP_PROTOCOL",
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "TRACEPARENT",
+ "TRACESTATE",
+] as const;
+
+let resolvedMachineAuth: MachineClaudeAuth = {};
+
+export function setMachineClaudeConfigDir(configDir: string | undefined): void {
+ resolvedMachineAuth = configDir ? { configDir } : {};
+}
+
+export function machineClaudeAuth(): MachineClaudeAuth {
+ return resolvedMachineAuth;
+}
+
+export function applyMachineClaudeAuth(
+ env: Record<string, string | undefined>,
+ auth: MachineClaudeAuth,
+): void {
+ for (const key of MACHINE_AUTH_STRIPPED_KEYS) {
+ delete env[key];
+ }
+ if (auth.configDir) {
+ env.CLAUDE_CONFIG_DIR = auth.configDir;
+ } else {
+ env.CLAUDE_CONFIG_DIR = path.join(os.homedir(), ".claude");
+ }
+}
+
+export function machineClaudeAuthShellEnv(auth: MachineClaudeAuth): {
+ set: Record<string, string>;
+ unset: string[];
+} {
+ const unset: string[] = [...MACHINE_AUTH_STRIPPED_KEYS];
+ if (auth.configDir) {
+ return { set: { CLAUDE_CONFIG_DIR: auth.configDir }, unset };
+ }
+ return {
+ set: { CLAUDE_CONFIG_DIR: path.join(os.homedir(), ".claude") },
+ unset,
+ };
+}
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/models.ts b/products/desktop/packages/agent/src/adapters/claude/session/models.ts
index 044837e4bd18..29f7b0b15eb1 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/models.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/models.ts
@@ -26,10 +26,14 @@ export function resolveFallbackModel(modelId: string): string | undefined {
export function rerootedModelOptions(
modelId: string | undefined,
existingFallbackModel?: string,
+ machineAuth?: boolean,
):
| { model: string; fallbackModel: string | undefined }
| Record<string, never> {
if (!modelId) return {};
+ if (machineAuth) {
+ return { model: modelId, fallbackModel: undefined };
+ }
const fallbackModel =
existingFallbackModel && existingFallbackModel !== modelId
? existingFallbackModel
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
index d26b880bf8bf..a1663c13e654 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.test.ts
@@ -447,6 +447,111 @@ describe("buildSessionOptions", () => {
);
});
+ describe("machineAuth (own Claude subscription)", () => {
+ const STRIPPED_KEYS = [
+ "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_AUTH_TOKEN",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_CUSTOM_HEADERS",
+ "CLAUDE_CODE_USE_BEDROCK",
+ "CLAUDE_CODE_USE_VERTEX",
+ "CLAUDE_CODE_USE_FOUNDRY",
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
+ "CLAUDE_CODE_USE_MANTLE",
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ "TRACEPARENT",
+ ] as const;
+ const original: Partial<Record<string, string | undefined>> = {};
+
+ beforeEach(() => {
+ for (const key of STRIPPED_KEYS) {
+ original[key] = process.env[key];
+ process.env[key] = `ambient-${key}`;
+ }
+ process.env.CLAUDE_CODE_OAUTH_TOKEN = "user-oauth-token";
+ });
+
+ afterEach(() => {
+ for (const key of STRIPPED_KEYS) {
+ const value = original[key];
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
+ });
+
+ it("strips ambient and gateway credentials and telemetry, and sends no x-posthog headers", () => {
+ const env = buildSessionOptions({
+ ...makeParams(),
+ machineAuth: {},
+ gatewayEnv: {
+ anthropicBaseUrl: "https://gateway.example.com",
+ anthropicAuthToken: "gateway-token",
+ openaiBaseUrl: "https://gateway.example.com/v1",
+ openaiApiKey: "gateway-token",
+ anthropicCustomHeaders: "x-posthog-property-task_id: task-abc",
+ posthogProjectId: "42",
+ },
+ }).env;
+
+ expect(env).toBeDefined();
+ for (const key of STRIPPED_KEYS) {
+ expect(env?.[key]).toBeUndefined();
+ }
+ expect(env?.OPENAI_BASE_URL).toBeUndefined();
+ expect(env?.OPENAI_API_KEY).toBeUndefined();
+ expect(env?.CLAUDE_CODE_OAUTH_TOKEN).toBe("user-oauth-token");
+ for (const [key, value] of Object.entries(env ?? {})) {
+ expect(value).not.toContain("x-posthog-");
+ expect(key).not.toMatch(/X-PostHog/i);
+ }
+ });
+
+ it.each([
+ { configDir: undefined, expected: path.join(os.homedir(), ".claude") },
+ { configDir: "/home/me/.claude", expected: "/home/me/.claude" },
+ ])(
+ "runs against the machine config dir $configDir, not the app one",
+ ({ configDir, expected }) => {
+ process.env.CLAUDE_CONFIG_DIR = "/app-data/claude";
+ try {
+ const env = buildSessionOptions({
+ ...makeParams(),
+ machineAuth: { configDir },
+ }).env;
+
+ expect(env?.CLAUDE_CONFIG_DIR).toBe(expected);
+ } finally {
+ delete process.env.CLAUDE_CONFIG_DIR;
+ }
+ },
+ );
+
+ it("keeps session behavior flags and the Electron node mode", () => {
+ const env = buildSessionOptions({
+ ...makeParams(),
+ machineAuth: {},
+ }).env;
+
+ expect(env?.CLAUDE_CODE_ENABLE_ASK_USER_QUESTION_TOOL).toBe("true");
+ expect(env?.ENABLE_TOOL_SEARCH).toBe("auto:0");
+ expect(env?.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS).toBe("1");
+ });
+
+ it("skips the pinned gateway-era fallback model", () => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ machineAuth: {},
+ });
+
+ expect(options.fallbackModel).toBeUndefined();
+ });
+ });
+
describe("per-session context wiki env", () => {
const KEYS = [
"POSTHOG_CONTEXT_LAYER_PATH",
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
index 6de0c0fdf9ba..c797d1d9a21a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -40,6 +40,10 @@ import {
type EnrichedReadCache,
type OnModeChange,
} from "../hooks";
+import {
+ applyMachineClaudeAuth,
+ type MachineClaudeAuth,
+} from "../machine-auth";
import { type CodeExecutionMode, toSdkPermissionMode } from "../tools";
import type { EffortLevel } from "../types";
import { buildAppendedInstructions } from "./instructions";
@@ -115,6 +119,7 @@ export interface BuildOptionsParams {
getCurrentModelId?: () => string | undefined;
/** Explicit gateway config — prevents global process.env mutation. */
gatewayEnv?: GatewayEnv;
+ machineAuth?: MachineClaudeAuth;
/** Matched `bedrock-llm-gateway` variant; `test` serves this session from Bedrock. */
bedrockGatewayVariant?: BedrockGatewayVariant;
/** Per-session context wiki mount — prevents global process.env mutation. */
@@ -175,7 +180,45 @@ function buildEnvironment(
sessionId?: string,
bedrockGatewayVariant?: BedrockGatewayVariant,
contextWiki?: ContextWikiEnv,
+ machineAuth?: MachineClaudeAuth,
): Record<string, string> {
+ // SDK 0.3.142 made MCP servers connect in the background by default. That
+ // default is what we want: a slow or unreachable user MCP server (PostHog
+ // MCP, custom stdio servers) would otherwise stall turn 1 by up to ~5s per
+ // server. We honor an explicit override from the caller's environment for
+ // sessions that genuinely need MCP tools available on turn 1.
+ const mcpNonblocking = process.env.MCP_CONNECTION_NONBLOCKING;
+
+ const env: Record<string, string> = {
+ ...process.env,
+ ...((process.versions.electron || process.env.ELECTRON_RUN_AS_NODE) && {
+ ELECTRON_RUN_AS_NODE: "1",
+ }),
+ CLAUDE_CODE_ENABLE_ASK_USER_QUESTION_TOOL: "true",
+ // Offload all MCP tools by default
+ ENABLE_TOOL_SEARCH: "auto:0",
+ // Enable idle state as end-of-turn signal (required for SDK 0.2.114+)
+ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1",
+ ...(mcpNonblocking !== undefined && {
+ MCP_CONNECTION_NONBLOCKING: mcpNonblocking,
+ }),
+ };
+
+ if (machineAuth) {
+ applyMachineClaudeAuth(env, machineAuth);
+ } else {
+ applyGatewayAuth(env, gateway, sessionId, bedrockGatewayVariant);
+ }
+ applyContextWikiEnv(env, contextWiki);
+ return env;
+}
+
+function applyGatewayAuth(
+ env: Record<string, string>,
+ gateway: GatewayEnv | undefined,
+ sessionId: string | undefined,
+ bedrockGatewayVariant: BedrockGatewayVariant | undefined,
+): void {
// Custom HTTP headers reach the model only through the Claude CLI subprocess,
// which reads them from this env var (newline-delimited `name: value` lines)
// — the SDK has no direct header option. We finalize them here, the single
@@ -218,14 +261,28 @@ function buildEnvironment(
`x-posthog-flag-${BEDROCK_LLM_GATEWAY_FLAG}: ${bedrockGatewayVariant}`,
);
}
- const customHeaders = headerLines.join("\n");
+ env.ANTHROPIC_CUSTOM_HEADERS = headerLines.join("\n");
- // SDK 0.3.142 made MCP servers connect in the background by default. That
- // default is what we want: a slow or unreachable user MCP server (PostHog
- // MCP, custom stdio servers) would otherwise stall turn 1 by up to ~5s per
- // server. We honor an explicit override from the caller's environment for
- // sessions that genuinely need MCP tools available on turn 1.
- const mcpNonblocking = process.env.MCP_CONNECTION_NONBLOCKING;
+ // Explicit gateway values win over whatever happens to be in process.env.
+ // This prevents concurrent Agent instances from clobbering each other's
+ // gateway config when process.env was mutated globally.
+ if (gateway?.anthropicBaseUrl) {
+ env.ANTHROPIC_BASE_URL = gateway.anthropicBaseUrl;
+ }
+ if (gateway?.anthropicAuthToken) {
+ env.ANTHROPIC_AUTH_TOKEN = gateway.anthropicAuthToken;
+ env.ANTHROPIC_API_KEY = gateway.anthropicAuthToken;
+ }
+ if (gateway?.openaiBaseUrl) {
+ env.OPENAI_BASE_URL = gateway.openaiBaseUrl;
+ }
+ if (gateway?.openaiApiKey) {
+ env.OPENAI_API_KEY = gateway.openaiApiKey;
+ }
+
+ if (!gateway?.anthropicBaseUrl) {
+ return;
+ }
// Every var is load-bearing (ablation-tested): the CLI stamps the per-turn
// traceparent only once its OTel tracer initializes, and the dead endpoint
@@ -237,54 +294,18 @@ function buildEnvironment(
// inside the CLI and can redirect the endpoint or turn on content capture
// (OTEL_LOG_TOOL_CONTENT, …) — pre-existing settingSources exposure, not
// closable from here; hardening tracked separately.
- const gatewayTracing: Record<string, string> = gateway?.anthropicBaseUrl
- ? {
- CLAUDE_CODE_ENABLE_TELEMETRY: "1",
- CLAUDE_CODE_ENHANCED_TELEMETRY_BETA: "1",
- CLAUDE_CODE_PROPAGATE_TRACEPARENT: "1",
- OTEL_TRACES_EXPORTER: "otlp",
- OTEL_EXPORTER_OTLP_PROTOCOL: "http/json",
- OTEL_EXPORTER_OTLP_ENDPOINT:
- process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://127.0.0.1:9",
- }
- : {};
-
- const env: Record<string, string> = {
- ...process.env,
- ...gatewayTracing,
- // Explicit gateway values win over whatever happens to be in process.env.
- // This prevents concurrent Agent instances from clobbering each other's
- // gateway config when process.env was mutated globally.
- ...(gateway?.anthropicBaseUrl && {
- ANTHROPIC_BASE_URL: gateway.anthropicBaseUrl,
- }),
- ...(gateway?.anthropicAuthToken && {
- ANTHROPIC_AUTH_TOKEN: gateway.anthropicAuthToken,
- ANTHROPIC_API_KEY: gateway.anthropicAuthToken,
- }),
- ...(gateway?.openaiBaseUrl && { OPENAI_BASE_URL: gateway.openaiBaseUrl }),
- ...(gateway?.openaiApiKey && { OPENAI_API_KEY: gateway.openaiApiKey }),
- ...((process.versions.electron || process.env.ELECTRON_RUN_AS_NODE) && {
- ELECTRON_RUN_AS_NODE: "1",
- }),
- CLAUDE_CODE_ENABLE_ASK_USER_QUESTION_TOOL: "true",
- // Offload all MCP tools by default
- ENABLE_TOOL_SEARCH: "auto:0",
- // Enable idle state as end-of-turn signal (required for SDK 0.2.114+)
- CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1",
- ...(mcpNonblocking !== undefined && {
- MCP_CONNECTION_NONBLOCKING: mcpNonblocking,
- }),
- ANTHROPIC_CUSTOM_HEADERS: customHeaders,
- };
- if (gateway?.anthropicBaseUrl) {
- // The CLI parents every turn under an inherited ambient TRACEPARENT,
- // collapsing the per-turn trace ids this block exists to produce.
- delete env.TRACEPARENT;
- delete env.TRACESTATE;
- }
- applyContextWikiEnv(env, contextWiki);
- return env;
+ env.CLAUDE_CODE_ENABLE_TELEMETRY = "1";
+ env.CLAUDE_CODE_ENHANCED_TELEMETRY_BETA = "1";
+ env.CLAUDE_CODE_PROPAGATE_TRACEPARENT = "1";
+ env.OTEL_TRACES_EXPORTER = "otlp";
+ env.OTEL_EXPORTER_OTLP_PROTOCOL = "http/json";
+ env.OTEL_EXPORTER_OTLP_ENDPOINT =
+ process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://127.0.0.1:9";
+
+ // The CLI parents every turn under an inherited ambient TRACEPARENT,
+ // collapsing the per-turn trace ids this block exists to produce.
+ delete env.TRACEPARENT;
+ delete env.TRACESTATE;
}
function buildHooks(
@@ -552,6 +573,7 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
params.sessionId,
params.bedrockGatewayVariant,
params.contextWiki,
+ params.machineAuth,
),
hooks: buildHooks(
params.userProvidedOptions?.hooks,
@@ -599,7 +621,7 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
options.model = DEFAULT_MODEL;
}
- if (!options.fallbackModel) {
+ if (!options.fallbackModel && !params.machineAuth) {
options.fallbackModel = resolveFallbackModel(
options.model ?? DEFAULT_MODEL,
);
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/settings.ts b/products/desktop/packages/agent/src/adapters/claude/session/settings.ts
index c4b8d5505c34..5c68bc432a43 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/settings.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/settings.ts
@@ -4,10 +4,27 @@ import * as path from "node:path";
import type { PermissionRuleValue } from "@anthropic-ai/claude-agent-sdk";
import { minimatch } from "minimatch";
import { AsyncMutex } from "../../../utils/async-mutex";
+import { MACHINE_AUTH_STRIPPED_KEYS } from "../machine-auth";
import { resolveMainRepoPath } from "./repo-path";
const ACP_TOOL_NAME_PREFIX = "mcp__acp__";
+const MACHINE_AUTH_REJECTED_ENV_KEYS = new Set<string>(
+ MACHINE_AUTH_STRIPPED_KEYS,
+);
+
+function filterMachineAuthEnv(
+ env: Record<string, string>,
+): Record<string, string> {
+ const filtered: Record<string, string> = {};
+ for (const [key, value] of Object.entries(env)) {
+ if (!MACHINE_AUTH_REJECTED_ENV_KEYS.has(key)) {
+ filtered[key] = value;
+ }
+ }
+ return filtered;
+}
+
const acpToolNames = {
read: `${ACP_TOOL_NAME_PREFIX}Read`,
edit: `${ACP_TOOL_NAME_PREFIX}Edit`,
@@ -250,10 +267,12 @@ export class SettingsManager {
private initialized = false;
private initPromise: Promise<void> | null = null;
private writeMutex = new AsyncMutex();
+ private readonly machineAuth: boolean;
- constructor(cwd: string) {
+ constructor(cwd: string, machineAuth = false) {
this.cwd = cwd;
this.repoRoot = cwd;
+ this.machineAuth = machineAuth;
}
async initialize(): Promise<void> {
@@ -342,7 +361,11 @@ export class SettingsManager {
}
}
if (settings.env) {
- merged.env = { ...merged.env, ...settings.env };
+ let env = settings.env;
+ if (this.machineAuth && (layer === "project" || layer === "local")) {
+ env = filterMachineAuthEnv(env);
+ }
+ merged.env = { ...merged.env, ...env };
}
if (settings.model) {
merged.model = settings.model;
diff --git a/products/desktop/packages/agent/src/adapters/claude/subscription-login.test.ts b/products/desktop/packages/agent/src/adapters/claude/subscription-login.test.ts
new file mode 100644
index 000000000000..93404036540b
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/subscription-login.test.ts
@@ -0,0 +1,237 @@
+import { EventEmitter } from "node:events";
+import { existsSync } from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const spawnMock = vi.hoisted(() => vi.fn());
+
+vi.mock("node:child_process", async () => {
+ const actual =
+ await vi.importActual<typeof import("node:child_process")>(
+ "node:child_process",
+ );
+ return { ...actual, spawn: spawnMock };
+});
+vi.mock("node:fs", async () => {
+ const actual = await vi.importActual<typeof import("node:fs")>("node:fs");
+ return { ...actual, existsSync: vi.fn(actual.existsSync) };
+});
+
+import { hasClaudeLogin } from "./subscription-login";
+
+class FakeChildProcess extends EventEmitter {
+ stdout = new EventEmitter();
+ stderr = new EventEmitter();
+ kill = vi.fn();
+}
+
+const STRIPPED_KEYS = [
+ "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_AUTH_TOKEN",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_CUSTOM_HEADERS",
+ "CLAUDE_CODE_USE_BEDROCK",
+ "CLAUDE_CODE_USE_VERTEX",
+ "CLAUDE_CODE_USE_FOUNDRY",
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
+ "CLAUDE_CODE_USE_MANTLE",
+] as const;
+
+function statusJson(loggedIn: boolean, authMethod: string): string {
+ return JSON.stringify({ loggedIn, authMethod });
+}
+
+describe("hasClaudeLogin", () => {
+ const original: Partial<Record<string, string | undefined>> = {};
+ let child: FakeChildProcess;
+
+ beforeEach(() => {
+ vi.mocked(existsSync).mockReturnValue(true);
+ child = new FakeChildProcess();
+ spawnMock.mockReturnValue(child);
+ for (const key of STRIPPED_KEYS) {
+ original[key] = process.env[key];
+ process.env[key] = `ambient-${key}`;
+ }
+ process.env.CLAUDE_CODE_OAUTH_TOKEN = "user-oauth-token";
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ for (const key of STRIPPED_KEYS) {
+ const value = original[key];
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+ delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
+ });
+
+ function emitStdout(data: string): void {
+ queueMicrotask(() => {
+ child.stdout.emit("data", Buffer.from(data, "utf8"));
+ child.emit("exit", 0);
+ });
+ }
+
+ function exit(code: number): void {
+ queueMicrotask(() => child.emit("exit", code));
+ }
+
+ it("reports logged in for a claude.ai subscription", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(true, "claude.ai"));
+ await expect(result).resolves.toBe("logged-in");
+ });
+
+ it("reports logged in for an oauth_token subscription", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(true, "oauth_token"));
+ await expect(result).resolves.toBe("logged-in");
+ });
+
+ it("reports logged out for a third-party Bedrock provider", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(true, "third_party"));
+ await expect(result).resolves.toBe("logged-out");
+ });
+
+ it("reports logged out for an api_key auth method", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(true, "api_key"));
+ await expect(result).resolves.toBe("logged-out");
+ });
+
+ it("reports logged out when the CLI confirms no login", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(false, "none"));
+ await expect(result).resolves.toBe("logged-out");
+ });
+
+ it("reports unknown when the CLI exits non-zero with no JSON", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ exit(1);
+ await expect(result).resolves.toBe("unknown");
+ });
+
+ it("reports unknown when the CLI cannot start", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ queueMicrotask(() => child.emit("error", new Error("spawn failed")));
+ await expect(result).resolves.toBe("unknown");
+ });
+
+ it("reports unknown when the bundled binary is missing", async () => {
+ vi.mocked(existsSync).mockReturnValue(false);
+ await expect(
+ hasClaudeLogin({ claudeCliPath: "/bundled/claude", machineAuth: {} }),
+ ).resolves.toBe("unknown");
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it("spawns the bundled binary with ambient credentials stripped", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(true, "claude.ai"));
+ await result;
+
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ const [command, args, spawnOptions] = spawnMock.mock.calls[0] as [
+ string,
+ string[],
+ { env: NodeJS.ProcessEnv },
+ ];
+ expect(command).toBe("/bundled/claude");
+ expect(args).toEqual(["auth", "status", "--json"]);
+ for (const key of STRIPPED_KEYS) {
+ expect(spawnOptions.env[key]).toBeUndefined();
+ }
+ expect(spawnOptions.env.CLAUDE_CODE_OAUTH_TOKEN).toBe("user-oauth-token");
+ });
+
+ it.each([
+ { configDir: undefined, expected: path.join(os.homedir(), ".claude") },
+ { configDir: "/home/me/.claude", expected: "/home/me/.claude" },
+ ])(
+ "checks the machine config dir $configDir, not the app one",
+ async ({ configDir, expected }) => {
+ process.env.CLAUDE_CONFIG_DIR = "/app-data/claude";
+ try {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: { configDir },
+ });
+ emitStdout(statusJson(true, "claude.ai"));
+ await result;
+
+ const [, , spawnOptions] = spawnMock.mock.calls[0] as [
+ string,
+ string[],
+ { env: NodeJS.ProcessEnv },
+ ];
+ expect(spawnOptions.env.CLAUDE_CONFIG_DIR).toBe(expected);
+ } finally {
+ delete process.env.CLAUDE_CONFIG_DIR;
+ }
+ },
+ );
+
+ it("runs a legacy cli.js through the current JS runtime", async () => {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude/cli.js",
+ machineAuth: {},
+ });
+ emitStdout(statusJson(true, "claude.ai"));
+ await result;
+
+ const [command, args] = spawnMock.mock.calls[0] as [string, string[]];
+ expect(command).toBe(process.execPath);
+ expect(args).toEqual([
+ "/bundled/claude/cli.js",
+ "auth",
+ "status",
+ "--json",
+ ]);
+ });
+
+ it("reports unknown when the status check times out", async () => {
+ vi.useFakeTimers();
+ try {
+ const result = hasClaudeLogin({
+ claudeCliPath: "/bundled/claude",
+ machineAuth: {},
+ timeoutMs: 100,
+ });
+ vi.advanceTimersByTime(200);
+ await expect(result).resolves.toBe("unknown");
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts b/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts
new file mode 100644
index 000000000000..2055357044ee
--- /dev/null
+++ b/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts
@@ -0,0 +1,154 @@
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import {
+ applyMachineClaudeAuth,
+ type MachineClaudeAuth,
+ machineClaudeAuthShellEnv,
+} from "./machine-auth";
+
+export type ClaudeAuthAction = "login" | "logout";
+
+export interface ClaudeAuthTerminalCommand {
+ command: string;
+ env: { set: Record<string, string>; unset: string[] };
+}
+
+function shellQuote(value: string): string {
+ if (process.platform === "win32") {
+ return `"${value.replaceAll('"', '\\"')}"`;
+ }
+ return `'${value.replaceAll("'", `'\\''`)}'`;
+}
+
+export function claudeAuthTerminalCommand(
+ action: ClaudeAuthAction,
+ claudeCliPath: string,
+ machineAuth: MachineClaudeAuth,
+): ClaudeAuthTerminalCommand {
+ const args = action === "login" ? ["auth", "login"] : ["auth", "logout"];
+ const isLegacyJs = claudeCliPath.endsWith(".js");
+ const parts = isLegacyJs
+ ? [process.execPath, claudeCliPath, ...args]
+ : [claudeCliPath, ...args];
+ const env = machineClaudeAuthShellEnv(machineAuth);
+ if (isLegacyJs && process.versions.electron) {
+ env.set.ELECTRON_RUN_AS_NODE = "1";
+ }
+ return { command: parts.map(shellQuote).join(" "), env };
+}
+
+export interface ClaudeLoginCheckLogger {
+ debug(message: string, ...args: unknown[]): void;
+}
+
+const STATUS_TIMEOUT_MS = 15_000;
+
+export interface ClaudeLoginCheckOptions {
+ claudeCliPath: string;
+ machineAuth: MachineClaudeAuth;
+ logger?: ClaudeLoginCheckLogger;
+ timeoutMs?: number;
+}
+
+export type ClaudeLoginResult = "logged-in" | "logged-out" | "unknown";
+
+interface ClaudeAuthStatusJson {
+ loggedIn?: unknown;
+ authMethod?: unknown;
+ apiProvider?: unknown;
+ subscriptionType?: unknown;
+}
+
+function isSubscriptionLogin(status: ClaudeAuthStatusJson): boolean {
+ if (status.loggedIn !== true) return false;
+ const method = status.authMethod;
+ return method === "claude.ai" || method === "oauth_token";
+}
+
+function parseAuthStatusJson(stdout: string): ClaudeAuthStatusJson | null {
+ const trimmed = stdout.trim();
+ if (!trimmed) return null;
+ try {
+ const parsed = JSON.parse(trimmed);
+ if (parsed && typeof parsed === "object") {
+ return parsed as ClaudeAuthStatusJson;
+ }
+ } catch {}
+ return null;
+}
+
+export async function hasClaudeLogin(
+ options: ClaudeLoginCheckOptions,
+): Promise<ClaudeLoginResult> {
+ if (!existsSync(options.claudeCliPath)) {
+ options.logger?.debug("Claude CLI not found, reporting unknown", {
+ claudeCliPath: options.claudeCliPath,
+ });
+ return "unknown";
+ }
+
+ const isLegacyJs = options.claudeCliPath.endsWith(".js");
+ const command = isLegacyJs ? process.execPath : options.claudeCliPath;
+ const args = isLegacyJs
+ ? [options.claudeCliPath, "auth", "status", "--json"]
+ : ["auth", "status", "--json"];
+
+ const env: NodeJS.ProcessEnv = { ...process.env };
+ applyMachineClaudeAuth(env, options.machineAuth);
+ if (process.versions.electron || process.env.ELECTRON_RUN_AS_NODE) {
+ env.ELECTRON_RUN_AS_NODE = "1";
+ }
+
+ return new Promise<ClaudeLoginResult>((resolve) => {
+ let settled = false;
+ const finish = (result: ClaudeLoginResult): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(result);
+ };
+
+ const child = spawn(command, args, {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+
+ const timer = setTimeout(() => {
+ child.kill("SIGTERM");
+ finish("unknown");
+ }, options.timeoutMs ?? STATUS_TIMEOUT_MS);
+
+ let stdout = "";
+ let stderr = "";
+ child.stdout?.on("data", (chunk: Buffer) => {
+ if (stdout.length < 10_000) stdout += chunk.toString("utf8");
+ });
+ child.stderr?.on("data", (chunk: Buffer) => {
+ if (stderr.length < 500) stderr += chunk.toString("utf8");
+ });
+ child.on("error", (error) => {
+ options.logger?.debug("Failed to run claude auth status", {
+ error: error.message,
+ });
+ finish("unknown");
+ });
+ child.on("exit", (code) => {
+ const status = parseAuthStatusJson(stdout);
+ options.logger?.debug("claude auth status finished", {
+ claudeCliPath: options.claudeCliPath,
+ exitCode: code,
+ authMethod: status?.authMethod ?? null,
+ stderr: stderr.slice(0, 500),
+ });
+ if (status && isSubscriptionLogin(status)) {
+ finish("logged-in");
+ return;
+ }
+ if (status || code === 0) {
+ finish("logged-out");
+ return;
+ }
+ finish("unknown");
+ });
+ });
+}
diff --git a/products/desktop/packages/agent/src/agent.test.ts b/products/desktop/packages/agent/src/agent.test.ts
index cf9666ce6643..04ecb1d37e2a 100644
--- a/products/desktop/packages/agent/src/agent.test.ts
+++ b/products/desktop/packages/agent/src/agent.test.ts
@@ -85,6 +85,51 @@ describe("Agent", () => {
);
});
+ it("uses the machine's Claude Code login for an own-subscription session", async () => {
+ const agent = new Agent({ skipLogPersistence: true });
+
+ await agent.run("task-1", "run-1", {
+ adapter: "claude",
+ claudeModelAccess: "own-subscription",
+ repositoryPath: "/tmp/repo",
+ });
+
+ const [[config]] = createAcpConnectionMock.mock.calls as unknown as [
+ [AcpConnectionConfig],
+ ];
+ expect(config.claudeMachineAuth).toBeDefined();
+ expect(config.claudeGatewayEnv).toBeUndefined();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("keeps gateway auth for a Claude session on PostHog credits", async () => {
+ const agent = new Agent({
+ posthog: {
+ apiUrl: "https://us.posthog.com",
+ getApiKey: vi.fn().mockResolvedValue("token"),
+ projectId: 1,
+ },
+ skipLogPersistence: true,
+ });
+
+ await agent.run("task-1", "run-1", {
+ adapter: "claude",
+ claudeModelAccess: "posthog-gateway",
+ repositoryPath: "/tmp/repo",
+ });
+
+ const [[config]] = createAcpConnectionMock.mock.calls as unknown as [
+ [AcpConnectionConfig],
+ ];
+ expect(config.claudeMachineAuth).toBeUndefined();
+ expect(config.claudeGatewayEnv).toEqual(
+ expect.objectContaining({
+ anthropicBaseUrl: expect.any(String),
+ anthropicAuthToken: "token",
+ }),
+ );
+ });
+
it("stops before starting Codex without authentication", async () => {
const agent = new Agent({ skipLogPersistence: true });
diff --git a/products/desktop/packages/agent/src/agent.ts b/products/desktop/packages/agent/src/agent.ts
index 6ca4fb5d798f..9658583056b7 100644
--- a/products/desktop/packages/agent/src/agent.ts
+++ b/products/desktop/packages/agent/src/agent.ts
@@ -1,4 +1,9 @@
-import { buildPrOutput, mergePrUrls, readPrUrls } from "@posthog/shared";
+import {
+ buildPrOutput,
+ isAnthropicModelId,
+ mergePrUrls,
+ readPrUrls,
+} from "@posthog/shared";
import {
buildPosthogPropertyHeaderLines,
buildPosthogPropertyHeaderRecord,
@@ -9,6 +14,7 @@ import {
createAcpConnection,
type InProcessAcpConnection,
} from "./adapters/acp-connection";
+import { machineClaudeAuth } from "./adapters/claude/machine-auth";
import type { GatewayEnv } from "./adapters/claude/session/options";
import {
DEFAULT_CODEX_MODEL,
@@ -82,13 +88,17 @@ export class Agent {
taskRunId: string,
options: TaskExecutionOptions = {},
): Promise<InProcessAcpConnection> {
- const gatewayConfig = await this._resolveGatewayConfig(options.gatewayUrl);
+ const claudeSubscription =
+ options.adapter === "claude" &&
+ options.claudeModelAccess === "own-subscription";
+ const gatewayConfig = claudeSubscription
+ ? null
+ : await this._resolveGatewayConfig(options.gatewayUrl);
this.taskRunId = taskRunId;
- // getTask and getUserNode are independent, so start both before building
- // attribution rather than serializing two startup round trips.
+ const needsAttribution = !claudeSubscription && gatewayConfig !== null;
const taskPromise =
- this.posthogAPI && taskId !== "__preview__"
+ needsAttribution && this.posthogAPI && taskId !== "__preview__"
? this.posthogAPI.getTask(taskId).catch((error) => {
this.logger.debug("Failed to fetch task attribution", error);
return null;
@@ -97,8 +107,9 @@ export class Agent {
// The node the gateway holds a person's spend limit against. Null (a
// task-scoped credential) simply carries no user node, so the limit does
// not apply rather than applying to the wrong person.
- const userNodePromise =
- this.posthogAPI?.getUserNode() ?? Promise.resolve(null);
+ const userNodePromise = needsAttribution
+ ? (this.posthogAPI?.getUserNode() ?? Promise.resolve(null))
+ : Promise.resolve(null);
const [task, userNode] = await Promise.all([taskPromise, userNodePromise]);
const attribution =
@@ -181,12 +192,23 @@ export class Agent {
: (allowedModelIds[0] ?? sanitizedModel);
}
}
- if (!sanitizedModel && options.adapter !== "codex") {
+ if (!sanitizedModel && options.adapter !== "codex" && !claudeSubscription) {
+ sanitizedModel = DEFAULT_GATEWAY_MODEL;
+ }
+ if (
+ claudeSubscription &&
+ sanitizedModel &&
+ !isAnthropicModelId(sanitizedModel)
+ ) {
+ this.logger.warn(
+ "Saved model is not available on the Claude subscription; using default",
+ { savedModel: sanitizedModel, fallback: DEFAULT_GATEWAY_MODEL },
+ );
sanitizedModel = DEFAULT_GATEWAY_MODEL;
}
const claudeGatewayEnv: GatewayEnv | undefined =
- options.adapter !== "codex" && gatewayConfig
+ options.adapter !== "codex" && !claudeSubscription && gatewayConfig
? {
anthropicBaseUrl: gatewayConfig.gatewayUrl,
anthropicAuthToken: gatewayConfig.apiKey,
@@ -221,6 +243,7 @@ export class Agent {
posthogApiConfig: this.posthogApiConfig,
enricherEnabled: this.enricherEnabled,
claudeGatewayEnv,
+ claudeMachineAuth: claudeSubscription ? machineClaudeAuth() : undefined,
contextWiki: options.contextWiki,
codexOptions:
options.adapter === "codex" && (codexSubscription || gatewayConfig)
diff --git a/products/desktop/packages/agent/src/types.ts b/products/desktop/packages/agent/src/types.ts
index 035ddcf07689..fd2201f7591b 100644
--- a/products/desktop/packages/agent/src/types.ts
+++ b/products/desktop/packages/agent/src/types.ts
@@ -1,8 +1,4 @@
-import type {
- Adapter,
- CodexModelAccess,
- PostHogAPIConfig,
-} from "@posthog/shared";
+import type { Adapter, ModelAccess, PostHogAPIConfig } from "@posthog/shared";
import type { EffortLevel } from "@posthog/shared/domain-types";
export type {
@@ -69,7 +65,8 @@ export interface TaskExecutionOptions {
adapter?: Adapter;
model?: string;
gatewayUrl?: string;
- codexModelAccess?: CodexModelAccess;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
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 199cbaeaa9f6..60eaeb759789 100644
--- a/products/desktop/packages/agent/tsup.config.ts
+++ b/products/desktop/packages/agent/tsup.config.ts
@@ -194,6 +194,8 @@ export default defineConfig([
"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/subscription-login.ts",
+ "src/adapters/claude/machine-auth.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 ccb6049c5c76..dece5f02464c 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -24,7 +24,6 @@ import {
type AgentSession,
type BedrockGatewayVariant,
type CloudRegion,
- type CodexModelAccess,
classifyGatewayLimitError,
type ExecutionMode,
flattenSelectOptions,
@@ -40,6 +39,7 @@ import {
isRateLimitError,
isTransientUpstreamError,
leadingSlashCommand,
+ type ModelAccess,
mergeConfigOptions,
type OptimisticItem,
type PermissionRequest,
@@ -499,7 +499,8 @@ export interface SessionServiceDeps {
spokenNotifications?: boolean;
spokenNarrationEnabled?: boolean;
bedrockGatewayVariant?: BedrockGatewayVariant;
- codexModelAccess?: CodexModelAccess;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
};
usageLimit: { show: (...args: any[]) => any };
readonly addDirectoryDialog: { open: boolean };
@@ -532,13 +533,19 @@ type AuthCredentialsStatus =
| { kind: "restoring" }
| { kind: "missing" };
+export interface AdapterModelAccess {
+ codex?: ModelAccess;
+ claude?: ModelAccess;
+}
+
export interface ConnectParams {
task: Task;
repoPath: string;
initialPrompt?: ContentBlock[];
executionMode?: ExecutionMode;
adapter?: Adapter;
- codexModelAccess?: CodexModelAccess;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
model?: string;
reasoningLevel?: string;
contextWindow?: "200k" | "1m";
@@ -1928,6 +1935,7 @@ export class SessionService {
private stampRunConfig(session: AgentSession, params: ConnectParams): void {
session.adapter = params.adapter;
session.codexModelAccess = params.codexModelAccess;
+ session.claudeModelAccess = params.claudeModelAccess;
session.model = params.model;
session.executionMode = params.executionMode;
session.reasoningLevel = params.reasoningLevel;
@@ -1946,6 +1954,7 @@ export class SessionService {
executionMode,
adapter,
codexModelAccess,
+ claudeModelAccess,
model,
reasoningLevel,
contextWindow,
@@ -2065,7 +2074,7 @@ export class SessionService {
importedSessionId,
contextWindow,
fastMode,
- codexModelAccess,
+ { codex: codexModelAccess, claude: claudeModelAccess },
);
}
} catch (error) {
@@ -2286,6 +2295,7 @@ export class SessionService {
spokenNarrationEnabled,
bedrockGatewayVariant,
codexModelAccess,
+ claudeModelAccess: settingsClaudeModelAccess,
} = this.d.settings;
const result = await this.d.trpc.agent.reconnect.mutate({
taskId,
@@ -2293,6 +2303,7 @@ export class SessionService {
repoPath,
rtkEnabled: rtkEnabledLocal,
codexModelAccess,
+ claudeModelAccess: settingsClaudeModelAccess,
spokenNarration: spokenNarrationEnabled === true,
bedrockGatewayVariant,
apiHost: auth.apiHost,
@@ -2628,7 +2639,7 @@ export class SessionService {
importedSessionId?: string,
contextWindow?: "200k" | "1m",
fastMode?: boolean,
- codexModelAccess?: CodexModelAccess,
+ modelAccess?: AdapterModelAccess,
): Promise<void> {
const { client } = auth;
if (!client) {
@@ -2646,9 +2657,12 @@ export class SessionService {
spokenNarrationEnabled,
bedrockGatewayVariant,
codexModelAccess: settingsCodexModelAccess,
+ claudeModelAccess: settingsClaudeModelAccess,
} = this.d.settings;
- const resolvedCodexModelAccess =
- codexModelAccess ?? settingsCodexModelAccess;
+ const resolvedModelAccess: AdapterModelAccess = {
+ codex: modelAccess?.codex ?? settingsCodexModelAccess,
+ claude: modelAccess?.claude ?? settingsClaudeModelAccess,
+ };
const preferredModel = model ?? this.d.DEFAULT_GATEWAY_MODEL;
const result = await this.d.trpc.agent.start.mutate({
taskId,
@@ -2658,7 +2672,8 @@ export class SessionService {
projectId: auth.projectId,
permissionMode: executionMode,
adapter,
- codexModelAccess: resolvedCodexModelAccess,
+ codexModelAccess: resolvedModelAccess.codex,
+ claudeModelAccess: resolvedModelAccess.claude,
customInstructions: startCustomInstructions || undefined,
rtkEnabled: rtkEnabledLocal,
spokenNarration: spokenNarrationEnabled === true,
@@ -2676,7 +2691,8 @@ export class SessionService {
session.channel = result.channel;
session.status = "connected";
session.adapter = adapter;
- session.codexModelAccess = resolvedCodexModelAccess;
+ session.codexModelAccess = resolvedModelAccess.codex;
+ session.claudeModelAccess = resolvedModelAccess.claude;
session.model = model;
session.executionMode = executionMode;
session.reasoningLevel = reasoningLevel;
@@ -6083,6 +6099,7 @@ export class SessionService {
contextWindow,
fastMode,
codexModelAccess,
+ claudeModelAccess,
} = session;
await this.teardownSession(session.taskRunId);
const authStatus = await this.getAuthCredentialsStatus();
@@ -6107,7 +6124,7 @@ export class SessionService {
undefined,
contextWindow,
fastMode,
- codexModelAccess,
+ { codex: codexModelAccess, claude: claudeModelAccess },
);
return;
}
diff --git a/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts
index 77830a97bbd1..026aec4b59b9 100644
--- a/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts
@@ -126,6 +126,7 @@ describe("SessionService.clearSessionError retry config", () => {
model: "claude-fable-5",
adapter: "codex",
codexModelAccess: "own-subscription",
+ claudeModelAccess: "own-subscription",
executionMode: "auto",
reasoningLevel: "high",
contextWindow: "1m",
@@ -148,7 +149,7 @@ describe("SessionService.clearSessionError retry config", () => {
undefined,
"1m",
true,
- "own-subscription",
+ { codex: "own-subscription", claude: "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 bfccf9d7d9be..287fee11dd86 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -1515,4 +1515,28 @@ describe("TaskCreationSaga", () => {
);
},
);
+
+ it("forwards the selected Claude model access to the agent session", async () => {
+ const createTaskMock = vi.fn().mockResolvedValue(createTask());
+ mockHost.addFolder.mockResolvedValue({ id: "folder-1", path: "/repo" });
+ mockHost.detectRepo.mockResolvedValue(null);
+
+ const saga = makeSaga({ createTask: createTaskMock });
+
+ const result = await saga.run({
+ content: "Ship the fix",
+ repoPath: "/repo",
+ workspaceMode: "local",
+ adapter: "claude",
+ claudeModelAccess: "own-subscription",
+ });
+
+ expect(result.success).toBe(true);
+ expect(sessionService.connectToTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: "claude",
+ claudeModelAccess: "own-subscription",
+ }),
+ );
+ });
});
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index 6902ced24997..96122df0fd04 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -585,6 +585,8 @@ export class TaskCreationSaga extends Saga<
if (input.adapter) connectParams.adapter = input.adapter;
if (input.codexModelAccess)
connectParams.codexModelAccess = input.codexModelAccess;
+ if (input.claudeModelAccess)
+ connectParams.claudeModelAccess = input.claudeModelAccess;
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 d54d7ba42da4..792313107c62 100644
--- a/products/desktop/packages/core/src/task-detail/taskInput.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskInput.test.ts
@@ -69,6 +69,16 @@ describe("prepareTaskInput", () => {
expect(input.codexModelAccess).toBe("own-subscription");
});
+ it("preserves the selected Claude model access", () => {
+ const input = prepareTaskInput("do the thing", [], {
+ workspaceMode: "local",
+ adapter: "claude",
+ claudeModelAccess: "own-subscription",
+ });
+
+ expect(input.claudeModelAccess).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 e040ca947093..1ebd78faefb2 100644
--- a/products/desktop/packages/core/src/task-detail/taskInput.ts
+++ b/products/desktop/packages/core/src/task-detail/taskInput.ts
@@ -3,8 +3,8 @@ import type {
Adapter,
AgentRuntime,
CloudMcpServerRelayDesignation,
- CodexModelAccess,
McpServerConnection,
+ ModelAccess,
TaskCreationInput,
WorkspaceMode,
} from "@posthog/shared";
@@ -22,7 +22,8 @@ export interface PrepareTaskInputOptions {
reuseExistingWorktree?: boolean;
executionMode?: ExecutionMode;
adapter?: Adapter;
- codexModelAccess?: CodexModelAccess;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
runtime?: AgentRuntime;
model?: string;
reasoningLevel?: string;
@@ -73,6 +74,7 @@ export function prepareTaskInput(
executionMode: options.executionMode,
adapter: options.adapter,
codexModelAccess: options.codexModelAccess,
+ claudeModelAccess: options.claudeModelAccess,
runtime,
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 f7678de317f2..d83141b94ad6 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,9 @@ import {
cancelPermissionInput,
cancelPromptInput,
cancelSessionInput,
+ claudeAuthTerminalInput,
+ claudeAuthTerminalOutput,
+ claudeSubscriptionStatusOutput,
codexSubscriptionLoginOutput,
codexSubscriptionStatusOutput,
getPiModelCatalogInput,
@@ -94,6 +97,23 @@ export const agentRouter = router({
.getCodexSubscriptionStatus(),
),
+ claudeSubscriptionStatus: publicProcedure
+ .output(claudeSubscriptionStatusOutput)
+ .query(({ ctx }) =>
+ ctx.container
+ .get<AgentService>(AGENT_SERVICE)
+ .getClaudeSubscriptionStatus(),
+ ),
+
+ claudeAuthTerminal: publicProcedure
+ .input(claudeAuthTerminalInput)
+ .output(claudeAuthTerminalOutput)
+ .query(({ ctx, input }) =>
+ ctx.container
+ .get<AgentService>(AGENT_SERVICE)
+ .getClaudeAuthTerminal(input.action),
+ ),
+
codexSubscriptionLoginStart: publicProcedure
.output(codexSubscriptionLoginOutput)
.mutation(({ ctx }) =>
diff --git a/products/desktop/packages/host-router/src/routers/shell.router.ts b/products/desktop/packages/host-router/src/routers/shell.router.ts
index efcb396f6335..2742ec2f275a 100644
--- a/products/desktop/packages/host-router/src/routers/shell.router.ts
+++ b/products/desktop/packages/host-router/src/routers/shell.router.ts
@@ -46,6 +46,8 @@ export const shellRouter = router({
command: input.command,
cwd: input.cwd,
taskId: input.taskId,
+ additionalEnv: input.additionalEnv,
+ unsetEnv: input.unsetEnv,
}),
),
diff --git a/products/desktop/packages/shared/src/adapter.ts b/products/desktop/packages/shared/src/adapter.ts
index 66f9816e68c4..bb0bb7983586 100644
--- a/products/desktop/packages/shared/src/adapter.ts
+++ b/products/desktop/packages/shared/src/adapter.ts
@@ -1,3 +1,3 @@
export type Adapter = "claude" | "codex";
-export type CodexModelAccess = "posthog-gateway" | "own-subscription";
+export type ModelAccess = "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 30a0b2aabb9c..e66626c1cf6a 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1,6 +1,6 @@
// Analytics event types and properties
-import type { Adapter } from "./adapter";
+import type { Adapter, ModelAccess } from "./adapter";
import type { EffortLevel } from "./domain-types";
import type { SourceProduct } from "./inbox-types";
@@ -102,7 +102,8 @@ 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";
+ codex_model_access?: ModelAccess;
+ claude_model_access?: ModelAccess;
}
export interface TaskViewProperties {
@@ -1538,6 +1539,8 @@ export const ANALYTICS_EVENTS = {
CUSTOM_SOUND_RECORDING_SILENT: "Custom sound recording silent",
CODEX_SUBSCRIPTION_CONNECTED: "Codex subscription connected",
CODEX_SUBSCRIPTION_SIGNED_OUT: "Codex subscription signed out",
+ CLAUDE_SUBSCRIPTION_CONNECTED: "Claude subscription connected",
+ CLAUDE_SUBSCRIPTION_SIGNED_OUT: "Claude subscription signed out",
// Feedback events
AI_METRIC: "$ai_metric",
@@ -1742,6 +1745,8 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.CUSTOM_SOUND_RECORDING_SILENT]: never;
[ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_CONNECTED]: never;
[ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_SIGNED_OUT]: never;
+ [ANALYTICS_EVENTS.CLAUDE_SUBSCRIPTION_CONNECTED]: never;
+ [ANALYTICS_EVENTS.CLAUDE_SUBSCRIPTION_SIGNED_OUT]: never;
// Feedback events
[ANALYTICS_EVENTS.AI_METRIC]: AiMetricProperties;
diff --git a/products/desktop/packages/shared/src/cloud-task-models.ts b/products/desktop/packages/shared/src/cloud-task-models.ts
index f7163de85908..5c152a05fa61 100644
--- a/products/desktop/packages/shared/src/cloud-task-models.ts
+++ b/products/desktop/packages/shared/src/cloud-task-models.ts
@@ -161,6 +161,10 @@ export function isAnthropicModel(model: GatewayModel): boolean {
return model.id.startsWith("claude-") || model.id.startsWith("anthropic/");
}
+export function isAnthropicModelId(modelId: string): boolean {
+ return modelId.startsWith("claude-") || modelId.startsWith("anthropic/");
+}
+
export function isOpenAIModel(model: GatewayModel): boolean {
if (model.owned_by) {
return model.owned_by === "openai";
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 579b4d783b1c..f8576c0ea647 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -37,6 +37,8 @@ export const FAST_MODE_FLAG = "posthog-desktop-fast-mode";
export const SPOKEN_NARRATION_FLAG = "posthog-code-spoken-narration";
export const CODEX_OWN_SUBSCRIPTION_FLAG =
"posthog-code-codex-own-subscription";
+export const CLAUDE_OWN_SUBSCRIPTION_FLAG =
+ "posthog-code-claude-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/index.ts b/products/desktop/packages/shared/src/index.ts
index 4c06b3c505dc..b6fcf14c2283 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -74,6 +74,7 @@ export {
getCloudTaskGatewayUrl,
getProviderName,
isAnthropicModel,
+ isAnthropicModelId,
isBasetenModel,
isBlockedModelId,
isCloudflareModel,
diff --git a/products/desktop/packages/shared/src/models.test.ts b/products/desktop/packages/shared/src/models.test.ts
index 6c01e414e6f9..7b7dbf4dc74d 100644
--- a/products/desktop/packages/shared/src/models.test.ts
+++ b/products/desktop/packages/shared/src/models.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import { isAnthropicModelId } from "./cloud-task-models";
import { defaultEligibleModel } from "./models";
describe("defaultEligibleModel", () => {
@@ -20,3 +21,19 @@ describe("defaultEligibleModel", () => {
expect(defaultEligibleModel(modelId)).toBe(expected);
});
});
+
+describe("isAnthropicModelId", () => {
+ it.each([
+ ["claude-sonnet-5", true],
+ ["anthropic/claude-opus-4", true],
+ ["@cf/zai-org/glm-5.2", false],
+ ["modal/claude-3", false],
+ ["deepseek/deepseek-chat", false],
+ ["glm-4", false],
+ ["baseten/claude-3", false],
+ ["gpt-5", false],
+ ["", false],
+ ] as const)("%s -> %s", (modelId, expected) => {
+ expect(isAnthropicModelId(modelId)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/shared/src/sessions.ts b/products/desktop/packages/shared/src/sessions.ts
index 43fb5f2918a7..d82df90340aa 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, CodexModelAccess } from "./adapter";
+import type { Adapter, ModelAccess } from "./adapter";
import type { SkillButtonId } from "./analytics-events";
import type { TaskRunArtifact, TaskRunStatus } from "./domain-types";
import type { ExecutionMode } from "./exec-types";
@@ -77,7 +77,8 @@ export interface AgentSession {
processedLineCount?: number;
framework?: "claude";
adapter?: Adapter;
- codexModelAccess?: CodexModelAccess;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
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 45bfb5c3d48c..7654b180a95a 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, CodexModelAccess } from "./adapter";
+import type { Adapter, ModelAccess } from "./adapter";
import type { AgentRuntime } from "./agent-runtime";
import type { CloudRunSource, PrAuthorshipMode } from "./cloud";
import type { Task } from "./domain-types";
@@ -37,7 +37,8 @@ export interface TaskCreationInput {
githubUserIntegrationId?: string;
executionMode?: ExecutionMode;
adapter?: Adapter;
- codexModelAccess?: CodexModelAccess;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
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 52a8e5f0e05f..4555ac0b3e8f 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -5,6 +5,10 @@ import type {
import { isValidConfigValue } from "@posthog/core/task-detail/configOptions";
import type { AgentRuntime } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
+import {
+ subscriptionModelAccess,
+ useAdapterSubscription,
+} from "@posthog/ui/features/settings/adapterSubscription";
import {
forwardRef,
useCallback,
@@ -116,6 +120,8 @@ export const ChannelHomeComposer = forwardRef<
} = useSettingsStore();
const adapter = lastUsedAdapter;
+ const claudeSubscription = useAdapterSubscription("claude");
+ const codexSubscription = useAdapterSubscription("codex");
const [runtime, setRuntime] = useState<AgentRuntime>("acp");
// Keep the menu open when a harness switch swaps its ACP/Pi control.
const [modelMenuOpen, setModelMenuOpen] = useState(false);
@@ -493,6 +499,11 @@ export const ChannelHomeComposer = forwardRef<
onConfigOptionChange={setConfigOption}
menuOpen={modelMenuOpen}
onMenuOpenChange={setModelMenuOpen}
+ modelAccess={subscriptionModelAccess(
+ adapter === "codex" ? codexSubscription : claudeSubscription,
+ workspaceMode,
+ )}
+ showBillingMenu
disabled={isBusy}
isLoading={isLoading}
/>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx b/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx
index 266b465d2a93..1753d464b72c 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ModelRadioItem.tsx
@@ -1,17 +1,27 @@
-import { Lock } from "@phosphor-icons/react";
-import { DropdownMenuRadioItem } from "@posthog/quill";
+import { Lock, Prohibit } from "@phosphor-icons/react";
+import {
+ DropdownMenuRadioItem,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@posthog/quill";
import { isRestrictedModel } from "@posthog/ui/features/billing/modelGate";
import { ModelCostChip } from "@posthog/ui/features/sessions/components/ModelCostChip";
+const TOOLTIP_DELAY_MS = 150;
+
/**
* Model picker entry. Plan-restricted models render dimmed with a lock;
* picking one is intercepted by the selector's change handler, which opens
* the upgrade gate instead of selecting. Priced models carry a per-token
- * cost multiplier chip.
+ * cost multiplier chip. A model the current billing source cannot run
+ * renders dimmed and names the reason on hover.
*/
export function ModelRadioItem({
model,
closeOnClick,
+ unavailableReason,
}: {
model: {
value: string;
@@ -19,20 +29,38 @@ export function ModelRadioItem({
_meta?: Record<string, unknown> | null;
};
closeOnClick?: boolean;
+ unavailableReason?: string;
}) {
const restricted = isRestrictedModel(model);
- return (
+ const item = (
<DropdownMenuRadioItem
value={model.value}
closeOnClick={closeOnClick}
- className={restricted ? "opacity-60" : undefined}
+ className={restricted || unavailableReason ? "opacity-60" : undefined}
>
<span className="whitespace-nowrap">{model.name}</span>
- {restricted ? (
+ {unavailableReason ? (
+ <Prohibit size={11} className="ml-auto text-muted-foreground" />
+ ) : restricted ? (
<Lock size={11} className="ml-auto text-muted-foreground" />
) : (
<ModelCostChip modelId={model.value} />
)}
</DropdownMenuRadioItem>
);
+
+ if (!unavailableReason) {
+ return item;
+ }
+
+ return (
+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>
+ <Tooltip disableHoverablePopup>
+ <TooltipTrigger render={item} />
+ <TooltipContent side="right" className="max-w-60">
+ {unavailableReason}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx
index 7b1558e5f852..b37e306a792b 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.test.tsx
@@ -65,6 +65,20 @@ function claudeModelOption(
} as unknown as SessionConfigOption;
}
+function mixedModelOption(currentValue = "claude-opus-5"): SessionConfigOption {
+ return {
+ type: "select",
+ id: "model",
+ name: "Model",
+ category: "model",
+ currentValue,
+ options: [
+ { name: "Claude Opus 5", value: "claude-opus-5" },
+ { name: "GLM 5.2", value: "@cf/zai-org/glm-5.2" },
+ ],
+ } as unknown as SessionConfigOption;
+}
+
function effortlessModelOption(): SessionConfigOption {
return {
type: "select",
@@ -106,8 +120,11 @@ function fastOption(currentValue = "off"): SessionConfigOption {
} as unknown as SessionConfigOption;
}
-async function openAdvanced(user: ReturnType<typeof userEvent.setup>) {
- await user.click(screen.getByRole("button", { name: "Reasoning: High" }));
+async function openAdvanced(
+ user: ReturnType<typeof userEvent.setup>,
+ triggerName: string | RegExp = "Reasoning: High",
+) {
+ await user.click(screen.getByRole("button", { name: triggerName }));
await user.click(await screen.findByRole("button", { name: "Advanced" }));
}
@@ -637,4 +654,57 @@ describe("ReasoningLevelSelector", () => {
await screen.findByRole("menuitem", { name: /Harness/ }),
).toBeInTheDocument();
});
+
+ it("blocks a model the Claude plan cannot run and names the reason", async () => {
+ const onModelChange = vi.fn();
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <ReasoningLevelSelector
+ thoughtOption={thoughtOption()}
+ modelOption={mixedModelOption()}
+ adapter="claude"
+ modelAccess="own-subscription"
+ onModelChange={onModelChange}
+ />
+ </Theme>,
+ );
+
+ await user.click(
+ screen.getByRole("button", { name: /^Model and reasoning/ }),
+ );
+ await openSub(user, /^Model/);
+ const gatewayOnly = await screen.findByRole("menuitemradio", {
+ name: /GLM 5\.2/,
+ });
+
+ fireEvent.click(gatewayOnly);
+ expect(onModelChange).not.toHaveBeenCalled();
+ }, 20000);
+
+ it("lets every model through on PostHog credits", async () => {
+ const onModelChange = vi.fn();
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <ReasoningLevelSelector
+ thoughtOption={thoughtOption()}
+ modelOption={mixedModelOption()}
+ adapter="claude"
+ modelAccess="posthog-gateway"
+ onModelChange={onModelChange}
+ />
+ </Theme>,
+ );
+
+ await user.click(
+ screen.getByRole("button", { name: /^Model and reasoning/ }),
+ );
+ await openSub(user, /^Model/);
+ fireEvent.click(
+ await screen.findByRole("menuitemradio", { name: /GLM 5\.2/ }),
+ );
+
+ expect(onModelChange).toHaveBeenCalledWith("@cf/zai-org/glm-5.2");
+ }, 20000);
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
index 39e100641e33..d262355130d8 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ReasoningLevelSelector.tsx
@@ -22,8 +22,10 @@ import {
} from "@posthog/quill";
import {
FAST_MODE_FLAG,
+ isAnthropicModelId,
isDefaultSelectOption,
isRestrictedModelOption,
+ type ModelAccess,
selectOptionDocsUrl,
} from "@posthog/shared";
import {
@@ -38,6 +40,7 @@ import {
} from "@posthog/ui/features/sessions/components/HarnessSubmenu";
import { ModelCostFooter } from "@posthog/ui/features/sessions/components/ModelCostChip";
import { ModelRadioItem } from "@posthog/ui/features/sessions/components/ModelRadioItem";
+import { SubscriptionSubmenu } from "@posthog/ui/features/sessions/components/SubscriptionSubmenu";
import type { AgentAdapter } from "@posthog/ui/features/settings/settingsStore";
import { AnimatedHeight } from "@posthog/ui/primitives/AnimatedHeight";
import { Spinner } from "@posthog/ui/primitives/Spinner";
@@ -71,6 +74,8 @@ interface ReasoningLevelSelectorProps {
onMenuOpenChange?: (open: boolean) => void;
disabled?: boolean;
isLoading?: boolean;
+ modelAccess?: ModelAccess;
+ showBillingMenu?: boolean;
}
function toDropdownOptions(
@@ -106,6 +111,8 @@ export function ReasoningLevelSelector({
onMenuOpenChange,
disabled,
isLoading,
+ modelAccess,
+ showBillingMenu,
}: ReasoningLevelSelectorProps) {
const [internalMenuOpen, setInternalMenuOpen] = useState(false);
const open = menuOpen ?? internalMenuOpen;
@@ -133,6 +140,13 @@ export function ReasoningLevelSelector({
const modelSelect =
displayModel?.type === "select" ? displayModel : undefined;
+ const onOwnSubscription =
+ adapter === "claude" && modelAccess === "own-subscription";
+ const unavailableReason = (modelId: string): string | undefined =>
+ onOwnSubscription && !isAnthropicModelId(modelId)
+ ? "Your Claude plan cannot run this model. Change billing to PostHog credits to use it."
+ : undefined;
+
const handleHarnessSelect = (harness: AgentHarness) => {
if (harness === adapter) {
return;
@@ -231,6 +245,7 @@ export function ReasoningLevelSelector({
(candidate) => candidate.value === notch.model,
);
if (!entry || isRestrictedModelOption(entry._meta)) return [];
+ if (unavailableReason(notch.model)) return [];
const efforts = getReasoningEffortOptions(adapter, notch.model) ?? [];
if (!efforts.some((option) => option.value === notch.effort)) {
return [];
@@ -437,6 +452,9 @@ export function ReasoningLevelSelector({
onChange={handleHarnessSelect}
/>
)}
+ {showBillingMenu && adapter && (
+ <SubscriptionSubmenu adapter={adapter} />
+ )}
{modelSelect && (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
@@ -449,6 +467,7 @@ export function ReasoningLevelSelector({
<DropdownMenuRadioGroup
value={currentModel ?? ""}
onValueChange={(value) => {
+ if (unavailableReason(value)) return;
// A plan-restricted model opens the upgrade gate
// instead of becoming the selection.
if (gateRestrictedModelPick(modelEntries, value)) {
@@ -471,6 +490,9 @@ export function ReasoningLevelSelector({
key={model.value}
model={model}
closeOnClick={false}
+ unavailableReason={unavailableReason(
+ model.value,
+ )}
/>
))}
</Fragment>
@@ -484,6 +506,9 @@ export function ReasoningLevelSelector({
key={model.value}
model={model}
closeOnClick={false}
+ unavailableReason={unavailableReason(
+ model.value,
+ )}
/>
))}
</DropdownMenuRadioGroup>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx
new file mode 100644
index 000000000000..c8838d945136
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx
@@ -0,0 +1,103 @@
+import { SignIn } from "@phosphor-icons/react";
+import {
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from "@posthog/quill";
+import type { Adapter, ModelAccess } from "@posthog/shared";
+import {
+ applyModelAccess,
+ useAdapterSubscription,
+} from "@posthog/ui/features/settings/adapterSubscription";
+import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+
+const PLAN_LABEL: Record<Adapter, string> = {
+ claude: "Your Claude plan",
+ codex: "Your ChatGPT plan",
+};
+
+const LOGIN_LABEL: Record<Adapter, string> = {
+ claude: "Log in to Claude Code",
+ codex: "Log in to ChatGPT",
+};
+
+export const SUBSCRIPTION_LOGIN_ACTION: Record<Adapter, string> = {
+ claude: "claude-login",
+ codex: "codex-login",
+};
+
+interface SubscriptionSubmenuProps {
+ adapter: Adapter;
+ closeOnChange?: boolean;
+}
+
+export function SubscriptionSubmenu({
+ adapter,
+ closeOnChange = false,
+}: SubscriptionSubmenuProps): React.JSX.Element | null {
+ const subscription = useAdapterSubscription(adapter);
+ if (!subscription.flagEnabled) {
+ return null;
+ }
+
+ const planLabel = PLAN_LABEL[adapter];
+ const value: ModelAccess = subscription.subscriptionOn
+ ? "own-subscription"
+ : "posthog-gateway";
+ const valueLabel =
+ subscription.subscriptionOn && subscription.loggedIn
+ ? planLabel
+ : "PostHog credits";
+
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <span>Billing</span>
+ <span className="flex-1 text-right text-muted-foreground">
+ {valueLabel}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup
+ value={value}
+ onValueChange={(next) =>
+ applyModelAccess(
+ adapter,
+ next === "own-subscription"
+ ? "own-subscription"
+ : "posthog-gateway",
+ subscription.loggedIn,
+ )
+ }
+ >
+ <DropdownMenuRadioItem
+ value="posthog-gateway"
+ closeOnClick={closeOnChange}
+ >
+ PostHog credits
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="own-subscription"
+ closeOnClick={closeOnChange}
+ disabled={!subscription.loggedIn}
+ >
+ {planLabel}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ {subscription.loggedIn ? null : (
+ <DropdownMenuItem
+ onClick={() =>
+ openSettings("harness", SUBSCRIPTION_LOGIN_ACTION[adapter])
+ }
+ >
+ <SignIn size={12} />
+ {LOGIN_LABEL[adapter]}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
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 7a09e38be845..9020185153ab 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -272,6 +272,9 @@ const mockFeatureFlags = vi.hoisted(() => ({
const mockSettingsState = vi.hoisted(() => ({
customInstructions: "",
codexModelAccess: "posthog-gateway" as "posthog-gateway" | "own-subscription",
+ claudeModelAccess: "posthog-gateway" as
+ | "posthog-gateway"
+ | "own-subscription",
spokenNotifications: false,
syncCustomInstructionsFromFile: false,
syncedCustomInstructions: null as {
@@ -486,6 +489,7 @@ describe("SessionService", () => {
resetSessionService();
mockSettingsState.customInstructions = "";
mockSettingsState.codexModelAccess = "posthog-gateway";
+ mockSettingsState.claudeModelAccess = "posthog-gateway";
mockSettingsState.spokenNotifications = false;
mockFeatureFlags.isEnabled.mockReturnValue(false);
mockSettingsState.syncCustomInstructionsFromFile = false;
@@ -905,6 +909,40 @@ describe("SessionService", () => {
);
});
+ it("starts Claude 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: "claude",
+ claudeModelAccess: "own-subscription",
+ });
+
+ expect(mockTrpcAgent.start.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: "claude",
+ claudeModelAccess: "own-subscription",
+ }),
+ );
+ expect(mockSessionStoreSetters.setSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: "claude",
+ claudeModelAccess: "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 4565a1282c5d..f98aa90bb910 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,
+ CLAUDE_OWN_SUBSCRIPTION_FLAG,
CODEX_OWN_SUBSCRIPTION_FLAG,
SPOKEN_NARRATION_FLAG,
} from "@posthog/shared";
@@ -156,6 +157,9 @@ function buildSessionServiceDeps(): SessionServiceDeps {
const codexSubscriptionEnabled =
featureFlags.isEnabled(CODEX_OWN_SUBSCRIPTION_FLAG) ||
import.meta.env.DEV;
+ const claudeSubscriptionEnabled =
+ featureFlags.isEnabled(CLAUDE_OWN_SUBSCRIPTION_FLAG) ||
+ import.meta.env.DEV;
return {
...state,
customInstructions: getEffectiveCustomInstructions(state),
@@ -170,6 +174,9 @@ function buildSessionServiceDeps(): SessionServiceDeps {
codexModelAccess: codexSubscriptionEnabled
? state.codexModelAccess
: undefined,
+ claudeModelAccess: claudeSubscriptionEnabled
+ ? state.claudeModelAccess
+ : undefined,
};
},
usageLimit: {
diff --git a/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts b/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts
new file mode 100644
index 000000000000..f72ba7bd3f8c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts
@@ -0,0 +1,186 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { registerAdapterSubscription } = vi.hoisted(() => ({
+ registerAdapterSubscription: vi.fn(),
+}));
+
+vi.mock("@posthog/ui/shell/posthogAnalyticsImpl", () => ({
+ registerAdapterSubscription,
+}));
+
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import {
+ effectiveModelAccess,
+ registerSubscriptionAtBoot,
+ type SubscriptionStatus,
+ subscriptionNeedsConnection,
+} from "./adapterSubscription";
+
+const status = (loginState: "logged-in" | "logged-out" | "unknown") => ({
+ loginState,
+});
+
+describe("adapter subscription gating", () => {
+ it.each([
+ [
+ "cloud tasks never bill the subscription",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loginState: "logged-in" as const,
+ workspaceMode: "cloud" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "not signed in falls back to the gateway",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loginState: "logged-out" as const,
+ workspaceMode: "local" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "unknown status while loading falls back to the gateway",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loginState: "unknown" as const,
+ workspaceMode: "local" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "flag off falls back to the gateway",
+ {
+ flagEnabled: false,
+ subscriptionOn: true,
+ loginState: "logged-in" as const,
+ workspaceMode: "local" as const,
+ },
+ "posthog-gateway",
+ ],
+ [
+ "local on the subscription",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loginState: "logged-in" as const,
+ workspaceMode: "local" as const,
+ },
+ "own-subscription",
+ ],
+ [
+ "worktree on the subscription",
+ {
+ flagEnabled: true,
+ subscriptionOn: true,
+ loginState: "logged-in" as const,
+ workspaceMode: "worktree" as const,
+ },
+ "own-subscription",
+ ],
+ ])("%s", (_name, input, expected) => {
+ expect(effectiveModelAccess(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("logged-out") },
+ true,
+ ],
+ [
+ "signed in does not need connection",
+ { flagEnabled: true, subscriptionOn: true, status: status("logged-in") },
+ false,
+ ],
+ [
+ "unknown status does not need connection",
+ { flagEnabled: true, subscriptionOn: true, status: status("unknown") },
+ false,
+ ],
+ [
+ "subscription off never needs connection",
+ {
+ flagEnabled: true,
+ subscriptionOn: false,
+ status: status("logged-out"),
+ },
+ false,
+ ],
+ [
+ "flag off never needs connection",
+ {
+ flagEnabled: false,
+ subscriptionOn: true,
+ status: status("logged-out"),
+ },
+ false,
+ ],
+ ])("%s", (_name, input, expected) => {
+ expect(subscriptionNeedsConnection(input)).toBe(expected);
+ });
+
+ describe("registerSubscriptionAtBoot", () => {
+ beforeEach(() => {
+ registerAdapterSubscription.mockClear();
+ useSettingsStore.setState({
+ _hasHydrated: true,
+ claudeModelAccess: "own-subscription",
+ });
+ });
+
+ it("reports the access value even when the login check fails", async () => {
+ await expect(
+ registerSubscriptionAtBoot(
+ "claude",
+ () => Promise.reject(new Error("claude auth status timed out")),
+ true,
+ ),
+ ).rejects.toThrow("claude auth status timed out");
+
+ expect(registerAdapterSubscription).toHaveBeenCalledWith("claude", {
+ access: "own-subscription",
+ connected: false,
+ });
+ });
+
+ it("reports the login state once the check answers", async () => {
+ await registerSubscriptionAtBoot(
+ "claude",
+ () => Promise.resolve({ loginState: "logged-in" }),
+ true,
+ );
+
+ expect(registerAdapterSubscription).toHaveBeenLastCalledWith("claude", {
+ access: "own-subscription",
+ connected: true,
+ });
+ });
+
+ it("re-reads the setting after the probe so a toggle change is not stale", async () => {
+ useSettingsStore.setState({
+ _hasHydrated: true,
+ claudeModelAccess: "own-subscription",
+ });
+ const fetchStatus = vi.fn((): Promise<SubscriptionStatus> => {
+ useSettingsStore.setState({ claudeModelAccess: "posthog-gateway" });
+ return Promise.resolve({ loginState: "logged-in" });
+ });
+ await registerSubscriptionAtBoot("claude", fetchStatus, true);
+
+ expect(registerAdapterSubscription).toHaveBeenLastCalledWith("claude", {
+ access: "posthog-gateway",
+ connected: true,
+ });
+ });
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts b/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts
new file mode 100644
index 000000000000..c68e871791ea
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts
@@ -0,0 +1,183 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import {
+ type Adapter,
+ ANALYTICS_EVENTS,
+ CLAUDE_OWN_SUBSCRIPTION_FLAG,
+ CODEX_OWN_SUBSCRIPTION_FLAG,
+ type ModelAccess,
+} from "@posthog/shared";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import {
+ type SettingsStore,
+ useSettingsStore,
+} from "@posthog/ui/features/settings/settingsStore";
+import { track } from "@posthog/ui/shell/analytics";
+import { registerAdapterSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";
+import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";
+import { useQuery } from "@tanstack/react-query";
+
+export interface SubscriptionStatus {
+ loginState: "logged-in" | "logged-out" | "unknown";
+}
+
+export type WorkspaceModeForAccess = "local" | "worktree" | "cloud";
+
+interface AdapterSubscriptionSpec {
+ flag: string;
+ settingName: string;
+ statusProcedure: "claudeSubscriptionStatus" | "codexSubscriptionStatus";
+ readAccess: (state: SettingsStore) => ModelAccess;
+ writeAccess: (state: SettingsStore, next: ModelAccess) => void;
+}
+
+const SPECS: Record<Adapter, AdapterSubscriptionSpec> = {
+ claude: {
+ flag: CLAUDE_OWN_SUBSCRIPTION_FLAG,
+ settingName: "claude_model_access",
+ statusProcedure: "claudeSubscriptionStatus",
+ readAccess: (state) => state.claudeModelAccess,
+ writeAccess: (state, next) => state.setClaudeModelAccess(next),
+ },
+ codex: {
+ flag: CODEX_OWN_SUBSCRIPTION_FLAG,
+ settingName: "codex_model_access",
+ statusProcedure: "codexSubscriptionStatus",
+ readAccess: (state) => state.codexModelAccess,
+ writeAccess: (state, next) => state.setCodexModelAccess(next),
+ },
+};
+
+export function subscriptionNeedsConnection(input: {
+ flagEnabled: boolean;
+ subscriptionOn: boolean;
+ status: SubscriptionStatus | undefined;
+}): boolean {
+ return (
+ input.flagEnabled &&
+ input.subscriptionOn &&
+ input.status?.loginState === "logged-out"
+ );
+}
+
+export function effectiveModelAccess(input: {
+ flagEnabled: boolean;
+ subscriptionOn: boolean;
+ loginState: "logged-in" | "logged-out" | "unknown";
+ workspaceMode: WorkspaceModeForAccess;
+}): ModelAccess {
+ const usesOwnSubscription =
+ input.flagEnabled &&
+ input.subscriptionOn &&
+ input.loginState === "logged-in" &&
+ input.workspaceMode !== "cloud";
+ return usesOwnSubscription ? "own-subscription" : "posthog-gateway";
+}
+
+export function subscriptionModelAccess(
+ subscription: AdapterSubscription,
+ workspaceMode: WorkspaceModeForAccess,
+): ModelAccess {
+ return effectiveModelAccess({
+ flagEnabled: subscription.flagEnabled,
+ subscriptionOn: subscription.subscriptionOn,
+ loginState: subscription.loginState,
+ workspaceMode,
+ });
+}
+
+export function applyModelAccess(
+ adapter: Adapter,
+ next: ModelAccess,
+ connected: boolean,
+): void {
+ const spec = SPECS[adapter];
+ const state = useSettingsStore.getState();
+ const prev = spec.readAccess(state);
+ if (prev !== next) {
+ spec.writeAccess(state, next);
+ track(ANALYTICS_EVENTS.SETTING_CHANGED, {
+ setting_name: spec.settingName,
+ new_value: next,
+ old_value: prev,
+ });
+ }
+ registerAdapterSubscription(adapter, { access: next, connected });
+}
+
+export async function registerSubscriptionAtBoot(
+ adapter: Adapter,
+ fetchStatus: () => Promise<SubscriptionStatus>,
+ flagEnabled: boolean,
+): Promise<void> {
+ await settingsHydrated();
+ const access: ModelAccess = flagEnabled
+ ? SPECS[adapter].readAccess(useSettingsStore.getState())
+ : "posthog-gateway";
+ registerAdapterSubscription(adapter, { access, connected: false });
+ const status = await fetchStatus();
+ const freshAccess = flagEnabled
+ ? SPECS[adapter].readAccess(useSettingsStore.getState())
+ : "posthog-gateway";
+ registerAdapterSubscription(adapter, {
+ access: freshAccess,
+ connected: status.loginState === "logged-in",
+ });
+}
+
+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 AdapterSubscription {
+ flagEnabled: boolean;
+ subscriptionOn: boolean;
+ status: SubscriptionStatus | undefined;
+ loggedIn: boolean;
+ loginState: "logged-in" | "logged-out" | "unknown";
+ needsConnection: boolean;
+ setSubscriptionOn: (on: boolean) => void;
+}
+
+export function useAdapterSubscription(adapter: Adapter): AdapterSubscription {
+ const spec = SPECS[adapter];
+ const flagEnabled = useFeatureFlag(spec.flag) || import.meta.env.DEV;
+ const modelAccess = useSettingsStore(spec.readAccess);
+ const { localWorkspaces } = useHostCapabilities();
+ const hostTRPC = useHostTRPC();
+ const { data: status } = useQuery({
+ ...hostTRPC.agent[spec.statusProcedure].queryOptions(),
+ enabled: flagEnabled && localWorkspaces,
+ staleTime: 30_000,
+ });
+
+ const subscriptionOn = modelAccess === "own-subscription";
+ const loggedIn = status?.loginState === "logged-in";
+ const loginState = status?.loginState ?? "unknown";
+
+ return {
+ flagEnabled,
+ subscriptionOn,
+ status,
+ loggedIn,
+ loginState,
+ needsConnection: subscriptionNeedsConnection({
+ flagEnabled,
+ subscriptionOn,
+ status,
+ }),
+ setSubscriptionOn: (on) =>
+ applyModelAccess(
+ adapter,
+ on ? "own-subscription" : "posthog-gateway",
+ loggedIn,
+ ),
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx
new file mode 100644
index 000000000000..94be9af1dd40
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx
@@ -0,0 +1,200 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@posthog/quill";
+import { destroyTerminalSession } from "@posthog/ui/features/terminal/destroyShellTerminal";
+import { Terminal } from "@posthog/ui/features/terminal/Terminal";
+import { useThemeStore } from "@posthog/ui/shell/themeStore";
+import { secureRandomString } from "@posthog/ui/utils/random";
+import { useQuery } from "@tanstack/react-query";
+import { type ReactElement, useCallback, useEffect, useState } from "react";
+
+export type ClaudeAuthAction = "login" | "logout";
+
+interface ClaudeAuthTerminalDialogProps {
+ action: ClaudeAuthAction;
+ onClose: () => void;
+ onFinished: () => void;
+}
+
+const SURFACE = {
+ dark: { body: "#131316", chrome: "#1c1c21", text: "#e6e6e6" },
+ light: { body: "#f2f3ee", chrome: "#e7e9e1", text: "#3a4036" },
+} as const;
+
+const COPY = {
+ login: {
+ title: "Log in to Claude Code",
+ lead: "The CLI opens your browser. If it asks for a code, paste the code in the terminal.",
+ command: "claude auth login",
+ ok: "Claude Code is logged in. You can close this window.",
+ failed: "The login did not complete. Read the output, then try again.",
+ },
+ logout: {
+ title: "Log out of Claude Code",
+ lead: "This signs out the Claude Code CLI on this machine. Sessions on your Claude subscription stop until you log in again.",
+ command: "claude auth logout",
+ ok: "Claude Code is logged out. You can close this window.",
+ failed: "The sign-out did not complete. Read the output, then try again.",
+ },
+} as const;
+
+type Status = "running" | "checking" | "done" | "failed";
+
+const PILL: Record<Status, { dot: string; label: string }> = {
+ running: {
+ dot: "animate-pulse bg-(--amber-9) motion-reduce:animate-none",
+ label: "Running",
+ },
+ checking: {
+ dot: "animate-pulse bg-(--gray-9) motion-reduce:animate-none",
+ label: "Checking",
+ },
+ done: { dot: "bg-(--green-9)", label: "Done" },
+ failed: { dot: "bg-(--red-9)", label: "Failed" },
+};
+
+export function ClaudeAuthTerminalDialog({
+ action,
+ onClose,
+ onFinished,
+}: ClaudeAuthTerminalDialogProps): ReactElement {
+ const hostTRPC = useHostTRPC();
+ const isDarkMode = useThemeStore((state) => state.isDarkMode);
+ const [started, setStarted] = useState(action === "login");
+ const { data: terminal } = useQuery({
+ ...hostTRPC.agent.claudeAuthTerminal.queryOptions({ action }),
+ enabled: started,
+ });
+ const [sessionId] = useState(
+ () => `claude-auth-${action}-${secureRandomString(7)}`,
+ );
+ const [stopped, setStopped] = useState(false);
+
+ const statusQuery = useQuery({
+ ...hostTRPC.agent.claudeSubscriptionStatus.queryOptions(),
+ enabled: stopped,
+ });
+ const loggedIn = statusQuery.data?.loginState === "logged-in";
+ const statusKnown = statusQuery.data?.loginState !== undefined;
+ const verified = ((): boolean | undefined => {
+ if (!stopped || statusQuery.isFetching || !statusKnown) {
+ return undefined;
+ }
+ return action === "login" ? loggedIn : !loggedIn;
+ })();
+
+ const copy = COPY[action];
+ const surface = isDarkMode ? SURFACE.dark : SURFACE.light;
+
+ const status = ((): Status => {
+ if (!stopped) return "running";
+ if (verified === undefined) return "checking";
+ return verified ? "done" : "failed";
+ })();
+
+ const hint = ((): string => {
+ if (!started) return "Nothing changes until you select Log out.";
+ if (status === "running") return "The command runs. Close to stop it.";
+ if (status === "checking") return "Reading the login status.";
+ return verified ? copy.ok : copy.failed;
+ })();
+
+ const handleExit = useCallback(() => {
+ setStopped(true);
+ onFinished();
+ }, [onFinished]);
+
+ const handleClose = useCallback(() => {
+ destroyTerminalSession(sessionId);
+ onClose();
+ }, [sessionId, onClose]);
+
+ useEffect(() => {
+ return () => {
+ destroyTerminalSession(sessionId);
+ };
+ }, [sessionId]);
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && handleClose()}>
+ <DialogContent className="max-w-xl">
+ <DialogHeader>
+ <DialogTitle>{copy.title}</DialogTitle>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-3">
+ <p className="text-(--gray-11) text-xs leading-relaxed">
+ {copy.lead}
+ </p>
+
+ {started && terminal ? (
+ <div
+ className="overflow-hidden rounded-(--radius-3) border border-(--gray-6) shadow-sm"
+ style={{ backgroundColor: surface.body, color: surface.text }}
+ >
+ <div
+ className="flex items-center justify-between border-black/10 border-b px-3 py-1.5"
+ style={{ backgroundColor: surface.chrome }}
+ >
+ <span className="flex items-center gap-2 font-mono text-[11px] opacity-80">
+ <span aria-hidden>❯</span>
+ {copy.command}
+ </span>
+ <span className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-wide opacity-70">
+ <span
+ className={`inline-block h-1.5 w-1.5 rounded-full ${PILL[status].dot}`}
+ aria-hidden
+ />
+ {PILL[status].label}
+ </span>
+ </div>
+ <div className="h-44">
+ <Terminal
+ sessionId={sessionId}
+ persistenceKey={sessionId}
+ cwd={terminal.cwd}
+ command={terminal.command}
+ additionalEnv={terminal.additionalEnv}
+ unsetEnv={terminal.unsetEnv}
+ sensitive
+ onExit={handleExit}
+ />
+ </div>
+ </div>
+ ) : null}
+ </DialogBody>
+ <DialogFooter className="items-center justify-between gap-3">
+ <span className="text-(--gray-10) text-[11px]">{hint}</span>
+ {started ? (
+ <Button
+ variant={status === "done" ? "primary" : "outline"}
+ size="sm"
+ onClick={handleClose}
+ >
+ {status === "running" ? "Cancel" : "Close"}
+ </Button>
+ ) : (
+ <span className="flex items-center gap-2">
+ <Button variant="outline" size="sm" onClick={handleClose}>
+ Keep me logged in
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ onClick={() => setStarted(true)}
+ >
+ Log out
+ </Button>
+ </span>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx
new file mode 100644
index 000000000000..55d18409715c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx
@@ -0,0 +1,154 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import { Button, Switch } from "@posthog/quill";
+import { ANALYTICS_EVENTS } from "@posthog/shared";
+import { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/sessions/components/SubscriptionSubmenu";
+import { useAdapterSubscription } from "@posthog/ui/features/settings/adapterSubscription";
+import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";
+import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";
+import { track } from "@posthog/ui/shell/analytics";
+import { registerAdapterSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { type ReactElement, useEffect, useRef, useState } from "react";
+import {
+ type ClaudeAuthAction,
+ ClaudeAuthTerminalDialog,
+} from "./ClaudeAuthTerminalDialog";
+
+export function ClaudeSubscriptionSettings(): ReactElement | null {
+ const subscription = useAdapterSubscription("claude");
+ const hostTRPC = useHostTRPC();
+ const queryClient = useQueryClient();
+ const [authAction, setAuthAction] = useState<ClaudeAuthAction | null>(null);
+
+ const statusQuery = hostTRPC.agent.claudeSubscriptionStatus.queryOptions();
+ const {
+ data: status,
+ isFetching,
+ isPending,
+ isError,
+ } = useQuery({
+ ...statusQuery,
+ enabled: subscription.flagEnabled,
+ });
+ const loggedIn = status?.loginState === "logged-in";
+ const statusUnknown = status?.loginState === "unknown";
+ const settled = !isPending && !isError && !statusUnknown;
+
+ useEffect(() => {
+ if (
+ useSettingsPageStore.getState().initialAction ===
+ SUBSCRIPTION_LOGIN_ACTION.claude
+ ) {
+ useSettingsPageStore.getState().consumeInitialAction();
+ setAuthAction("login");
+ }
+ }, []);
+
+ const lastKnownLoggedIn = useRef<boolean | null>(null);
+ useEffect(() => {
+ if (!settled) return;
+ const previous = lastKnownLoggedIn.current;
+ lastKnownLoggedIn.current = loggedIn;
+ if (previous === null || previous === loggedIn) return;
+ if (loggedIn) {
+ track(ANALYTICS_EVENTS.CLAUDE_SUBSCRIPTION_CONNECTED);
+ } else {
+ track(ANALYTICS_EVENTS.CLAUDE_SUBSCRIPTION_SIGNED_OUT);
+ }
+ registerAdapterSubscription("claude", {
+ access: subscription.subscriptionOn
+ ? "own-subscription"
+ : "posthog-gateway",
+ connected: loggedIn,
+ });
+ }, [settled, loggedIn, subscription.subscriptionOn]);
+
+ if (!subscription.flagEnabled) {
+ return null;
+ }
+
+ const refreshStatus = (): void => {
+ void queryClient.invalidateQueries({ queryKey: statusQuery.queryKey });
+ };
+
+ const usingSubscription = loggedIn && subscription.subscriptionOn;
+ const summary = usingSubscription
+ ? "Local and worktree Claude sessions run on your Claude plan instead of PostHog credits. Cloud tasks always use PostHog credits"
+ : loggedIn
+ ? "Your Claude account is connected, but the switch is off. Local and worktree Claude sessions still use PostHog credits. Turn the switch on to use your Claude plan"
+ : "Run local and worktree Claude sessions on your Claude plan instead of PostHog credits. Log in once with the Claude Code CLI, then re-check";
+
+ const statusLine = ((): { color: string; label: string } => {
+ if (isPending) {
+ return { color: "bg-(--gray-9)", label: "Checking" };
+ }
+ if (isError || statusUnknown) {
+ return { color: "bg-(--amber-9)", label: "Could not check the login" };
+ }
+ if (loggedIn) {
+ return { color: "bg-(--green-9)", label: "Claude Code logged in" };
+ }
+ return { color: "bg-(--red-9)", label: "Not logged in" };
+ })();
+
+ const description = (
+ <span className="flex flex-col gap-1">
+ <span>{summary}</span>
+ <span className="flex items-center gap-1.5">
+ <span
+ className={`inline-block h-1.5 w-1.5 rounded-full ${statusLine.color}`}
+ aria-hidden
+ />
+ {statusLine.label}
+ </span>
+ {!loggedIn && settled ? (
+ <span className="text-[11px] text-muted-foreground">
+ Log in here, or run claude in a terminal and use /login
+ </span>
+ ) : null}
+ </span>
+ );
+
+ return (
+ <SettingsCardRow
+ label="Use your Claude subscription"
+ description={description}
+ >
+ <span className="flex flex-wrap items-center justify-end gap-2">
+ <Button
+ variant={loggedIn ? "outline" : "primary"}
+ size="sm"
+ disabled={isPending}
+ onClick={() => setAuthAction(loggedIn ? "logout" : "login")}
+ >
+ {loggedIn ? "Log out" : "Log in"}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ loading={isFetching}
+ disabled={isFetching}
+ onClick={refreshStatus}
+ >
+ Re-check
+ </Button>
+ <Switch
+ size="sm"
+ aria-label="Use your Claude subscription"
+ checked={subscription.subscriptionOn}
+ onCheckedChange={(checked) => {
+ subscription.setSubscriptionOn(checked === true);
+ refreshStatus();
+ }}
+ />
+ </span>
+ {authAction ? (
+ <ClaudeAuthTerminalDialog
+ action={authAction}
+ onClose={() => setAuthAction(null)}
+ onFinished={refreshStatus}
+ />
+ ) : null}
+ </SettingsCardRow>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx
index a9d1ea9751a7..0e0e5665a409 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/CodexSubscriptionSettings.tsx
@@ -1,16 +1,17 @@
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 { SUBSCRIPTION_LOGIN_ACTION } from "@posthog/ui/features/sessions/components/SubscriptionSubmenu";
import {
- applyCodexModelAccess,
- shouldShowCodexSubscriptionControls,
- useCodexSubscription,
-} from "@posthog/ui/features/settings/useCodexSubscription";
+ applyModelAccess,
+ useAdapterSubscription,
+} from "@posthog/ui/features/settings/adapterSubscription";
+import { SettingsCardRow } from "@posthog/ui/features/settings/components/SettingsCard";
+import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";
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 { registerAdapterSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { type ReactElement, useEffect, useState } from "react";
@@ -18,7 +19,7 @@ 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 subscription = useAdapterSubscription("codex");
const hostTRPC = useHostTRPC();
const queryClient = useQueryClient();
const [awaitingLogin, setAwaitingLogin] = useState(false);
@@ -29,16 +30,21 @@ export function CodexSubscriptionSettings(): ReactElement | null {
...statusQuery,
enabled: subscription.flagEnabled,
refetchInterval: (query) =>
- awaitingLogin && query.state.data?.appLoggedIn !== true ? 2000 : false,
+ awaitingLogin && query.state.data?.loginState !== "logged-in"
+ ? 2000
+ : false,
});
- const loggedIn = status?.appLoggedIn === true;
+ const loggedIn = status?.loginState === "logged-in";
useEffect(() => {
if (!awaitingLogin || !loggedIn) return;
setAwaitingLogin(false);
track(ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_CONNECTED);
- applyCodexModelAccess("own-subscription", true);
- registerCodexSubscription({ access: "own-subscription", connected: true });
+ applyModelAccess("codex", "own-subscription", true);
+ registerAdapterSubscription("codex", {
+ access: "own-subscription",
+ connected: true,
+ });
}, [awaitingLogin, loggedIn]);
const login = useMutation({
@@ -71,12 +77,22 @@ export function CodexSubscriptionSettings(): ReactElement | null {
return () => clearTimeout(timer);
}, [awaitingLogin]);
const connecting = login.isPending || launching;
+ useEffect(() => {
+ if (
+ useSettingsPageStore.getState().initialAction ===
+ SUBSCRIPTION_LOGIN_ACTION.codex
+ ) {
+ useSettingsPageStore.getState().consumeInitialAction();
+ login.mutate();
+ }
+ }, [login.mutate]);
+
const signOut = useMutation({
...hostTRPC.agent.codexSubscriptionSignOut.mutationOptions(),
onSuccess: () => {
track(ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_SIGNED_OUT);
- applyCodexModelAccess("posthog-gateway", false);
- registerCodexSubscription({
+ applyModelAccess("codex", "posthog-gateway", false);
+ registerAdapterSubscription("codex", {
access: "posthog-gateway",
connected: false,
});
@@ -91,11 +107,7 @@ export function CodexSubscriptionSettings(): ReactElement | null {
},
});
- const visible = shouldShowCodexSubscriptionControls({
- flagEnabled: subscription.flagEnabled,
- adapter: "codex",
- });
- if (!visible) {
+ if (!subscription.flagEnabled) {
return null;
}
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 4d722cba7958..a0c890460c52 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 { ClaudeSubscriptionSettings } from "@posthog/ui/features/settings/sections/ClaudeSubscriptionSettings";
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";
@@ -114,6 +115,7 @@ export function HarnessSettings() {
description="Configuration that lives with the Claude Code harness; run these commands in a terminal to change it"
>
<SettingsCard>
+ <ClaudeSubscriptionSettings />
<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 10bff4fb436d..cc0d9aabcf09 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -10,8 +10,8 @@ import { clampAutoCompactPercent } from "@posthog/core/sessions/autoCompact";
import type {
Adapter,
AgentRuntime,
- CodexModelAccess,
ExecutionMode,
+ ModelAccess,
WorkspaceMode,
} from "@posthog/shared";
import type { EffortLevel } from "@posthog/shared/domain-types";
@@ -133,7 +133,7 @@ export interface SyncedCustomInstructions {
// ---------- Store shape ----------
-interface SettingsStore {
+export interface SettingsStore {
// Run mode + last-used flow defaults
defaultRunMode: DefaultRunMode;
lastUsedRunMode: "local" | "cloud";
@@ -283,14 +283,16 @@ interface SettingsStore {
// sessions, cloud covers cloud runs.
rtkEnabledLocal: boolean;
rtkEnabledCloud: boolean;
- codexModelAccess: CodexModelAccess;
+ codexModelAccess: ModelAccess;
+ claudeModelAccess: ModelAccess;
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;
+ setCodexModelAccess: (mode: ModelAccess) => void;
+ setClaudeModelAccess: (mode: ModelAccess) => void;
// Terminal
terminalFont: TerminalFont;
@@ -550,6 +552,7 @@ export const useSettingsStore = create<SettingsStore>()(
rtkEnabledLocal: true,
rtkEnabledCloud: true,
codexModelAccess: "posthog-gateway",
+ claudeModelAccess: "posthog-gateway",
setAllowBypassPermissions: (enabled) =>
set({ allowBypassPermissions: enabled }),
setPreventSleepWhileRunning: (enabled) =>
@@ -560,6 +563,7 @@ export const useSettingsStore = create<SettingsStore>()(
setRtkEnabledLocal: (enabled) => set({ rtkEnabledLocal: enabled }),
setRtkEnabledCloud: (enabled) => set({ rtkEnabledCloud: enabled }),
setCodexModelAccess: (mode) => set({ codexModelAccess: mode }),
+ setClaudeModelAccess: (mode) => set({ claudeModelAccess: mode }),
// Terminal
terminalFont: "berkeley-mono",
@@ -710,6 +714,7 @@ export const useSettingsStore = create<SettingsStore>()(
rtkEnabledLocal: state.rtkEnabledLocal,
rtkEnabledCloud: state.rtkEnabledCloud,
codexModelAccess: state.codexModelAccess,
+ claudeModelAccess: state.claudeModelAccess,
// 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
deleted file mode 100644
index 6a492845b128..000000000000
--- a/products/desktop/packages/ui/src/features/settings/useCodexSubscription.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-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
deleted file mode 100644
index 78d4c1e76ecb..000000000000
--- a/products/desktop/packages/ui/src/features/settings/useCodexSubscription.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-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 4c19eaa59f03..f9c609c6a1bc 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
@@ -30,8 +30,11 @@ import {
} from "@posthog/ui/features/canvas/stores/taskRepositoryDraftStore";
import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";
import { useOpenInboxReport } from "@posthog/ui/features/inbox/hooks/useOpenInboxReport";
+import {
+ subscriptionModelAccess,
+ useAdapterSubscription,
+} from "@posthog/ui/features/settings/adapterSubscription";
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";
@@ -364,7 +367,8 @@ export function TaskInput({
!!channelContextPath || (!!channelContext && !channelContextDismissed);
const adapter = lastUsedAdapter;
- const codexSubscription = useCodexSubscription();
+ const codexSubscription = useAdapterSubscription("codex");
+ const claudeSubscription = useAdapterSubscription("claude");
const prefillRequestKey = initialPromptKey ?? initialPrompt;
// Applying a prefilled prompt replaces whatever the composer had, so it must
@@ -502,6 +506,20 @@ export function TaskInput({
workspaceMode !== "cloud" &&
codexSubscription.needsConnection;
+ const showClaudeNotConnectedNotice =
+ runtime !== "pi" &&
+ adapter === "claude" &&
+ workspaceMode !== "cloud" &&
+ claudeSubscription.needsConnection;
+
+ const composerModelAccess =
+ runtime === "pi"
+ ? undefined
+ : subscriptionModelAccess(
+ adapter === "codex" ? codexSubscription : claudeSubscription,
+ workspaceMode,
+ );
+
const {
repositories: visibleCloudRepositories,
isPending: cloudRepositoriesLoading,
@@ -1573,6 +1591,8 @@ export function TaskInput({
onMenuOpenChange={setModelMenuOpen}
disabled={isCreatingTask}
isLoading={isPreviewLoading}
+ modelAccess={composerModelAccess}
+ showBillingMenu
/>
)
}
@@ -1583,6 +1603,19 @@ export function TaskInput({
if (canSubmit) void submitTask();
}}
/>
+ {showClaudeNotConnectedNotice && (
+ <div className="mx-2 mt-1.5 text-[12px] text-gray-10">
+ Claude is set to use your Claude plan, but no account is
+ logged in. Sessions use PostHog credits.{" "}
+ <button
+ type="button"
+ className="underline"
+ onClick={() => openSettings("harness")}
+ >
+ Log in in Settings
+ </button>
+ </div>
+ )}
{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
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 3f1ed1a4ebef..f45a97dc6e33 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
@@ -2,7 +2,6 @@ import {
ArrowsSplit,
Cloud,
Cube,
- Gear,
Laptop,
Plus,
Star,
@@ -25,11 +24,8 @@ import {
MenuLabel,
} from "@posthog/quill";
import type { Adapter, WorkspaceMode } from "@posthog/shared";
+import { useAdapterSubscription } from "@posthog/ui/features/settings/adapterSubscription";
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 {
@@ -43,6 +39,11 @@ import { useCloudTargetOptions } from "../hooks/useCloudTarget";
export type { WorkspaceMode };
+const SUBSCRIPTION_IN_USE_LABEL: Record<Adapter, string> = {
+ codex: "Using Codex subscription",
+ claude: "Using Claude subscription",
+};
+
interface WorkspaceModeSelectProps {
value: WorkspaceMode;
onChange: (mode: WorkspaceMode) => void;
@@ -92,7 +93,18 @@ export function WorkspaceModeSelect({
}: WorkspaceModeSelectProps) {
const { localWorkspaces } = useHostCapabilities();
const cloudModeEnabled = useCloudModeEnabled();
- const codexSubscription = useCodexSubscription();
+ const codexSubscription = useAdapterSubscription("codex");
+ const claudeSubscription = useAdapterSubscription("claude");
+ const adapterSubscription = adapter
+ ? { codex: codexSubscription, claude: claudeSubscription }[adapter]
+ : undefined;
+ const subscriptionInUseLabel =
+ adapter &&
+ adapterSubscription?.flagEnabled &&
+ adapterSubscription.subscriptionOn &&
+ adapterSubscription.loggedIn
+ ? SUBSCRIPTION_IN_USE_LABEL[adapter]
+ : null;
const { options, favoriteKey, toggleFavorite } = useCloudTargetOptions();
const [menuOpen, setMenuOpen] = useState(false);
@@ -177,29 +189,10 @@ export function WorkspaceModeSelect({
{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={ICON_BUTTON_CLASS}
- >
- <Gear size={12} />
- </button>
- </div>
+ {subscriptionInUseLabel && (
+ <span className="text-[11px] text-muted-foreground">
+ {subscriptionInUseLabel}
+ </span>
)}
</div>
)}
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 fd1ef8fdf5b6..f5294bda867c 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,7 +16,7 @@ import {
type Adapter,
type AgentRuntime,
ANALYTICS_EVENTS,
- type CodexModelAccess,
+ type ModelAccess,
PROJECT_BLUEBIRD_FLAG,
type TaskCreationInput,
type WorkspaceMode,
@@ -30,9 +30,9 @@ import { useTaskChannels } from "@posthog/ui/features/canvas/hooks/useTaskChanne
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";
+ subscriptionModelAccess,
+ useAdapterSubscription,
+} from "@posthog/ui/features/settings/adapterSubscription";
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";
@@ -140,7 +140,8 @@ async function trackTaskCreated(
input: TaskCreationInput,
selectedDirectory: string,
hostClient: HostTrpcClient,
- codexModelAccess?: CodexModelAccess,
+ codexModelAccess?: ModelAccess,
+ claudeModelAccess?: ModelAccess,
): Promise<void> {
try {
const workspaceMode = input.workspaceMode ?? "local";
@@ -182,6 +183,7 @@ async function trackTaskCreated(
uses_worktree_include: usesWorktreeInclude,
adapter: input.adapter,
codex_model_access: codexModelAccess,
+ claude_model_access: claudeModelAccess,
});
} catch (error) {
log.warn("Failed to track Task created event", { error });
@@ -223,7 +225,8 @@ export function useTaskCreation({
const [isCreatingTask, setIsCreatingTask] = useState(false);
const [isExitingComposer, setIsExitingComposer] = useState(false);
const hostClient = useHostTRPCClient();
- const codexSubscription = useCodexSubscription();
+ const codexSubscription = useAdapterSubscription("codex");
+ const claudeSubscription = useAdapterSubscription("claude");
const trpc = useHostTRPC();
const queryClient = useQueryClient();
const defaultAdditionalDirectoriesQuery = useQuery(
@@ -411,12 +414,11 @@ export function useTaskCreation({
);
const codexModelAccess =
runtime !== "pi" && adapter === "codex"
- ? effectiveCodexModelAccess({
- flagEnabled: codexSubscription.flagEnabled,
- subscriptionOn: codexSubscription.subscriptionOn,
- loggedIn: codexSubscription.loggedIn,
- workspaceMode,
- })
+ ? subscriptionModelAccess(codexSubscription, workspaceMode)
+ : undefined;
+ const claudeModelAccess =
+ runtime !== "pi" && adapter === "claude"
+ ? subscriptionModelAccess(claudeSubscription, workspaceMode)
: undefined;
const input = prepareTaskInput(serializedContent, filePaths, {
// Repo-optional surfaces may still supply an explicit task folder or
@@ -433,6 +435,7 @@ export function useTaskCreation({
executionMode,
adapter,
codexModelAccess,
+ claudeModelAccess,
runtime,
model,
reasoningLevel,
@@ -570,6 +573,7 @@ export function useTaskCreation({
selectedDirectory,
hostClient,
input.codexModelAccess,
+ input.claudeModelAccess,
);
// Repo-less channel tasks create no workspace row (the agent runs in
// a scratch dir surfaced as a synthetic workspace), so the normal
@@ -706,8 +710,13 @@ export function useTaskCreation({
taskService,
tasks,
codexSubscription.flagEnabled,
- codexSubscription.loggedIn,
+ codexSubscription.loginState,
codexSubscription.subscriptionOn,
+ claudeSubscription.flagEnabled,
+ claudeSubscription.loginState,
+ claudeSubscription.subscriptionOn,
+ claudeSubscription,
+ codexSubscription,
],
);
diff --git a/products/desktop/packages/ui/src/features/terminal/Terminal.tsx b/products/desktop/packages/ui/src/features/terminal/Terminal.tsx
index a945054da075..df3467067d2f 100644
--- a/products/desktop/packages/ui/src/features/terminal/Terminal.tsx
+++ b/products/desktop/packages/ui/src/features/terminal/Terminal.tsx
@@ -14,6 +14,9 @@ export interface TerminalProps {
initialState?: string;
taskId?: string;
command?: string;
+ additionalEnv?: Record<string, string>;
+ unsetEnv?: string[];
+ sensitive?: boolean;
onReady?: () => void;
onExit?: (exitCode?: number) => void;
}
@@ -25,6 +28,9 @@ export function Terminal({
initialState,
taskId,
command,
+ additionalEnv,
+ unsetEnv,
+ sensitive,
onReady,
onExit,
}: TerminalProps) {
@@ -36,19 +42,31 @@ export function Terminal({
);
const terminalGpuRendering = useSettingsStore((s) => s.terminalGpuRendering);
- // Create instance (idempotent)
+ const createOptions = useRef({
+ persistenceKey,
+ cwd,
+ initialState,
+ taskId,
+ command,
+ additionalEnv,
+ unsetEnv,
+ sensitive,
+ });
+ createOptions.current = {
+ persistenceKey,
+ cwd,
+ initialState,
+ taskId,
+ command,
+ additionalEnv,
+ unsetEnv,
+ sensitive,
+ };
+
useEffect(() => {
- if (!terminalManager.has(sessionId)) {
- terminalManager.create({
- sessionId,
- persistenceKey,
- cwd,
- initialState,
- taskId,
- command,
- });
- }
- }, [sessionId, persistenceKey, cwd, initialState, taskId, command]);
+ if (terminalManager.has(sessionId)) return;
+ terminalManager.create({ sessionId, ...createOptions.current });
+ }, [sessionId]);
// Attach/detach from DOM
useEffect(() => {
@@ -108,7 +126,10 @@ export function Terminal({
}, [sessionId]);
return (
- <Box onMouseDown={handleMouseDown} className="relative h-full p-3">
+ <Box
+ onMouseDown={handleMouseDown}
+ className={`relative h-full p-3 ${sensitive ? "ph-no-capture" : ""}`}
+ >
<div ref={terminalRef} className="h-full w-full" />
<style>
{`
diff --git a/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts b/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts
index b27306cbb0ad..820f2182f408 100644
--- a/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts
+++ b/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts
@@ -50,12 +50,19 @@ interface TerminalInstance {
resizeObserver: ResizeObserver | null;
saveTimeout: number | null;
persistenceKey: string;
+ sensitive: boolean;
cwd?: string;
taskId?: string;
command?: string;
+ commandEnv?: CommandEnv;
recoveryPromise: Promise<void> | null;
}
+export interface CommandEnv {
+ additionalEnv?: Record<string, string>;
+ unsetEnv?: string[];
+}
+
interface CreateOptions {
sessionId: string;
persistenceKey: string;
@@ -63,6 +70,9 @@ interface CreateOptions {
initialState?: string;
taskId?: string;
command?: string;
+ additionalEnv?: Record<string, string>;
+ unsetEnv?: string[];
+ sensitive?: boolean;
}
type ReadyPayload = { sessionId: string; persistenceKey: string };
@@ -184,8 +194,17 @@ class TerminalManagerImpl {
}
create(options: CreateOptions): TerminalInstance {
- const { sessionId, persistenceKey, cwd, initialState, taskId, command } =
- options;
+ const {
+ sessionId,
+ persistenceKey,
+ cwd,
+ initialState,
+ taskId,
+ command,
+ additionalEnv,
+ unsetEnv,
+ sensitive,
+ } = options;
const existing = this.instances.get(sessionId);
if (existing) {
@@ -222,9 +241,11 @@ class TerminalManagerImpl {
resizeObserver: null,
saveTimeout: null,
persistenceKey,
+ sensitive: sensitive === true,
cwd,
taskId,
command,
+ commandEnv: { additionalEnv, unsetEnv },
recoveryPromise: null,
};
@@ -255,7 +276,7 @@ class TerminalManagerImpl {
instance.cleanups.push(() => exitSub.unsubscribe());
// Initialize shell session
- this.initializeSession(sessionId, instance, cwd, taskId, command);
+ this.initializeSession(sessionId, instance);
this.instances.set(sessionId, instance);
return instance;
@@ -264,10 +285,8 @@ class TerminalManagerImpl {
private async initializeSession(
sessionId: string,
instance: TerminalInstance,
- cwd?: string,
- taskId?: string,
- command?: string,
): Promise<void> {
+ const { cwd, taskId, command, commandEnv } = instance;
try {
const sessionExists = await resolveService<ShellClient>(
SHELL_CLIENT,
@@ -283,6 +302,8 @@ class TerminalManagerImpl {
command,
cwd,
taskId,
+ additionalEnv: commandEnv?.additionalEnv,
+ unsetEnv: commandEnv?.unsetEnv,
});
} else {
await resolveService<ShellClient>(SHELL_CLIENT).create({
@@ -427,8 +448,6 @@ class TerminalManagerImpl {
instance.recoveryPromise = this.initializeSession(
sessionId,
instance,
- instance.cwd,
- instance.taskId,
).finally(() => {
instance.recoveryPromise = null;
});
@@ -437,6 +456,10 @@ class TerminalManagerImpl {
}
private scheduleSave(sessionId: string, instance: TerminalInstance): void {
+ if (instance.sensitive) {
+ return;
+ }
+
if (instance.saveTimeout) {
clearTimeout(instance.saveTimeout);
}
@@ -543,12 +566,13 @@ class TerminalManagerImpl {
// Drain buffered output so the serialized snapshot reflects the latest data.
this.flushWrite(sessionId, instance);
- const serialized = instance.serializeAddon.serialize();
- this.emit("stateChange", {
- sessionId,
- persistenceKey: instance.persistenceKey,
- serializedState: serialized,
- });
+ if (!instance.sensitive) {
+ this.emit("stateChange", {
+ sessionId,
+ persistenceKey: instance.persistenceKey,
+ serializedState: instance.serializeAddon.serialize(),
+ });
+ }
if (instance.terminalElement) {
getParkingContainer().appendChild(instance.terminalElement);
diff --git a/products/desktop/packages/ui/src/features/terminal/destroyShellTerminal.ts b/products/desktop/packages/ui/src/features/terminal/destroyShellTerminal.ts
index 22e334bed573..6ee5843b885e 100644
--- a/products/desktop/packages/ui/src/features/terminal/destroyShellTerminal.ts
+++ b/products/desktop/packages/ui/src/features/terminal/destroyShellTerminal.ts
@@ -11,16 +11,25 @@ const log = logger.scope("destroy-shell-terminal");
// Standalone terminals have no task/workspace teardown to kill their pty, so
// removal must destroy the server-side session explicitly.
+export function destroyTerminalSession(
+ sessionId: string,
+ stateKey: string = sessionId,
+): void {
+ terminalManager.destroy(sessionId);
+ useTerminalStore.getState().clearTerminalState(stateKey);
+ resolveService<ShellClient>(SHELL_CLIENT)
+ .destroy({ sessionId })
+ .catch((error: Error) => {
+ log.error("Failed to destroy shell session:", sessionId, error);
+ });
+}
+
export function destroyShellTerminal(stateKey: string): void {
const sessionId =
useTerminalStore.getState().terminalStates[stateKey]?.sessionId;
if (sessionId) {
- terminalManager.destroy(sessionId);
- resolveService<ShellClient>(SHELL_CLIENT)
- .destroy({ sessionId })
- .catch((error: Error) => {
- log.error("Failed to destroy shell session:", sessionId, error);
- });
+ destroyTerminalSession(sessionId, stateKey);
+ return;
}
useTerminalStore.getState().clearTerminalState(stateKey);
}
diff --git a/products/desktop/packages/ui/src/features/terminal/shellClient.ts b/products/desktop/packages/ui/src/features/terminal/shellClient.ts
index 6667d9b7c5bd..2841418bb2eb 100644
--- a/products/desktop/packages/ui/src/features/terminal/shellClient.ts
+++ b/products/desktop/packages/ui/src/features/terminal/shellClient.ts
@@ -9,6 +9,8 @@ export interface ShellCreateCommandInput {
command: string;
cwd: string;
taskId?: string;
+ additionalEnv?: Record<string, string>;
+ unsetEnv?: string[];
}
export interface ShellResizeInput {
diff --git a/products/desktop/packages/ui/src/features/terminal/terminalStore.test.ts b/products/desktop/packages/ui/src/features/terminal/terminalStore.test.ts
index 497125865ee2..79625f92a3f2 100644
--- a/products/desktop/packages/ui/src/features/terminal/terminalStore.test.ts
+++ b/products/desktop/packages/ui/src/features/terminal/terminalStore.test.ts
@@ -10,7 +10,11 @@ vi.mock("./TerminalManager", () => ({
},
}));
-import { clearPersistedSessionIds, useTerminalStore } from "./terminalStore";
+import {
+ clearPersistedSessionIds,
+ clearPersistedTranscripts,
+ useTerminalStore,
+} from "./terminalStore";
describe("terminalStore persistence", () => {
beforeEach(() => {
@@ -56,4 +60,23 @@ describe("terminalStore persistence", () => {
},
});
});
+
+ it("drops only auth terminal transcripts, not task terminal scrollback", () => {
+ expect(
+ clearPersistedTranscripts({
+ terminalStates: {
+ "claude-auth-login-abc": {
+ serializedState: "a login transcript",
+ sessionId: null,
+ },
+ "task-1-shell": { serializedState: "scrollback", sessionId: null },
+ },
+ }),
+ ).toEqual({
+ terminalStates: {
+ "claude-auth-login-abc": { serializedState: null, sessionId: null },
+ "task-1-shell": { serializedState: "scrollback", sessionId: null },
+ },
+ });
+ });
});
diff --git a/products/desktop/packages/ui/src/features/terminal/terminalStore.ts b/products/desktop/packages/ui/src/features/terminal/terminalStore.ts
index f124ab919606..262b96818a6f 100644
--- a/products/desktop/packages/ui/src/features/terminal/terminalStore.ts
+++ b/products/desktop/packages/ui/src/features/terminal/terminalStore.ts
@@ -61,6 +61,32 @@ export function clearPersistedSessionIds(persistedState: unknown) {
};
}
+export function clearPersistedTranscripts(persistedState: unknown) {
+ if (!persistedState || typeof persistedState !== "object") {
+ return persistedState;
+ }
+
+ const state = persistedState as {
+ terminalStates?: Record<string, Partial<TerminalState>>;
+ };
+
+ if (!state.terminalStates || typeof state.terminalStates !== "object") {
+ return persistedState;
+ }
+
+ return {
+ ...state,
+ terminalStates: Object.fromEntries(
+ Object.entries(state.terminalStates).map(([key, value]) => [
+ key,
+ key.startsWith("claude-auth-")
+ ? { ...value, serializedState: null }
+ : value,
+ ]),
+ ),
+ };
+}
+
export const useTerminalStore = create<TerminalStoreState>()(
persist(
(set, get) => ({
@@ -128,9 +154,15 @@ export const useTerminalStore = create<TerminalStoreState>()(
}),
{
name: "terminal-store",
- version: 1,
- migrate: (persistedState) =>
- clearPersistedSessionIds(persistedState) as PersistedTerminalStoreState,
+ version: 2,
+ migrate: (persistedState, version) => {
+ const withoutSessionIds = clearPersistedSessionIds(persistedState);
+ return (
+ version < 2
+ ? clearPersistedTranscripts(withoutSessionIds)
+ : withoutSessionIds
+ ) as PersistedTerminalStoreState;
+ },
partialize: (state): PersistedTerminalStoreState => ({
terminalStates: Object.fromEntries(
Object.entries(state.terminalStates).map(([k, v]) => [
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
index 30b094711f53..2e65bb312bc8 100644
--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.subscription-verify.test.ts
+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.subscription-verify.test.ts
@@ -1,10 +1,11 @@
import { setRootContainer } from "@posthog/di/container";
+import type { Adapter } from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import { ANALYTICS_TRACKER, track } from "@posthog/ui/shell/analytics";
import {
initializePostHog,
posthogAnalyticsTracker,
- registerCodexSubscription,
+ registerAdapterSubscription,
} from "@posthog/ui/shell/posthogAnalyticsImpl";
import posthog from "posthog-js/dist/module.full.no-external";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -68,57 +69,51 @@ describe("subscription analytics evidence", () => {
vi.unstubAllGlobals();
});
- it("registers the subscription state as SDK super properties", () => {
- registerCodexSubscription({ access: "own-subscription", connected: true });
+ it.each<Adapter>(["codex", "claude"])(
+ "registers the %s subscription state as SDK super properties",
+ (adapter) => {
+ registerAdapterSubscription(adapter, {
+ 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");
- });
+ expect(posthog.get_property(`${adapter}_model_access` as never)).toBe(
+ "own-subscription",
+ );
+ expect(
+ posthog.get_property(`${adapter}_subscription_connected` as never),
+ ).toBe(true);
+ },
+ );
- it("gateway runs are tracked too, with their own billing value", async () => {
- const { enqueued } = tapRequestQueue();
- registerCodexSubscription({
- access: "posthog-gateway",
- connected: false,
- });
+ it.each<[Adapter, "own-subscription" | "posthog-gateway", boolean]>([
+ ["codex", "own-subscription", true],
+ ["codex", "posthog-gateway", false],
+ ["claude", "own-subscription", true],
+ ["claude", "posthog-gateway", false],
+ ])(
+ "sends a %s run event billed to %s",
+ async (adapter, access, connected) => {
+ const { enqueued } = tapRequestQueue();
+ registerAdapterSubscription(adapter, { access, connected });
- track(ANALYTICS_EVENTS.TASK_RUN, {
- task_id: "task-evidence-gw",
- execution_type: "local",
- });
- await Promise.resolve();
+ track(ANALYTICS_EVENTS.TASK_RUN, {
+ task_id: `task-evidence-${adapter}-${access}`,
+ 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");
- });
+ const runEvents = captureEventsOnWire(enqueued).filter(
+ (e) => e.event === ANALYTICS_EVENTS.TASK_RUN,
+ );
+ expect(runEvents).toHaveLength(1);
+ expect(runEvents[0]?.properties[`${adapter}_model_access`]).toBe(access);
+ expect(
+ runEvents[0]?.properties[`${adapter}_subscription_connected`],
+ ).toBe(connected);
+ expect(runEvents[0]?.properties.task_id).toBe(
+ `task-evidence-${adapter}-${access}`,
+ );
+ },
+ );
});
diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts
index 45b2b84892c6..01719352d3d1 100644
--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts
+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts
@@ -128,6 +128,40 @@ describe("registerAppVersion", () => {
});
});
+describe("registerAdapterSubscription", () => {
+ it("reports the saved access when connected", async () => {
+ const { initializePostHog, registerAdapterSubscription } =
+ await loadAnalytics();
+ initializePostHog();
+
+ registerAdapterSubscription("claude", {
+ access: "own-subscription",
+ connected: true,
+ });
+
+ expect(mockPosthog.register).toHaveBeenCalledWith({
+ claude_model_access: "own-subscription",
+ claude_subscription_connected: true,
+ });
+ });
+
+ it("reports the gateway as effective access when disconnected", async () => {
+ const { initializePostHog, registerAdapterSubscription } =
+ await loadAnalytics();
+ initializePostHog();
+
+ registerAdapterSubscription("claude", {
+ access: "own-subscription",
+ connected: false,
+ });
+
+ expect(mockPosthog.register).toHaveBeenCalledWith({
+ claude_model_access: "posthog-gateway",
+ claude_subscription_connected: false,
+ });
+ });
+});
+
describe("track", () => {
it("stamps inbox_client on inbox events", async () => {
const { initializePostHog, track } = await loadAnalytics();
diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
index d79204acfeea..ed32b4e3d5e9 100644
--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
@@ -7,6 +7,7 @@ import type {
AnalyticsProperties,
IAnalytics,
} from "@posthog/platform/analytics";
+import type { Adapter, ModelAccess } from "@posthog/shared";
import {
type EventPropertyMap,
isInboxAnalyticsEvent,
@@ -33,15 +34,15 @@ export type HostInfoProperties = { platform: string; arch: string };
let isInitialized = false;
-export type CodexSubscriptionState = {
- access: "posthog-gateway" | "own-subscription";
+export type AdapterSubscriptionState = {
+ access: ModelAccess;
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;
+const registeredSubscriptions = new Map<Adapter, AdapterSubscriptionState>();
// posthog.reset() wipes super properties, so these are re-registered after each reset.
function registerPersistentSuperProperties(): void {
@@ -53,9 +54,7 @@ function registerPersistentSuperProperties(): void {
...(registeredHostInfo !== null
? hostInfoProperties(registeredHostInfo)
: {}),
- ...(registeredCodexSubscription !== null
- ? codexSubscriptionProperties(registeredCodexSubscription)
- : {}),
+ ...subscriptionSuperProperties(),
});
}
@@ -66,26 +65,35 @@ 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;
-} {
+function subscriptionProperties(
+ adapter: Adapter,
+ { access, connected }: AdapterSubscriptionState,
+): Record<string, string | boolean> {
+ const effectiveAccess = connected ? access : "posthog-gateway";
return {
- codex_model_access: access,
- codex_subscription_connected: connected,
+ [`${adapter}_model_access`]: effectiveAccess,
+ [`${adapter}_subscription_connected`]: connected,
};
}
-export function registerCodexSubscription(state: CodexSubscriptionState): void {
- registeredCodexSubscription = state;
+function subscriptionSuperProperties(): Record<string, string | boolean> {
+ const properties: Record<string, string | boolean> = {};
+ for (const [adapter, state] of registeredSubscriptions) {
+ Object.assign(properties, subscriptionProperties(adapter, state));
+ }
+ return properties;
+}
+
+export function registerAdapterSubscription(
+ adapter: Adapter,
+ state: AdapterSubscriptionState,
+): void {
+ registeredSubscriptions.set(adapter, state);
if (!isInitialized) {
return;
}
- posthog.register(codexSubscriptionProperties(state));
+ posthog.register(subscriptionProperties(adapter, state));
}
type PendingFlagListener = {
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 552611f4eb78..3da447f022bf 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
@@ -314,6 +314,51 @@ describe("AgentService", () => {
vi.unstubAllGlobals();
});
+ describe("claude auth terminal", () => {
+ it.each([
+ { action: "login" as const, expected: "'auth' 'login'" },
+ { action: "logout" as const, expected: "'auth' 'logout'" },
+ ])(
+ "describes the claude auth $action terminal",
+ async ({ action, expected }) => {
+ const terminal = await service.getClaudeAuthTerminal(action);
+
+ expect(terminal.command).toContain(
+ "/mock/appPath/.vite/build/claude-cli/claude",
+ );
+ expect(terminal.command).toContain(expected);
+ expect(terminal.additionalEnv.CLAUDE_CONFIG_DIR).toMatch(
+ /[\\/]\.claude$/,
+ );
+ expect(terminal.unsetEnv).toContain("ANTHROPIC_API_KEY");
+ },
+ );
+
+ it("stops active subscription sessions when logout starts", async () => {
+ const sessions = (
+ service as unknown as { sessions: Map<string, unknown> }
+ ).sessions;
+ const cleanedUp: string[] = [];
+ vi.spyOn(
+ service as unknown as { cleanupSession: (id: string) => Promise<void> },
+ "cleanupSession",
+ ).mockImplementation((taskRunId: string) => {
+ cleanedUp.push(taskRunId);
+ return Promise.resolve();
+ });
+ sessions.set("run-sub-1", {
+ config: { claudeModelAccess: "own-subscription" },
+ });
+ sessions.set("run-gw-1", {
+ config: { claudeModelAccess: "posthog-gateway" },
+ });
+
+ await service.getClaudeAuthTerminal("logout");
+
+ expect(cleanedUp).toEqual(["run-sub-1"]);
+ });
+ });
+
describe("context wiki mount", () => {
const credentials = {
apiHost: "https://app.posthog.test",
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 cba19b4bdc1e..2e85d77e03e6 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts
@@ -19,8 +19,14 @@ import {
POSTHOG_METHODS,
POSTHOG_NOTIFICATIONS,
} from "@posthog/agent";
+import { machineClaudeAuth } from "@posthog/agent/adapters/claude/machine-auth";
import type { McpToolApprovals } from "@posthog/agent/adapters/claude/mcp/tool-metadata";
import { hydrateSessionJsonl } from "@posthog/agent/adapters/claude/session/jsonl-hydration";
+import {
+ type ClaudeAuthAction,
+ claudeAuthTerminalCommand,
+ hasClaudeLogin,
+} from "@posthog/agent/adapters/claude/subscription-login";
import {
type CodexLoginSession,
hasCodexChatgptLogin,
@@ -76,9 +82,9 @@ import {
type BedrockGatewayVariant,
buildCloudTaskConfigOptions,
type CloudRegion,
- type CodexModelAccess,
type ExecutionMode,
isAuthError,
+ type ModelAccess,
resolveCloudInitialPermissionMode,
serializeError,
TypedEventEmitter,
@@ -119,6 +125,8 @@ import type {
import {
AgentServiceEvent,
type AgentServiceEvents,
+ type ClaudeAuthTerminal,
+ type ClaudeSubscriptionStatus,
type CodexSubscriptionStatus,
type Credentials,
type EffortLevel,
@@ -286,7 +294,8 @@ 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;
+ codexModelAccess?: ModelAccess;
+ claudeModelAccess?: ModelAccess;
/** Permission mode to use for the session */
permissionMode?: string;
/** Custom instructions injected into the system prompt */
@@ -523,16 +532,62 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
private codexLogin?: CodexLoginSession;
private codexAuthGeneration = 0;
+ private claudeAuthGeneration = 0;
async getCodexSubscriptionStatus(): Promise<CodexSubscriptionStatus> {
- if (this.codexLogin) return { appLoggedIn: false };
+ if (this.codexLogin) return { loginState: "logged-out" };
+ const loggedIn = await hasCodexChatgptLogin({
+ binaryPath: this.getCodexBinaryPath(),
+ });
+ return { loginState: loggedIn ? "logged-in" : "logged-out" };
+ }
+
+ async getClaudeSubscriptionStatus(): Promise<ClaudeSubscriptionStatus> {
return {
- appLoggedIn: await hasCodexChatgptLogin({
- binaryPath: this.getCodexBinaryPath(),
+ loginState: await hasClaudeLogin({
+ claudeCliPath: this.getClaudeCliPath(),
+ machineAuth: machineClaudeAuth(),
+ logger: this.log,
}),
};
}
+ async getClaudeAuthTerminal(
+ action: ClaudeAuthAction,
+ ): Promise<ClaudeAuthTerminal> {
+ if (action === "logout") {
+ await this.prepareClaudeAccountChange();
+ }
+ const { command, env } = claudeAuthTerminalCommand(
+ action,
+ this.getClaudeCliPath(),
+ machineClaudeAuth(),
+ );
+ return {
+ command,
+ cwd: homedir(),
+ additionalEnv: env.set,
+ unsetEnv: env.unset,
+ };
+ }
+
+ private async prepareClaudeAccountChange(): Promise<void> {
+ this.claudeAuthGeneration += 1;
+ await this.stopClaudeSubscriptionSessions();
+ }
+
+ private async stopClaudeSubscriptionSessions(): Promise<void> {
+ const sessionIds = [...this.sessions.entries()]
+ .filter(
+ ([, session]) =>
+ session.config.claudeModelAccess === "own-subscription",
+ )
+ .map(([taskRunId]) => taskRunId);
+ await Promise.all(
+ sessionIds.map((taskRunId) => this.cleanupSession(taskRunId)),
+ );
+ }
+
async startCodexSubscriptionLogin(): Promise<{ authUrl: string }> {
await this.prepareCodexAccountChange();
const login = await startCodexChatgptLogin({
@@ -947,7 +1002,24 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
);
const codexSubscription =
adapter === "codex" && config.codexModelAccess === "own-subscription";
+ let claudeSubscription =
+ adapter === "claude" && config.claudeModelAccess === "own-subscription";
+ if (claudeSubscription) {
+ const loginState = await hasClaudeLogin({
+ claudeCliPath: this.getClaudeCliPath(),
+ machineAuth: machineClaudeAuth(),
+ logger: this.log,
+ });
+ if (loginState !== "logged-in") {
+ this.log.warn(
+ "Claude own-subscription requested but login is not active; using gateway",
+ { loginState, isReconnect },
+ );
+ claudeSubscription = false;
+ }
+ }
const codexAuthGeneration = this.codexAuthGeneration;
+ const claudeAuthGeneration = this.claudeAuthGeneration;
let codexHome: string | undefined;
if (adapter === "codex") {
@@ -967,6 +1039,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
const acpConnection = await agent.run(taskId, taskRunId, {
adapter,
codexModelAccess: codexSubscription ? "own-subscription" : undefined,
+ claudeModelAccess: claudeSubscription ? "own-subscription" : undefined,
gatewayUrl: proxyUrl,
contextWiki: contextWiki ?? undefined,
codexBinaryPath:
@@ -1290,6 +1363,13 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {
await this.cleanupSession(taskRunId);
throw new Error("The Codex account changed during task setup.");
}
+ if (
+ claudeSubscription &&
+ claudeAuthGeneration !== this.claudeAuthGeneration
+ ) {
+ await this.cleanupSession(taskRunId);
+ throw new Error("The Claude account changed during task setup.");
+ }
this.recordActivity(taskRunId);
if (isRetry) {
@@ -2238,6 +2318,8 @@ For git operations while detached:
adapter: "adapter" in params ? params.adapter : undefined,
codexModelAccess:
"codexModelAccess" in params ? params.codexModelAccess : undefined,
+ claudeModelAccess:
+ "claudeModelAccess" in params ? params.claudeModelAccess : undefined,
permissionMode:
"permissionMode" in params ? params.permissionMode : undefined,
customInstructions:
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 04373848c4be..b9fc43afcc31 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
@@ -14,7 +14,7 @@ export const credentialsSchema = z.object({
export type Credentials = z.infer<typeof credentialsSchema>;
-const codexModelAccessSchema = z.enum(["posthog-gateway", "own-subscription"]);
+const modelAccessSchema = 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
@@ -38,7 +38,8 @@ export const startSessionInput = z.object({
autoProgress: z.boolean().optional(),
runMode: z.enum(["local", "cloud"]).optional(),
adapter: z.enum(["claude", "codex"]).optional(),
- codexModelAccess: codexModelAccessSchema.optional(),
+ codexModelAccess: modelAccessSchema.optional(),
+ claudeModelAccess: modelAccessSchema.optional(),
additionalDirectories: z.array(z.string()).optional(),
customInstructions: customInstructionsField,
/**
@@ -221,7 +222,8 @@ export const reconnectSessionInput = z.object({
logUrl: z.string().optional(),
sessionId: z.string().optional(),
adapter: z.enum(["claude", "codex"]).optional(),
- codexModelAccess: codexModelAccessSchema.optional(),
+ codexModelAccess: modelAccessSchema.optional(),
+ claudeModelAccess: modelAccessSchema.optional(),
/** Additional directories Claude can access beyond cwd (for worktree support) */
additionalDirectories: z.array(z.string()).optional(),
permissionMode: z.string().optional(),
@@ -250,13 +252,34 @@ export const rtkStatusOutput = z.object({
export type RtkStatus = z.infer<typeof rtkStatusOutput>;
export const codexSubscriptionStatusOutput = z.object({
- appLoggedIn: z.boolean(),
+ loginState: z.enum(["logged-in", "logged-out", "unknown"]),
});
export type CodexSubscriptionStatus = z.infer<
typeof codexSubscriptionStatusOutput
>;
+export const claudeSubscriptionStatusOutput = z.object({
+ loginState: z.enum(["logged-in", "logged-out", "unknown"]),
+});
+
+export type ClaudeSubscriptionStatus = z.infer<
+ typeof claudeSubscriptionStatusOutput
+>;
+
+export const claudeAuthTerminalInput = z.object({
+ action: z.enum(["login", "logout"]),
+});
+
+export const claudeAuthTerminalOutput = z.object({
+ command: z.string(),
+ cwd: z.string(),
+ additionalEnv: z.record(z.string(), z.string()),
+ unsetEnv: z.array(z.string()),
+});
+
+export type ClaudeAuthTerminal = z.infer<typeof claudeAuthTerminalOutput>;
+
export const codexSubscriptionLoginOutput = z.object({
authUrl: z.string(),
});
diff --git a/products/desktop/packages/workspace-server/src/services/shell/schemas.ts b/products/desktop/packages/workspace-server/src/services/shell/schemas.ts
index a7974033c757..d6774e20794c 100644
--- a/products/desktop/packages/workspace-server/src/services/shell/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/shell/schemas.ts
@@ -13,6 +13,8 @@ export const createCommandInput = sessionIdInput.extend({
command: z.string().min(1),
cwd: z.string(),
taskId: z.string().optional(),
+ additionalEnv: z.record(z.string(), z.string()).optional(),
+ unsetEnv: z.array(z.string()).optional(),
});
export const writeInput = sessionIdInput.extend({
diff --git a/products/desktop/packages/workspace-server/src/services/shell/shell.ts b/products/desktop/packages/workspace-server/src/services/shell/shell.ts
index bf9b4afa4f4f..705a9c25f08a 100644
--- a/products/desktop/packages/workspace-server/src/services/shell/shell.ts
+++ b/products/desktop/packages/workspace-server/src/services/shell/shell.ts
@@ -63,11 +63,27 @@ function getShellArgs(shell: string): string[] {
return ["-l"];
}
+function getCommandShellArgs(shell: string, command: string): string[] {
+ if (platform() === "win32") {
+ const lower = shell.toLowerCase();
+ if (lower.includes("powershell") || lower.includes("pwsh")) {
+ return ["-NoLogo", "-Command", command];
+ }
+ return ["/c", command];
+ }
+ return ["-c", command];
+}
+
function buildShellEnv(
additionalEnv?: Record<string, string>,
+ unsetEnv?: string[],
): Record<string, string> {
const env = { ...process.env } as Record<string, string>;
+ for (const key of unsetEnv ?? []) {
+ delete env[key];
+ }
+
// User-facing shells must not inherit the workspace-server's internal
// markers: ELECTRON_RUN_AS_NODE makes any Electron-based CLI run as node,
// and the internal-child marker makes the packaged app refuse to launch.
@@ -232,8 +248,11 @@ export class ShellService extends TypedEventEmitter<ShellEvents> {
command: string;
cwd: string;
taskId?: string;
+ additionalEnv?: Record<string, string>;
+ unsetEnv?: string[];
}): Promise<void> {
- const { sessionId, command, cwd, taskId } = options;
+ const { sessionId, command, cwd, taskId, additionalEnv, unsetEnv } =
+ options;
const existing = this.sessions.get(sessionId);
if (existing) {
@@ -241,15 +260,16 @@ export class ShellService extends TypedEventEmitter<ShellEvents> {
}
const taskEnv = await this.getTaskEnv(taskId);
+ const mergedEnv = { ...taskEnv, ...additionalEnv };
const workingDir = this.resolveWorkingDir(sessionId, cwd);
const shell = getDefaultShell();
- const ptyProcess = pty.spawn(shell, ["-c", command], {
+ const ptyProcess = pty.spawn(shell, getCommandShellArgs(shell, command), {
name: "xterm-256color",
cols: 80,
rows: 24,
cwd: workingDir,
- env: buildShellEnv(taskEnv),
+ env: buildShellEnv(mergedEnv, unsetEnv),
encoding: PTY_ENCODING,
});