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): use claude subscriptions for cloud tasks (#95656)

Shy Alter9d5595cfeec2
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.ts
index 593482a7878f..37f0f485deff 100644
--- a/products/desktop/apps/code/src/main/di/bindings.ts
+++ b/products/desktop/apps/code/src/main/di/bindings.ts
@@ -9,7 +9,9 @@ import type {
AUTH_TOKEN_OVERRIDE,
} from "@posthog/core/auth/identifiers";
import type {
+ CLAUDE_SUBSCRIPTION_TOKEN_STORE,
CLOUD_TASK_AUTH,
+ ClaudeSubscriptionTokenStore,
ICloudTaskAuth,
MCP_RELAY_EXECUTOR,
McpRelayExecutor,
@@ -387,6 +389,7 @@ export interface MainBindings {
[MCP_PROXY_AUTH]: McpProxyAuth;
[MCP_RELAY_SERVICE]: McpRelayService;
[MCP_RELAY_EXECUTOR]: McpRelayExecutor;
+ [CLAUDE_SUBSCRIPTION_TOKEN_STORE]: ClaudeSubscriptionTokenStore;
// Archive / suspension host ports
[ARCHIVE_SESSION_CANCELLER]: SessionCanceller;
diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.ts
index b6fb62fa89a5..e9fd74afcbcf 100644
--- a/products/desktop/apps/code/src/main/di/container.ts
+++ b/products/desktop/apps/code/src/main/di/container.ts
@@ -21,6 +21,7 @@ import {
import { canvasCoreModule } from "@posthog/core/canvas/canvas.module";
import { cloudTaskModule } from "@posthog/core/cloud-task/cloud-task.module";
import {
+ CLAUDE_SUBSCRIPTION_TOKEN_STORE,
CLOUD_TASK_AUTH,
CLOUD_TASK_SERVICE,
MCP_RELAY_EXECUTOR,
@@ -239,6 +240,7 @@ import { ElectronAppLifecycle } from "../platform-adapters/electron-app-lifecycl
import { ElectronAppMeta } from "../platform-adapters/electron-app-meta";
import { ElectronAppMetrics } from "../platform-adapters/electron-app-metrics";
import { ElectronBundledResources } from "../platform-adapters/electron-bundled-resources";
+import { ElectronClaudeSubscriptionTokenStore } from "../platform-adapters/electron-claude-subscription-token-store";
import { ElectronClipboard } from "../platform-adapters/electron-clipboard";
import { ElectronContextMenu } from "../platform-adapters/electron-context-menu";
import { ElectronCrypto } from "../platform-adapters/electron-crypto";
@@ -469,11 +471,19 @@ container.bind(CLOUD_TASK_AUTH).toDynamicValue((ctx) => ({
ctx
.get<AuthService>(MAIN_AUTH_SERVICE)
.authenticatedFetch(fetch, url, init),
- getCloudContext: async () => {
+ getCloudContext: async (options?: { includeAccount?: boolean }) => {
const auth = ctx.get<AuthService>(MAIN_AUTH_SERVICE);
const { apiHost } = await auth.getValidAccessToken();
const teamId = auth.getState().currentProjectId;
- return teamId === null ? null : { apiHost, teamId };
+ return teamId === null
+ ? null
+ : {
+ apiHost,
+ teamId,
+ ...(options?.includeAccount && {
+ accountKey: await auth.getAccountKey(),
+ }),
+ };
},
}));
container.bind(MAIN_CLOUD_TASK_SERVICE).toService(CLOUD_TASK_SERVICE);
@@ -636,6 +646,16 @@ container
.bind(MCP_RELAY_EXECUTOR)
.toDynamicValue((ctx) => ctx.get(MCP_RELAY_SERVICE))
.inSingletonScope();
+container
+ .bind(CLAUDE_SUBSCRIPTION_TOKEN_STORE)
+ .toDynamicValue(
+ (ctx) =>
+ new ElectronClaudeSubscriptionTokenStore(
+ join(getUserDataDir(), "claude-subscriptions"),
+ () => ctx.get<AuthService>(MAIN_AUTH_SERVICE).getAccountKey(),
+ ),
+ )
+ .inSingletonScope();
container.load(claudeCliSessionsModule);
container.load(additionalDirectoriesModule);
container.bind(MAIN_SLEEP_SERVICE).to(SleepService);
diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-claude-subscription-token-store.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-claude-subscription-token-store.ts
new file mode 100644
index 000000000000..197670a34aa1
--- /dev/null
+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-claude-subscription-token-store.ts
@@ -0,0 +1,95 @@
+import { createHash, randomUUID } from "node:crypto";
+import {
+ mkdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { join } from "node:path";
+import type { ClaudeSubscriptionTokenStore } from "@posthog/core/cloud-task/identifiers";
+import { safeStorage } from "electron";
+
+export class ElectronClaudeSubscriptionTokenStore
+ implements ClaudeSubscriptionTokenStore
+{
+ constructor(
+ private readonly directory: string,
+ private readonly getAccountKey: () => Promise<string | null>,
+ ) {}
+
+ private requireEncryption(): void {
+ if (
+ !safeStorage.isEncryptionAvailable() ||
+ (process.platform === "linux" &&
+ safeStorage.getSelectedStorageBackend() === "basic_text")
+ ) {
+ throw new Error(
+ "Secure storage is not available. Unlock your system key store and try again.",
+ );
+ }
+ }
+
+ private async tokenPath(expectedAccountKey?: string): Promise<string> {
+ const accountKey = await this.getAccountKey();
+ if (
+ !accountKey ||
+ (expectedAccountKey !== undefined && accountKey !== expectedAccountKey)
+ ) {
+ throw new Error("Sign in to the account that owns this Claude token.");
+ }
+ return join(
+ this.directory,
+ createHash("sha256").update(accountKey).digest("hex"),
+ );
+ }
+
+ async get(expectedAccountKey?: string): Promise<string | null> {
+ const file = await this.tokenPath(expectedAccountKey);
+ this.requireEncryption();
+ let encrypted: Buffer;
+ try {
+ encrypted = readFileSync(file);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw new Error("Cannot read the saved Claude token.");
+ }
+ try {
+ return safeStorage.decryptString(encrypted);
+ } catch {
+ throw new Error(
+ "Cannot read the token. Unlock your system key store. If the error continues, replace or remove the token.",
+ );
+ }
+ }
+
+ async save(token: string): Promise<void> {
+ const file = await this.tokenPath();
+ this.requireEncryption();
+ const temporary = `${file}.${randomUUID()}.tmp`;
+ try {
+ const encrypted = safeStorage.encryptString(token);
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
+ writeFileSync(temporary, encrypted, { flag: "wx", mode: 0o600 });
+ renameSync(temporary, file);
+ } catch {
+ throw new Error(
+ "Cannot save the token. Check your system key store and try again.",
+ );
+ } finally {
+ rmSync(temporary, { force: true });
+ }
+ }
+
+ async clear(): Promise<void> {
+ rmSync(await this.tokenPath(), { force: true });
+ }
+
+ async clearAll(): Promise<void> {
+ rmSync(this.directory, { recursive: true, force: true });
+ }
+
+ async has(): Promise<boolean> {
+ return (await this.get()) !== null;
+ }
+}
diff --git a/products/desktop/apps/code/src/main/services/secure-store/service.test.ts b/products/desktop/apps/code/src/main/services/secure-store/service.test.ts
index a86b9abf1e34..dd3593ceda3f 100644
--- a/products/desktop/apps/code/src/main/services/secure-store/service.test.ts
+++ b/products/desktop/apps/code/src/main/services/secure-store/service.test.ts
@@ -1,6 +1,28 @@
-import { describe, expect, it, vi } from "vitest";
+import {
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { secureStoreRouter } from "@posthog/host-router/routers/secure-store.router";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ElectronClaudeSubscriptionTokenStore } from "../../platform-adapters/electron-claude-subscription-token-store";
import { type SecureStoreBackend, SecureStoreService } from "./service";
+const safeStorage = vi.hoisted(() => ({
+ isEncryptionAvailable: vi.fn(() => true),
+ getSelectedStorageBackend: vi.fn(() => "gnome_libsecret"),
+ encryptString: vi.fn((value: string) => Buffer.from(`encrypted:${value}`)),
+ decryptString: vi.fn((value: Buffer) => value.toString().slice(10)),
+}));
+
+vi.mock("electron", () => ({ safeStorage }));
+
function makeFakeBackend(initial: Record<string, string> = {}) {
const data = new Map<string, string>(Object.entries(initial));
const backend: SecureStoreBackend = {
@@ -19,6 +41,24 @@ function makeFakeBackend(initial: Record<string, string> = {}) {
return { backend, data };
}
+const tokenDirectories: string[] = [];
+
+function makeTokenStore(
+ getAccountKey = async (): Promise<string | null> => "account-1",
+) {
+ const directory = mkdtempSync(join(tmpdir(), "claude-token-test-"));
+ tokenDirectories.push(directory);
+ return {
+ store: new ElectronClaudeSubscriptionTokenStore(directory, getAccountKey),
+ directory,
+ };
+}
+
+afterEach(() => {
+ for (const directory of tokenDirectories.splice(0))
+ rmSync(directory, { recursive: true, force: true });
+});
+
describe("SecureStoreService", () => {
it("round-trips a value through encryption", () => {
const { backend, data } = makeFakeBackend();
@@ -39,6 +79,109 @@ describe("SecureStoreService", () => {
expect(service.getItem("nope")).toBeNull();
});
+ it("keeps the Claude token outside the renderer store and removes it with Clear all data", async () => {
+ const { store, directory } = makeTokenStore();
+ const renderer = new SecureStoreService(makeFakeBackend().backend, store);
+ const caller = secureStoreRouter.createCaller({
+ container: { get: <T>() => renderer as T },
+ });
+ await store.save("fake-token");
+ await expect(store.has()).resolves.toBe(true);
+ const files = readdirSync(directory);
+ expect(files).toHaveLength(1);
+ expect(readFileSync(join(directory, files[0])).toString()).toBe(
+ "encrypted:fake-token",
+ );
+ if (process.platform !== "win32")
+ expect(statSync(join(directory, files[0])).mode & 0o777).toBe(0o600);
+ await expect(caller.getItem({ key: "token" })).resolves.toBeNull();
+ await caller.clear();
+ await expect(store.has()).resolves.toBe(false);
+ });
+
+ it.each(["other-user", "other-server"])(
+ "separates the token from %s",
+ async (otherAccount) => {
+ const account = vi.fn(
+ async (): Promise<string | null> => "original-account",
+ );
+ const { store } = makeTokenStore(account);
+ await store.save("fake-token");
+ account.mockResolvedValue(otherAccount);
+ await expect(store.get()).resolves.toBeNull();
+ await expect(store.get("original-account")).rejects.toThrow("Sign in");
+ await store.save("other-token");
+ await store.clear();
+ account.mockResolvedValue("original-account");
+ await expect(store.get()).resolves.toBe("fake-token");
+ account.mockResolvedValue(null);
+ await store.clearAll();
+ account.mockResolvedValue("original-account");
+ await expect(store.get()).resolves.toBeNull();
+ },
+ );
+
+ it.each(["unavailable", "encrypt", "write", "decrypt"] as const)(
+ "keeps the previous token when OS storage fails at %s",
+ async (failure) => {
+ const { store, directory } = makeTokenStore();
+ await store.save("fake-token");
+ if (failure === "unavailable") {
+ safeStorage.isEncryptionAvailable.mockReturnValueOnce(false);
+ } else if (failure === "encrypt") {
+ safeStorage.encryptString.mockImplementationOnce(() => {
+ throw new Error("encryption failed");
+ });
+ } else if (failure === "write") {
+ renameSync(directory, `${directory}.saved`);
+ writeFileSync(directory, "blocked");
+ } else {
+ safeStorage.decryptString.mockImplementationOnce(() => {
+ throw new Error("key store locked");
+ });
+ }
+ try {
+ await expect(
+ failure === "decrypt" ? store.get() : store.save("replacement-token"),
+ ).rejects.toThrow();
+ } finally {
+ if (failure === "write") {
+ rmSync(directory);
+ renameSync(`${directory}.saved`, directory);
+ }
+ }
+ await expect(store.get()).resolves.toBe("fake-token");
+ },
+ );
+
+ it("can replace or remove a token that cannot be decrypted", async () => {
+ const { store } = makeTokenStore();
+ await store.save("fake-token");
+ safeStorage.decryptString.mockImplementationOnce(() => {
+ throw new Error("invalid ciphertext");
+ });
+ await expect(store.has()).rejects.toThrow("replace or remove");
+ await store.save("replacement-token");
+ await expect(store.get()).resolves.toBe("replacement-token");
+ await store.clear();
+ await expect(store.has()).resolves.toBe(false);
+ });
+
+ it("rejects the Linux plain text backend", async () => {
+ const platform = process.platform;
+ Object.defineProperty(process, "platform", { value: "linux" });
+ safeStorage.getSelectedStorageBackend.mockReturnValueOnce("basic_text");
+ const { store, directory } = makeTokenStore();
+ try {
+ await expect(store.save("fake-token")).rejects.toThrow(
+ "Secure storage is not available",
+ );
+ expect(readdirSync(directory)).toEqual([]);
+ } finally {
+ Object.defineProperty(process, "platform", { value: platform });
+ }
+ });
+
it("removes a stored item", () => {
const { backend } = makeFakeBackend();
const service = new SecureStoreService(backend);
@@ -47,12 +190,12 @@ describe("SecureStoreService", () => {
expect(service.getItem("k")).toBeNull();
});
- it("clears all items", () => {
+ it("clears all items", async () => {
const { backend, data } = makeFakeBackend();
const service = new SecureStoreService(backend);
service.setItem("a", "1");
service.setItem("b", "2");
- service.clear();
+ await service.clear();
expect(data.size).toBe(0);
});
diff --git a/products/desktop/apps/code/src/main/services/secure-store/service.ts b/products/desktop/apps/code/src/main/services/secure-store/service.ts
index e13501288023..d02fa7ebc3fb 100644
--- a/products/desktop/apps/code/src/main/services/secure-store/service.ts
+++ b/products/desktop/apps/code/src/main/services/secure-store/service.ts
@@ -1,7 +1,11 @@
import { SECURE_STORE_BACKEND } from "@main/di/tokens";
import { decrypt, encrypt } from "@main/utils/encryption";
import { logger } from "@main/utils/logger";
-import { inject, injectable } from "inversify";
+import {
+ CLAUDE_SUBSCRIPTION_TOKEN_STORE,
+ type ClaudeSubscriptionTokenStore,
+} from "@posthog/core/cloud-task/identifiers";
+import { inject, injectable, optional } from "inversify";
const log = logger.scope("secureStore");
@@ -30,6 +34,9 @@ export class SecureStoreService {
constructor(
@inject(SECURE_STORE_BACKEND)
private readonly store: SecureStoreBackend,
+ @inject(CLAUDE_SUBSCRIPTION_TOKEN_STORE)
+ @optional()
+ private readonly claudeTokens: ClaudeSubscriptionTokenStore | null = null,
) {}
getItem(key: string): string | null {
@@ -66,7 +73,8 @@ export class SecureStoreService {
}
}
- clear(): void {
+ async clear(): Promise<void> {
+ await this.claudeTokens?.clearAll();
try {
this.store.clear();
} catch (error) {
diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.ts
index 8dc5bd1d7359..b960ed54f6c5 100644
--- a/products/desktop/apps/code/src/main/trpc/router.ts
+++ b/products/desktop/apps/code/src/main/trpc/router.ts
@@ -10,6 +10,7 @@ import { canvasDataRouter } from "@posthog/host-router/routers/canvas-data.route
import { canvasTemplatesRouter } from "@posthog/host-router/routers/canvas-templates.router";
import { channelTasksRouter } from "@posthog/host-router/routers/channel-tasks.router";
import { claudeCliSessionsRouter } from "@posthog/host-router/routers/claude-cli-sessions.router";
+import { claudeSubscriptionTokenRouter } from "@posthog/host-router/routers/claude-subscription-token.router";
import { cloudTaskRouter } from "@posthog/host-router/routers/cloud-task.router";
import { connectivityRouter } from "@posthog/host-router/routers/connectivity.router";
import { contextMenuRouter } from "@posthog/host-router/routers/context-menu.router";
@@ -107,6 +108,7 @@ export const trpcRouter = router({
sleep: sleepRouter,
suspension: suspensionRouter,
secureStore: secureStoreRouter,
+ claudeSubscriptionToken: claudeSubscriptionTokenRouter,
shell: shellRouter,
speech: speechRouter,
skills: skillsRouter,
diff --git a/products/desktop/apps/code/src/renderer/desktop-services.ts b/products/desktop/apps/code/src/renderer/desktop-services.ts
index 617843e4e6e2..d34b0ccd8513 100644
--- a/products/desktop/apps/code/src/renderer/desktop-services.ts
+++ b/products/desktop/apps/code/src/renderer/desktop-services.ts
@@ -1,3 +1,4 @@
+import { CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS } from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
// Desktop host service bindings live here as features move into packages.
// Importing the renderer container performs today's existing bindings.
import "@renderer/di/container";
@@ -411,6 +412,13 @@ container.bind<UserNameProvider>(SPEECH_USER_NAME_PROVIDER).toConstantValue({
},
});
+container.bind(CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS).toConstantValue({
+ has: () => hostTrpcClient.claudeSubscriptionToken.has.query(),
+ save: (token: string) =>
+ hostTrpcClient.claudeSubscriptionToken.save.mutate({ token }),
+ clear: () => hostTrpcClient.claudeSubscriptionToken.clear.mutate(),
+});
+
container.bind<ISpeechKeyStore>(SPEECH_KEY_STORE).toConstantValue({
save: (apiKey) =>
hostTrpcClient.secureStore.setItem
diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.ts
index 454d90018b26..5f6a559787ac 100644
--- a/products/desktop/apps/code/src/renderer/di/bindings.ts
+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts
@@ -241,6 +241,10 @@ import {
MCP_TOOL_BLOCK_COMPONENT,
type McpToolBlockComponent,
} from "@posthog/ui/features/sessions/components/session-update/identifiers";
+import {
+ CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ type ClaudeSubscriptionTokenSettings,
+} from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
import {
DEV_MODE_CLIENT,
type DevModeClient,
@@ -374,6 +378,7 @@ export interface RendererBindings {
[SPEECH_USER_NAME_PROVIDER]: UserNameProvider;
[SPEECH_NOTIFY_SETTINGS]: ISpeechNotifySettings;
[SPEECH_KEY_STORE]: ISpeechKeyStore;
+ [CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS]: ClaudeSubscriptionTokenSettings;
[FILE_WATCHER_CLIENT]: FileWatcherClient;
[FEATURE_FLAGS]: FeatureFlags;
[AUTH_SIDE_EFFECTS]: IAuthSideEffects;
diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.ts
index e2661e8b5129..2b9bfe92dfaf 100644
--- a/products/desktop/apps/web/src/web-container.ts
+++ b/products/desktop/apps/web/src/web-container.ts
@@ -494,7 +494,6 @@ container.bind(CLOUD_TASK_AUTH).toDynamicValue((ctx) => ({
return teamId === null ? null : { apiHost, teamId };
},
}));
-
// ── Canvas / Channels: host-agnostic dashboard + freeform canvas services ──
// They only need AuthService + fetch (they reach the PostHog canvases and
// task_channels APIs), so the web host binds them by loading the same core
diff --git a/products/desktop/docs/CLOUD-MCP-RELAY.md b/products/desktop/docs/CLOUD-MCP-RELAY.md
index 4d6a979a244d..53bf782dfe4c 100644
--- a/products/desktop/docs/CLOUD-MCP-RELAY.md
+++ b/products/desktop/docs/CLOUD-MCP-RELAY.md
@@ -273,3 +273,60 @@ persisted, with caps and the no-secrets rule above.**
4. Creation-payload plumbing (`relayed_mcp_servers`) + composer UX flips the
"Requires your machine" annotation to "Relayed via your machine".
5. Enable `posthog-code-local-mcp-import` for staff once the Django side lands.
+
+
+## Claude subscription credentials
+
+The cloud subscription feature uses the same transport under `posthog-code-claude-own-subscription-cloud`.
+Keep the flag off until the backend and sandbox agent build are deployed.
+Desktop runs `claude setup-token` in the same terminal dialog used for local login.
+Users complete Claude's own login, copy the token, then paste it into Cloud tasks in Settings.
+The token field removes spaces and line breaks when users paste.
+Desktop encrypts each token with Electron `safeStorage`. Each server and account has a separate file with owner-only permissions.
+On macOS, the Keychain protects the encryption key. The token itself is in the encrypted file, not a Keychain entry.
+Windows uses DPAPI. Linux uses the system secret store; Desktop rejects the `basic_text` fallback.
+If secure storage is not available, Desktop refuses to save or read the token.
+The renderer can save, remove, and check for a token. Its generic store API cannot read the saved token.
+Only the main process reads the saved token for relay.
+Sign-out keeps the account's encrypted token. Other accounts cannot use it. Clear all data deletes all saved Claude tokens.
+An unreadable token does not stop app startup. Users can replace or remove it without decryption.
+This protects stored data. It does not protect a token from a compromised app process or sandbox while the token is in use.
+
+A subscription run emits a `credential_request` before initializing Claude.
+Desktop checks the authenticated user against the server-set run owner before it accepts a token request.
+Delivery stays bound to that account, API host, project, task, and run.
+After a Desktop restart, a pending request triggers the same account and run-owner checks before token delivery resumes.
+Hosts without a token store ignore token requests.
+Sandbox credentials cannot select subscription billing, including through a resumed run.
+The API checks the run owner again and blocks redirects when it forwards the token.
+Only that owner can drive model use or obtain a direct sandbox connection token. Other users can still read a shared run.
+Other viewers ignore the request.
+Request metadata uses the durable event stream so a late watcher can receive it.
+The `credential_response` command carries the secret in flight to sandbox memory, never into stored events, task state, logs, or analytics.
+Desktop retries temporary delivery failures until the request expires, and duplicate responses are safe.
+
+The run fails if the token does not arrive within 120 seconds, the backend flag is unavailable, or the sandbox lacks `--claudeSubscription` support.
+It never changes an explicit subscription choice to PostHog model billing.
+Pi hides subscription billing. Desktop omits the subscription choice from Pi requests and does not send a token.
+The API and worker reject direct Pi subscription requests before sandbox startup.
+Continuation keeps that choice. Desktop checks the token before uploading attachments.
+Clients must explicitly confirm subscription billing on resume. Clients without token support receive an error before sandbox creation.
+The worker checks the feature flag for the subscription owner. A sandbox stop check uses the provider state, not the billing record.
+Subscription runs skip prewarming because a warm Claude process has already selected its credentials.
+An unused warm run expires through its idle timeout; its cleanup does not block a subscription run.
+Sandbox compute still uses PostHog credits.
+
+Claude tokens go only to the signed-in PostHog server and project. Token requests cannot follow redirects.
+Desktop checks for a token before all Claude cloud starts and resumes, including Inbox actions.
+If delivery fails after a new run starts, Desktop cancels that run. It releases unused warm runs when the billing choice changes.
+The native Claude process reads the token from a private pipe. The token is absent from its environment and command arguments.
+The pipe is empty after Claude reads it. Child processes do not receive the token. Tool shells also clear credential variables.
+Explicit Claude settings fix the Anthropic endpoint and credential handling.
+Subscription runs ignore executable overrides and disable project API key helpers and other provider routes.
+They also block proxy and custom CA settings and require TLS verification.
+Logs and event streams remove Claude token strings, including tokens split across adjacent text chunks.
+Log redaction covers combined message chunks, buffered tool updates, cached responses, and task failures. These controls do not protect against a compromised process with access to Claude's memory.
+The task sandbox has the same credential boundary as GitHub runs. Code inside it can obtain run credentials.
+A Claude setup token lasts longer than a GitHub token. Remove token does not revoke it or clear an active Claude process.
+
+Direct event uploads stay open by default. Local development closes each batch because local proxies can buffer an open request.
diff --git a/products/desktop/packages/agent/src/acp-extensions.ts b/products/desktop/packages/agent/src/acp-extensions.ts
index ffb0594d434d..88872a60b14d 100644
--- a/products/desktop/packages/agent/src/acp-extensions.ts
+++ b/products/desktop/packages/agent/src/acp-extensions.ts
@@ -100,6 +100,8 @@ export const POSTHOG_NOTIFICATIONS = {
CODEX_GOAL: "_posthog/codex_goal",
/** Desktop → sandbox reply to an MCP relay request (docs/CLOUD-MCP-RELAY.md). */
MCP_RESPONSE: "_posthog/mcp_response",
+ CREDENTIAL_REQUEST: "_posthog/credential_request",
+ CREDENTIAL_RESPONSE: "_posthog/credential_response",
} as const;
export type SteerDeclineCause =
diff --git a/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md b/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md
index 1c066cc0c94d..a420256120e3 100644
--- a/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md
+++ b/products/desktop/packages/agent/src/adapters/claude/UPSTREAM.md
@@ -47,6 +47,9 @@ Fork of `@anthropic-ai/claude-agent-acp`. Upstream repo: https://github.com/anth
- SettingsManager `PreToolUse` hook for permission rules
- `ensureLocalSettings` / `clearStatsigCache`
- `ELECTRON_RUN_AS_NODE` / `ENABLE_TOOL_SEARCH` env vars
+- `machine-auth.ts` (`MachineClaudeAuth`, `applyMachineClaudeAuth`): strips gateway/telemetry env
+ and sets `CLAUDE_CONFIG_DIR` or `CLAUDE_CODE_OAUTH_TOKEN` so a session bills the user's own
+ Claude plan instead of the PostHog gateway
## Intentional Divergences
diff --git a/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts b/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
index 4acf116e7206..fd2a0ffd97af 100644
--- a/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/machine-auth.ts
@@ -3,6 +3,7 @@ import * as path from "node:path";
export interface MachineClaudeAuth {
configDir?: string;
+ oauthToken?: string;
}
export const MACHINE_AUTH_STRIPPED_KEYS = [
@@ -16,6 +17,7 @@ export const MACHINE_AUTH_STRIPPED_KEYS = [
"CLAUDE_CODE_USE_VERTEX",
"CLAUDE_CODE_USE_FOUNDRY",
"CLAUDE_CODE_USE_ANTHROPIC_AWS",
+ "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
"CLAUDE_CODE_USE_MANTLE",
"CLAUDE_CODE_ENABLE_TELEMETRY",
"CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
@@ -29,6 +31,21 @@ export const MACHINE_AUTH_STRIPPED_KEYS = [
let resolvedMachineAuth: MachineClaudeAuth = {};
+export const CLOUD_AUTH_STRIPPED_KEYS = [
+ "ANTHROPIC_UNIX_SOCKET",
+ "CLAUDE_CODE_EXECUTABLE",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "all_proxy",
+ "NODE_EXTRA_CA_CERTS",
+ "SSL_CERT_FILE",
+ "SSL_CERT_DIR",
+ "NODE_OPTIONS",
+] as const;
+
export function setMachineClaudeConfigDir(configDir: string | undefined): void {
resolvedMachineAuth = configDir ? { configDir } : {};
}
@@ -44,6 +61,13 @@ export function applyMachineClaudeAuth(
for (const key of MACHINE_AUTH_STRIPPED_KEYS) {
delete env[key];
}
+ if (auth.oauthToken) {
+ for (const key of CLOUD_AUTH_STRIPPED_KEYS) delete env[key];
+ env.NODE_TLS_REJECT_UNAUTHORIZED = "1";
+ delete env.CLAUDE_CODE_OAUTH_TOKEN;
+ delete env.CLAUDE_CODE_REMOTE;
+ env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB = "0";
+ }
if (auth.configDir) {
env.CLAUDE_CONFIG_DIR = auth.configDir;
} else {
@@ -55,7 +79,11 @@ export function machineClaudeAuthShellEnv(auth: MachineClaudeAuth): {
set: Record<string, string>;
unset: string[];
} {
- const unset: string[] = [...MACHINE_AUTH_STRIPPED_KEYS];
+ const unset: string[] = [
+ ...MACHINE_AUTH_STRIPPED_KEYS,
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
+ ];
if (auth.configDir) {
return { set: { CLAUDE_CONFIG_DIR: auth.configDir }, unset };
}
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 e36285056114..d008bd147a30 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
@@ -619,6 +619,97 @@ describe("buildSessionOptions", () => {
expect(options.fallbackModel).toBeUndefined();
});
+
+ it("keeps the relayed OAuth token out of the environment", async () => {
+ const options = buildSessionOptions({
+ ...makeParams(),
+ userProvidedOptions: {
+ pathToClaudeCodeExecutable: "/tmp/untrusted-claude",
+ executable: "node",
+ executableArgs: ["--eval", "throw new Error('wrong executable')"],
+ settings: {
+ apiKeyHelper: "printf fake-api-key",
+ env: {
+ ANTHROPIC_BASE_URL: "https://example.com",
+ HTTPS_PROXY: "https://proxy.example.com",
+ NODE_EXTRA_CA_CERTS: "/tmp/example-ca.pem",
+ NODE_TLS_REJECT_UNAUTHORIZED: "0",
+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: "0",
+ CLAUDE_CODE_REMOTE: "1",
+ ANTHROPIC_UNIX_SOCKET: "/tmp/untrusted.sock",
+ CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD: "1",
+ },
+ },
+ },
+ machineAuth: { oauthToken: "sk-ant-oat01-fake-test-token" },
+ 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",
+ },
+ });
+ const env = options.env;
+
+ expect(env?.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();
+ expect(env?.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB).toBe("0");
+ for (const key of STRIPPED_KEYS) {
+ expect(env?.[key]).toBeUndefined();
+ }
+ expect(env?.OPENAI_BASE_URL).toBeUndefined();
+ expect(env?.OPENAI_API_KEY).toBeUndefined();
+ for (const [key, value] of Object.entries(env ?? {})) {
+ expect(value).not.toContain("x-posthog-");
+ expect(key).not.toMatch(/X-PostHog/i);
+ }
+ expect(options.settings).toMatchObject({
+ apiKeyHelper: "",
+ env: {
+ ANTHROPIC_BASE_URL: "https://api.anthropic.com",
+ HTTPS_PROXY: "",
+ NODE_EXTRA_CA_CERTS: "",
+ NODE_TLS_REJECT_UNAUTHORIZED: "1",
+ CLAUDE_CODE_OAUTH_TOKEN: "",
+ CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR: "3",
+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: "0",
+ CLAUDE_CODE_REMOTE: "",
+ ANTHROPIC_UNIX_SOCKET: "",
+ CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD: "",
+ },
+ });
+ expect(options.pathToClaudeCodeExecutable).toBeUndefined();
+ expect(options.executable).toBeUndefined();
+ expect(options.executableArgs).toBeUndefined();
+ expect(options.spawnClaudeCodeProcess).toBeTypeOf("function");
+ expect(JSON.stringify(options)).not.toContain(
+ "sk-ant-oat01-fake-test-token",
+ );
+ const child = options.spawnClaudeCodeProcess?.({
+ command: process.execPath,
+ args: [
+ "-e",
+ 'const fs = require("node:fs"); const token = fs.readFileSync("/dev/fd/3", "utf8"); process.stdout.write(JSON.stringify({ received: token === "sk-ant-oat01-fake-test-token", inEnvironment: Object.values(process.env).includes(token), remaining: fs.readFileSync("/dev/fd/3", "utf8") }));',
+ ],
+ cwd: os.tmpdir(),
+ env: options.env ?? {},
+ signal: new AbortController().signal,
+ });
+ expect(child).toBeDefined();
+ if (!child) throw new Error("Claude process did not start.");
+ let output = "";
+ const exited = new Promise<number | null>((resolve) => {
+ child.on("exit", resolve);
+ });
+ for await (const chunk of child.stdout) output += chunk.toString();
+ expect(await exited).toBe(0);
+ expect(JSON.parse(output)).toEqual({
+ received: true,
+ inEnvironment: false,
+ remaining: "",
+ });
+ });
});
describe("per-session context wiki env", () => {
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 e22d50ae3dcb..c726a9f1b341 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
+import type { Writable } from "node:stream";
import type {
CanUseTool,
McpServerConfig,
@@ -42,6 +43,8 @@ import {
} from "../hooks";
import {
applyMachineClaudeAuth,
+ CLOUD_AUTH_STRIPPED_KEYS,
+ MACHINE_AUTH_STRIPPED_KEYS,
type MachineClaudeAuth,
} from "../machine-auth";
import { type CodeExecutionMode, toSdkPermissionMode } from "../tools";
@@ -479,19 +482,42 @@ function getAbortController(
function buildSpawnWrapper(
sessionId: string,
- onProcessSpawned: (info: ProcessSpawnedInfo) => void,
+ onProcessSpawned?: (info: ProcessSpawnedInfo) => void,
onProcessExited?: (pid: number) => void,
logger?: Logger,
+ oauthToken?: string,
): (options: SpawnOptions) => SpawnedProcess {
return (spawnOpts: SpawnOptions): SpawnedProcess => {
- const child = spawn(spawnOpts.command, spawnOpts.args, {
+ const command = oauthToken ? "/bin/bash" : spawnOpts.command;
+ const args = oauthToken
+ ? [
+ "-p",
+ "-c",
+ 'exec "$@" 3< <(/bin/cat <&3)',
+ "--",
+ spawnOpts.command,
+ ...spawnOpts.args,
+ ]
+ : spawnOpts.args;
+ const child = spawn(command, args, {
cwd: spawnOpts.cwd,
- env: spawnOpts.env as NodeJS.ProcessEnv,
- stdio: ["pipe", "pipe", "pipe"],
+ env: {
+ ...spawnOpts.env,
+ ...(oauthToken ? { CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR: "3" } : {}),
+ },
+ stdio: oauthToken
+ ? ["pipe", "pipe", "pipe", "pipe"]
+ : ["pipe", "pipe", "pipe"],
});
+ if (oauthToken) {
+ const tokenPipe = child.stdio[3] as Writable;
+ tokenPipe.on("error", () => child.kill("SIGTERM"));
+ tokenPipe.end(oauthToken);
+ }
+
if (child.pid) {
- onProcessSpawned({
+ onProcessSpawned?.({
pid: child.pid,
command: `${spawnOpts.command} ${spawnOpts.args.join(" ")}`,
sessionId,
@@ -603,7 +629,9 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
const agents = buildAgents(params.userProvidedOptions?.agents);
const registeredAgentNames = new Set(Object.keys(agents));
- const claudeCodeExecutable = process.env.CLAUDE_CODE_EXECUTABLE;
+ const claudeCodeExecutable = params.machineAuth?.oauthToken
+ ? undefined
+ : process.env.CLAUDE_CODE_EXECUTABLE;
const options: Options = {
...params.userProvidedOptions,
@@ -667,16 +695,50 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {
abortController: getAbortController(
params.userProvidedOptions?.abortController,
),
- ...(params.onProcessSpawned && {
+ ...((params.onProcessSpawned || params.machineAuth?.oauthToken) && {
spawnClaudeCodeProcess: buildSpawnWrapper(
params.sessionId,
params.onProcessSpawned,
params.onProcessExited,
params.logger,
+ params.machineAuth?.oauthToken,
),
}),
};
+ if (params.machineAuth?.oauthToken) {
+ delete options.pathToClaudeCodeExecutable;
+ delete options.executable;
+ delete options.executableArgs;
+ if (typeof options.settings === "string")
+ throw new Error("Cloud subscription settings must be an object.");
+ const extraSettings = options.extraArgs?.settings;
+ const inlineSettings: Settings = extraSettings
+ ? JSON.parse(extraSettings)
+ : {};
+ if (options.extraArgs) delete options.extraArgs.settings;
+ options.settings = {
+ ...inlineSettings,
+ ...options.settings,
+ apiKeyHelper: "",
+ env: {
+ ...inlineSettings.env,
+ ...options.settings?.env,
+ ...Object.fromEntries(
+ [...MACHINE_AUTH_STRIPPED_KEYS, ...CLOUD_AUTH_STRIPPED_KEYS].map(
+ (key) => [key, ""],
+ ),
+ ),
+ NODE_TLS_REJECT_UNAUTHORIZED: "1",
+ ANTHROPIC_BASE_URL: "https://api.anthropic.com",
+ CLAUDE_CODE_OAUTH_TOKEN: "",
+ CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR: "3",
+ CLAUDE_CODE_REMOTE: "",
+ CLAUDE_CODE_SUBPROCESS_ENV_SCRUB: "0",
+ },
+ };
+ }
+
if (claudeCodeExecutable) {
options.pathToClaudeCodeExecutable = claudeCodeExecutable;
if (isLegacyJavaScriptClaudeExecutable(claudeCodeExecutable)) {
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/settings.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/settings.test.ts
index 5f6a91f4253b..4abedbea7117 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/settings.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/settings.test.ts
@@ -26,6 +26,7 @@ describe("SettingsManager per-repo persistence", () => {
runGit(mainRepo, ["init", "-b", "main"]);
runGit(mainRepo, ["config", "user.email", "[email protected]"]);
runGit(mainRepo, ["config", "user.name", "test"]);
+ runGit(mainRepo, ["config", "commit.gpgsign", "false"]);
runGit(mainRepo, ["commit", "--allow-empty", "-m", "init"]);
runGit(mainRepo, ["worktree", "add", "-b", "feat", worktree]);
});
@@ -225,6 +226,7 @@ describe("availableModels merge", () => {
runGit(cwd, ["init", "-b", "main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "test"]);
+ runGit(cwd, ["config", "commit.gpgsign", "false"]);
runGit(cwd, ["commit", "--allow-empty", "-m", "init"]);
originalConfigDir = process.env.CLAUDE_CONFIG_DIR;
diff --git a/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts b/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts
index 9b8ef8e89032..f33bf6d00d89 100644
--- a/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/subscription-login.ts
@@ -6,7 +6,7 @@ import {
machineClaudeAuthShellEnv,
} from "./machine-auth";
-export type ClaudeAuthAction = "login" | "logout";
+export type ClaudeAuthAction = "login" | "logout" | "setup-token";
export interface ClaudeAuthTerminalCommand {
command: string;
@@ -25,7 +25,7 @@ export function claudeAuthTerminalCommand(
claudeCliPath: string,
machineAuth: MachineClaudeAuth,
): ClaudeAuthTerminalCommand {
- const args = action === "login" ? ["auth", "login"] : ["auth", "logout"];
+ const args = action === "setup-token" ? ["setup-token"] : ["auth", action];
const isLegacyJs = claudeCliPath.endsWith(".js");
const parts = isLegacyJs
? [process.execPath, claudeCliPath, ...args]
diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.ts
index 88a286837d52..17b046a87923 100644
--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.ts
+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/clone-repo.test.ts
@@ -43,6 +43,7 @@ describe("clone_repo", () => {
await git(["config", "user.name", "PostHog Code test"], sourcePath);
await git(["config", "user.email", "[email protected]"], sourcePath);
await git(["config", "commit.gpgsign", "false"], sourcePath);
+ await git(["config", "tag.gpgsign", "false"], sourcePath);
await writeFile(path.join(sourcePath, "README.md"), "master\n");
await git(["add", "README.md"], sourcePath);
await git(["commit", "-m", "initial commit"], sourcePath);
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index eba2310cceea..332c7d001141 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -768,86 +768,92 @@ describe("AgentServer HTTP Mode", () => {
);
});
- it("writes terminal failure status before completing event ingest", async () => {
- const order: string[] = [];
- const testServer = new AgentServer({
- port,
- jwtPublicKey: TEST_PUBLIC_KEY,
- repositoryPath: repo.path,
- apiUrl: "http://localhost:8000",
- apiKey: "test-api-key",
- projectId: 1,
- mode: "interactive",
- taskId: "test-task-id",
- runId: "test-run-id",
- resolveRtkSavings: async () => null,
- }) as unknown as {
- eventStreamSender: {
- enqueue: (event: Record<string, unknown>) => void;
- stop: () => Promise<void>;
+ it.each([
+ ["boom", "boom"],
+ ["Failure: sk-ant-oat01-fake-test-token", "Failure: [REDACTED]"],
+ ])(
+ "redacts terminal failure status before completing event ingest",
+ async (message, expected) => {
+ const order: string[] = [];
+ const testServer = new AgentServer({
+ port,
+ jwtPublicKey: TEST_PUBLIC_KEY,
+ repositoryPath: repo.path,
+ apiUrl: "http://localhost:8000",
+ apiKey: "test-api-key",
+ projectId: 1,
+ mode: "interactive",
+ taskId: "test-task-id",
+ runId: "test-run-id",
+ resolveRtkSavings: async () => null,
+ }) as unknown as {
+ eventStreamSender: {
+ enqueue: (event: Record<string, unknown>) => void;
+ stop: () => Promise<void>;
+ };
+ posthogAPI: {
+ updateTaskRun: (
+ taskId: string,
+ runId: string,
+ payload: Record<string, unknown>,
+ ) => Promise<unknown>;
+ };
+ signalTaskComplete(
+ payload: JwtPayload,
+ stopReason: string,
+ errorMessage?: string,
+ options?: { errorCategory?: string },
+ ): Promise<void>;
};
- posthogAPI: {
- updateTaskRun: (
- taskId: string,
- runId: string,
- payload: Record<string, unknown>,
- ) => Promise<unknown>;
+ testServer.eventStreamSender = {
+ enqueue: vi.fn(() => {
+ order.push("enqueue");
+ }),
+ stop: vi.fn(async () => {
+ order.push("stop");
+ }),
+ };
+ testServer.posthogAPI = {
+ updateTaskRun: vi.fn(async () => {
+ order.push("update");
+ return {};
+ }),
};
- signalTaskComplete(
- payload: JwtPayload,
- stopReason: string,
- errorMessage?: string,
- options?: { errorCategory?: string },
- ): Promise<void>;
- };
- testServer.eventStreamSender = {
- enqueue: vi.fn(() => {
- order.push("enqueue");
- }),
- stop: vi.fn(async () => {
- order.push("stop");
- }),
- };
- testServer.posthogAPI = {
- updateTaskRun: vi.fn(async () => {
- order.push("update");
- return {};
- }),
- };
- await testServer.signalTaskComplete(
- {
- run_id: "run-1",
- task_id: "task-1",
- team_id: 1,
- user_id: 1,
- distinct_id: "distinct-id",
- mode: "interactive",
- },
- "error",
- "boom",
- { errorCategory: "agent_error" },
- );
+ await testServer.signalTaskComplete(
+ {
+ run_id: "run-1",
+ task_id: "task-1",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "distinct-id",
+ mode: "interactive",
+ },
+ "error",
+ message,
+ { errorCategory: "agent_error" },
+ );
- expect(order).toEqual(["enqueue", "update", "stop"]);
- expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(
- expect.objectContaining({
- type: "notification",
- notification: expect.objectContaining({
- method: "_posthog/error",
- params: expect.objectContaining({ error: "boom" }),
+ expect(order).toEqual(["enqueue", "update", "stop"]);
+ expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: "notification",
+ notification: expect.objectContaining({
+ method: "_posthog/error",
+ params: expect.objectContaining({ error: expected }),
+ }),
}),
- }),
- );
- expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(
- "task-1",
- "run-1",
- {
- status: "failed",
- error_message: "agent_error: boom",
- },
- );
- });
+ );
+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ {
+ status: "failed",
+ error_message: `agent_error: ${expected}`,
+ },
+ );
+ },
+ );
it("writes the terminal error to the session log before the final flush", async () => {
// The Django drain reads the terminal `_posthog/error` from the S3 log,
@@ -3152,6 +3158,164 @@ describe("AgentServer HTTP Mode", () => {
});
describe("POST /command", () => {
+ it("keeps cancelled initialization work pending until it settles", async () => {
+ const s = createServer() as unknown as {
+ shutdownController: AbortController;
+ measureInitialization(
+ phase: "session_create",
+ work: () => Promise<void>,
+ ): Promise<void>;
+ };
+ let finish = () => {};
+ const work = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const settled = vi.fn();
+ const initialization = s.measureInitialization(
+ "session_create",
+ () => work,
+ );
+ const observed = initialization.then(settled, settled);
+ s.shutdownController.abort(new Error("cancelled"));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(settled).not.toHaveBeenCalled();
+ finish();
+ await observed;
+ expect(settled).toHaveBeenCalledWith(
+ expect.objectContaining({ message: "cancelled" }),
+ );
+ });
+
+ it.each(["token", "no_token", "cancel", "reconnect"])(
+ "handles %s during subscription initialization",
+ async (outcome) => {
+ const s = createServer({ claudeModelAccess: "own-subscription" });
+ const { app } = s as unknown as {
+ app: { fetch(request: Request): Promise<Response> | Response };
+ };
+ const authorization = `Bearer ${createToken()}`;
+ const response = await app.fetch(
+ new Request("http://localhost/events", {
+ headers: { Authorization: authorization },
+ }),
+ );
+ if (!response.body) throw new Error("Expected an event stream");
+ let reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffered = "";
+ const nextEvent = async (): Promise<Record<string, unknown>> => {
+ for (;;) {
+ const end = buffered.indexOf("\n\n");
+ if (end >= 0) {
+ const frame = buffered.slice(0, end);
+ buffered = buffered.slice(end + 2);
+ if (frame.startsWith("data: ")) return JSON.parse(frame.slice(6));
+ } else {
+ const chunk = await reader.read();
+ if (chunk.done)
+ throw new Error("Event stream ended before initialization");
+ buffered += decoder.decode(chunk.value, { stream: true });
+ }
+ }
+ };
+ try {
+ let event = await nextEvent();
+ while (event.type !== "credential_request") event = await nextEvent();
+ const health = await app.fetch(
+ new Request("http://localhost/health"),
+ );
+ expect((await health.json()).hasSession).toBe(false);
+ if (outcome === "cancel") {
+ await s.stop();
+ const stopped = await app.fetch(
+ new Request("http://localhost/health"),
+ );
+ expect((await stopped.json()).failureCode).toBeUndefined();
+ expect(JSON.stringify(appendLogCalls)).not.toContain(
+ "credential_relay",
+ );
+ return;
+ }
+ if (outcome === "reconnect") {
+ const replacement = await app.fetch(
+ new Request("http://localhost/events", {
+ headers: { Authorization: authorization },
+ }),
+ );
+ await reader.cancel();
+ if (!replacement.body) throw new Error("Expected an event stream");
+ reader = replacement.body.getReader();
+ buffered = "";
+ }
+ const body = JSON.stringify({
+ jsonrpc: "2.0",
+ id: "credential-reply",
+ method: "credential_response",
+ params: {
+ requestId: event.requestId,
+ credential: "claude_subscription_token",
+ ...(outcome === "no_token"
+ ? { error: "no_token" }
+ : { token: "sk-ant-oat01-fake-test-token" }),
+ },
+ });
+ for (const overrides of [
+ { task_id: "other-task" },
+ { run_id: "other-run" },
+ { team_id: 2 },
+ ]) {
+ const denied = await app.fetch(
+ new Request("http://localhost/command", {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${createToken(overrides)}`,
+ "Content-Type": "application/json",
+ },
+ body,
+ }),
+ );
+ expect(denied.status).toBe(400);
+ }
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const reply = await app.fetch(
+ new Request("http://localhost/command", {
+ method: "POST",
+ headers: {
+ Authorization: authorization,
+ "Content-Type": "application/json",
+ },
+ body,
+ }),
+ );
+ expect(await reply.json()).toEqual({
+ jsonrpc: "2.0",
+ id: "credential-reply",
+ result: { resolved: true },
+ });
+ }
+ if (outcome === "no_token") {
+ await vi.waitFor(async () => {
+ const failed = await app.fetch(
+ new Request("http://localhost/health"),
+ );
+ expect((await failed.json()).failureCode).toBe(
+ "claude_credential_unavailable",
+ );
+ });
+ return;
+ }
+ while (event.type !== "connected") event = await nextEvent();
+ const ready = await app.fetch(new Request("http://localhost/health"));
+ expect((await ready.json()).hasSession).toBe(true);
+ expect(JSON.stringify(appendLogCalls)).not.toContain(
+ "sk-ant-oat01-fake-test-token",
+ );
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ }
+ },
+ );
+
it("returns 401 without authorization", async () => {
await createServer().start();
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 87cfb325e571..4cf326c6e98b 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -124,12 +124,17 @@ import { createEventIdSource } from "../utils/event-id";
import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";
import { resolveGithubToken } from "../utils/github-token";
import { Logger } from "../utils/logger";
+import {
+ ClaudeTokenEventRedactor,
+ redactClaudeTokens,
+} from "../utils/redact-claude-tokens";
import { logAgentshRuntimeInfo } from "./agentsh-runtime";
import { AgentBootTracker } from "./boot-phases";
import {
normalizeCloudPromptContent,
promptBlocksToText,
} from "./cloud-prompt";
+import { CredentialRelay, CredentialRelayError } from "./credential-relay";
import { TaskRunEventStreamSender } from "./event-stream-sender";
import { type JwtPayload, JwtValidationError, validateJwt } from "./jwt";
import { type McpRelayResponse, McpRelayServer } from "./mcp-relay-server";
@@ -139,7 +144,11 @@ import {
} from "./pr-checkout";
import { createRtkSavingsNotification } from "./rtk-savings";
import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";
-import { jsonRpcRequestSchema, validateCommandParams } from "./schemas";
+import {
+ type CredentialResponseParams,
+ jsonRpcRequestSchema,
+ validateCommandParams,
+} from "./schemas";
import { buildStoreSkillsInstructions, syncStoreSkills } from "./store-skills";
import type { AgentServerConfig, ClaudeCodeConfig } from "./types";
import { waitForFile } from "./wait-for-file";
@@ -265,6 +274,8 @@ interface BuiltPrompt {
}
export const PREWARMED_RESUME_IDLE_CAPABILITY = "prewarmedResumeIdle";
+export const CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE =
+ "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.";
function hiddenTextBlock(text: string): ContentBlock {
return {
@@ -491,8 +502,15 @@ export class AgentServer {
// often arrives while newSession() is still awaited (this.session is still null),
// causing a second session to be created and duplicate Slack messages to be sent.
private initializationPromise: Promise<void> | null = null;
+ private readonly shutdownController = new AbortController();
+ private initializingConnection: ReturnType<
+ typeof createAcpConnection
+ > | null = null;
+ private initializationFailureCode: string | undefined;
+ private initializingSseController: SseController | null = null;
private initializingTelemetry: OtelRunTelemetry | undefined;
private pendingEvents: Record<string, unknown>[] = [];
+ private tokenEventRedactor = new ClaudeTokenEventRedactor();
/** ACP notifications emitted by newSession/resumeSession before this.session is assigned. */
private preSessionEvents: Record<string, unknown>[] = [];
private deliveredMessageIds = new Set<string>();
@@ -527,6 +545,9 @@ export class AgentServer {
private readonly posthogExecPermissionRegex: RegExp;
private readonly posthogExecPermissionRegexSource: string;
private mcpRelayServer: McpRelayServer | null = null;
+ private readonly credentialRelay = new CredentialRelay({
+ emitEvent: (event) => this.broadcastEvent(event),
+ });
/**
* Start loopback relay endpoints for the run's designated desktop-only MCP
@@ -551,6 +572,9 @@ export class AgentServer {
}
private detachSseController(controller: SseController): void {
+ if (this.initializingSseController === controller) {
+ this.initializingSseController = null;
+ }
if (this.session?.sseController === controller) {
this.session.sseController = null;
}
@@ -699,6 +723,7 @@ export class AgentServer {
status: "ok",
hasSession: !!this.session,
readiness: boot.state,
+ failureCode: this.initializationFailureCode,
bootMs: this.sessionReadyBootMs,
sessionInitMs: this.sessionInitMs,
boot,
@@ -727,6 +752,10 @@ export class AgentServer {
);
}
+ if (!this.isConfiguredRun(payload)) {
+ return c.json({ error: "Token does not match this task run" }, 403);
+ }
+
let keepaliveInterval: ReturnType<typeof setInterval> | null = null;
const clearKeepalive = (): void => {
if (keepaliveInterval) {
@@ -735,9 +764,9 @@ export class AgentServer {
}
};
+ let sseController: SseController | null = null;
const stream = new ReadableStream({
start: async (controller) => {
- let sseController: SseController | null = null;
const encoder = new TextEncoder();
const detachCurrentSseController = (): void => {
if (sseController) {
@@ -795,9 +824,7 @@ export class AgentServer {
cancel: () => {
clearKeepalive();
this.logger.debug("SSE connection closed");
- if (this.session?.sseController) {
- this.session.sseController = null;
- }
+ if (sseController) this.detachSseController(sseController);
},
});
@@ -827,7 +854,7 @@ export class AgentServer {
);
}
- if (!this.session || this.session.payload.run_id !== payload.run_id) {
+ if (!this.isConfiguredRun(payload)) {
return c.json({ error: "No active session for this run" }, 400);
}
@@ -839,6 +866,13 @@ export class AgentServer {
}
const command = parseResult.data;
+ const isCredentialResponse =
+ command.method === "credential_response" ||
+ command.method === "posthog/credential_response" ||
+ command.method === POSTHOG_NOTIFICATIONS.CREDENTIAL_RESPONSE;
+ if (!isCredentialResponse && !this.session) {
+ return c.json({ error: "No active session for this run" }, 400);
+ }
const paramsValidation = validateCommandParams(
command.method,
command.params ?? {},
@@ -859,10 +893,11 @@ export class AgentServer {
}
try {
- const result = await this.executeCommand(
- command.method,
- (command.params as Record<string, unknown>) || {},
- );
+ const result = isCredentialResponse
+ ? this.resolveCredentialResponse(
+ paramsValidation.data as CredentialResponseParams,
+ )
+ : await this.executeCommand(command.method, command.params ?? {});
return c.json({
jsonrpc: "2.0",
id: command.id,
@@ -1032,20 +1067,34 @@ export class AgentServer {
return this.resumeState?.nativeGoal;
}
+ private async cleanupInitializingConnection(): Promise<void> {
+ const connection = this.initializingConnection;
+ await withTimeout(connection?.cleanup() ?? Promise.resolve(), 5_000);
+ }
+
async stop(): Promise<void> {
this.logger.debug("Stopping agent server...");
-
- if (this.session) {
- await this.cleanupSession({ completeEventStream: true });
- } else {
- await this.eventStreamSender?.stop();
- }
-
- if (this.server) {
- this.server.close();
+ this.shutdownController.abort(new CredentialRelayError("cancelled"));
+ this.credentialRelay.stop();
+ try {
+ await withTimeout(
+ Promise.allSettled([
+ this.cleanupInitializingConnection(),
+ this.initializationPromise,
+ ]),
+ 5_000,
+ );
+ await withTimeout(
+ this.session
+ ? this.cleanupSession({ completeEventStream: true })
+ : (this.eventStreamSender?.stop({ complete: false }) ??
+ Promise.resolve()),
+ 5_000,
+ );
+ } finally {
+ this.server?.close();
this.server = null;
}
-
this.logger.debug("Agent server stopped");
}
@@ -1058,7 +1107,15 @@ export class AgentServer {
* run from a process-level handler with no session context.
*/
async reportFatalError(error: unknown): Promise<void> {
- const errorMessage = error instanceof Error ? error.message : String(error);
+ if (error instanceof CredentialRelayError && error.code === "cancelled")
+ return;
+ const errorMessage = redactClaudeTokens(
+ error instanceof CredentialRelayError
+ ? CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE
+ : error instanceof Error
+ ? error.message
+ : String(error),
+ );
this.logger.error("Fatal agent-server error; marking run failed", error);
try {
@@ -1114,6 +1171,35 @@ export class AgentServer {
}
}
+ private async reportClaudeSubscriptionTokenMissing(
+ reason: string,
+ ): Promise<void> {
+ this.initializationFailureCode = "claude_credential_unavailable";
+ this.logger.warn("claude_credential_unavailable");
+ try {
+ this.broadcastEvent({
+ type: "notification",
+ timestamp: new Date().toISOString(),
+ notification: {
+ jsonrpc: "2.0" as const,
+ method: POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED,
+ params: {
+ runtimeAdapter: this.getRuntimeAdapter(),
+ initializationPhase: "credential_relay",
+ reason,
+ message: CLAUDE_SUBSCRIPTION_TOKEN_MISSING_MESSAGE,
+ },
+ },
+ });
+ await this.eventStreamSender?.stop({ complete: false });
+ } catch (error) {
+ this.logger.error(
+ "Failed to flush events after credential relay failure",
+ error,
+ );
+ }
+ }
+
private authenticateRequest(
getHeader: (name: string) => string | undefined,
): JwtPayload {
@@ -1137,6 +1223,23 @@ export class AgentServer {
return validateJwt(token, this.config.jwtPublicKey);
}
+ private isConfiguredRun(payload: JwtPayload): boolean {
+ return (
+ payload.task_id === this.config.taskId &&
+ payload.run_id === this.config.runId &&
+ payload.team_id === this.config.projectId
+ );
+ }
+
+ private resolveCredentialResponse(params: CredentialResponseParams): {
+ resolved: true;
+ } {
+ if (!this.credentialRelay.resolve(params)) {
+ throw new Error("No pending credential request found");
+ }
+ return { resolved: true };
+ }
+
private async executeCommand(
method: string,
params: Record<string, unknown>,
@@ -1637,10 +1740,27 @@ export class AgentServer {
}
}
+ private async measureInitialization<T>(
+ phase: Parameters<AgentBootTracker["measure"]>[0],
+ work: () => Promise<T>,
+ ): Promise<T> {
+ this.shutdownController.signal.throwIfAborted();
+ const result = await this.bootTracker.measure(phase, work);
+ this.shutdownController.signal.throwIfAborted();
+ return result;
+ }
+
private async initializeSession(
payload: JwtPayload,
sseController: SseController | null,
): Promise<void> {
+ this.shutdownController.signal.throwIfAborted();
+ if (sseController) {
+ this.initializingSseController = sseController;
+ const events = this.pendingEvents;
+ this.pendingEvents = [];
+ for (const event of events) this.sendSseEvent(sseController, event);
+ }
// Race condition guard: autoInitializeSession() starts first, but while it awaits
// newSession() (which takes ~1-2s for MCP metadata fetch), the Temporal relay connects
// to GET /events. That handler sees this.session === null and calls initializeSession()
@@ -1666,15 +1786,16 @@ export class AgentServer {
this.httpReadyBootMs,
this.config.launcherToProcessMs,
);
- this.initializationPromise = this._doInitializeSession(
- payload,
- sseController,
- );
+ this.initializationPromise = this._doInitializeSession(payload);
const initStartedAt = Date.now();
try {
await this.initializationPromise;
} catch (error) {
+ if (this.shutdownController.signal.aborted) throw error;
this.bootTracker.markFailed();
+ if (error instanceof CredentialRelayError) {
+ this.initializationFailureCode = "claude_credential_unavailable";
+ }
const telemetry = this.initializingTelemetry;
telemetry?.append(payload.run_id, {
type: "notification",
@@ -1700,8 +1821,11 @@ export class AgentServer {
await telemetry?.shutdown();
throw error;
} finally {
+ await this.cleanupInitializingConnection();
+ this.initializingConnection = null;
this.initializingTelemetry = undefined;
this.initializationPromise = null;
+ this.initializingSseController = null;
}
}
@@ -1733,10 +1857,7 @@ export class AgentServer {
return null;
}
- private async _doInitializeSession(
- payload: JwtPayload,
- sseController: SseController | null,
- ): Promise<void> {
+ private async _doInitializeSession(payload: JwtPayload): Promise<void> {
if (this.session) {
await this.cleanupSession();
}
@@ -1760,7 +1881,7 @@ export class AgentServer {
name: process.env.HOSTNAME || "cloud-sandbox",
};
- const [preTaskRun, preTask] = await this.bootTracker.measure(
+ const [preTaskRun, preTask] = await this.measureInitialization(
"context_fetch",
() =>
Promise.all([
@@ -1884,6 +2005,25 @@ export class AgentServer {
sinks: telemetry ? [telemetry] : undefined,
});
+ let claudeSubscriptionToken: string | null = null;
+ if (
+ this.config.claudeModelAccess === "own-subscription" &&
+ runtimeAdapter === "claude"
+ ) {
+ try {
+ claudeSubscriptionToken = await this.credentialRelay.request(
+ "claude_subscription_token",
+ );
+ } catch (error) {
+ if (this.shutdownController.signal.aborted) throw error;
+ const reason = error instanceof Error ? error.message : String(error);
+ this.logger.warn("Claude subscription token relay failed", { reason });
+ await this.reportClaudeSubscriptionTokenMissing(reason);
+ throw error;
+ }
+ }
+
+ this.shutdownController.signal.throwIfAborted();
const acpConnection = createAcpConnection({
adapter: runtimeAdapter,
taskRunId: payload.run_id,
@@ -1894,7 +2034,14 @@ export class AgentServer {
onWireMessage: (message, eventId) =>
this.handleAcpTransportMessage(message, eventId),
logger: this.logger,
- claudeGatewayEnv: runtimeAdapter !== "codex" ? gatewayEnv : undefined,
+ claudeGatewayEnv:
+ runtimeAdapter !== "codex" && claudeSubscriptionToken === null
+ ? gatewayEnv
+ : undefined,
+ claudeMachineAuth:
+ runtimeAdapter !== "codex" && claudeSubscriptionToken !== null
+ ? { oauthToken: claudeSubscriptionToken }
+ : undefined,
codexOptions:
runtimeAdapter === "codex"
? {
@@ -1931,7 +2078,7 @@ export class AgentServer {
},
});
- // The connection's wire taps broadcast all ACP messages via SSE (mimics local transport)
+ this.initializingConnection = acpConnection;
this.adapterEmittedTurnComplete = false;
const clientStream = ndJsonStream(
acpConnection.clientStreams.writable as WritableStream<Uint8Array>,
@@ -1943,7 +2090,7 @@ export class AgentServer {
clientStream,
);
- const initializeResult = await this.bootTracker.measure(
+ const initializeResult = await this.measureInitialization(
"acp_initialize",
() =>
clientConnection.initialize({
@@ -2006,7 +2153,7 @@ export class AgentServer {
...this.buildClaudeCodeSessionMeta(runtimeAdapter),
};
- await this.bootTracker.measure("repository_ready", () =>
+ await this.measureInitialization("repository_ready", () =>
this.waitForRepoReady(),
);
const existingPrCheckoutPromise =
@@ -2024,7 +2171,7 @@ export class AgentServer {
let effectiveSessionMeta: typeof sessionMeta & {
nativeGoal?: NonNullable<ResumeState["nativeGoal"]>;
} = sessionMeta;
- const [nativeResume, sessionMcpServers] = await this.bootTracker.measure(
+ const [nativeResume, sessionMcpServers] = await this.measureInitialization(
"session_dependencies",
async () => {
try {
@@ -2060,7 +2207,7 @@ export class AgentServer {
},
);
- const acpSessionId = await this.bootTracker.measure(
+ const acpSessionId = await this.measureInitialization(
"session_create",
async () => {
let sessionId: string | null = null;
@@ -2092,6 +2239,7 @@ export class AgentServer {
}
}
if (!sessionId) {
+ this.shutdownController.signal.throwIfAborted();
const restoredNativeGoal =
this.getNativeGoalForFreshSession(runtimeAdapter);
effectiveSessionMeta = restoredNativeGoal
@@ -2114,17 +2262,19 @@ export class AgentServer {
this.evaluatedPrUrls.clear();
this.prAttributionChain = Promise.resolve();
+ this.shutdownController.signal.throwIfAborted();
+ this.initializingConnection = null;
this.session = {
payload,
acpSessionId,
acpConnection,
clientConnection,
- sseController,
+ sseController: this.initializingSseController,
deviceInfo,
logWriter,
telemetry,
permissionMode: initialPermissionMode,
- hasDesktopConnected: sseController !== null,
+ hasDesktopConnected: this.initializingSseController !== null,
sessionMeta: effectiveSessionMeta,
};
this.initializingTelemetry = undefined;
@@ -4717,6 +4867,7 @@ ${commonInstructions}
errorMessage?: string,
options?: { errorCategory?: AgentErrorClassification },
): Promise<void> {
+ errorMessage = redactClaudeTokens(errorMessage);
const currentSession = this.session;
const sessionMatchesRun = currentSession?.payload.run_id === payload.run_id;
const terminalErrorMessage = errorMessage ?? "Agent error";
@@ -5737,10 +5888,18 @@ ${commonInstructions}
}
private broadcastEvent(event: Record<string, unknown>): void {
+ for (const redacted of this.tokenEventRedactor.redact(event)) {
+ this.deliverEvent(redacted);
+ }
+ }
+
+ private deliverEvent(event: Record<string, unknown>): void {
this.eventStreamSender?.enqueue(event);
- if (this.session?.sseController) {
- this.sendSseEvent(this.session.sseController, event);
+ const controller =
+ this.session?.sseController ?? this.initializingSseController;
+ if (controller) {
+ this.sendSseEvent(controller, event);
} else {
// Buffers events raised before a session exists yet (e.g. an MCP relay
// request fired the instant the client subprocess starts, ahead of
diff --git a/products/desktop/packages/agent/src/server/bin.ts b/products/desktop/packages/agent/src/server/bin.ts
index 0f82254f108f..55e1136ee9ea 100644
--- a/products/desktop/packages/agent/src/server/bin.ts
+++ b/products/desktop/packages/agent/src/server/bin.ts
@@ -7,6 +7,7 @@ import { isSupportedReasoningEffort } from "../adapters/reasoning-effort";
import { DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE } from "../posthog-exec-permission";
import { AgentServer } from "./agent-server";
import { launcherToProcessMs } from "./boot-phases";
+import { CredentialRelayError } from "./credential-relay";
import { PiAgentServer } from "./pi-agent-server";
import {
claudeCodeConfigSchema,
@@ -142,6 +143,7 @@ program
"interactive",
)
.option("--repositoryPath <path>", "Path to the repository")
+ .option("--claudeSubscription", "Use a relayed Claude subscription token")
.option(
"--repoReadyFile <path>",
"Sentinel file; session creation blocks until it exists (set while cloning concurrently)",
@@ -187,6 +189,13 @@ program
}
const env = envResult.data;
+ if (
+ options.claudeSubscription &&
+ (env.POSTHOG_AGENT_RUNTIME === "pi" ||
+ env.POSTHOG_CODE_RUNTIME_ADAPTER === "codex")
+ ) {
+ program.error("--claudeSubscription requires the Claude runtime");
+ }
delete process.env.POSTHOG_AGENT_LAUNCH_STARTED_AT_MS;
// The telemetry token is only ever consumed here (into the server config);
@@ -286,6 +295,9 @@ program
),
runtimeAdapter: env.POSTHOG_CODE_RUNTIME_ADAPTER,
model: env.POSTHOG_CODE_MODEL,
+ claudeModelAccess: options.claudeSubscription
+ ? "own-subscription"
+ : "posthog-gateway",
reasoningEffort: env.POSTHOG_CODE_REASONING_EFFORT,
contextWindow: env.POSTHOG_CODE_CONTEXT_WINDOW,
fastMode: env.POSTHOG_CODE_FAST_MODE,
@@ -323,7 +335,13 @@ program
process.on("uncaughtException", handleFatalError);
process.on("unhandledRejection", handleFatalError);
- await server.start();
+ try {
+ await server.start();
+ } catch (error) {
+ if (error instanceof CredentialRelayError && error.code === "cancelled")
+ return;
+ await handleFatalError(error);
+ }
});
program.parse();
diff --git a/products/desktop/packages/agent/src/server/credential-relay.test.ts b/products/desktop/packages/agent/src/server/credential-relay.test.ts
new file mode 100644
index 000000000000..46c186a5b186
--- /dev/null
+++ b/products/desktop/packages/agent/src/server/credential-relay.test.ts
@@ -0,0 +1,105 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CredentialRelay } from "./credential-relay";
+
+describe("CredentialRelay", () => {
+ let events: Record<string, unknown>[];
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ events = [];
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function makeRelay(timeoutMs?: number): CredentialRelay {
+ return new CredentialRelay({
+ emitEvent: (event) => events.push(event),
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
+ });
+ }
+
+ it("resolves with the token when the matching response arrives", async () => {
+ const relay = makeRelay();
+ const tokenPromise = relay.request("claude_subscription_token");
+
+ expect(events).toHaveLength(1);
+ const event = events[0] as {
+ type: string;
+ requestId: string;
+ credential: string;
+ };
+ expect(event.type).toBe("credential_request");
+ expect(event.credential).toBe("claude_subscription_token");
+
+ relay.resolve({
+ requestId: event.requestId,
+ token: "sk-ant-oat01-fake-test-token",
+ });
+ await expect(tokenPromise).resolves.toBe("sk-ant-oat01-fake-test-token");
+ expect(
+ relay.resolve({ requestId: event.requestId, token: "another-token" }),
+ ).toBe(true);
+ });
+
+ it("rejects with a safe message when the response carries an error", async () => {
+ const relay = makeRelay();
+ const tokenPromise = relay.request("claude_subscription_token");
+ const { requestId } = events[0] as { requestId: string };
+
+ relay.resolve({ requestId, error: "sensitive-untrusted-error" });
+ await expect(tokenPromise).rejects.toThrow(
+ "PostHog Desktop could not provide the Claude token.",
+ );
+ });
+
+ it("rejects on timeout", async () => {
+ const relay = makeRelay(120_000);
+ const tokenPromise = relay.request("claude_subscription_token");
+
+ const assertion = expect(tokenPromise).rejects.toThrow(
+ "timed out waiting for PostHog Desktop",
+ );
+ await vi.advanceTimersByTimeAsync(120_000);
+ await assertion;
+ });
+
+ it("ignores a response with an unknown requestId", async () => {
+ const relay = makeRelay();
+ const tokenPromise = relay.request("claude_subscription_token");
+ const { requestId } = events[0] as { requestId: string };
+
+ const resolved = relay.resolve({
+ requestId: "not-a-pending-request",
+ token: "sk-ant-oat01-fake-test-token",
+ });
+
+ expect(resolved).toBe(false);
+ relay.resolve({ requestId, token: "sk-ant-oat01-fake-test-token" });
+ await expect(tokenPromise).resolves.toBe("sk-ant-oat01-fake-test-token");
+ });
+
+ it("emits no event containing the token", async () => {
+ const relay = makeRelay();
+ const tokenPromise = relay.request("claude_subscription_token");
+ const { requestId } = events[0] as { requestId: string };
+
+ relay.resolve({ requestId, token: "sk-ant-oat01-fake-test-token" });
+ await tokenPromise;
+
+ const serialized = JSON.stringify(events);
+ expect(serialized).not.toContain("sk-ant-oat01-fake-test-token");
+ });
+
+ it("rejects pending and future requests on shutdown", async () => {
+ const relay = makeRelay();
+ const pending = relay.request("claude_subscription_token");
+ relay.stop();
+ await expect(pending).rejects.toThrow("Session is shutting down.");
+ await expect(relay.request("claude_subscription_token")).rejects.toThrow(
+ "Session is shutting down.",
+ );
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/products/desktop/packages/agent/src/server/credential-relay.ts b/products/desktop/packages/agent/src/server/credential-relay.ts
new file mode 100644
index 000000000000..9ba73cb0b8ed
--- /dev/null
+++ b/products/desktop/packages/agent/src/server/credential-relay.ts
@@ -0,0 +1,90 @@
+import { randomUUID } from "node:crypto";
+
+export const CREDENTIAL_RELAY_TIMEOUT_MS = 120_000;
+
+export class CredentialRelayError extends Error {
+ constructor(readonly code: "cancelled" | "timeout" | "no_token") {
+ super(
+ code === "cancelled"
+ ? "Session is shutting down."
+ : code === "timeout"
+ ? "The credential request timed out waiting for PostHog Desktop."
+ : "PostHog Desktop could not provide the Claude token.",
+ );
+ this.name = "CredentialRelayError";
+ }
+}
+
+export interface CredentialRelayConfig {
+ emitEvent: (event: Record<string, unknown>) => void;
+ timeoutMs?: number;
+}
+
+interface PendingRequest {
+ resolve: (token: string) => void;
+ reject: (error: Error) => void;
+ timer: NodeJS.Timeout;
+}
+
+export class CredentialRelay {
+ private readonly pending = new Map<string, PendingRequest>();
+ private completedRequestId: string | null = null;
+ private stopped = false;
+
+ constructor(private readonly config: CredentialRelayConfig) {}
+
+ request(credential: string): Promise<string> {
+ if (this.stopped) {
+ return Promise.reject(new CredentialRelayError("cancelled"));
+ }
+ const requestId = randomUUID();
+ const timeoutMs = this.config.timeoutMs ?? CREDENTIAL_RELAY_TIMEOUT_MS;
+ const expiresAt = new Date(Date.now() + timeoutMs).toISOString();
+
+ const tokenPromise = new Promise<string>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(requestId);
+ reject(new CredentialRelayError("timeout"));
+ }, timeoutMs);
+ timer.unref?.();
+ this.pending.set(requestId, { resolve, reject, timer });
+ });
+ tokenPromise.catch(() => {});
+
+ this.config.emitEvent({
+ type: "credential_request",
+ requestId,
+ credential,
+ expiresAt,
+ });
+ return tokenPromise;
+ }
+
+ resolve(params: {
+ requestId: string;
+ token?: string;
+ error?: string;
+ }): boolean {
+ const pending = this.pending.get(params.requestId);
+ if (!pending) return params.requestId === this.completedRequestId;
+ this.pending.delete(params.requestId);
+ clearTimeout(pending.timer);
+ this.completedRequestId = params.requestId;
+ if (params.token && !params.error) {
+ pending.resolve(params.token);
+ } else {
+ pending.reject(new CredentialRelayError("no_token"));
+ }
+ return true;
+ }
+
+ stop(): void {
+ this.stopped = true;
+ this.completedRequestId = null;
+ for (const [requestId, pending] of this.pending) {
+ clearTimeout(pending.timer);
+ pending.reject(new CredentialRelayError("cancelled"));
+ this.pending.delete(requestId);
+ }
+ }
+}
diff --git a/products/desktop/packages/agent/src/server/event-stream-sender.test.ts b/products/desktop/packages/agent/src/server/event-stream-sender.test.ts
index 6001b2fdfa3d..7a0e0f4b6d11 100644
--- a/products/desktop/packages/agent/src/server/event-stream-sender.test.ts
+++ b/products/desktop/packages/agent/src/server/event-stream-sender.test.ts
@@ -129,50 +129,58 @@ describe("TaskRunEventStreamSender", () => {
vi.unstubAllGlobals();
});
- it("streams ordered NDJSON events with the run-scoped token", async () => {
- const requestBodies: string[] = [];
- const fetchMock = vi.fn(
- async (_url: string | URL | Request, init?: RequestInit) => {
- const body = await readRequestBody(init);
- requestBodies.push(body);
- return responseForBody(body);
- },
- );
- vi.stubGlobal("fetch", fetchMock);
-
- const sender = createSender();
-
- sender.enqueue({ type: "notification", notification: { method: "first" } });
- sender.enqueue({
- type: "notification",
- notification: { method: "second" },
- });
- await sender.stop();
+ it.each([true, false])(
+ "streams ordered NDJSON events with complete=%s",
+ async (complete) => {
+ const requestBodies: string[] = [];
+ const fetchMock = vi.fn(
+ async (_url: string | URL | Request, init?: RequestInit) => {
+ const body = await readRequestBody(init);
+ requestBodies.push(body);
+ return responseForBody(body);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
- expect(fetchMock).toHaveBeenCalledTimes(2);
- expect(fetchMock.mock.calls[1][0]).toBe(
- "http://localhost:8000/api/projects/1/tasks/task-1/runs/run-1/event_stream/",
- );
- expect(fetchMock.mock.calls[1][1]?.headers).toEqual({
- Authorization: "Bearer ingest-token",
- "Content-Type": "application/x-ndjson",
- });
- expect(fetchMock.mock.calls[1][1]?.headers).not.toHaveProperty(
- "X-PostHog-Event-Stream-Complete",
- );
+ const sender = createSender();
+
+ sender.enqueue({
+ type: "notification",
+ notification: { method: "first" },
+ });
+ sender.enqueue({
+ type: "notification",
+ notification: { method: "second" },
+ });
+ await sender.stop({ complete });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[1][0]).toBe(
+ "http://localhost:8000/api/projects/1/tasks/task-1/runs/run-1/event_stream/",
+ );
+ expect(fetchMock.mock.calls[1][1]?.headers).toEqual({
+ Authorization: "Bearer ingest-token",
+ "Content-Type": "application/x-ndjson",
+ });
+ expect(fetchMock.mock.calls[1][1]?.headers).not.toHaveProperty(
+ "X-PostHog-Event-Stream-Complete",
+ );
- expect(parseLines(requestBodies[1])).toEqual([
- {
- seq: 1,
- event: { type: "notification", notification: { method: "first" } },
- },
- {
- seq: 2,
- event: { type: "notification", notification: { method: "second" } },
- },
- { type: STREAM_COMPLETE_CONTROL_TYPE, final_seq: 2 },
- ]);
- });
+ expect(parseLines(requestBodies[1])).toEqual([
+ {
+ seq: 1,
+ event: { type: "notification", notification: { method: "first" } },
+ },
+ {
+ seq: 2,
+ event: { type: "notification", notification: { method: "second" } },
+ },
+ ...(complete
+ ? [{ type: STREAM_COMPLETE_CONTROL_TYPE, final_seq: 2 }]
+ : []),
+ ]);
+ },
+ );
it("routes the ingest POST to the agent-proxy run-scoped path when eventIngestBaseUrl is set", async () => {
const fetchMock = vi.fn(
@@ -195,43 +203,50 @@ describe("TaskRunEventStreamSender", () => {
expect(lastCall[0]).not.toContain("/api/projects/");
});
- it("closes the ingest upload per drained batch on the proxy path by default", async () => {
- const requestBodies: string[] = [];
- let contentUploads = 0;
- const fetchMock = vi.fn(
- async (_url: string | URL | Request, init?: RequestInit) => {
- if (!init?.body || typeof init.body === "string") {
- return responseForBody(await readRequestBody(init));
- }
+ it.each([undefined, "http://agent-proxy:8003/"])(
+ "closes each drained batch with ingest base %s",
+ async (eventIngestBaseUrl) => {
+ const requestBodies: string[] = [];
+ let contentUploads = 0;
+ const fetchMock = vi.fn(
+ async (_url: string | URL | Request, init?: RequestInit) => {
+ if (!init?.body || typeof init.body === "string") {
+ return responseForBody(await readRequestBody(init));
+ }
- // Resolves only once the sender closes the upload body.
- const body = await readRequestBody(init);
- contentUploads += 1;
- requestBodies.push(body);
- return responseForBody(body);
- },
- );
- vi.stubGlobal("fetch", fetchMock);
+ // Resolves only once the sender closes the upload body.
+ const body = await readRequestBody(init);
+ contentUploads += 1;
+ requestBodies.push(body);
+ return responseForBody(body);
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
- const sender = createSender({
- flushDelayMs: 0,
- eventIngestBaseUrl: "http://agent-proxy:8003/",
- });
+ const sender = createSender({
+ flushDelayMs: 0,
+ eventIngestBaseUrl,
+ keepProxyStreamOpen: false,
+ });
- sender.enqueue({ type: "notification", notification: { method: "first" } });
- await vi.waitFor(() => expect(contentUploads).toBe(1));
+ sender.enqueue({
+ type: "notification",
+ notification: { method: "first" },
+ });
+ await vi.waitFor(() => expect(contentUploads).toBe(1));
- sender.enqueue({
- type: "notification",
- notification: { method: "second" },
- });
- await vi.waitFor(() => expect(contentUploads).toBe(2));
+ sender.enqueue({
+ type: "notification",
+ notification: { method: "second" },
+ });
+ await vi.waitFor(() => expect(contentUploads).toBe(2));
- await sender.stop();
+ await sender.stop();
- expect(eventSequences(requestBodies[0] ?? "")).toEqual([1]);
- expect(eventSequences(requestBodies[1] ?? "")).toEqual([2]);
- });
+ expect(eventSequences(requestBodies[0] ?? "")).toEqual([1]);
+ expect(eventSequences(requestBodies[1] ?? "")).toEqual([2]);
+ },
+ );
it("holds one long-lived upload across batches when keepProxyStreamOpen is set", async () => {
const requestBodies: string[] = [];
diff --git a/products/desktop/packages/agent/src/server/event-stream-sender.ts b/products/desktop/packages/agent/src/server/event-stream-sender.ts
index a4f30b4cf04a..76eac355785b 100644
--- a/products/desktop/packages/agent/src/server/event-stream-sender.ts
+++ b/products/desktop/packages/agent/src/server/event-stream-sender.ts
@@ -70,7 +70,6 @@ export class TaskRunEventStreamSender {
private readonly requestTimeoutMs: number;
private readonly stopTimeoutMs: number;
private readonly streamWindowMs: number;
- private readonly usingProxy: boolean;
private readonly keepProxyStreamOpen: boolean;
private readonly createStreamingUpload: StreamingUploadFactory;
private readonly encoder = new TextEncoder();
@@ -103,7 +102,7 @@ export class TaskRunEventStreamSender {
config.logger.info("Event ingest target resolved", {
ingestUrl: this.ingestUrl,
routedToProxy: usingProxy,
- persistentUpload: !usingProxy || config.keepProxyStreamOpen === true,
+ persistentUpload: config.keepProxyStreamOpen ?? !usingProxy,
});
this.maxBufferedEvents =
config.maxBufferedEvents ?? DEFAULT_MAX_BUFFERED_EVENTS;
@@ -116,8 +115,7 @@ export class TaskRunEventStreamSender {
config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
this.stopTimeoutMs = config.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS;
this.streamWindowMs = config.streamWindowMs ?? DEFAULT_STREAM_WINDOW_MS;
- this.usingProxy = usingProxy;
- this.keepProxyStreamOpen = config.keepProxyStreamOpen ?? false;
+ this.keepProxyStreamOpen = config.keepProxyStreamOpen ?? !usingProxy;
this.createStreamingUpload =
config.createStreamingUpload ?? createNodeStreamingUpload;
}
@@ -137,7 +135,7 @@ export class TaskRunEventStreamSender {
this.scheduleFlush();
}
- async stop(): Promise<void> {
+ async stop({ complete = true }: { complete?: boolean } = {}): Promise<void> {
if (this.stopPromise) {
await this.stopPromise;
return;
@@ -150,7 +148,7 @@ export class TaskRunEventStreamSender {
this.flushTimer = null;
}
- this.stopPromise = this.drainForStop();
+ this.stopPromise = this.drainForStop(complete);
await this.stopPromise;
}
@@ -163,7 +161,7 @@ export class TaskRunEventStreamSender {
}, delayMs);
}
- private async drainForStop(): Promise<void> {
+ private async drainForStop(complete: boolean): Promise<void> {
const startedAtMs = Date.now();
const deadlineAtMs = startedAtMs + this.stopTimeoutMs;
@@ -173,8 +171,15 @@ export class TaskRunEventStreamSender {
try {
await this.flush();
- await this.writeCompletionLine();
+ if (complete) {
+ await this.writeCompletionLine();
+ }
await this.closeActiveStream();
+ if (this.bufferedEvents.length > 0) {
+ throw new Error(
+ "Event ingest stopped before all events were acknowledged",
+ );
+ }
this.transportCompleted = true;
return;
} catch (error) {
@@ -216,7 +221,7 @@ export class TaskRunEventStreamSender {
await flushPromise;
// The ingress ahead of the agent-proxy only forwards the request body once the
// upload closes, so close per drained batch to avoid stranding buffered events.
- if (!this.stopped && this.usingProxy && !this.keepProxyStreamOpen) {
+ if (!this.stopped && !this.keepProxyStreamOpen) {
await this.closeActiveStream();
}
return this.bufferedEvents.length < previousBufferLength;
diff --git a/products/desktop/packages/agent/src/server/schemas.test.ts b/products/desktop/packages/agent/src/server/schemas.test.ts
index c22d6887e412..3d6bbba8782d 100644
--- a/products/desktop/packages/agent/src/server/schemas.test.ts
+++ b/products/desktop/packages/agent/src/server/schemas.test.ts
@@ -343,6 +343,69 @@ describe("validateCommandParams", () => {
}).success,
).toBe(false);
});
+
+ it.each([
+ "credential_response",
+ "posthog/credential_response",
+ "_posthog/credential_response",
+ ])("accepts a valid %s carrying only a token", (method) => {
+ const result = validateCommandParams(method, {
+ requestId: "req-1",
+ credential: "claude_subscription_token",
+ token: "sk-ant-oat01-fake-test-token",
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it("accepts a credential_response carrying only an error", () => {
+ const result = validateCommandParams("credential_response", {
+ requestId: "req-1",
+ credential: "claude_subscription_token",
+ error: "no_token",
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it("rejects a credential_response without requestId", () => {
+ const result = validateCommandParams("credential_response", {
+ credential: "claude_subscription_token",
+ token: "sk-ant-oat01-fake-test-token",
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("rejects a credential_response with both token and error", () => {
+ const result = validateCommandParams("credential_response", {
+ requestId: "req-1",
+ credential: "claude_subscription_token",
+ token: "sk-ant-oat01-fake-test-token",
+ error: "no_token",
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("rejects a credential_response with neither token nor error", () => {
+ const result = validateCommandParams("credential_response", {
+ requestId: "req-1",
+ credential: "claude_subscription_token",
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it("rejects a credential_response naming a different credential", () => {
+ const result = validateCommandParams("credential_response", {
+ requestId: "req-1",
+ credential: "something_else",
+ token: "sk-ant-oat01-fake-test-token",
+ });
+
+ expect(result.success).toBe(false);
+ });
});
describe("relayMcpServerNamesSchema", () => {
diff --git a/products/desktop/packages/agent/src/server/schemas.ts b/products/desktop/packages/agent/src/server/schemas.ts
index cc76b730fb1c..497b10ea08d4 100644
--- a/products/desktop/packages/agent/src/server/schemas.ts
+++ b/products/desktop/packages/agent/src/server/schemas.ts
@@ -115,6 +115,21 @@ export const mcpResponseParamsSchema = z
error: "Exactly one of payload or error is required",
});
+export const credentialResponseParamsSchema = z
+ .object({
+ requestId: z.string().min(1, "requestId is required").max(128),
+ credential: z.literal("claude_subscription_token"),
+ token: z.string().min(1).max(4096).optional(),
+ error: z.enum(["no_token", "store_unavailable"]).optional(),
+ })
+ .refine((params) => Boolean(params.token) !== Boolean(params.error), {
+ error: "Exactly one of token or error is required",
+ });
+
+export type CredentialResponseParams = z.infer<
+ typeof credentialResponseParamsSchema
+>;
+
export const closeParamsSchema = z.object({}).optional();
export const commandParamsSchemas = {
@@ -134,6 +149,9 @@ export const commandParamsSchemas = {
mcp_response: mcpResponseParamsSchema,
"posthog/mcp_response": mcpResponseParamsSchema,
"_posthog/mcp_response": mcpResponseParamsSchema,
+ credential_response: credentialResponseParamsSchema,
+ "posthog/credential_response": credentialResponseParamsSchema,
+ "_posthog/credential_response": credentialResponseParamsSchema,
side_question: sideQuestionParamsSchema,
"posthog/side_question": sideQuestionParamsSchema,
} as const;
diff --git a/products/desktop/packages/agent/src/server/types.ts b/products/desktop/packages/agent/src/server/types.ts
index 207a027c74a6..a7111e64d117 100644
--- a/products/desktop/packages/agent/src/server/types.ts
+++ b/products/desktop/packages/agent/src/server/types.ts
@@ -59,6 +59,7 @@ export interface AgentServerConfig {
piRpcHostPath?: string;
runtimeAdapter?: Adapter;
model?: string;
+ claudeModelAccess?: "posthog-gateway" | "own-subscription";
reasoningEffort?: EffortLevel | "off" | "minimal";
contextWindow?: "200k" | "1m";
fastMode?: boolean;
diff --git a/products/desktop/packages/agent/src/session-log-writer.test.ts b/products/desktop/packages/agent/src/session-log-writer.test.ts
index 8e544f76dc58..0e5364575889 100644
--- a/products/desktop/packages/agent/src/session-log-writer.test.ts
+++ b/products/desktop/packages/agent/src/session-log-writer.test.ts
@@ -57,6 +57,7 @@ describe("SessionLogWriter", () => {
jsonrpc: "2.0",
method: "session/new",
params: {
+ output: "sk-ant-oat01-fake-test-token",
mcpServers: [
{
name: "posthog",
@@ -73,7 +74,11 @@ describe("SessionLogWriter", () => {
const entries: StoredNotification[] = mockAppendLog.mock.calls[0][2];
expect(JSON.stringify(entries)).not.toContain("protocol-secret");
+ expect(JSON.stringify(entries)).not.toContain(
+ "sk-ant-oat01-fake-test-token",
+ );
expect(entries[0].notification.params).toEqual({
+ output: "[REDACTED]",
mcpServers: [
{
name: "posthog",
@@ -208,40 +213,46 @@ describe("SessionLogWriter", () => {
});
describe("agent_message_chunk coalescing", () => {
- it("coalesces consecutive chunks into a single agent_message", async () => {
- const sessionId = "s1";
- logWriter.register(sessionId, { taskId: "t1", runId: sessionId });
+ it.each([
+ ["Hello ", "world", "Hello world"],
+ ["Token: sk-ant-", "oat01-fake-test-token", "Token: [REDACTED]"],
+ ])(
+ "coalesces and redacts message chunks",
+ async (first, second, expected) => {
+ const sessionId = "s1";
+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });
- logWriter.appendRawLine(
- sessionId,
- makeSessionUpdate("agent_message_chunk", {
- content: { type: "text", text: "Hello " },
- }),
- );
- logWriter.appendRawLine(
- sessionId,
- makeSessionUpdate("agent_message_chunk", {
- content: { type: "text", text: "world" },
- }),
- );
- // Non-chunk event triggers flush of chunks
- logWriter.appendRawLine(
- sessionId,
- makeSessionUpdate("tool_call", { toolCallId: "tc1" }),
- );
+ logWriter.appendRawLine(
+ sessionId,
+ makeSessionUpdate("agent_message_chunk", {
+ content: { type: "text", text: first },
+ }),
+ );
+ logWriter.appendRawLine(
+ sessionId,
+ makeSessionUpdate("agent_message_chunk", {
+ content: { type: "text", text: second },
+ }),
+ );
+ // Non-chunk event triggers flush of chunks
+ logWriter.appendRawLine(
+ sessionId,
+ makeSessionUpdate("tool_call", { toolCallId: "tc1" }),
+ );
- await logWriter.flush(sessionId);
+ await logWriter.flush(sessionId);
- const entries: StoredNotification[] = mockAppendLog.mock.calls[0][2];
- expect(entries).toHaveLength(2); // coalesced message + tool_call
+ const entries: StoredNotification[] = mockAppendLog.mock.calls[0][2];
+ expect(entries).toHaveLength(2); // coalesced message + tool_call
- const coalesced = entries[0].notification;
- expect(coalesced.params?.update).toEqual({
- sessionUpdate: "agent_message",
- content: { type: "text", text: "Hello world" },
- });
- expect(logWriter.getLastAgentMessage(sessionId)).toBe("Hello world");
- });
+ const coalesced = entries[0].notification;
+ expect(coalesced.params?.update).toEqual({
+ sessionUpdate: "agent_message",
+ content: { type: "text", text: expected },
+ });
+ expect(logWriter.getLastAgentMessage(sessionId)).toBe(expected);
+ },
+ );
it("stamps the coalesced entry with the covered chunk id range", async () => {
const sessionId = "s1";
@@ -952,6 +963,25 @@ describe("SessionLogWriter — local-cache tool_call_update coalescing", () => {
expect(sessionUpdateOf(log[1]).sessionUpdate).toBe("agent_message");
});
+ it("redacts buffered updates before writing the local cache", async () => {
+ writer.appendRawLine(
+ RUN,
+ update({ rawInput: { token: "sk-ant-oat01-fake-test-token" } }),
+ );
+ writer.appendRawLine(
+ RUN,
+ update({
+ status: "completed",
+ rawOutput: [{ name: "Authorization", value: "fake-bearer" }],
+ }),
+ );
+ const log = await readLog();
+ expect(sessionUpdateOf(log[0])).toMatchObject({
+ rawInput: { token: "[REDACTED]" },
+ rawOutput: [{ name: "Authorization", value: "[REDACTED]" }],
+ });
+ });
+
it("a terminal update merges into buffered snapshots, later fields winning", async () => {
writer.appendRawLine(RUN, update({ content: "a1" }));
writer.appendRawLine(RUN, update({ content: "a2" }));
diff --git a/products/desktop/packages/agent/src/session-log-writer.ts b/products/desktop/packages/agent/src/session-log-writer.ts
index df9fae3c29c8..a5583332dde7 100644
--- a/products/desktop/packages/agent/src/session-log-writer.ts
+++ b/products/desktop/packages/agent/src/session-log-writer.ts
@@ -6,6 +6,7 @@ import type { PostHogAPIClient } from "./posthog-api";
import type { StoredNotification } from "./types";
import { isEmptyContentBlock } from "./utils/acp-content";
import { Logger } from "./utils/logger";
+import { redactClaudeTokens } from "./utils/redact-claude-tokens";
/**
* Session context for a registered session.
@@ -80,7 +81,7 @@ function redactAuthorizationHeaders(value: unknown): unknown {
return value.map(redactAuthorizationHeaders);
}
if (value === null || typeof value !== "object") {
- return value;
+ return redactClaudeTokens(value);
}
const record = value as Record<string, unknown>;
@@ -268,6 +269,7 @@ export class SessionLogWriter {
this.emitCoalescedMessage(sessionId, session);
}
+ message = redactAuthorizationHeaders(message) as Record<string, unknown>;
const nonChunkAgentText = this.extractAgentMessageText(message);
if (nonChunkAgentText) {
session.lastAgentMessage = nonChunkAgentText;
@@ -282,9 +284,7 @@ export class SessionLogWriter {
...(supersededChunks?.firstEventId
? { first_event_id: supersededChunks.firstEventId }
: {}),
- notification: redactAuthorizationHeaders(
- message,
- ) as StoredNotification["notification"],
+ notification: message as StoredNotification["notification"],
};
this.emitToSinks(sessionId, entry);
@@ -592,8 +592,8 @@ export class SessionLogWriter {
private emitCoalescedMessage(sessionId: string, session: SessionState): void {
if (!session.chunkBuffer) return;
- const { text, firstTimestamp, firstEventId, lastEventId } =
- session.chunkBuffer;
+ const { firstTimestamp, firstEventId, lastEventId } = session.chunkBuffer;
+ const text = redactClaudeTokens(session.chunkBuffer.text);
session.chunkBuffer = undefined;
session.lastAgentMessage = text;
session.currentTurnMessages.push(text);
diff --git a/products/desktop/packages/agent/src/utils/logger.ts b/products/desktop/packages/agent/src/utils/logger.ts
index d9d3ae803c08..1c5677813ad0 100644
--- a/products/desktop/packages/agent/src/utils/logger.ts
+++ b/products/desktop/packages/agent/src/utils/logger.ts
@@ -1,4 +1,5 @@
import type { LogLevel as LogLevelType, OnLogCallback } from "../types";
+import { redactClaudeTokens } from "./redact-claude-tokens";
export interface LoggerConfig {
debug?: boolean;
@@ -36,6 +37,8 @@ export class Logger {
}
private emitLog(level: LogLevelType, message: string, data?: unknown) {
+ message = redactClaudeTokens(message) as string;
+ data = redactClaudeTokens(data);
if (this.onLog) {
this.onLog(level, this.scope, message, data);
return;
diff --git a/products/desktop/packages/agent/src/utils/redact-claude-tokens.test.ts b/products/desktop/packages/agent/src/utils/redact-claude-tokens.test.ts
new file mode 100644
index 000000000000..fc8fc1b64138
--- /dev/null
+++ b/products/desktop/packages/agent/src/utils/redact-claude-tokens.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { ClaudeTokenEventRedactor } from "./redact-claude-tokens";
+
+describe("ClaudeTokenEventRedactor", () => {
+ it.each(["agent_message_chunk", "agent_thought_chunk"])(
+ "protects tokens at every split in %s and preserves other text",
+ (sessionUpdate) => {
+ const token = "sk-ant-oat01-fake-test-token";
+ for (const text of [
+ `Token: ${token}. Next.`,
+ `${token} ${token}`,
+ "Plain text with s, sk-ant-, and sk-ant-oat01.",
+ ]) {
+ for (let split = 1; split < text.length; split++) {
+ const redactor = new ClaudeTokenEventRedactor();
+ const events = [text.slice(0, split), text.slice(split)].flatMap(
+ (part) =>
+ redactor.redact({
+ type: "notification",
+ notification: {
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate,
+ content: { type: "text", text: part },
+ },
+ },
+ },
+ }),
+ );
+ events.push(...redactor.redact({ type: "done" }));
+ const result = events
+ .map((event) => {
+ const notification = event.notification as
+ | { params: { update: { content: { text: string } } } }
+ | undefined;
+ return notification?.params.update.content.text ?? "";
+ })
+ .join("");
+ expect(result).toBe(text.replaceAll(token, "[REDACTED]"));
+ expect(JSON.stringify(events)).not.toContain("fake-test-token");
+ }
+ }
+ },
+ );
+});
diff --git a/products/desktop/packages/agent/src/utils/redact-claude-tokens.ts b/products/desktop/packages/agent/src/utils/redact-claude-tokens.ts
new file mode 100644
index 000000000000..81ba92956afe
--- /dev/null
+++ b/products/desktop/packages/agent/src/utils/redact-claude-tokens.ts
@@ -0,0 +1,123 @@
+export function redactClaudeTokens(value: string): string;
+export function redactClaudeTokens(
+ value: string | undefined,
+): string | undefined;
+export function redactClaudeTokens(value: unknown): unknown;
+export function redactClaudeTokens(value: unknown): unknown {
+ if (typeof value === "string")
+ return value.replace(/sk-ant-oat01-[A-Za-z0-9_-]+/g, "[REDACTED]");
+ if (Array.isArray(value)) return value.map(redactClaudeTokens);
+ if (value instanceof Error)
+ return {
+ name: value.name,
+ message: redactClaudeTokens(value.message),
+ stack: redactClaudeTokens(value.stack),
+ };
+ if (value instanceof Date) return value;
+ if (value !== null && typeof value === "object") {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, nested]) => [
+ key,
+ redactClaudeTokens(nested),
+ ]),
+ );
+ }
+ return value;
+}
+
+type TextEvent = Record<string, unknown> & {
+ notification: {
+ method: "session/update";
+ params: {
+ update: {
+ sessionUpdate: string;
+ content: { type: "text"; text: string };
+ };
+ };
+ };
+};
+
+function isTextChunk(event: Record<string, unknown>): event is TextEvent {
+ const notification = event.notification as
+ | TextEvent["notification"]
+ | undefined;
+ const update = notification?.params?.update;
+ return (
+ notification?.method === "session/update" &&
+ (update?.sessionUpdate === "agent_message_chunk" ||
+ update?.sessionUpdate === "agent_thought_chunk") &&
+ update.content?.type === "text" &&
+ typeof update.content.text === "string"
+ );
+}
+
+function withText(event: TextEvent, text: string): TextEvent {
+ return {
+ ...event,
+ notification: {
+ ...event.notification,
+ params: {
+ ...event.notification.params,
+ update: {
+ ...event.notification.params.update,
+ content: { ...event.notification.params.update.content, text },
+ },
+ },
+ },
+ };
+}
+
+export class ClaudeTokenEventRedactor {
+ private pending: TextEvent | null = null;
+ private redacting = false;
+ private chunkKind: string | null = null;
+
+ redact(event: Record<string, unknown>): Record<string, unknown>[] {
+ const events: Record<string, unknown>[] = [];
+ const chunk = isTextChunk(event);
+ const kind = chunk ? event.notification.params.update.sessionUpdate : null;
+ if (!chunk || kind !== this.chunkKind) {
+ if (this.pending) events.push(this.pending);
+ this.pending = null;
+ this.redacting = false;
+ }
+ this.chunkKind = kind;
+ if (!chunk) {
+ events.push(redactClaudeTokens(event) as Record<string, unknown>);
+ return events;
+ }
+ const previous = this.pending;
+ let text =
+ (previous?.notification.params.update.content.text ?? "") +
+ event.notification.params.update.content.text;
+ this.pending = null;
+ if (this.redacting) {
+ text = text.replace(/^[A-Za-z0-9_-]+/, "");
+ if (text.length > 0) this.redacting = false;
+ }
+ const prefix = "sk-ant-oat01-";
+ text = text.replace(
+ /sk-ant-oat01-[A-Za-z0-9_-]*/g,
+ (match, offset: number, source: string) => {
+ this.redacting = offset + match.length === source.length;
+ return "[REDACTED]";
+ },
+ );
+ const redacted = redactClaudeTokens(withText(event, text)) as TextEvent;
+ if (!this.redacting) {
+ for (let length = prefix.length - 1; length > 0; length--) {
+ if (text.endsWith(prefix.slice(0, length))) {
+ if (previous) {
+ events.push(withText(previous, text.slice(0, -length)));
+ this.pending = withText(redacted, text.slice(-length));
+ } else {
+ this.pending = redacted;
+ }
+ return events;
+ }
+ }
+ }
+ events.push(redacted);
+ return events;
+ }
+}
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index 267a084f486b..139273528ec8 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -987,38 +987,46 @@ describe("PostHogAPIClient", () => {
);
});
- it("omits the permission mode when no adapter is set", async () => {
- const client = new PostHogAPIClient(
- "http://localhost:8000",
- async () => "token",
- async () => "token",
- 123,
- );
+ it.each([false, true])(
+ "omits the permission mode when no adapter is set (Pi: %s)",
+ async (piRuntime) => {
+ const client = new PostHogAPIClient(
+ "http://localhost:8000",
+ async () => "token",
+ async () => "token",
+ 123,
+ );
- const post = vi.fn().mockResolvedValue({
- id: "task-123",
- title: "Task",
- description: "Task",
- created_at: "2026-04-14T00:00:00Z",
- updated_at: "2026-04-14T00:00:00Z",
- origin_product: "user_created",
- });
+ const post = vi.fn().mockResolvedValue({
+ id: "task-123",
+ title: "Task",
+ description: "Task",
+ created_at: "2026-04-14T00:00:00Z",
+ updated_at: "2026-04-14T00:00:00Z",
+ origin_product: "user_created",
+ });
- (client as unknown as { api: { post: typeof post } }).api = { post };
+ (client as unknown as { api: { post: typeof post } }).api = { post };
- await client.runTaskInCloud("task-123", "feature/no-adapter", {
- initialPermissionMode: "plan",
- });
+ await client.runTaskInCloud("task-123", "feature/no-adapter", {
+ initialPermissionMode: "plan",
+ piRuntime,
+ claudeModelAccess: "own-subscription",
+ });
- expect(post).toHaveBeenCalledWith(
- "/api/projects/{project_id}/tasks/{id}/run/",
- expect.objectContaining({
- body: expect.not.objectContaining({
- initial_permission_mode: expect.anything(),
+ expect(post).toHaveBeenCalledWith(
+ "/api/projects/{project_id}/tasks/{id}/run/",
+ expect.objectContaining({
+ body: expect.not.objectContaining({
+ initial_permission_mode: expect.anything(),
+ }),
}),
- }),
- );
- });
+ );
+ expect(post.mock.calls[0][1].body.claude_model_access).toBe(
+ piRuntime ? undefined : "own-subscription",
+ );
+ },
+ );
it.each([true, false])("forwards auto publish %s", async (autoPublish) => {
const client = new PostHogAPIClient(
@@ -1288,35 +1296,43 @@ describe("PostHogAPIClient", () => {
});
});
- it("omits the permission mode from created task runs without an adapter", async () => {
- const fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ id: "run-123", environment: "cloud" }),
- });
- const client = new PostHogAPIClient(
- "http://localhost:8000",
- async () => "token",
- async () => "token",
- 123,
- );
+ it.each([false, true])(
+ "omits the permission mode from created task runs without an adapter (Pi: %s)",
+ async (piRuntime) => {
+ const fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ id: "run-123", environment: "cloud" }),
+ });
+ const client = new PostHogAPIClient(
+ "http://localhost:8000",
+ async () => "token",
+ async () => "token",
+ 123,
+ );
- (
- client as unknown as {
- api: { baseUrl: string; fetcher: { fetch: typeof fetch } };
- }
- ).api = {
- baseUrl: "http://localhost:8000",
- fetcher: { fetch },
- };
+ (
+ client as unknown as {
+ api: { baseUrl: string; fetcher: { fetch: typeof fetch } };
+ }
+ ).api = {
+ baseUrl: "http://localhost:8000",
+ fetcher: { fetch },
+ };
- await client.createTaskRun("task-123", {
- environment: "cloud",
- initialPermissionMode: "plan",
- });
+ await client.createTaskRun("task-123", {
+ environment: "cloud",
+ initialPermissionMode: "plan",
+ piRuntime,
+ claudeModelAccess: "own-subscription",
+ });
- const body = JSON.parse(fetch.mock.calls[0][0].overrides.body as string);
- expect(body).not.toHaveProperty("initial_permission_mode");
- });
+ const body = JSON.parse(fetch.mock.calls[0][0].overrides.body as string);
+ expect(body).not.toHaveProperty("initial_permission_mode");
+ expect(body.claude_model_access).toBe(
+ piRuntime ? undefined : "own-subscription",
+ );
+ },
+ );
it("omits the permission mode when none is selected", async () => {
const client = new PostHogAPIClient(
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 49661b1337bc..3c7f35dbc328 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -5,6 +5,7 @@ import type {
CloudRunSource,
ExecutionMode,
McpServerConnection,
+ ModelAccess,
PrAuthorshipMode,
SourceProduct,
SourceType,
@@ -1080,6 +1081,7 @@ export interface CloudRunOptions {
autoPublish?: boolean;
/** Only false is sent: opts the run out of rtk command-output compression. */
rtkEnabled?: boolean;
+ claudeModelAccess?: ModelAccess;
runSource?: CloudRunSource;
signalReportId?: string;
initialPermissionMode?: ExecutionMode;
@@ -1230,6 +1232,9 @@ function buildCloudRunRequestBody(
if (options?.rtkEnabled === false) {
body.rtk_enabled = false;
}
+ if (!options?.piRuntime && options?.claudeModelAccess) {
+ body.claude_model_access = options.claudeModelAccess;
+ }
if (options?.runSource) {
body.run_source = options.runSource;
}
@@ -4064,6 +4069,7 @@ export class PostHogAPIClient {
taskId: string,
runId: string,
reason?: string,
+ onlyIfAwaitingFirstMessage = false,
): Promise<{ status?: string }> {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/cancel/`;
@@ -4072,7 +4078,12 @@ export class PostHogAPIClient {
url: new URL(`${this.api.baseUrl}${path}`),
path,
overrides: {
- body: JSON.stringify(reason ? { reason } : {}),
+ body: JSON.stringify({
+ ...(reason ? { reason } : {}),
+ ...(onlyIfAwaitingFirstMessage
+ ? { only_if_awaiting_first_message: true }
+ : {}),
+ }),
},
});
return (await response.json().catch(() => ({}))) as { status?: string };
diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.ts
index 7e2e02de5160..83ee9670d541 100644
--- a/products/desktop/packages/core/src/auth/auth.ts
+++ b/products/desktop/packages/core/src/auth/auth.ts
@@ -15,6 +15,7 @@ import {
withTimeout,
} from "@posthog/shared";
import { inject, injectable, postConstruct, preDestroy } from "inversify";
+import { z } from "zod";
import {
AUTH_CONNECTIVITY,
AUTH_OAUTH_FLOW_SERVICE,
@@ -143,6 +144,32 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
getState(): AuthState {
return { ...this.state };
}
+ async getAccountKey(): Promise<string | null> {
+ const generation = this.sessionGeneration;
+ const { apiHost } = await this.getValidAccessToken();
+ if (generation !== this.sessionGeneration) return null;
+ const session = this.session;
+ if (session?.accountKey && !this.tokenOverride) {
+ return JSON.stringify([apiHost, session.accountKey]);
+ }
+ const response = await this.authenticatedFetch(
+ fetch,
+ `${apiHost}/api/users/@me/`,
+ {
+ redirect: "error",
+ signal: AbortSignal.timeout(10_000),
+ },
+ );
+ if ([408, 429, 500, 502, 503, 504].includes(response.status)) {
+ throw new Error("Cannot check your account. Try again.");
+ }
+ if (!response.ok) return null;
+ const user = z
+ .object({ uuid: z.string() })
+ .safeParse(await response.json());
+ if (generation !== this.sessionGeneration) return null;
+ return user.success ? JSON.stringify([apiHost, user.data.uuid]) : null;
+ }
async login(region: CloudRegion): Promise<AuthState> {
this.sessionGeneration += 1;
const sessionGeneration = this.sessionGeneration;
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
index 69b5e17eb903..e65fc5b86f63 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
@@ -11,10 +11,16 @@ import {
TypedEventEmitter,
} from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
-import type { ICloudTaskAuth, McpRelayExecutor } from "./identifiers";
+import { z } from "zod";
+import type {
+ ClaudeSubscriptionTokenStore,
+ ICloudTaskAuth,
+ McpRelayExecutor,
+} from "./identifiers";
import {
CloudTaskEvent,
type CloudTaskEvents,
+ type DesignateClaudeSubscriptionInput,
type SendCommandInput,
type SendCommandOutput,
type StopInput,
@@ -242,6 +248,26 @@ function isMcpRequestEvent(data: unknown): data is McpRequestEventData {
);
}
+interface CredentialRequestEventData {
+ type: "credential_request";
+ requestId: string;
+ credential: "claude_subscription_token";
+ expiresAt: string;
+}
+
+function isCredentialRequestEvent(
+ data: unknown,
+): data is CredentialRequestEventData {
+ if (typeof data !== "object" || data === null) return false;
+ const candidate = data as Partial<CredentialRequestEventData>;
+ return (
+ candidate.type === "credential_request" &&
+ typeof candidate.requestId === "string" &&
+ typeof candidate.expiresAt === "string" &&
+ candidate.credential === "claude_subscription_token"
+ );
+}
+
/** Prefix marking a desktop-issued relay approval prompt, so `sendCommand` can
* resolve its response locally instead of POSTing it to the sandbox. */
const RELAY_APPROVAL_REQUEST_PREFIX = "relay-approval:";
@@ -442,6 +468,7 @@ export interface CloudTaskEngineDependencies {
analytics: IAnalytics;
logger: RootLogger;
mcpRelayExecutor?: McpRelayExecutor | null;
+ claudeSubscriptionTokenStore?: ClaudeSubscriptionTokenStore | null;
streamFetch?: CloudTaskFetch;
/**
* Cap on the entries a snapshot carries, for hosts that page older history
@@ -469,6 +496,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
private readonly auth: ICloudTaskAuth;
private readonly analytics: IAnalytics;
private readonly mcpRelayExecutor: McpRelayExecutor | null;
+ private readonly claudeSubscriptionTokenStore: ClaudeSubscriptionTokenStore | null;
private readonly streamFetch: CloudTaskFetch;
private readonly transcriptTailWindow: number | undefined;
@@ -477,6 +505,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
analytics,
logger,
mcpRelayExecutor = null,
+ claudeSubscriptionTokenStore = null,
streamFetch = globalThis.fetch.bind(globalThis),
transcriptTailWindow,
}: CloudTaskEngineDependencies) {
@@ -484,6 +513,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
this.auth = auth;
this.analytics = analytics;
this.mcpRelayExecutor = mcpRelayExecutor;
+ this.claudeSubscriptionTokenStore = claudeSubscriptionTokenStore;
this.streamFetch = streamFetch;
this.transcriptTailWindow = transcriptTailWindow;
this.log = logger.scope("cloud-task");
@@ -496,6 +526,8 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
* runs or names are dropped.
*/
private readonly relayDesignations = new Map<string, Set<string>>();
+ private readonly claudeSubscriptionRuns = new Map<string, string>();
+ private readonly credentialRequestsInFlight = new Set<string>();
/** requestId dedupe — the event stream is at-least-once and replays on reconnect. */
private readonly handledRelayRequestIds = new Set<string>();
private readonly handledRelayRequestOrder: string[] = [];
@@ -523,6 +555,76 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
});
}
+ private credentialRunKey(
+ input: Pick<WatchInput, "apiHost" | "teamId" | "taskId" | "runId">,
+ ): string {
+ return JSON.stringify([
+ input.apiHost.replace(/\/$/, ""),
+ input.teamId,
+ input.taskId,
+ input.runId,
+ ]);
+ }
+
+ async designateClaudeSubscription(
+ input: DesignateClaudeSubscriptionInput,
+ ): Promise<void> {
+ if (!this.claudeSubscriptionTokenStore) return;
+ const context = await this.auth.getCloudContext({ includeAccount: true });
+ if (!context?.accountKey)
+ throw new Error("Sign in before using your Claude plan.");
+ const base = new URL(context.apiHost);
+ if (
+ base.protocol !== "https:" &&
+ !(
+ base.protocol === "http:" &&
+ ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)
+ )
+ ) {
+ throw new Error("Claude tokens require a secure connection.");
+ }
+ const [userResponse, runResponse] = await Promise.all([
+ this.auth.authenticatedFetch(`${base.origin}/api/users/@me/`, {
+ redirect: "error",
+ signal: AbortSignal.timeout(10_000),
+ }),
+ this.auth.authenticatedFetch(
+ `${base.origin}/api/projects/${context.teamId}/tasks/${encodeURIComponent(input.taskId)}/runs/${encodeURIComponent(input.runId)}/`,
+ { redirect: "error", signal: AbortSignal.timeout(10_000) },
+ ),
+ ]);
+ if (!userResponse.ok || !runResponse.ok)
+ throw new Error("Cannot check the Claude run owner. Try again.");
+ const user = z
+ .object({ id: z.number() })
+ .safeParse(await userResponse.json());
+ const run = z
+ .object({
+ state: z.object({
+ claude_subscription_user_id: z.number(),
+ claude_model_access: z.literal("own-subscription"),
+ }),
+ })
+ .safeParse(await runResponse.json());
+ if (
+ !user.success ||
+ !run.success ||
+ run.data.state.claude_subscription_user_id !== user.data.id
+ ) {
+ throw new Error(
+ "Only the user who started this run can send a Claude token.",
+ );
+ }
+ this.claudeSubscriptionRuns.set(
+ this.credentialRunKey({ ...input, ...context }),
+ context.accountKey,
+ );
+ if (this.claudeSubscriptionRuns.size > MAX_HANDLED_RELAY_REQUEST_IDS) {
+ const oldest = this.claudeSubscriptionRuns.keys().next().value;
+ if (oldest !== undefined) this.claudeSubscriptionRuns.delete(oldest);
+ }
+ }
+
private markRelayRequestHandled(requestId: string): void {
this.handledRelayRequestIds.add(requestId);
this.handledRelayRequestOrder.push(requestId);
@@ -607,6 +709,146 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
await this.sendRelayResponse(watcher, data, execution);
}
+ private async handleCredentialRequest(
+ watcher: WatcherState,
+ data: CredentialRequestEventData,
+ ): Promise<void> {
+ if (!this.claudeSubscriptionTokenStore) return;
+ const runKey = this.credentialRunKey(watcher);
+ const requestKey = `${runKey}:${data.requestId}`;
+ if (
+ this.handledRelayRequestIds.has(requestKey) ||
+ this.credentialRequestsInFlight.has(requestKey)
+ )
+ return;
+ const expiresAt = Date.parse(data.expiresAt);
+ if (!Number.isFinite(expiresAt)) return;
+ const finish = (
+ outcome: "sent" | "no_token" | "expired" | "rejected",
+ ): void => {
+ this.markRelayRequestHandled(requestKey);
+ this.analytics.track(ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY, {
+ credential: data.credential,
+ outcome,
+ });
+ if (outcome === "expired" || outcome === "rejected") {
+ this.log.warn("Claude token delivery failed", { outcome });
+ }
+ };
+ if (expiresAt <= Date.now()) {
+ finish("expired");
+ return;
+ }
+ const deadline = Math.min(expiresAt, Date.now() + 120_000);
+ this.credentialRequestsInFlight.add(requestKey);
+ try {
+ while (
+ Date.now() < deadline &&
+ this.watchers.get(watcherKey(watcher.taskId, watcher.runId)) === watcher
+ ) {
+ const result = await this.deliverCredentialResponse(
+ watcher,
+ data,
+ deadline,
+ );
+ if (result !== "retry") {
+ finish(result);
+ return;
+ }
+ const delay = Math.min(1_000, deadline - Date.now());
+ if (delay > 0)
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ if (Date.now() >= deadline) finish("expired");
+ } finally {
+ this.credentialRequestsInFlight.delete(requestKey);
+ }
+ }
+
+ private async deliverCredentialResponse(
+ watcher: WatcherState,
+ data: CredentialRequestEventData,
+ deadline: number,
+ ): Promise<"sent" | "no_token" | "rejected" | "retry"> {
+ try {
+ if (!this.claudeSubscriptionRuns.has(this.credentialRunKey(watcher))) {
+ const context = await this.auth.getCloudContext();
+ if (
+ !context ||
+ this.credentialRunKey({ ...watcher, ...context }) !==
+ this.credentialRunKey(watcher)
+ ) {
+ return "rejected";
+ }
+ await this.designateClaudeSubscription(watcher);
+ }
+ const destination = await this.credentialDestination(watcher);
+ if (!destination) return "rejected";
+ const token =
+ (await this.claudeSubscriptionTokenStore?.get(
+ this.claudeSubscriptionRuns.get(this.credentialRunKey(watcher)),
+ )) ?? null;
+ const response = await this.auth.authenticatedFetch(destination, {
+ method: "POST",
+ redirect: "error",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: data.requestId,
+ method: "credential_response",
+ params: {
+ requestId: data.requestId,
+ credential: data.credential,
+ ...(token ? { token } : { error: "no_token" }),
+ },
+ }),
+ signal: AbortSignal.timeout(
+ Math.max(1, Math.min(10_000, deadline - Date.now())),
+ ),
+ });
+ if (!response.ok) {
+ return [408, 429, 500, 502, 503, 504].includes(response.status)
+ ? "retry"
+ : "rejected";
+ }
+ const body: unknown = await response.json();
+ return typeof body === "object" &&
+ body !== null &&
+ "result" in body &&
+ !("error" in body)
+ ? token
+ ? "sent"
+ : "no_token"
+ : "rejected";
+ } catch {
+ return "retry";
+ }
+ }
+
+ private async credentialDestination(
+ watcher: WatcherState,
+ ): Promise<string | null> {
+ const context = await this.auth.getCloudContext({ includeAccount: true });
+ if (
+ !context ||
+ context.accountKey !==
+ this.claudeSubscriptionRuns.get(this.credentialRunKey(watcher)) ||
+ this.credentialRunKey({ ...watcher, ...context }) !==
+ this.credentialRunKey(watcher)
+ )
+ return null;
+ const base = new URL(context.apiHost);
+ if (
+ base.protocol !== "https:" &&
+ !(
+ base.protocol === "http:" &&
+ ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)
+ )
+ )
+ return null;
+ return `${base.origin}/api/projects/${context.teamId}/tasks/${encodeURIComponent(watcher.taskId)}/runs/${encodeURIComponent(watcher.runId)}/command/`;
+ }
+
private relayRequestExpired(expiresAt: number): boolean {
return Number.isFinite(expiresAt) && expiresAt < Date.now();
}
@@ -1032,6 +1274,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
}
unwatchAll(): void {
+ this.claudeSubscriptionRuns.clear();
for (const key of [...this.watchers.keys()]) {
this.stopWatcher(key);
}
@@ -1767,6 +2010,11 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
return null;
}
+ if (isCredentialRequestEvent(event.data)) {
+ void this.handleCredentialRequest(watcher, event.data);
+ return null;
+ }
+
if (isPermissionRequestEvent(event.data)) {
this.emit(CloudTaskEvent.Update, {
taskId: watcher.taskId,
@@ -2226,6 +2474,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// A terminal run gets no further relay requests; drop its designation and
// approval state so the maps don't grow for the lifetime of the app session.
if (isTerminalStatus(watcher.lastStatus)) {
+ this.claudeSubscriptionRuns.delete(this.credentialRunKey(watcher));
this.relayDesignations.delete(watcher.runId);
this.evictRelayApprovalState(watcher.runId);
}
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task-service.test.ts b/products/desktop/packages/core/src/cloud-task/cloud-task-service.test.ts
index 644f9dd7cb69..4b651e837f24 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task-service.test.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task-service.test.ts
@@ -3,7 +3,7 @@ import { CloudTaskService } from "./cloud-task";
import { CloudTaskEngine } from "./cloud-task-engine";
describe("CloudTaskService", () => {
- it("preserves the injectable service API as a thin engine wrapper", () => {
+ it("preserves the service API and ignores subscription designation without a token store", async () => {
const scopedLog = {
debug: vi.fn(),
info: vi.fn(),
@@ -23,5 +23,8 @@ describe("CloudTaskService", () => {
expect(service.watch).toBeTypeOf("function");
expect(service.retry).toBeTypeOf("function");
expect(service.unwatchAll).toBeTypeOf("function");
+ await expect(
+ service.designateClaudeSubscription({ taskId: "task-1", runId: "run-1" }),
+ ).resolves.toBeUndefined();
});
});
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts b/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts
index ffa8f5eb044e..135eb1576f87 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts
@@ -1,4 +1,4 @@
-import { TRANSCRIPT_TAIL_WINDOW } from "@posthog/shared";
+import { ANALYTICS_EVENTS, TRANSCRIPT_TAIL_WINDOW } from "@posthog/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CloudTaskEvent } from "./schemas";
@@ -4474,3 +4474,363 @@ describe("CloudTaskEngine MCP relay", () => {
});
});
});
+
+describe("CloudTaskEngine credential relay", () => {
+ let relayService: CloudTaskEngine;
+ let tokenStore: { get: ReturnType<typeof vi.fn> };
+ let analyticsMock: { track: ReturnType<typeof vi.fn> };
+ const commandResponse = vi.fn();
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mockAuthService.getCloudContext.mockResolvedValue({
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ accountKey: "account-a",
+ });
+ const scopedLog = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ const loggerMock = { ...scopedLog, scope: vi.fn(() => scopedLog) };
+ analyticsMock = { track: vi.fn() };
+ tokenStore = { get: vi.fn() };
+ relayService = createCloudTaskEngine({
+ auth: mockAuthService as never,
+ analytics: analyticsMock as never,
+ logger: loggerMock,
+ claudeSubscriptionTokenStore: tokenStore as never,
+ streamFetch: fetchRouter,
+ });
+
+ mockNetFetch.mockReset();
+ commandResponse.mockReset();
+ commandResponse.mockImplementation(() =>
+ createJsonResponse({ result: {} }),
+ );
+ mockNetFetch.mockImplementation((url: string) =>
+ Promise.resolve(
+ url.includes("/command/")
+ ? commandResponse()
+ : url.includes("/api/users/@me/")
+ ? createJsonResponse({ id: 1 })
+ : createJsonResponse({
+ id: "run-1",
+ status: "in_progress",
+ state: {
+ claude_model_access: "own-subscription",
+ claude_subscription_user_id: 1,
+ },
+ }),
+ ),
+ );
+ mockStreamFetch.mockReset();
+ mockStreamTokenFetch.mockReset();
+ mockStreamTokenFetch.mockImplementation(() =>
+ Promise.resolve(
+ createJsonResponse({ token: "test-token", stream_base_url: null }),
+ ),
+ );
+ mockAuthService.authenticatedFetch.mockReset();
+ vi.stubGlobal("fetch", fetchRouter);
+ mockAuthService.authenticatedFetch.mockImplementation(
+ async (input: string | Request, init?: RequestInit) => {
+ return fetchRouter(input, {
+ ...init,
+ headers: {
+ ...(init?.headers ?? {}),
+ Authorization: "Bearer token",
+ },
+ });
+ },
+ );
+ });
+
+ afterEach(() => {
+ relayService.unwatchAll();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ function credentialRequestSseLine(
+ overrides: Partial<{ requestId: string; expiresAt: string }> = {},
+ ): string {
+ const event = {
+ type: "credential_request",
+ requestId: overrides.requestId ?? "cred-req-1",
+ credential: "claude_subscription_token",
+ expiresAt:
+ overrides.expiresAt ?? new Date(Date.now() + 120_000).toISOString(),
+ };
+ return `data: ${JSON.stringify(event)}\n\n`;
+ }
+
+ async function watchRun(runId: string, designated = true): Promise<void> {
+ if (designated) {
+ await relayService.designateClaudeSubscription({
+ taskId: "task-1",
+ runId,
+ });
+ }
+ relayService.watch({
+ taskId: "task-1",
+ runId,
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ resumeFromEntryCount: 0,
+ });
+ }
+
+ function commandPosts(): Array<{ method: string; params: unknown }> {
+ return mockNetFetch.mock.calls
+ .filter(([url]) => (url as string).includes("/command/"))
+ .map(
+ ([, init]) =>
+ JSON.parse((init as RequestInit).body as string) as {
+ method: string;
+ params: unknown;
+ },
+ );
+ }
+
+ it.each([{ id: 2 }, { id: "1" }, {}, null])(
+ "rejects an invalid run owner: %j",
+ async (user) => {
+ mockNetFetch.mockResolvedValueOnce(createJsonResponse(user));
+ await expect(
+ relayService.designateClaudeSubscription({
+ taskId: "task-1",
+ runId: "run-1",
+ }),
+ ).rejects.toThrow("Only the user who started");
+ expect(tokenStore.get).not.toHaveBeenCalled();
+ },
+ );
+
+ it("retries a temporary auth failure before reading the token", async () => {
+ tokenStore.get.mockResolvedValue("sk-ant-oat01-fake-test-token");
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(credentialRequestSseLine()),
+ );
+ await watchRun("run-1");
+ mockAuthService.getCloudContext.mockRejectedValueOnce(
+ new Error("auth unavailable"),
+ );
+ await vi.advanceTimersByTimeAsync(0);
+ expect(tokenStore.get).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(commandPosts()).toHaveLength(1);
+ });
+
+ it.each([true, false])(
+ "answers a credential request after designation or restart: %s",
+ async (designated) => {
+ const token = "sk-ant-oat01-fake-test-token";
+ tokenStore.get.mockResolvedValue(token);
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(credentialRequestSseLine()),
+ );
+ await watchRun("run-1", designated);
+
+ await vi.advanceTimersByTimeAsync(0);
+ const post = commandPosts()[0];
+ expect(post.method).toBe("credential_response");
+ expect(post.params).toEqual({
+ requestId: "cred-req-1",
+ credential: "claude_subscription_token",
+ token,
+ });
+ expect(mockAuthService.authenticatedFetch).toHaveBeenCalledWith(
+ "https://app.example.com/api/projects/2/tasks/task-1/runs/run-1/command/",
+ expect.objectContaining({ redirect: "error" }),
+ );
+ expect(analyticsMock.track).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY,
+ { credential: "claude_subscription_token", outcome: "sent" },
+ );
+ },
+ );
+
+ it.each([
+ { apiHost: "https://example.org", teamId: 2 },
+ { apiHost: "https://app.example.com", teamId: 3 },
+ { apiHost: "https://app.example.com", teamId: 2, accountKey: "account-b" },
+ null,
+ ])(
+ "does not send a token after the account context changes to %s",
+ async (context) => {
+ tokenStore.get.mockResolvedValue("sk-ant-oat01-fake-test-token");
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(credentialRequestSseLine()),
+ );
+ await watchRun("run-1");
+ mockAuthService.getCloudContext.mockResolvedValue(context);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(commandPosts()).toHaveLength(0);
+ expect(tokenStore.get).not.toHaveBeenCalled();
+ },
+ );
+
+ it("ignores a duplicate request with the same requestId", async () => {
+ const token = "sk-ant-oat01-fake-test-token";
+ tokenStore.get.mockResolvedValue(token);
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(
+ credentialRequestSseLine() + credentialRequestSseLine(),
+ ),
+ );
+ await watchRun("run-1");
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(commandPosts()).toHaveLength(1);
+ });
+
+ it("reports no_token when the store has no token", async () => {
+ tokenStore.get.mockResolvedValue(null);
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(credentialRequestSseLine()),
+ );
+ await watchRun("run-1");
+
+ await vi.advanceTimersByTimeAsync(0);
+ const post = commandPosts()[0];
+ expect(post.method).toBe("credential_response");
+ expect(post.params).toEqual({
+ requestId: "cred-req-1",
+ credential: "claude_subscription_token",
+ error: "no_token",
+ });
+ expect(analyticsMock.track).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY,
+ { credential: "claude_subscription_token", outcome: "no_token" },
+ );
+ });
+
+ it.each(["expired", "malformed", "observer", "other-project"])(
+ "does not disclose a token for an %s request",
+ async (scenario) => {
+ tokenStore.get.mockResolvedValue("sk-ant-oat01-fake-test-token");
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(
+ credentialRequestSseLine({
+ expiresAt:
+ scenario === "expired"
+ ? new Date(Date.now() - 1_000).toISOString()
+ : scenario === "malformed"
+ ? "not-a-date"
+ : new Date(Date.now() + 120_000).toISOString(),
+ }),
+ ),
+ );
+ if (scenario === "other-project") {
+ mockAuthService.getCloudContext.mockResolvedValue({
+ apiHost: "https://app.example.com",
+ teamId: 3,
+ accountKey: "account-a",
+ });
+ await relayService.designateClaudeSubscription({
+ taskId: "task-1",
+ runId: "run-1",
+ });
+ }
+ if (scenario === "observer") {
+ mockNetFetch.mockImplementation((url: string) =>
+ Promise.resolve(
+ createJsonResponse(
+ url.includes("/api/users/@me/")
+ ? { id: 2 }
+ : {
+ id: "run-1",
+ status: "in_progress",
+ state: {
+ claude_model_access: "own-subscription",
+ claude_subscription_user_id: 1,
+ },
+ },
+ ),
+ ),
+ );
+ }
+ await watchRun(
+ "run-1",
+ scenario === "expired" || scenario === "malformed",
+ );
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(commandPosts()).toHaveLength(0);
+ expect(tokenStore.get).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([500, 503])(
+ "retries HTTP %s without reporting an early success",
+ async (status) => {
+ tokenStore.get.mockResolvedValue("sk-ant-oat01-fake-test-token");
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(credentialRequestSseLine()),
+ );
+ commandResponse.mockReturnValueOnce(
+ new Response("unavailable", { status }),
+ );
+ await watchRun("run-1");
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(commandPosts()).toHaveLength(1);
+ expect(analyticsMock.track).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(commandPosts()).toHaveLength(2);
+ expect(analyticsMock.track).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY,
+ {
+ credential: "claude_subscription_token",
+ outcome: "sent",
+ },
+ );
+ },
+ );
+
+ it("stops retries at the credential deadline", async () => {
+ tokenStore.get.mockResolvedValue("sk-ant-oat01-fake-test-token");
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(
+ credentialRequestSseLine({
+ expiresAt: new Date(Date.now() + 1_500).toISOString(),
+ }),
+ ),
+ );
+ commandResponse.mockImplementation(
+ () => new Response("unavailable", { status: 503 }),
+ );
+ await watchRun("run-1");
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(commandPosts()).toHaveLength(2);
+ expect(analyticsMock.track).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY,
+ { credential: "claude_subscription_token", outcome: "expired" },
+ );
+ });
+
+ it("handles secure-store errors without exposing their contents", async () => {
+ tokenStore.get.mockRejectedValueOnce(new Error("secret-store-value"));
+ tokenStore.get.mockResolvedValue("sk-ant-oat01-fake-test-token");
+ mockStreamFetch.mockResolvedValueOnce(
+ createOpenSseResponse(credentialRequestSseLine()),
+ );
+ await watchRun("run-1");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(commandPosts()).toEqual([]);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(commandPosts()).toMatchObject([
+ {
+ method: "credential_response",
+ params: {
+ requestId: "cred-req-1",
+ credential: "claude_subscription_token",
+ token: "sk-ant-oat01-fake-test-token",
+ },
+ },
+ ]);
+ });
+});
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task.ts b/products/desktop/packages/core/src/cloud-task/cloud-task.ts
index b1ced3f888d1..4bd308e7ab69 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task.ts
@@ -7,7 +7,9 @@ import { TRANSCRIPT_TAIL_WINDOW } from "@posthog/shared";
import { inject, injectable, optional, preDestroy } from "inversify";
import { CloudTaskEngine } from "./cloud-task-engine";
import {
+ CLAUDE_SUBSCRIPTION_TOKEN_STORE,
CLOUD_TASK_AUTH,
+ type ClaudeSubscriptionTokenStore,
type ICloudTaskAuth,
MCP_RELAY_EXECUTOR,
type McpRelayExecutor,
@@ -25,6 +27,9 @@ export class CloudTaskService extends CloudTaskEngine {
@inject(MCP_RELAY_EXECUTOR)
@optional()
mcpRelayExecutor: McpRelayExecutor | null = null,
+ @inject(CLAUDE_SUBSCRIPTION_TOKEN_STORE)
+ @optional()
+ claudeSubscriptionTokenStore: ClaudeSubscriptionTokenStore | null = null,
) {
// The desktop renderer pages older history in from `windowStart`.
super({
@@ -32,6 +37,7 @@ export class CloudTaskService extends CloudTaskEngine {
analytics,
logger,
mcpRelayExecutor,
+ claudeSubscriptionTokenStore,
transcriptTailWindow: TRANSCRIPT_TAIL_WINDOW,
});
}
diff --git a/products/desktop/packages/core/src/cloud-task/identifiers.ts b/products/desktop/packages/core/src/cloud-task/identifiers.ts
index 04e17f1996be..2b48566d4622 100644
--- a/products/desktop/packages/core/src/cloud-task/identifiers.ts
+++ b/products/desktop/packages/core/src/cloud-task/identifiers.ts
@@ -3,9 +3,25 @@ export const CLOUD_TASK_AUTH = Symbol.for("posthog.core.cloudTaskAuth");
export interface ICloudTaskAuth {
authenticatedFetch(url: string, init?: RequestInit): Promise<Response>;
- getCloudContext(): Promise<{ apiHost: string; teamId: number } | null>;
+ getCloudContext(options?: { includeAccount?: boolean }): Promise<{
+ apiHost: string;
+ teamId: number;
+ accountKey?: string | null;
+ } | null>;
}
+export interface ClaudeSubscriptionTokenStore {
+ get(expectedAccountKey?: string): Promise<string | null>;
+ save(token: string): Promise<void>;
+ clear(): Promise<void>;
+ clearAll(): Promise<void>;
+ has(): Promise<boolean>;
+}
+
+export const CLAUDE_SUBSCRIPTION_TOKEN_STORE = Symbol.for(
+ "posthog.cloud-task.claudeSubscriptionTokenStore",
+);
+
/**
* Host-bound executor for MCP relay requests (docs/CLOUD-MCP-RELAY.md).
* Desktop binds this to the workspace-server relay service; hosts without a
diff --git a/products/desktop/packages/core/src/cloud-task/schemas.ts b/products/desktop/packages/core/src/cloud-task/schemas.ts
index ae79c62437c2..7ad212d48909 100644
--- a/products/desktop/packages/core/src/cloud-task/schemas.ts
+++ b/products/desktop/packages/core/src/cloud-task/schemas.ts
@@ -40,6 +40,14 @@ export const watchInput = z.object({
export type WatchInput = z.infer<typeof watchInput>;
+export const designateClaudeSubscriptionInput = watchInput.pick({
+ taskId: true,
+ runId: true,
+});
+export type DesignateClaudeSubscriptionInput = z.infer<
+ typeof designateClaudeSubscriptionInput
+>;
+
export const unwatchInput = z.object({
taskId: z.string(),
runId: z.string(),
@@ -68,6 +76,7 @@ export const sendCommandInput = z.object({
"permission_response",
"set_config_option",
"mcp_response",
+ "credential_response",
"pi/rpc",
"queue_get",
"queue_clear",
diff --git a/products/desktop/packages/core/src/sessions/acpNotifications.ts b/products/desktop/packages/core/src/sessions/acpNotifications.ts
index f713ede6997b..4a9bbcb6b5f9 100644
--- a/products/desktop/packages/core/src/sessions/acpNotifications.ts
+++ b/products/desktop/packages/core/src/sessions/acpNotifications.ts
@@ -5,6 +5,7 @@ export const POSTHOG_NOTIFICATIONS = {
TURN_COMPLETE: "_posthog/turn_complete",
BACKGROUND_TURN_COMPLETE: "_posthog/background_turn_complete",
ERROR: "_posthog/error",
+ INITIALIZATION_FAILED: "_posthog/initialization_failed",
CONSOLE: "_posthog/console",
SDK_SESSION: "_posthog/sdk_session",
MODE_CHANGE: "_posthog/mode_change",
diff --git a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts
index 41264cb6aeb7..32caaaf8a0cd 100644
--- a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts
@@ -282,6 +282,26 @@ describe("cloud task update notifications", () => {
]);
});
+ it("shows the credential error from cloud startup", () => {
+ const harness = createHarness();
+ harness.sendUpdate(
+ logsUpdate(
+ [
+ {
+ type: "notification",
+ notification: {
+ method: "_posthog/initialization_failed",
+ params: { initializationPhase: "credential_relay" },
+ },
+ },
+ ],
+ 1,
+ ),
+ );
+ expect(harness.session.errorMessage).toContain("Settings > Harness");
+ expect(harness.session.status).toBe("error");
+ });
+
it("does not seed a reopened run before its history is known", () => {
expect(createHarness().session.optimisticItems).toEqual([]);
});
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 1391f2c06ff0..947895e0ddbc 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -329,6 +329,7 @@ export interface SessionTrpc {
onSessionIdleKilled: TrpcSubscription;
};
workspace: { verify: TrpcQuery };
+ claudeSubscriptionToken: { has: TrpcQuery };
cloudTask: {
watch: TrpcMutation;
unwatch: TrpcMutation;
@@ -336,6 +337,7 @@ export interface SessionTrpc {
sendCommand: TrpcMutation;
stop: TrpcMutation;
designateRelayedMcpServers: TrpcMutation;
+ designateClaudeSubscription: TrpcMutation;
onUpdate: TrpcSubscription;
};
logs: {
@@ -503,6 +505,8 @@ export interface SessionServiceDeps {
bedrockGatewayVariant?: BedrockGatewayVariant;
codexModelAccess?: ModelAccess;
claudeModelAccess?: ModelAccess;
+ claudeCloudSubscriptionOn?: boolean;
+ claudeCloudSubscriptionEnabled?: boolean;
};
usageLimit: { show: (...args: any[]) => any };
readonly addDirectoryDialog: { open: boolean };
@@ -4950,6 +4954,16 @@ export class SessionService {
}
const { auth } = authStatus;
+ if (session.claudeModelAccess === "own-subscription") {
+ await this.designateClaudeSubscription(
+ session.taskId,
+ session.taskRunId,
+ ).catch((error) => {
+ this.d.store.clearTailOptimisticItems(session.taskRunId);
+ throw error;
+ });
+ }
+
this.watchCloudTask(
session.taskId,
session.taskRunId,
@@ -5261,13 +5275,6 @@ export class SessionService {
let updatedTask: Task;
let runtimeOptions: CloudRuntimeOptions;
try {
- const artifactIds = await this.d.h.uploadTaskStagedAttachments(
- authCredentials.client,
- session.taskId,
- transport.filePaths,
- transport.skillBundles,
- );
-
const previousRun = await authCredentials.client.getTaskRun(
session.taskId,
session.taskRunId,
@@ -5297,6 +5304,23 @@ export class SessionService {
});
runtimeOptions = getCloudRuntimeOptions(session, previousRun);
+ if (previousState.claude_model_access === "own-subscription") {
+ if (session.isTaskAuthor === false) {
+ const task = await authCredentials.client.getTask(session.taskId);
+ if (task.channel) {
+ throw new Error(
+ "Only the person who created this task can resume it. Start a new task to continue.",
+ );
+ }
+ }
+ await this.resolveClaudeCloudModelAccess("own-subscription");
+ }
+ const artifactIds = await this.d.h.uploadTaskStagedAttachments(
+ authCredentials.client,
+ session.taskId,
+ transport.filePaths,
+ transport.skillBundles,
+ );
try {
this.markTaskCreationInFlight(session.taskId);
@@ -5310,6 +5334,10 @@ export class SessionService {
reasoningLevel: runtimeOptions.reasoningLevel,
initialPermissionMode: runtimeOptions.initialPermissionMode,
resumeFromRunId: session.taskRunId,
+ claudeModelAccess:
+ previousState.claude_model_access === "own-subscription"
+ ? "own-subscription"
+ : undefined,
pendingUserMessage: transport.messageText,
pendingUserArtifactIds:
artifactIds.length > 0 ? artifactIds : undefined,
@@ -5323,6 +5351,22 @@ export class SessionService {
: undefined,
},
);
+ if (
+ previousState.claude_model_access === "own-subscription" &&
+ updatedTask.latest_run?.id
+ ) {
+ try {
+ await this.designateClaudeSubscription(
+ session.taskId,
+ updatedTask.latest_run.id,
+ );
+ } catch (error) {
+ await authCredentials.client
+ .cancelTaskRun(session.taskId, updatedTask.latest_run.id)
+ .catch(() => undefined);
+ throw error;
+ }
+ }
} catch (error) {
// Only the resume call gates on authorship: non-creators of a channeled
// task get a 404 (not a 403) here, so on a task the app can already read
@@ -6453,6 +6497,39 @@ export class SessionService {
});
}
+ async resolveClaudeCloudModelAccess(
+ requested?: ModelAccess,
+ ): Promise<ModelAccess> {
+ const access =
+ requested ??
+ (this.d.settings.claudeCloudSubscriptionOn
+ ? "own-subscription"
+ : "posthog-gateway");
+ if (access === "own-subscription") {
+ if (!this.d.settings.claudeCloudSubscriptionEnabled) {
+ throw new Error(
+ "Claude plan billing is unavailable for cloud tasks. Try again later.",
+ );
+ }
+ if (!(await this.d.trpc.claudeSubscriptionToken.has.query())) {
+ throw new Error(
+ "Save a Claude token in Settings > Harness before you start or resume this task.",
+ );
+ }
+ }
+ return access;
+ }
+
+ async designateClaudeSubscription(
+ taskId: string,
+ runId: string,
+ ): Promise<void> {
+ await this.d.trpc.cloudTask.designateClaudeSubscription.mutate({
+ taskId,
+ runId,
+ });
+ }
+
watchCloudTask(
taskId: string,
runId: string,
@@ -6478,6 +6555,14 @@ export class SessionService {
) {
this.d.store.setTaskStarting?.(taskId, taskRunId);
}
+ const claudeModelAccess =
+ runState?.claude_model_access === "own-subscription" ||
+ runState?.claude_model_access === "posthog-gateway"
+ ? runState.claude_model_access
+ : undefined;
+ if (claudeModelAccess && watchedSession?.taskRunId === taskRunId) {
+ this.d.store.updateSession(taskRunId, { claudeModelAccess });
+ }
const persistedConfigOptions = this.d.getPersistedConfigOptions(taskRunId);
const persistedAdapter = this.d.adapterStore.getAdapter(taskRunId);
const buildInitialConfigOptions = (
@@ -6675,6 +6760,7 @@ export class SessionService {
? [runState.resume_from_run_id]
: undefined;
session.adapter = adapter;
+ session.claudeModelAccess = claudeModelAccess;
session.configOptions = buildInitialConfigOptions(
initialMode,
existing?.taskRunId === taskRunId ? existing.adapter : persistedAdapter,
@@ -7874,6 +7960,8 @@ export class SessionService {
throw new Error("No active cloud session for task");
}
+ if (session.errorRetryable === false) return;
+
const previousErrorTitle = session.errorTitle;
const previousErrorMessage = session.errorMessage;
const previousErrorRetryable = session.errorRetryable;
@@ -7923,6 +8011,7 @@ export class SessionService {
for (const session of Object.values(sessions)) {
if (!session.isCloud) continue;
if (session.status !== "error") continue;
+ if (session.errorRetryable === false) continue;
this.d.log.info("Auto-retrying errored cloud session on focus", {
taskId: session.taskId,
});
@@ -8608,6 +8697,28 @@ export class SessionService {
this.stopCloudTaskWatch(update.taskId);
}
}
+ if (update.kind === "logs" || update.kind === "snapshot") {
+ for (const entry of update.newEntries) {
+ if (entry.type !== "notification") continue;
+ const notification = entry.notification as {
+ method?: string;
+ params?: { initializationPhase?: string; message?: string };
+ };
+ if (
+ notification.method === POSTHOG_NOTIFICATIONS.INITIALIZATION_FAILED &&
+ notification.params?.initializationPhase === "credential_relay"
+ ) {
+ this.d.store.updateSession(taskRunId, {
+ status: "error",
+ errorTitle: "Claude token unavailable",
+ errorMessage:
+ "Open Desktop and check your Claude token in Settings > Harness. Then start the task again.",
+ errorRetryable: false,
+ isPromptPending: false,
+ });
+ }
+ }
+ }
}
async getCloudAttachmentPreviewUrl(
diff --git a/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts
index 2ea378604c8b..091366a5e7f5 100644
--- a/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts
@@ -146,6 +146,19 @@ describe("SessionService cloud subscription recovery", () => {
vi.useRealTimers();
});
+ it("keeps permanent token errors on focus and manual retry", async () => {
+ const { service, sessions, store } = createHarness();
+ Object.assign(sessions[RUN_ID], {
+ status: "error",
+ errorRetryable: false,
+ errorTitle: "Claude token unavailable",
+ });
+ service.retryUnhealthyCloudSessions();
+ await service.retryCloudTaskWatch(TASK_ID);
+ expect(store.updateSession).not.toHaveBeenCalled();
+ expect(sessions[RUN_ID].errorTitle).toBe("Claude token unavailable");
+ });
+
it("rebuilds the subscription and re-issues watch after a subscription error", async () => {
const { service, subscriptions, watchMutate } = createHarness();
watchTask(service);
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts b/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts
index 004eccf808b3..49c3814f40e6 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts
@@ -4,6 +4,7 @@ import type {
CloudMcpServerRelayDesignation,
CloudRunSource,
McpServerConnection,
+ ModelAccess,
PrAuthorshipMode,
} from "@posthog/shared";
import type { Task, TaskRun } from "@posthog/shared/domain-types";
@@ -13,6 +14,7 @@ export interface CreateTaskRunClientOptions {
mode?: "interactive" | "background";
branch?: string | null;
adapter?: Adapter;
+ claudeModelAccess?: ModelAccess;
piRuntime?: boolean;
model?: string;
reasoningLevel?: string;
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 bd20a90f43c6..1e19ca8c2488 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts
@@ -56,6 +56,7 @@ const sessionService = {
rememberInitialCloudPrompt: vi.fn(),
markTaskCreationInFlight: vi.fn(),
clearVisibleTaskStarting: vi.fn(),
+ designateClaudeSubscription: vi.fn(),
} as unknown as SessionService;
const createTask = (overrides: Partial<Task> = {}): Task => ({
@@ -139,6 +140,48 @@ describe("TaskCreationSaga", () => {
);
});
+ it.each([true, false])(
+ "starts a cold subscription run only when credential designation succeeds (%s)",
+ async (designationSucceeds) => {
+ const createTaskMock = vi.fn().mockResolvedValue(createTask());
+ const createTaskRunMock = vi.fn().mockResolvedValue(createRun());
+ const startTaskRunMock = vi
+ .fn()
+ .mockResolvedValue(createTask({ latest_run: createRun() }));
+ const designate = vi.mocked(sessionService.designateClaudeSubscription);
+ designate.mockImplementationOnce(async () => {
+ if (!designationSucceeds) throw new Error("Host unavailable");
+ });
+ const saga = makeSaga({
+ createTask: createTaskMock,
+ createTaskRun: createTaskRunMock,
+ startTaskRun: startTaskRunMock,
+ });
+
+ const result = await saga.run({
+ content: "Ship the fix",
+ repository: "posthog/posthog",
+ workspaceMode: "cloud",
+ branch: "main",
+ adapter: "claude",
+ claudeCloudModelAccess: "own-subscription",
+ });
+
+ expect(createTaskMock.mock.calls[0][0].branch).toBeUndefined();
+ expect(createTaskRunMock).toHaveBeenCalledWith(
+ "task-123",
+ expect.objectContaining({
+ claudeModelAccess: "own-subscription",
+ }),
+ );
+ expect(designate).toHaveBeenCalledWith("task-123", "run-123");
+ expect(result.success).toBe(designationSucceeds);
+ expect(startTaskRunMock).toHaveBeenCalledTimes(
+ designationSucceeds ? 1 : 0,
+ );
+ },
+ );
+
it("waits for the cloud run response before surfacing the task", async () => {
const createdTask = createTask();
const startedTask = createTask({ latest_run: createRun() });
@@ -524,6 +567,7 @@ describe("TaskCreationSaga", () => {
repository: "posthog/posthog",
workspaceMode: "cloud",
runtime: "pi",
+ claudeCloudModelAccess: "own-subscription",
branch: "main",
adapter: "codex",
model: "gpt-5.4",
@@ -539,6 +583,7 @@ describe("TaskCreationSaga", () => {
branch: "main",
adapter: undefined,
piRuntime: true,
+ claudeModelAccess: undefined,
model: "gpt-5.4",
reasoningLevel: "high",
initialPermissionMode: undefined,
@@ -549,6 +594,7 @@ describe("TaskCreationSaga", () => {
pendingUserArtifactIds: undefined,
});
expect(piRunner.create).not.toHaveBeenCalled();
+ expect(sessionService.designateClaudeSubscription).not.toHaveBeenCalled();
});
it("uploads initial cloud attachments before starting the run", async () => {
diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
index f6917a56015c..8b854f15bd19 100644
--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts
@@ -102,6 +102,9 @@ export class TaskCreationSaga extends Saga<
): Promise<TaskCreationOutput> {
const taskId = input.taskId;
const isPiRuntime = input.runtime === "pi";
+ const claudeCloudModelAccess = isPiRuntime
+ ? undefined
+ : input.claudeCloudModelAccess;
const folderPromise =
!taskId && input.repoPath
? this.resolveFolder(input.repoPath)
@@ -112,7 +115,10 @@ export class TaskCreationSaga extends Saga<
: await this.importClaudeSession(input);
const warmPayload =
- !isPiRuntime && !taskId && input.workspaceMode === "cloud"
+ !isPiRuntime &&
+ !taskId &&
+ input.workspaceMode === "cloud" &&
+ claudeCloudModelAccess !== "own-subscription"
? await this.prepareWarmActivation(input)
: null;
@@ -436,6 +442,7 @@ export class TaskCreationSaga extends Saga<
branch,
adapter: cloudAdapter,
...(isPiRuntime ? { piRuntime: true } : {}),
+ claudeModelAccess: claudeCloudModelAccess,
model: input.model,
reasoningLevel: input.reasoningLevel,
contextWindow: isPiRuntime ? undefined : input.contextWindow,
@@ -458,6 +465,13 @@ export class TaskCreationSaga extends Saga<
throw new Error("Failed to create cloud run");
}
+ if (claudeCloudModelAccess === "own-subscription") {
+ await this.deps.sessionService.designateClaudeSubscription(
+ task.id,
+ taskRun.id,
+ );
+ }
+
if (!isPiRuntime && input.relayedMcpServers?.length) {
// Best-effort: relay designation failing must not fail creation —
// the run still works, minus desktop-relayed servers.
@@ -851,7 +865,9 @@ export class TaskCreationSaga extends Saga<
this.deps.fileReadClient,
);
const canActivateWarmRun =
- input.runtime !== "pi" && !warmPayload?.suppressWarmReuse;
+ input.runtime !== "pi" &&
+ !warmPayload?.suppressWarmReuse &&
+ input.claudeCloudModelAccess !== "own-subscription";
const result = await this.deps.posthogClient.createTask({
description,
naming_source: namingSource,
diff --git a/products/desktop/packages/core/src/task-detail/taskInput.ts b/products/desktop/packages/core/src/task-detail/taskInput.ts
index 1ebd78faefb2..ee39ddaeab3e 100644
--- a/products/desktop/packages/core/src/task-detail/taskInput.ts
+++ b/products/desktop/packages/core/src/task-detail/taskInput.ts
@@ -24,6 +24,7 @@ export interface PrepareTaskInputOptions {
adapter?: Adapter;
codexModelAccess?: ModelAccess;
claudeModelAccess?: ModelAccess;
+ claudeCloudModelAccess?: ModelAccess;
runtime?: AgentRuntime;
model?: string;
reasoningLevel?: string;
@@ -75,6 +76,7 @@ export function prepareTaskInput(
adapter: options.adapter,
codexModelAccess: options.codexModelAccess,
claudeModelAccess: options.claudeModelAccess,
+ claudeCloudModelAccess: options.claudeCloudModelAccess,
runtime,
model: options.model,
reasoningLevel: options.reasoningLevel,
diff --git a/products/desktop/packages/core/src/task-detail/taskService.test.ts b/products/desktop/packages/core/src/task-detail/taskService.test.ts
index 90b3f4aae64b..1eab889146cc 100644
--- a/products/desktop/packages/core/src/task-detail/taskService.test.ts
+++ b/products/desktop/packages/core/src/task-detail/taskService.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import type { PiRunner } from "../pi-runtime/piRunner";
import type { TaskCreationEffects } from "./taskCreationEffects";
import type { ITaskCreationHost } from "./taskCreationHost";
+import { TaskCreationSaga } from "./taskCreationSaga";
import { buildWorktreeAdoptionInput } from "./taskInput";
import { TaskService } from "./taskService";
@@ -20,7 +21,7 @@ const rootLogger = {
const fileReadClient = { readAbsoluteFile: vi.fn(async () => null) };
-function makeService(): TaskService {
+function makeService(overrides: Partial<SessionService> = {}): TaskService {
const host = {
// The API client's createTask rejects so tests can observe that an input
// made it past validation (failedStep lands on task_creation, not
@@ -43,6 +44,7 @@ function makeService(): TaskService {
markTaskCreationInFlight: vi.fn(),
connectToTask: vi.fn(),
disconnectFromTask: vi.fn(),
+ ...overrides,
} as unknown as SessionService;
const effects = {
onWorkspaceCreated: vi.fn(),
@@ -180,6 +182,60 @@ describe("TaskService.resumeCloudPiRun", () => {
});
describe("TaskService.createTask validation", () => {
+ it.each([
+ { runtime: "acp" as const, adapter: "claude" as const, blocked: false },
+ { runtime: "acp" as const, adapter: "codex" as const, blocked: false },
+ { runtime: "pi" as const, adapter: "claude" as const, blocked: false },
+ { runtime: "acp" as const, adapter: "claude" as const, blocked: true },
+ ])(
+ "checks Claude billing before cloud creation for %s",
+ async ({ runtime, adapter, blocked }) => {
+ const resolveClaudeCloudModelAccess = vi
+ .fn()
+ .mockImplementation(async () => {
+ if (blocked) throw new Error("Save a Claude token first.");
+ return "own-subscription";
+ });
+ const run = vi
+ .spyOn(TaskCreationSaga.prototype, "run")
+ .mockResolvedValue({
+ success: false,
+ failedStep: "task_creation",
+ error: "test result",
+ });
+ try {
+ const result = await makeService({
+ resolveClaudeCloudModelAccess,
+ }).createTask(
+ {
+ content: "Check the build",
+ workspaceMode: "cloud",
+ runtime,
+ adapter,
+ },
+ undefined,
+ { skipCloudUsagePreflight: true },
+ );
+ if (blocked) {
+ expect(run).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ success: false,
+ error: "Save a Claude token first.",
+ });
+ } else if (runtime === "acp" && adapter === "claude") {
+ expect(run.mock.calls[0][0].claudeCloudModelAccess).toBe(
+ "own-subscription",
+ );
+ } else {
+ expect(resolveClaudeCloudModelAccess).not.toHaveBeenCalled();
+ expect(run.mock.calls[0][0].claudeCloudModelAccess).toBeUndefined();
+ }
+ } finally {
+ run.mockRestore();
+ }
+ },
+ );
+
it("rejects an input with neither content nor a taskDescription", async () => {
const result = await makeService().createTask({
content: " ",
diff --git a/products/desktop/packages/core/src/task-detail/taskService.ts b/products/desktop/packages/core/src/task-detail/taskService.ts
index f9a17ce4bfc0..d75351d69371 100644
--- a/products/desktop/packages/core/src/task-detail/taskService.ts
+++ b/products/desktop/packages/core/src/task-detail/taskService.ts
@@ -153,6 +153,31 @@ export class TaskService {
}
}
+ if (
+ input.workspaceMode === "cloud" &&
+ input.runtime !== "pi" &&
+ (input.adapter ?? "claude") === "claude"
+ ) {
+ try {
+ input = {
+ ...input,
+ claudeCloudModelAccess:
+ await this.sessionService.resolveClaudeCloudModelAccess(
+ input.claudeCloudModelAccess,
+ ),
+ };
+ } catch (error) {
+ return {
+ success: false,
+ failedStep: "validation",
+ error:
+ error instanceof Error
+ ? error.message
+ : "Could not check Claude plan billing.",
+ };
+ }
+ }
+
const creator = new TaskCreationSaga(
{
posthogClient,
diff --git a/products/desktop/packages/git/src/signed-commit.test.ts b/products/desktop/packages/git/src/signed-commit.test.ts
index cdead2575957..2754f820538e 100644
--- a/products/desktop/packages/git/src/signed-commit.test.ts
+++ b/products/desktop/packages/git/src/signed-commit.test.ts
@@ -527,6 +527,7 @@ describe("resolveWriteBase", () => {
run(clone, "init", "--initial-branch", "main");
run(clone, "config", "user.email", "[email protected]");
run(clone, "config", "user.name", "e2e");
+ run(clone, "config", "commit.gpgsign", "false");
writeFileSync(path.join(clone, "a.txt"), "a\n");
run(clone, "add", "a.txt");
run(clone, "commit", "-m", "init");
diff --git a/products/desktop/packages/host-router/src/router.ts b/products/desktop/packages/host-router/src/router.ts
index 06fd5b661516..94194670939a 100644
--- a/products/desktop/packages/host-router/src/router.ts
+++ b/products/desktop/packages/host-router/src/router.ts
@@ -9,6 +9,7 @@ import { canvasDataRouter } from "./routers/canvas-data.router";
import { canvasTemplatesRouter } from "./routers/canvas-templates.router";
import { channelTasksRouter } from "./routers/channel-tasks.router";
import { claudeCliSessionsRouter } from "./routers/claude-cli-sessions.router";
+import { claudeSubscriptionTokenRouter } from "./routers/claude-subscription-token.router";
import { cloudTaskRouter } from "./routers/cloud-task.router";
import { connectivityRouter } from "./routers/connectivity.router";
import { contextMenuRouter } from "./routers/context-menu.router";
@@ -93,6 +94,7 @@ export const hostRouter = router({
processTracking: processTrackingRouter,
provisioning: provisioningRouter,
secureStore: secureStoreRouter,
+ claudeSubscriptionToken: claudeSubscriptionTokenRouter,
shell: shellRouter,
speech: speechRouter,
skills: skillsRouter,
diff --git a/products/desktop/packages/host-router/src/routers/claude-subscription-token.router.ts b/products/desktop/packages/host-router/src/routers/claude-subscription-token.router.ts
new file mode 100644
index 000000000000..03a184fe3da1
--- /dev/null
+++ b/products/desktop/packages/host-router/src/routers/claude-subscription-token.router.ts
@@ -0,0 +1,26 @@
+import {
+ CLAUDE_SUBSCRIPTION_TOKEN_STORE,
+ type ClaudeSubscriptionTokenStore,
+} from "@posthog/core/cloud-task/identifiers";
+import { publicProcedure, router } from "@posthog/host-trpc/trpc";
+import { claudeSubscriptionTokenInput } from "@posthog/workspace-server/services/claude-subscription/schemas";
+
+export const claudeSubscriptionTokenRouter = router({
+ has: publicProcedure.query(({ ctx }) =>
+ ctx.container
+ .get<ClaudeSubscriptionTokenStore>(CLAUDE_SUBSCRIPTION_TOKEN_STORE)
+ .has(),
+ ),
+ save: publicProcedure
+ .input(claudeSubscriptionTokenInput)
+ .mutation(({ ctx, input }) =>
+ ctx.container
+ .get<ClaudeSubscriptionTokenStore>(CLAUDE_SUBSCRIPTION_TOKEN_STORE)
+ .save(input.token),
+ ),
+ clear: publicProcedure.mutation(({ ctx }) =>
+ ctx.container
+ .get<ClaudeSubscriptionTokenStore>(CLAUDE_SUBSCRIPTION_TOKEN_STORE)
+ .clear(),
+ ),
+});
diff --git a/products/desktop/packages/host-router/src/routers/cloud-task.router.ts b/products/desktop/packages/host-router/src/routers/cloud-task.router.ts
index 57061998d3dc..0894f65dfe63 100644
--- a/products/desktop/packages/host-router/src/routers/cloud-task.router.ts
+++ b/products/desktop/packages/host-router/src/routers/cloud-task.router.ts
@@ -3,6 +3,7 @@ import { CLOUD_TASK_SERVICE } from "@posthog/core/cloud-task/identifiers";
import {
CloudTaskEvent,
cloudContextOutput,
+ designateClaudeSubscriptionInput,
designateRelayedMcpServersInput,
onUpdateInput,
retryInput,
@@ -52,6 +53,14 @@ export const cloudTaskRouter = router({
.designateRelayedMcpServers(input.runId, input.servers),
),
+ designateClaudeSubscription: publicProcedure
+ .input(designateClaudeSubscriptionInput)
+ .mutation(({ ctx, input }) =>
+ ctx.container
+ .get<CloudTaskService>(CLOUD_TASK_SERVICE)
+ .designateClaudeSubscription(input),
+ ),
+
sendCommand: publicProcedure
.input(sendCommandInput)
.output(sendCommandOutput)
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index c6d9f1aa4d0d..cf545793f1e3 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -344,6 +344,11 @@ export interface SettingChangedProperties {
old_value?: string | boolean | number;
}
+export interface CloudCredentialRelayProperties {
+ credential: "claude_subscription_token";
+ outcome: "sent" | "no_token" | "expired" | "rejected";
+}
+
export interface CustomSoundAddedProperties {
// How the clip was captured.
source: "recording" | "import";
@@ -1593,6 +1598,9 @@ export const ANALYTICS_EVENTS = {
CODEX_SUBSCRIPTION_SIGNED_OUT: "Codex subscription signed out",
CLAUDE_SUBSCRIPTION_CONNECTED: "Claude subscription connected",
CLAUDE_SUBSCRIPTION_SIGNED_OUT: "Claude subscription signed out",
+ CLAUDE_CLOUD_TOKEN_SAVED: "Claude cloud token saved",
+ CLAUDE_CLOUD_TOKEN_REMOVED: "Claude cloud token removed",
+ CLOUD_CREDENTIAL_RELAY: "Cloud credential relay",
// Feedback events
AI_METRIC: "$ai_metric",
@@ -1797,6 +1805,9 @@ export type EventPropertyMap = {
// Settings events
[ANALYTICS_EVENTS.SETTING_CHANGED]: SettingChangedProperties;
+ [ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_SAVED]: never;
+ [ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_REMOVED]: never;
+ [ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY]: CloudCredentialRelayProperties;
[ANALYTICS_EVENTS.CUSTOM_SOUND_ADDED]: CustomSoundAddedProperties;
[ANALYTICS_EVENTS.CUSTOM_SOUND_RECORDING_SILENT]: never;
[ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_CONNECTED]: never;
diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.json
index 7eadb45effcd..65925382b48b 100644
--- a/products/desktop/packages/shared/src/feature-flag-keys.json
+++ b/products/desktop/packages/shared/src/feature-flag-keys.json
@@ -7,6 +7,7 @@
"CHANNEL_REPORTS_FLAG": "posthog-desktop-channel-reports",
"CHANNELS_LAYOUT_FLAG": "code-spaces-layout",
"CLAUDE_OWN_SUBSCRIPTION_FLAG": "posthog-code-claude-own-subscription",
+ "CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG": "posthog-code-claude-own-subscription-cloud",
"CLOUD_COMPUTE_BILLING_FLAG": "posthog-desktop-cloud-compute-billing",
"CODEX_OWN_SUBSCRIPTION_FLAG": "posthog-code-codex-own-subscription",
"CONTEXT_LAYER_FLAG": "context-layer",
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index d59f4f7e4763..84d9074a333b 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -44,6 +44,8 @@ export const CODEX_OWN_SUBSCRIPTION_FLAG =
featureFlagKeys.CODEX_OWN_SUBSCRIPTION_FLAG;
export const CLAUDE_OWN_SUBSCRIPTION_FLAG =
featureFlagKeys.CLAUDE_OWN_SUBSCRIPTION_FLAG;
+export const CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG =
+ featureFlagKeys.CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG;
// Gates importing and relaying local MCP servers into cloud task runs.
export const LOCAL_MCP_IMPORT_FLAG = featureFlagKeys.LOCAL_MCP_IMPORT_FLAG;
/**
diff --git a/products/desktop/packages/shared/src/task-creation-domain.ts b/products/desktop/packages/shared/src/task-creation-domain.ts
index 114d30faa06f..ace250e44ffa 100644
--- a/products/desktop/packages/shared/src/task-creation-domain.ts
+++ b/products/desktop/packages/shared/src/task-creation-domain.ts
@@ -39,6 +39,7 @@ export interface TaskCreationInput {
adapter?: Adapter;
codexModelAccess?: ModelAccess;
claudeModelAccess?: ModelAccess;
+ claudeCloudModelAccess?: ModelAccess;
runtime?: AgentRuntime;
model?: string;
reasoningLevel?: string;
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 3b653ce118fc..7af4d20427aa 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
@@ -77,6 +77,8 @@ function subscriptionState(
flagEnabled: boolean;
subscriptionOn: boolean;
loggedIn: boolean;
+ cloudFlagEnabled: boolean;
+ cloudSubscriptionOn: boolean;
}>,
) {
const state = {
@@ -964,11 +966,11 @@ describe("ReasoningLevelSelector", () => {
}, 20000);
it.each([
- ["claude", "Anthropic", "Anthropic"],
- ["codex", "OpenAI", "OpenAI"],
+ ["claude", "Anthropic", /^Claude plan billing is unavailable/],
+ ["codex", "OpenAI", /^OpenAI billing only works/],
] as const)(
"disables the %s billing option for cloud tasks and names the reason",
- async (adapter, planLabel, reasonPrefix) => {
+ async (adapter, planLabel, reason) => {
useAdapterSubscription.mockReturnValue(subscriptionState());
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
@@ -989,35 +991,46 @@ describe("ReasoningLevelSelector", () => {
});
expect(planItem).toHaveAttribute("aria-disabled", "true");
- await expect(
- screen.findByText(new RegExp(`^${reasonPrefix} billing only works`)),
- ).resolves.toBeInTheDocument();
+ await expect(screen.findByText(reason)).resolves.toBeInTheDocument();
},
20000,
);
- it("keeps the billing option selectable for local tasks", async () => {
- useAdapterSubscription.mockReturnValue(subscriptionState());
- const user = userEvent.setup({ pointerEventsCheck: 0 });
- render(
- <Theme>
- <ReasoningLevelSelector
- thoughtOption={thoughtOption()}
- adapter="claude"
- showBillingMenu
- workspaceMode="local"
- />
- </Theme>,
- );
+ it.each(["local", "cloud"] as const)(
+ "keeps enabled subscription billing selectable for %s tasks",
+ async (workspaceMode) => {
+ useAdapterSubscription.mockReturnValue(
+ subscriptionState({
+ cloudFlagEnabled: true,
+ cloudSubscriptionOn: true,
+ }),
+ );
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <Theme>
+ <ReasoningLevelSelector
+ thoughtOption={thoughtOption()}
+ adapter="claude"
+ showBillingMenu
+ workspaceMode={workspaceMode}
+ />
+ </Theme>,
+ );
- await openAdvanced(user);
- await openSub(user, /^Billing/);
- expect(
- screen.getByRole("menuitemradio", { name: "Anthropic" }),
- ).not.toHaveAttribute("aria-disabled", "true");
- // Logged in, so the login note stays hidden.
- expect(screen.queryByText(/Log in to Claude Code/)).not.toBeInTheDocument();
- }, 20000);
+ await openAdvanced(user);
+ await openSub(user, /^Billing/);
+ expect(
+ screen.getByRole("menuitemradio", { name: "Anthropic" }),
+ ).not.toHaveAttribute("aria-disabled", "true");
+ expect(
+ screen.getByRole("menuitemradio", { name: "Anthropic" }),
+ ).toHaveAttribute("aria-checked", "true");
+ expect(
+ screen.queryByText(/Log in to Claude Code/),
+ ).not.toBeInTheDocument();
+ },
+ 20000,
+ );
it("shows the login note only when the logged-out billing pick needs it", async () => {
// Persisted billing is PostHog, account is logged out: no login prompt.
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx
index a46fa79e6b64..191ce24a7338 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SubscriptionSubmenu.tsx
@@ -12,6 +12,7 @@ import {
import type { Adapter, ModelAccess } from "@posthog/shared";
import {
applyModelAccess,
+ subscriptionModelAccess,
useAdapterSubscription,
type WorkspaceModeForAccess,
} from "@posthog/ui/features/settings/adapterSubscription";
@@ -40,7 +41,7 @@ export const SUBSCRIPTION_LOGIN_ACTION: Record<Adapter, string> = {
const CLOUD_ONLY_REASON: Record<Adapter, string> = {
claude:
- "Anthropic billing only works for local and worktree tasks. Cloud tasks always use PostHog.",
+ "Claude plan billing is unavailable for cloud tasks. Try again later.",
codex:
"OpenAI billing only works for local and worktree tasks. Cloud tasks always use PostHog.",
};
@@ -50,7 +51,6 @@ const TOOLTIP_DELAY_MS = 150;
interface SubscriptionSubmenuProps {
adapter: Adapter;
closeOnChange?: boolean;
- /** Workspace mode of the task being composed; cloud forces PostHog credits. */
workspaceMode?: WorkspaceModeForAccess;
}
@@ -60,20 +60,26 @@ export function SubscriptionSubmenu({
workspaceMode,
}: SubscriptionSubmenuProps): React.JSX.Element | null {
const subscription = useAdapterSubscription(adapter);
- if (!subscription.flagEnabled) {
+ const cloudTask = workspaceMode === "cloud";
+ const cloudAvailable = adapter === "claude" && subscription.cloudFlagEnabled;
+ if (
+ cloudTask
+ ? !subscription.flagEnabled &&
+ !cloudAvailable &&
+ !subscription.cloudSubscriptionOn
+ : !subscription.flagEnabled
+ ) {
return null;
}
-
- // Cloud tasks always bill PostHog credits (see effectiveModelAccess), so the
- // provider option is disabled there instead of silently overriding the pick.
- const cloudTask = workspaceMode === "cloud";
const providerLabel = PROVIDER_LABEL[adapter];
- const value: ModelAccess =
- cloudTask || !subscription.subscriptionOn
- ? "posthog-gateway"
- : "own-subscription";
+ const value: ModelAccess = cloudTask
+ ? subscriptionModelAccess(subscription, "cloud")
+ : subscription.subscriptionOn
+ ? "own-subscription"
+ : "posthog-gateway";
const valueLabel =
- subscription.subscriptionOn && subscription.loggedIn && !cloudTask
+ subscriptionModelAccess(subscription, workspaceMode ?? "local") ===
+ "own-subscription"
? providerLabel
: "PostHog";
@@ -89,13 +95,17 @@ export function SubscriptionSubmenu({
<DropdownMenuRadioGroup
value={value}
onValueChange={(next) =>
- applyModelAccess(
- adapter,
- next === "own-subscription"
- ? "own-subscription"
- : "posthog-gateway",
- subscription.loggedIn,
- )
+ cloudTask && adapter === "claude"
+ ? subscription.setCloudSubscriptionOn?.(
+ next === "own-subscription",
+ )
+ : applyModelAccess(
+ adapter,
+ next === "own-subscription"
+ ? "own-subscription"
+ : "posthog-gateway",
+ subscription.loggedIn,
+ )
}
>
<DropdownMenuRadioItem
@@ -104,7 +114,7 @@ export function SubscriptionSubmenu({
>
PostHog
</DropdownMenuRadioItem>
- {cloudTask ? (
+ {cloudTask && !cloudAvailable ? (
<TooltipProvider delay={TOOLTIP_DELAY_MS}>
<Tooltip disableHoverablePopup>
<TooltipTrigger render={<span className="flex" />}>
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 f10ff2f7c306..dc47f780a2da 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -38,6 +38,7 @@ const mockTrpcLogs = vi.hoisted(() => ({
}));
const mockTrpcCloudTask = vi.hoisted(() => ({
+ designateClaudeSubscription: { mutate: vi.fn() },
sendCommand: { mutate: vi.fn() },
watch: { mutate: vi.fn().mockResolvedValue(undefined) },
retry: { mutate: vi.fn().mockResolvedValue(undefined) },
@@ -337,6 +338,9 @@ vi.mock("@posthog/di/container", () => ({
workspace: mockTrpcWorkspace,
logs: mockTrpcLogs,
cloudTask: mockTrpcCloudTask,
+ claudeSubscriptionToken: {
+ has: { query: vi.fn().mockResolvedValue(true) },
+ },
fs: mockTrpcFs,
skills: mockTrpcSkills,
};
@@ -7686,78 +7690,104 @@ describe("SessionService", () => {
);
});
- it("resumes when the active workflow has already ended", async () => {
- const service = getSessionService();
- mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
- createMockSession({
- isCloud: true,
- cloudStatus: "in_progress",
- status: "connected",
- cloudBranch: "feature/cloud-run",
- }),
- );
- mockTrpcCloudTask.sendCommand.mutate.mockResolvedValue({
- success: false,
- status: 409,
- error: "Task run workflow has ended",
- });
- mockAuthenticatedClient.getTaskRun.mockResolvedValue({
- id: "run-123",
- task: "task-123",
- team: 123,
- branch: "feature/cloud-run",
- runtime_adapter: "claude",
- model: "claude-sonnet-4-20250514",
- reasoning_effort: null,
- environment: "cloud",
- status: "completed",
- log_url: "https://example.com/logs/run-123",
- error_message: null,
- output: {},
- state: {},
- created_at: "2026-04-14T00:00:00Z",
- updated_at: "2026-04-14T00:00:00Z",
- completed_at: "2026-04-14T00:05:00Z",
- });
- mockAuthenticatedClient.getTask.mockResolvedValue(createMockTask());
- mockAuthenticatedClient.runTaskInCloud.mockResolvedValue(
- createMockTask({
- latest_run: {
- id: "run-456",
- task: "task-123",
- team: 123,
- branch: "feature/cloud-run",
- runtime_adapter: "claude",
- model: "claude-sonnet-4-20250514",
- reasoning_effort: null,
- environment: "cloud",
- status: "queued",
- log_url: "https://example.com/logs/run-456",
- error_message: null,
- output: {},
- state: {},
- created_at: "2026-04-14T00:06:00Z",
- updated_at: "2026-04-14T00:06:00Z",
- completed_at: null,
- },
- }),
- );
+ it.each(["posthog-gateway", "own-subscription"])(
+ "resumes when the active workflow has already ended using %s",
+ async (claudeModelAccess) => {
+ mockFeatureFlags.isEnabled.mockReturnValue(true);
+ const service = getSessionService();
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
+ createMockSession({
+ isCloud: true,
+ cloudStatus: "in_progress",
+ status: "connected",
+ cloudBranch: "feature/cloud-run",
+ }),
+ );
+ mockTrpcCloudTask.sendCommand.mutate.mockResolvedValue({
+ success: false,
+ status: 409,
+ error: "Task run workflow has ended",
+ });
+ mockAuthenticatedClient.getTaskRun.mockResolvedValue({
+ id: "run-123",
+ task: "task-123",
+ team: 123,
+ branch: "feature/cloud-run",
+ runtime_adapter: "claude",
+ model: "claude-sonnet-4-20250514",
+ reasoning_effort: null,
+ environment: "cloud",
+ status: "completed",
+ log_url: "https://example.com/logs/run-123",
+ error_message: null,
+ output: {},
+ state: { claude_model_access: claudeModelAccess },
+ created_at: "2026-04-14T00:00:00Z",
+ updated_at: "2026-04-14T00:00:00Z",
+ completed_at: "2026-04-14T00:05:00Z",
+ });
+ mockAuthenticatedClient.getTask.mockResolvedValue(createMockTask());
+ mockAuthenticatedClient.runTaskInCloud.mockResolvedValue(
+ createMockTask({
+ latest_run: {
+ id: "run-456",
+ task: "task-123",
+ team: 123,
+ branch: "feature/cloud-run",
+ runtime_adapter: "claude",
+ model: "claude-sonnet-4-20250514",
+ reasoning_effort: null,
+ environment: "cloud",
+ status: "queued",
+ log_url: "https://example.com/logs/run-456",
+ error_message: null,
+ output: {},
+ state: {},
+ created_at: "2026-04-14T00:06:00Z",
+ updated_at: "2026-04-14T00:06:00Z",
+ completed_at: null,
+ },
+ }),
+ );
- const result = await service.sendPrompt("task-123", "Continue");
+ const result = await service.sendPrompt("task-123", "Continue");
- expect(result.stopReason).toBe("queued");
- expect(mockAuthenticatedClient.runTaskInCloud).toHaveBeenCalledWith(
- "task-123",
- "feature/cloud-run",
- expect.objectContaining({
- resumeFromRunId: "run-123",
- pendingUserMessage: "Continue",
- }),
- );
- expect(
- mockSessionStoreSetters.clearTailOptimisticItems,
- ).toHaveBeenCalledWith("run-123");
- });
+ expect(result.stopReason).toBe("queued");
+ if (claudeModelAccess === "own-subscription") {
+ expect(
+ mockTrpcCloudTask.designateClaudeSubscription.mutate,
+ ).toHaveBeenCalledWith({
+ taskId: "task-123",
+ runId: "run-456",
+ });
+ expect(
+ mockTrpcCloudTask.designateClaudeSubscription.mutate.mock
+ .invocationCallOrder[0],
+ ).toBeLessThan(
+ mockTrpcCloudTask.watch.mutate.mock.invocationCallOrder[
+ mockTrpcCloudTask.watch.mutate.mock.calls.findIndex(
+ ([input]) => input.runId === "run-456",
+ )
+ ],
+ );
+ } else {
+ expect(
+ mockTrpcCloudTask.designateClaudeSubscription.mutate,
+ ).not.toHaveBeenCalled();
+ }
+ expect(mockAuthenticatedClient.runTaskInCloud).toHaveBeenCalledWith(
+ "task-123",
+ "feature/cloud-run",
+ expect.objectContaining({
+ resumeFromRunId: "run-123",
+ pendingUserMessage: "Continue",
+ }),
+ );
+ expect(
+ mockSessionStoreSetters.clearTailOptimisticItems,
+ ).toHaveBeenCalledWith("run-123");
+ },
+ );
it("preserves codex runtime selection when resuming a terminal cloud run", async () => {
const service = getSessionService();
@@ -7858,122 +7888,145 @@ describe("SessionService", () => {
);
});
- it("shows an optimistic user bubble when resuming a terminal cloud run", async () => {
- const service = getSessionService();
- mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
- createMockSession({
- isCloud: true,
- cloudStatus: "completed",
- cloudBranch: "feature/cloud-run",
- }),
- );
- mockAuthenticatedClient.getTaskRun.mockResolvedValue({
- id: "run-123",
- task: "task-123",
- team: 123,
- branch: "feature/cloud-run",
- runtime_adapter: "claude",
- model: "claude-sonnet-4-20250514",
- reasoning_effort: null,
- environment: "cloud",
- status: "completed",
- log_url: "https://example.com/logs/run-123",
- error_message: null,
- output: {},
- state: {},
- created_at: "2026-04-14T00:00:00Z",
- updated_at: "2026-04-14T00:00:00Z",
- completed_at: "2026-04-14T00:05:00Z",
- });
- mockAuthenticatedClient.getTask.mockResolvedValue(createMockTask());
- mockTrpcFs.readFileAsBase64.query.mockResolvedValue("aGVsbG8=");
- mockAuthenticatedClient.prepareTaskStagedArtifactUploads.mockResolvedValue(
- [
- {
- id: "artifact-1",
- name: "test.txt",
- type: "user_attachment",
- source: "posthog_code",
- size: 5,
- content_type: "text/plain",
- storage_path: "tasks/artifacts/test.txt",
- expires_in: 3600,
- presigned_post: {
- url: "https://uploads.example.com",
- fields: { key: "tasks/artifacts/test.txt" },
+ it.each([false, true])(
+ "checks the token before uploading resume attachments (missing: %s)",
+ async (tokenMissing) => {
+ const service = getSessionService();
+ mockFeatureFlags.isEnabled.mockReturnValue(true);
+ if (tokenMissing)
+ vi.spyOn(
+ service,
+ "resolveClaudeCloudModelAccess",
+ ).mockRejectedValueOnce(new Error("Save a Claude token first."));
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
+ createMockSession({
+ isCloud: true,
+ cloudStatus: "completed",
+ cloudBranch: "feature/cloud-run",
+ }),
+ );
+ mockAuthenticatedClient.getTaskRun.mockResolvedValue({
+ id: "run-123",
+ task: "task-123",
+ team: 123,
+ branch: "feature/cloud-run",
+ runtime_adapter: "claude",
+ model: "claude-sonnet-4-20250514",
+ reasoning_effort: null,
+ environment: "cloud",
+ status: "completed",
+ log_url: "https://example.com/logs/run-123",
+ error_message: null,
+ output: {},
+ state: { claude_model_access: "own-subscription" },
+ created_at: "2026-04-14T00:00:00Z",
+ updated_at: "2026-04-14T00:00:00Z",
+ completed_at: "2026-04-14T00:05:00Z",
+ });
+ mockAuthenticatedClient.getTask.mockResolvedValue(createMockTask());
+ mockTrpcFs.readFileAsBase64.query.mockResolvedValue("aGVsbG8=");
+ mockAuthenticatedClient.prepareTaskStagedArtifactUploads.mockResolvedValue(
+ [
+ {
+ id: "artifact-1",
+ name: "test.txt",
+ type: "user_attachment",
+ source: "posthog_code",
+ size: 5,
+ content_type: "text/plain",
+ storage_path: "tasks/artifacts/test.txt",
+ expires_in: 3600,
+ presigned_post: {
+ url: "https://uploads.example.com",
+ fields: { key: "tasks/artifacts/test.txt" },
+ },
},
- },
- ],
- );
- mockAuthenticatedClient.finalizeTaskStagedArtifactUploads.mockResolvedValue(
- [
+ ],
+ );
+ mockAuthenticatedClient.finalizeTaskStagedArtifactUploads.mockResolvedValue(
+ [
+ {
+ id: "artifact-1",
+ name: "test.txt",
+ type: "user_attachment",
+ source: "posthog_code",
+ size: 5,
+ content_type: "text/plain",
+ storage_path: "tasks/artifacts/test.txt",
+ uploaded_at: "2026-04-16T00:00:00Z",
+ },
+ ],
+ );
+ mockAuthenticatedClient.runTaskInCloud.mockResolvedValue(
+ createMockTask({
+ latest_run: {
+ id: "run-456",
+ task: "task-123",
+ team: 123,
+ branch: "feature/cloud-run",
+ runtime_adapter: "claude",
+ model: "claude-sonnet-4-20250514",
+ reasoning_effort: null,
+ environment: "cloud",
+ status: "queued",
+ log_url: "https://example.com/logs/run-456",
+ error_message: null,
+ output: {},
+ state: {},
+ created_at: "2026-04-14T00:06:00Z",
+ updated_at: "2026-04-14T00:06:00Z",
+ completed_at: null,
+ },
+ }),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true } as Response),
+ );
+
+ const prompt: ContentBlock[] = [
+ { type: "text", text: "what is this about?" },
{
- id: "artifact-1",
+ type: "resource_link",
+ uri: "file:///tmp/test.txt",
name: "test.txt",
- type: "user_attachment",
- source: "posthog_code",
- size: 5,
- content_type: "text/plain",
- storage_path: "tasks/artifacts/test.txt",
- uploaded_at: "2026-04-16T00:00:00Z",
+ mimeType: "text/plain",
},
- ],
- );
- mockAuthenticatedClient.runTaskInCloud.mockResolvedValue(
- createMockTask({
- latest_run: {
- id: "run-456",
- task: "task-123",
- team: 123,
- branch: "feature/cloud-run",
- runtime_adapter: "claude",
- model: "claude-sonnet-4-20250514",
- reasoning_effort: null,
- environment: "cloud",
- status: "queued",
- log_url: "https://example.com/logs/run-456",
- error_message: null,
- output: {},
- state: {},
- created_at: "2026-04-14T00:06:00Z",
- updated_at: "2026-04-14T00:06:00Z",
- completed_at: null,
- },
- }),
- );
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue({ ok: true } as Response),
- );
-
- const prompt: ContentBlock[] = [
- { type: "text", text: "what is this about?" },
- {
- type: "resource_link",
- uri: "file:///tmp/test.txt",
- name: "test.txt",
- mimeType: "text/plain",
- },
- ];
+ ];
- const result = await service.sendPrompt("task-123", prompt);
+ if (tokenMissing) {
+ await expect(service.sendPrompt("task-123", prompt)).rejects.toThrow(
+ "Save a Claude token first.",
+ );
+ expect(
+ mockAuthenticatedClient.prepareTaskStagedArtifactUploads,
+ ).not.toHaveBeenCalled();
+ expect(
+ mockAuthenticatedClient.finalizeTaskStagedArtifactUploads,
+ ).not.toHaveBeenCalled();
+ return;
+ }
+ const result = await service.sendPrompt("task-123", prompt);
- expect(result.stopReason).toBe("queued");
- expect(mockSessionStoreSetters.appendOptimisticItem).toHaveBeenCalledWith(
- "run-123",
- expect.objectContaining({
- type: "user_message",
- content: "what is this about?\n\nAttached files: test.txt",
- pinToTop: false,
- }),
- );
- expect(mockSessionStoreSetters.setSession).toHaveBeenCalledWith(
- expect.objectContaining({
- taskRunId: "run-456",
- isPromptPending: true,
- }),
- );
- });
+ expect(result.stopReason).toBe("queued");
+ expect(
+ mockSessionStoreSetters.appendOptimisticItem,
+ ).toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({
+ type: "user_message",
+ content: "what is this about?\n\nAttached files: test.txt",
+ pinToTop: false,
+ }),
+ );
+ expect(mockSessionStoreSetters.setSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ taskRunId: "run-456",
+ isPromptPending: true,
+ }),
+ );
+ },
+ );
const mockPreBootFailedSession = (overrides: Partial<AgentSession> = {}) =>
mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
index f98aa90bb910..ab903c6df578 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_CLOUD_FLAG,
CLAUDE_OWN_SUBSCRIPTION_FLAG,
CODEX_OWN_SUBSCRIPTION_FLAG,
SPOKEN_NARRATION_FLAG,
@@ -162,6 +163,9 @@ function buildSessionServiceDeps(): SessionServiceDeps {
import.meta.env.DEV;
return {
...state,
+ claudeCloudSubscriptionEnabled: featureFlags.isEnabled(
+ CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG,
+ ),
customInstructions: getEffectiveCustomInstructions(state),
spokenNarrationEnabled: shouldEnableSpokenNarration(
state.spokenNotifications,
diff --git a/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts b/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts
index 5040d2202c26..83c339d639c8 100644
--- a/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts
+++ b/products/desktop/packages/ui/src/features/settings/adapterSubscription.test.ts
@@ -13,6 +13,7 @@ import {
effectiveModelAccess,
registerSubscriptionAtBoot,
type SubscriptionStatus,
+ subscriptionModelAccess,
subscriptionNeedsConnection,
} from "./adapterSubscription";
@@ -86,6 +87,32 @@ describe("adapter subscription gating", () => {
expect(effectiveModelAccess(input)).toBe(expected);
});
+ it.each([
+ ["subscription selected", true, true, "own-subscription"],
+ ["rollout disabled after selection", true, false, "own-subscription"],
+ ["gateway selected", false, true, "posthog-gateway"],
+ ])(
+ "cloud billing preserves intent: %s",
+ (_name, cloudSubscriptionOn, cloudFlagEnabled, expected) => {
+ expect(
+ subscriptionModelAccess(
+ {
+ flagEnabled: false,
+ subscriptionOn: false,
+ cloudSubscriptionOn,
+ cloudFlagEnabled,
+ status: undefined,
+ loggedIn: false,
+ loginState: "unknown",
+ needsConnection: false,
+ setSubscriptionOn: () => {},
+ },
+ "cloud",
+ ),
+ ).toBe(expected);
+ },
+ );
+
it.each([
[
"unknown status while loading is not treated as signed out",
diff --git a/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts b/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts
index 99c7aceeec8c..45bf53b26058 100644
--- a/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts
+++ b/products/desktop/packages/ui/src/features/settings/adapterSubscription.ts
@@ -2,6 +2,7 @@ import { useHostTRPC } from "@posthog/host-router/react";
import {
type Adapter,
ANALYTICS_EVENTS,
+ CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG,
CLAUDE_OWN_SUBSCRIPTION_FLAG,
CODEX_OWN_SUBSCRIPTION_FLAG,
type ModelAccess,
@@ -80,6 +81,11 @@ export function subscriptionModelAccess(
subscription: AdapterSubscription,
workspaceMode: WorkspaceModeForAccess,
): ModelAccess {
+ if (workspaceMode === "cloud") {
+ return subscription.cloudSubscriptionOn
+ ? "own-subscription"
+ : "posthog-gateway";
+ }
return effectiveModelAccess({
flagEnabled: subscription.flagEnabled,
subscriptionOn: subscription.subscriptionOn,
@@ -107,6 +113,18 @@ export function applyModelAccess(
registerAdapterSubscription(adapter, { access: next, connected });
}
+export function setClaudeCloudSubscriptionOn(next: boolean): void {
+ const state = useSettingsStore.getState();
+ const previous = state.claudeCloudSubscriptionOn;
+ if (previous === next) return;
+ state.setClaudeCloudSubscriptionOn(next);
+ track(ANALYTICS_EVENTS.SETTING_CHANGED, {
+ setting_name: "claude_cloud_subscription_on",
+ old_value: previous,
+ new_value: next,
+ });
+}
+
export async function registerSubscriptionAtBoot(
adapter: Adapter,
fetchStatus: () => Promise<SubscriptionStatus>,
@@ -142,6 +160,9 @@ function settingsHydrated(): Promise<void> {
}
export interface AdapterSubscription {
+ cloudFlagEnabled?: boolean;
+ cloudSubscriptionOn?: boolean;
+ setCloudSubscriptionOn?: (on: boolean) => void;
flagEnabled: boolean;
subscriptionOn: boolean;
status: SubscriptionStatus | undefined;
@@ -153,6 +174,10 @@ export interface AdapterSubscription {
export function useAdapterSubscription(adapter: Adapter): AdapterSubscription {
const spec = SPECS[adapter];
+ const cloudFlagEnabled = useFeatureFlag(CLAUDE_OWN_SUBSCRIPTION_CLOUD_FLAG);
+ const cloudSubscriptionOn = useSettingsStore(
+ (state) => state.claudeCloudSubscriptionOn,
+ );
const flagEnabled = useFeatureFlag(spec.flag) || import.meta.env.DEV;
const modelAccess = useSettingsStore(spec.readAccess);
const { localWorkspaces } = useHostCapabilities();
@@ -174,6 +199,10 @@ export function useAdapterSubscription(adapter: Adapter): AdapterSubscription {
const loginState = status?.loginState ?? "unknown";
return {
+ cloudFlagEnabled:
+ adapter === "claude" && localWorkspaces && cloudFlagEnabled,
+ cloudSubscriptionOn: adapter === "claude" && cloudSubscriptionOn,
+ setCloudSubscriptionOn: setClaudeCloudSubscriptionOn,
flagEnabled,
subscriptionOn,
status,
diff --git a/products/desktop/packages/ui/src/features/settings/claudeSubscriptionTokenSettings.ts b/products/desktop/packages/ui/src/features/settings/claudeSubscriptionTokenSettings.ts
new file mode 100644
index 000000000000..22713a96c8e2
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/claudeSubscriptionTokenSettings.ts
@@ -0,0 +1,20 @@
+import type { ClaudeSubscriptionTokenStore } from "@posthog/core/cloud-task/identifiers";
+
+export type ClaudeSubscriptionTokenSettings = Pick<
+ ClaudeSubscriptionTokenStore,
+ "has" | "save" | "clear"
+>;
+
+export const CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS = Symbol.for(
+ "posthog.ui.claudeSubscriptionTokenSettings",
+);
+
+export const claudeSubscriptionTokenQueryKey = [
+ "claudeSubscriptionToken",
+ "has",
+] as const;
+
+export function isValidClaudeSetupToken(value: string): boolean {
+ const token = value.trim();
+ return /^sk-ant-oat01-\S{29,}$/.test(token) && token.length <= 4096;
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx
index 94be9af1dd40..8b68b31b43f8 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeAuthTerminalDialog.tsx
@@ -15,7 +15,7 @@ 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";
+export type ClaudeAuthAction = "login" | "logout" | "setup-token";
interface ClaudeAuthTerminalDialogProps {
action: ClaudeAuthAction;
@@ -29,9 +29,17 @@ const SURFACE = {
} as const;
const COPY = {
+ "setup-token": {
+ title: "Create a Claude token",
+ lead: "Follow the steps in this terminal. Copy the token. Close this window, then paste the token into Cloud tasks.",
+ command: "claude setup-token",
+ ok: "Copy the token. Close this window, then paste the token into Cloud tasks.",
+ failed:
+ "Token setup did not finish. Read the terminal output, then try again.",
+ },
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.",
+ lead: "Claude opens your browser. If it asks for a code, paste it in this 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.",
@@ -67,8 +75,12 @@ export function ClaudeAuthTerminalDialog({
}: ClaudeAuthTerminalDialogProps): ReactElement {
const hostTRPC = useHostTRPC();
const isDarkMode = useThemeStore((state) => state.isDarkMode);
- const [started, setStarted] = useState(action === "login");
- const { data: terminal } = useQuery({
+ const [started, setStarted] = useState(action !== "logout");
+ const {
+ data: terminal,
+ isPending: terminalPending,
+ isError: terminalError,
+ } = useQuery({
...hostTRPC.agent.claudeAuthTerminal.queryOptions({ action }),
enabled: started,
});
@@ -76,24 +88,30 @@ export function ClaudeAuthTerminalDialog({
() => `claude-auth-${action}-${secureRandomString(7)}`,
);
const [stopped, setStopped] = useState(false);
+ const [exitCode, setExitCode] = useState<number | undefined>();
const statusQuery = useQuery({
...hostTRPC.agent.claudeSubscriptionStatus.queryOptions(),
- enabled: stopped,
+ enabled: stopped && action !== "setup-token",
});
const loggedIn = statusQuery.data?.loginState === "logged-in";
const statusKnown = statusQuery.data?.loginState !== undefined;
const verified = ((): boolean | undefined => {
+ if (action === "setup-token") return stopped ? exitCode === 0 : undefined;
+ if (statusQuery.isError) return false;
if (!stopped || statusQuery.isFetching || !statusKnown) {
return undefined;
}
- return action === "login" ? loggedIn : !loggedIn;
+ return action === "login"
+ ? loggedIn
+ : statusQuery.data?.loginState === "logged-out";
})();
const copy = COPY[action];
const surface = isDarkMode ? SURFACE.dark : SURFACE.light;
const status = ((): Status => {
+ if (terminalError) return "failed";
if (!stopped) return "running";
if (verified === undefined) return "checking";
return verified ? "done" : "failed";
@@ -101,15 +119,22 @@ export function ClaudeAuthTerminalDialog({
const hint = ((): string => {
if (!started) return "Nothing changes until you select Log out.";
+ if (terminalError)
+ return "Could not open the terminal. Close this window and try again.";
+ if (terminalPending) return "Opening the terminal.";
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 handleExit = useCallback(
+ (code?: number) => {
+ setExitCode(code);
+ setStopped(true);
+ onFinished();
+ },
+ [onFinished],
+ );
const handleClose = useCallback(() => {
destroyTerminalSession(sessionId);
@@ -133,6 +158,16 @@ export function ClaudeAuthTerminalDialog({
{copy.lead}
</p>
+ {started && terminalPending ? (
+ <output className="text-muted-foreground text-xs">
+ Opening the terminal…
+ </output>
+ ) : null}
+ {started && terminalError ? (
+ <span role="alert" className="text-xs">
+ Could not open the terminal. Close this window and try again.
+ </span>
+ ) : null}
{started && terminal ? (
<div
className="overflow-hidden rounded-(--radius-3) border border-(--gray-6) shadow-sm"
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.stories.tsx
new file mode 100644
index 000000000000..3dc564d69dca
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.stories.tsx
@@ -0,0 +1,64 @@
+import type { ServiceContainer } from "@posthog/di/container";
+import { ServiceProvider } from "@posthog/di/react";
+import {
+ CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ type ClaudeSubscriptionTokenSettings,
+} from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { useMemo } from "react";
+import { ClaudeCloudTokenSection } from "./ClaudeCloudTokenSection";
+
+const meta: Meta<typeof ClaudeCloudTokenSection> = {
+ title: "Settings/ClaudeCloudTokenSection",
+ component: ClaudeCloudTokenSection,
+ args: { cloudSubscriptionOn: false, onCreateToken: () => {} },
+ decorators: [
+ (Story, context) => {
+ const { container, queryClient } = useMemo(() => {
+ let saved = context.parameters.tokenSaved === true;
+ const tokenSettings: ClaudeSubscriptionTokenSettings = {
+ has: async () => {
+ if (context.parameters.tokenError)
+ throw new Error("Unlock your system key store and try again.");
+ return saved;
+ },
+ save: async () => {
+ saved = true;
+ },
+ clear: async () => {
+ saved = false;
+ },
+ };
+ const container: ServiceContainer = {
+ get: () => tokenSettings,
+ getAll: () => [],
+ isBound: (token) => token === CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ bind: () => {
+ throw new Error("Story services are fixed");
+ },
+ };
+ return { container, queryClient: new QueryClient() };
+ }, [context.parameters.tokenSaved, context.parameters.tokenError]);
+ return (
+ <ServiceProvider container={container}>
+ <QueryClientProvider client={queryClient}>
+ <div className="mx-auto my-8 max-w-2xl px-4">
+ <Story />
+ </div>
+ </QueryClientProvider>
+ </ServiceProvider>
+ );
+ },
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof ClaudeCloudTokenSection>;
+
+export const NoToken: Story = {};
+export const StorageError: Story = { parameters: { tokenError: true } };
+export const TokenSaved: Story = {
+ args: { cloudSubscriptionOn: true },
+ parameters: { tokenSaved: true },
+};
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.test.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.test.tsx
new file mode 100644
index 000000000000..2bb088eef49a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.test.tsx
@@ -0,0 +1,190 @@
+import type { ServiceContainer } from "@posthog/di/container";
+import { ServiceProvider } from "@posthog/di/react";
+import { ANALYTICS_EVENTS } from "@posthog/shared";
+import { CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS } from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { tokenStore, track, setClaudeCloudSubscriptionOn, toast } = vi.hoisted(
+ () => ({
+ tokenStore: {
+ save: vi.fn(),
+ clear: vi.fn(),
+ has: vi.fn(),
+ },
+ track: vi.fn(),
+ setClaudeCloudSubscriptionOn: vi.fn(),
+ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
+ }),
+);
+
+vi.mock("@posthog/ui/features/settings/settingsStore", () => ({
+ useSettingsStore: (selector: (s: unknown) => unknown) =>
+ selector({ setClaudeCloudSubscriptionOn }),
+}));
+
+vi.mock("@posthog/ui/primitives/toast", () => ({ toast }));
+
+vi.mock("@posthog/ui/shell/analytics", () => ({ track }));
+
+import { ClaudeCloudTokenSection } from "./ClaudeCloudTokenSection";
+
+const onCreateToken = vi.fn();
+
+const VALID_TOKEN = "sk-ant-oat01-fake-test-token-00000000000000";
+
+function renderSection(cloudSubscriptionOn = false): ReturnType<typeof render> {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const container: ServiceContainer = {
+ get: () => tokenStore,
+ getAll: () => [],
+ isBound: (token) => token === CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ bind: () => {
+ throw new Error("Test services are fixed");
+ },
+ };
+ return render(
+ <ServiceProvider container={container}>
+ <QueryClientProvider client={queryClient}>
+ <ClaudeCloudTokenSection
+ cloudSubscriptionOn={cloudSubscriptionOn}
+ onCreateToken={onCreateToken}
+ />
+ </QueryClientProvider>
+ </ServiceProvider>,
+ );
+}
+
+describe("ClaudeCloudTokenSection", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ tokenStore.has.mockResolvedValue(false);
+ });
+
+ it("shows the validation message and does not save a malformed token", async () => {
+ const user = userEvent.setup();
+ renderSection();
+
+ const input = await screen.findByLabelText("Claude setup token");
+ await user.type(input, "not-a-claude-token");
+ await user.click(screen.getByRole("button", { name: "Save token" }));
+
+ const error = await screen.findByRole("alert");
+ expect(error).toHaveTextContent(
+ "Paste the full token from the terminal. It starts with sk-ant-oat01-.",
+ );
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ expect(input).toHaveAttribute("aria-describedby", error.id);
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(tokenStore.save).not.toHaveBeenCalled();
+ await user.clear(input);
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ expect(input).not.toHaveAttribute("aria-invalid");
+ });
+
+ it.each([
+ { replacing: false, pasted: VALID_TOKEN },
+ { replacing: true, pasted: VALID_TOKEN },
+ {
+ replacing: false,
+ pasted: " sk-ant-oat01-fake-test-\n token-00000000000000\n",
+ },
+ {
+ replacing: true,
+ pasted: "\tsk-ant-oat01-fake-\r\n test-token-\r\n 00000000000000 ",
+ },
+ ])(
+ "saves a pasted token without clearing the previous one (case %#)",
+ async ({ replacing, pasted }) => {
+ const user = userEvent.setup();
+ tokenStore.save.mockResolvedValue(undefined);
+ tokenStore.has.mockResolvedValue(replacing);
+ renderSection();
+ if (replacing) {
+ await user.click(
+ await screen.findByRole("button", { name: "Replace token" }),
+ );
+ }
+
+ const input = await screen.findByLabelText("Claude setup token");
+ await user.click(screen.getByRole("button", { name: "Create token" }));
+ expect(onCreateToken).toHaveBeenCalledTimes(1);
+ await user.click(input);
+ await user.paste(pasted);
+ await user.click(screen.getByRole("button", { name: "Save token" }));
+
+ expect(tokenStore.save).toHaveBeenCalledTimes(1);
+ expect(tokenStore.save).toHaveBeenCalledWith(VALID_TOKEN);
+ expect(tokenStore.clear).not.toHaveBeenCalled();
+ expect(track).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_SAVED,
+ );
+ expect(await screen.findByText("Token saved")).toBeInTheDocument();
+ },
+ );
+
+ it("shows the saved state and removes the token on demand", async () => {
+ const user = userEvent.setup();
+ tokenStore.has.mockResolvedValue(true);
+ tokenStore.clear.mockResolvedValue(undefined);
+ renderSection();
+
+ expect(await screen.findByText("Token saved")).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Replace token" }));
+ await user.type(screen.getByLabelText("Claude setup token"), "draft-token");
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(screen.getByText("Token saved")).toBeInTheDocument();
+ expect(tokenStore.save).not.toHaveBeenCalled();
+ expect(tokenStore.clear).not.toHaveBeenCalled();
+ await user.click(screen.getByRole("button", { name: "Remove token" }));
+ expect(tokenStore.clear).not.toHaveBeenCalled();
+ await user.click(screen.getByRole("button", { name: "Confirm removal" }));
+ expect(tokenStore.clear).toHaveBeenCalledTimes(1);
+ expect(track).toHaveBeenCalledWith(
+ ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_REMOVED,
+ );
+ });
+ it.each(["Replace token", "Remove token"])(
+ "permits %s after decryption fails",
+ async (action) => {
+ const user = userEvent.setup();
+ tokenStore.has.mockRejectedValue(
+ new Error("Unlock your system key store and try again."),
+ );
+ renderSection(true);
+ await screen.findByRole("alert");
+ await user.click(screen.getByRole("button", { name: action }));
+ if (action === "Remove token") {
+ await user.click(
+ screen.getByRole("button", { name: "Confirm removal" }),
+ );
+ expect(tokenStore.clear).toHaveBeenCalledOnce();
+ } else {
+ expect(screen.getByLabelText("Claude setup token")).toBeInTheDocument();
+ }
+ },
+ );
+
+ it("shows a retryable error instead of treating an unreadable token as missing", async () => {
+ const user = userEvent.setup();
+ tokenStore.has.mockRejectedValueOnce(
+ new Error("Unlock your system key store and try again."),
+ );
+ renderSection(true);
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Unlock your system key store and try again.",
+ );
+ expect(
+ screen.queryByLabelText("Claude setup token"),
+ ).not.toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Try again" }));
+ expect(
+ await screen.findByLabelText("Claude setup token"),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsx
new file mode 100644
index 000000000000..68f63a823451
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeCloudTokenSection.tsx
@@ -0,0 +1,259 @@
+import { useServiceOptional } from "@posthog/di/react";
+import { Button, Input, Switch } from "@posthog/quill";
+import { ANALYTICS_EVENTS } from "@posthog/shared";
+import { setClaudeCloudSubscriptionOn as setCloudSubscriptionOn } from "@posthog/ui/features/settings/adapterSubscription";
+import {
+ CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ type ClaudeSubscriptionTokenSettings,
+ claudeSubscriptionTokenQueryKey,
+ isValidClaudeSetupToken,
+} from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
+import { toast } from "@posthog/ui/primitives/toast";
+import { track } from "@posthog/ui/shell/analytics";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { type ReactElement, useId, useState } from "react";
+
+interface ClaudeCloudTokenSectionProps {
+ cloudSubscriptionOn: boolean;
+ onCreateToken: () => void;
+}
+
+export function ClaudeCloudTokenSection({
+ cloudSubscriptionOn,
+ onCreateToken,
+}: ClaudeCloudTokenSectionProps): ReactElement | null {
+ const tokenStore = useServiceOptional<ClaudeSubscriptionTokenSettings>(
+ CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ );
+ const queryClient = useQueryClient();
+ const tokenQuery = useQuery({
+ queryKey: claudeSubscriptionTokenQueryKey,
+ queryFn: () => tokenStore?.has() ?? Promise.resolve(false),
+ enabled: !!tokenStore,
+ retry: false,
+ });
+ const [tokenDraft, setTokenDraft] = useState("");
+ const [validationError, setValidationError] = useState<string | null>(null);
+ const validationErrorId = useId();
+ const [pendingAction, setPendingAction] = useState<"save" | "remove" | null>(
+ null,
+ );
+ const [confirmRemoval, setConfirmRemoval] = useState(false);
+ const [replacingToken, setReplacingToken] = useState(false);
+
+ if (!tokenStore) return null;
+
+ const saveToken = async (): Promise<void> => {
+ if (pendingAction) return;
+ const token = tokenDraft.trim();
+ if (!isValidClaudeSetupToken(token)) {
+ setValidationError(
+ "Paste the full token from the terminal. It starts with sk-ant-oat01-.",
+ );
+ return;
+ }
+ setValidationError(null);
+ setPendingAction("save");
+ try {
+ await tokenStore.save(token);
+ setTokenDraft("");
+ setReplacingToken(false);
+ queryClient.setQueryData(claudeSubscriptionTokenQueryKey, true);
+ track(ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_SAVED);
+ toast.success("Token saved");
+ } catch (error) {
+ toast.error("Cannot save the token.", {
+ description:
+ error instanceof Error
+ ? error.message
+ : "Check your system key store and try again.",
+ });
+ } finally {
+ setPendingAction(null);
+ }
+ };
+
+ const removeToken = async (): Promise<void> => {
+ if (pendingAction) return;
+ setPendingAction("remove");
+ try {
+ await tokenStore.clear();
+ queryClient.setQueryData(claudeSubscriptionTokenQueryKey, false);
+ setConfirmRemoval(false);
+ track(ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_REMOVED);
+ toast.success("Token removed");
+ } catch {
+ toast.error("Cannot remove the token. Try again.");
+ } finally {
+ setPendingAction(null);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium text-xs">Cloud tasks</span>
+ <Switch
+ size="sm"
+ aria-label="Use your Claude plan for cloud tasks"
+ data-attr="claude-cloud-subscription-toggle"
+ checked={cloudSubscriptionOn}
+ disabled={!!pendingAction}
+ onCheckedChange={(checked) => {
+ const next = checked === true;
+ if (next === cloudSubscriptionOn) return;
+ setCloudSubscriptionOn(next);
+ }}
+ />
+ </div>
+ <span className="text-muted-foreground text-xs">
+ Keep Desktop open to start or resume. Compute is billed separately.
+ </span>
+ {tokenQuery.isPending ? (
+ <output className="text-muted-foreground text-xs">
+ Checking token…
+ </output>
+ ) : (tokenQuery.data || tokenQuery.isError) && !replacingToken ? (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span
+ role={tokenQuery.isError ? "alert" : undefined}
+ className="text-muted-foreground text-xs"
+ >
+ {confirmRemoval
+ ? "Remove the saved token?"
+ : tokenQuery.isError
+ ? tokenQuery.error.message
+ : "Token saved"}
+ </span>
+ {confirmRemoval ? (
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!!pendingAction}
+ onClick={() => setConfirmRemoval(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!!pendingAction}
+ loading={pendingAction === "remove"}
+ data-attr="claude-cloud-token-remove"
+ onClick={() => void removeToken()}
+ >
+ Confirm removal
+ </Button>
+ </div>
+ ) : (
+ <div className="flex items-center gap-2">
+ {tokenQuery.isError ? (
+ <Button
+ size="sm"
+ variant="outline"
+ loading={tokenQuery.isFetching}
+ onClick={() => void tokenQuery.refetch()}
+ >
+ Try again
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setReplacingToken(true)}
+ data-attr="claude-cloud-token-replace"
+ >
+ Replace token
+ </Button>
+ <Button
+ type="button"
+ variant="link-muted"
+ size="sm"
+ onClick={() => setConfirmRemoval(true)}
+ >
+ Remove token
+ </Button>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="flex flex-col gap-3 rounded-md border border-border p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-muted-foreground text-xs">
+ Create a token, then paste it below.
+ </span>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onCreateToken}
+ disabled={!!pendingAction}
+ >
+ Create token
+ </Button>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <Input
+ type="password"
+ autoComplete="off"
+ placeholder="Paste your Claude token"
+ aria-label="Claude setup token"
+ aria-invalid={validationError ? true : undefined}
+ aria-describedby={validationError ? validationErrorId : undefined}
+ data-attr="claude-cloud-subscription-token"
+ className="h-7 min-w-40 flex-1 text-xs"
+ value={tokenDraft}
+ onChange={(event) => {
+ setTokenDraft(event.currentTarget.value.replace(/\s/g, ""));
+ setValidationError(null);
+ }}
+ disabled={!!pendingAction}
+ />
+ <Button
+ type="button"
+ variant="primary"
+ size="sm"
+ data-attr="claude-cloud-token-save"
+ onClick={() => void saveToken()}
+ disabled={!tokenDraft.trim() || !!pendingAction}
+ loading={pendingAction === "save"}
+ >
+ Save token
+ </Button>
+ {replacingToken ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={!!pendingAction}
+ onClick={() => {
+ setTokenDraft("");
+ setValidationError(null);
+ setReplacingToken(false);
+ }}
+ >
+ Cancel
+ </Button>
+ ) : null}
+ </div>
+ {validationError ? (
+ <span
+ id={validationErrorId}
+ role="alert"
+ className="text-(--red-11) text-xs"
+ >
+ {validationError}
+ </span>
+ ) : null}
+ <span className="text-muted-foreground text-xs">
+ Protected by your system key store. Used only for your cloud tasks.
+ </span>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx
index 050fbc370040..fd4ce9517a7f 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/ClaudeSubscriptionSettings.tsx
@@ -4,6 +4,7 @@ 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 { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
import { useSettingsPageStore } from "@posthog/ui/features/settings/stores/settingsPageStore";
import { track } from "@posthog/ui/shell/analytics";
import { registerAdapterSubscription } from "@posthog/ui/shell/posthogAnalyticsImpl";
@@ -13,6 +14,7 @@ import {
type ClaudeAuthAction,
ClaudeAuthTerminalDialog,
} from "./ClaudeAuthTerminalDialog";
+import { ClaudeCloudTokenSection } from "./ClaudeCloudTokenSection";
interface ClaudeAccountStatus {
email?: string;
@@ -65,6 +67,10 @@ export function ClaudeSubscriptionSettings(): ReactElement | null {
}
}, []);
+ const cloudSubscriptionOn = useSettingsStore(
+ (state) => state.claudeCloudSubscriptionOn,
+ );
+
const lastKnownLoggedIn = useRef<boolean | null>(null);
useEffect(() => {
if (!settled) return;
@@ -84,7 +90,7 @@ export function ClaudeSubscriptionSettings(): ReactElement | null {
});
}, [settled, loggedIn, subscription.subscriptionOn]);
- if (!subscription.flagEnabled) {
+ if (!subscription.flagEnabled && !subscription.cloudFlagEnabled) {
return null;
}
@@ -92,13 +98,6 @@ export function ClaudeSubscriptionSettings(): ReactElement | null {
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" };
@@ -112,57 +111,67 @@ export function ClaudeSubscriptionSettings(): ReactElement | null {
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}
+ stacked
+ label="Claude subscription"
+ description="Choose where to use your Claude plan. Model use counts toward your plan limits."
>
- <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>
+ <div className="flex flex-col gap-5 pt-2">
+ {subscription.flagEnabled ? (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium text-xs">Local tasks</span>
+ <Switch
+ size="sm"
+ aria-label="Use your Claude plan for local tasks"
+ checked={subscription.subscriptionOn}
+ onCheckedChange={(checked) => {
+ subscription.setSubscriptionOn(checked === true);
+ refreshStatus();
+ }}
+ />
+ </div>
+ <span className="text-muted-foreground text-xs">
+ Use your Claude Code login for local and worktree tasks.
+ </span>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs">
+ <span
+ className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${statusLine.color}`}
+ aria-hidden
+ />
+ <span className="break-words">{statusLine.label}</span>
+ </span>
+ <div className="flex items-center 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>
+ </div>
+ </div>
+ </div>
+ ) : null}
+ {subscription.cloudFlagEnabled ? (
+ <ClaudeCloudTokenSection
+ cloudSubscriptionOn={cloudSubscriptionOn}
+ onCreateToken={() => setAuthAction("setup-token")}
+ />
+ ) : null}
+ </div>
{authAction ? (
<ClaudeAuthTerminalDialog
action={authAction}
diff --git a/products/desktop/packages/ui/src/features/settings/settingsStore.ts b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
index 9bf05ee08226..ea7f700fcd4b 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsStore.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsStore.ts
@@ -290,6 +290,7 @@ export interface SettingsStore {
rtkEnabledCloud: boolean;
codexModelAccess: ModelAccess;
claudeModelAccess: ModelAccess;
+ claudeCloudSubscriptionOn: boolean;
setAllowBypassPermissions: (enabled: boolean) => void;
setPreventSleepWhileRunning: (enabled: boolean) => void;
setDebugLogsCloudRuns: (enabled: boolean) => void;
@@ -298,6 +299,7 @@ export interface SettingsStore {
setRtkEnabledCloud: (enabled: boolean) => void;
setCodexModelAccess: (mode: ModelAccess) => void;
setClaudeModelAccess: (mode: ModelAccess) => void;
+ setClaudeCloudSubscriptionOn: (enabled: boolean) => void;
// Terminal
terminalFont: TerminalFont;
@@ -560,6 +562,7 @@ export const useSettingsStore = create<SettingsStore>()(
rtkEnabledCloud: true,
codexModelAccess: "posthog-gateway",
claudeModelAccess: "posthog-gateway",
+ claudeCloudSubscriptionOn: false,
setAllowBypassPermissions: (enabled) =>
set({ allowBypassPermissions: enabled }),
setPreventSleepWhileRunning: (enabled) =>
@@ -571,6 +574,8 @@ export const useSettingsStore = create<SettingsStore>()(
setRtkEnabledCloud: (enabled) => set({ rtkEnabledCloud: enabled }),
setCodexModelAccess: (mode) => set({ codexModelAccess: mode }),
setClaudeModelAccess: (mode) => set({ claudeModelAccess: mode }),
+ setClaudeCloudSubscriptionOn: (enabled) =>
+ set({ claudeCloudSubscriptionOn: enabled }),
// Terminal
terminalFont: "berkeley-mono",
@@ -723,6 +728,7 @@ export const useSettingsStore = create<SettingsStore>()(
rtkEnabledCloud: state.rtkEnabledCloud,
codexModelAccess: state.codexModelAccess,
claudeModelAccess: state.claudeModelAccess,
+ claudeCloudSubscriptionOn: state.claudeCloudSubscriptionOn,
// Terminal
terminalFont: state.terminalFont,
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 fa700c7e073e..6fc202ae1dd7 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
@@ -928,6 +928,7 @@ export function TaskInput({
: effectiveReasoningLevel;
useWarmTask({
+ claudeModelAccess: adapter === "claude" ? composerModelAccess : undefined,
workspaceMode,
selectedRepository: selectedCloudRepository,
repositories: repoOptional ? taskRepositories : undefined,
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsx
index dae66e3b2420..d3423a75f1ae 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useTaskCreation.test.tsx
@@ -19,9 +19,14 @@ const createTaskMock = vi.hoisted(() => vi.fn());
const invalidateTasksMock = vi.hoisted(() => vi.fn());
const openTaskMock = vi.hoisted(() => vi.fn());
const trackMock = vi.hoisted(() => vi.fn());
+const cloudSubscription = vi.hoisted(() => ({
+ cloudSubscriptionOn: false,
+ cloudFlagEnabled: true,
+}));
vi.mock("@posthog/di/react", () => ({
useService: () => ({ createTask: createTaskMock }),
+ useServiceOptional: () => undefined,
}));
vi.mock("@posthog/host-router/react", () => ({
useHostTRPC: () => ({
@@ -47,11 +52,13 @@ vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
}));
vi.mock("@posthog/ui/features/settings/adapterSubscription", () => ({
useAdapterSubscription: () => ({
+ ...cloudSubscription,
flagEnabled: false,
loginState: "logged-out",
subscriptionOn: false,
}),
- subscriptionModelAccess: () => undefined,
+ subscriptionModelAccess: () =>
+ cloudSubscription.cloudSubscriptionOn ? "own-subscription" : undefined,
}));
vi.mock("@posthog/ui/features/tasks/useTaskCrudMutations", () => ({
useCreateTask: () => ({ invalidateTasks: invalidateTasksMock }),
@@ -140,6 +147,7 @@ function wrapper({ children }: { children: ReactNode }) {
function renderTaskCreation(
content: EditorContent,
workspaceMode: "local" | "cloud" = "local",
+ runtime: "acp" | "pi" = "acp",
) {
return renderHook(
() =>
@@ -149,6 +157,8 @@ function renderTaskCreation(
selectedDirectory: "/repo",
allowNoRepo: true,
workspaceMode,
+ runtime,
+ adapter: "claude",
editorIsEmpty: false,
}),
{ wrapper },
@@ -159,10 +169,36 @@ describe("useTaskCreation prompt records", () => {
beforeEach(() => {
vi.clearAllMocks();
createTaskMock.mockReset();
+ cloudSubscription.cloudSubscriptionOn = false;
usePendingTaskPromptStore.setState({ byKey: {}, _hasHydrated: true });
useTaskInputPrefillStore.setState({ prefill: {} });
});
+ it("omits subscription billing when Pi is selected", async () => {
+ cloudSubscription.cloudSubscriptionOn = true;
+ createTaskMock.mockResolvedValueOnce({
+ success: true,
+ data: { task: fakeTask(), workspace: null },
+ });
+ const { result } = renderTaskCreation(
+ textToContent("Check the build"),
+ "cloud",
+ "pi",
+ );
+
+ await act(async () => {
+ expect(await result.current.handleSubmit()).toBe(true);
+ });
+
+ expect(createTaskMock).toHaveBeenCalledOnce();
+ expect(createTaskMock.mock.calls[0][0]).toMatchObject({
+ runtime: "pi",
+ claudeCloudModelAccess: undefined,
+ claudeModelAccess: undefined,
+ codexModelAccess: undefined,
+ });
+ });
+
it.each(["local", "cloud"] as const)(
"keeps the submitted prompt visible after successful %s creation until the chat takes over",
async (workspaceMode) => {
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 aec35d5e5b04..3a62a832fce5 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
@@ -9,7 +9,7 @@ import {
type TaskService,
} from "@posthog/core/task-detail/taskService";
import { pendingPromptRecordFromContent } from "@posthog/core/tasks/pendingPrompts";
-import { useService } from "@posthog/di/react";
+import { useService, useServiceOptional } from "@posthog/di/react";
import type { HostTrpcClient } from "@posthog/host-router/client";
import { useHostTRPC, useHostTRPCClient } from "@posthog/host-router/react";
import {
@@ -30,6 +30,10 @@ import {
subscriptionModelAccess,
useAdapterSubscription,
} from "@posthog/ui/features/settings/adapterSubscription";
+import {
+ CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ type ClaudeSubscriptionTokenSettings,
+} from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
import { settleFailedPromptRecord } from "@posthog/ui/features/task-detail/pendingPromptActions";
import { useTaskInputPrefillStore } from "@posthog/ui/features/task-detail/stores/taskInputPrefillStore";
import { openTask } from "@posthog/ui/router/useOpenTask";
@@ -256,6 +260,9 @@ export function useTaskCreation({
PROJECT_BLUEBIRD_FLAG,
import.meta.env.DEV,
);
+ const claudeTokenStore = useServiceOptional<ClaudeSubscriptionTokenSettings>(
+ CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS,
+ );
const { personalChannel } = useTaskChannels({ enabled: bluebirdEnabled });
const hasRequiredPath = allowNoRepo
@@ -303,6 +310,35 @@ export function useTaskCreation({
setIsCreatingTask(true);
try {
+ if (
+ workspaceMode === "cloud" &&
+ runtime !== "pi" &&
+ adapter === "claude" &&
+ claudeSubscription.cloudSubscriptionOn
+ ) {
+ if (!claudeSubscription.cloudFlagEnabled) {
+ toast.error("Claude plan billing is unavailable for cloud tasks", {
+ description:
+ "Try again later, or select PostHog in the Billing menu.",
+ });
+ return false;
+ }
+ try {
+ if (!claudeTokenStore || !(await claudeTokenStore.has())) {
+ toast.error("Add your Claude token before starting this task", {
+ description:
+ "Open Settings > Harness and save a token for cloud tasks.",
+ });
+ return false;
+ }
+ } catch {
+ toast.error("Cannot check your Claude token", {
+ description: "Open Settings > Harness and try again.",
+ });
+ return false;
+ }
+ }
+
if (workspaceMode === "cloud" && !(await assertCloudUsageAvailable())) {
return false;
}
@@ -433,6 +469,8 @@ export function useTaskCreation({
adapter,
codexModelAccess,
claudeModelAccess,
+ claudeCloudModelAccess:
+ workspaceMode === "cloud" ? claudeModelAccess : undefined,
runtime,
model,
reasoningLevel,
@@ -669,6 +707,7 @@ export function useTaskCreation({
claudeSubscription.subscriptionOn,
claudeSubscription,
codexSubscription,
+ claudeTokenStore,
],
);
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.test.tsx
index 9f279bbe9b7a..f254da2ea2bb 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.test.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.test.tsx
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mockClient = vi.hoisted(() => ({
warmTask: vi.fn(),
+ cancelTaskRun: vi.fn().mockResolvedValue({}),
}));
const flagState = vi.hoisted(() => ({ enabled: true }));
@@ -22,6 +23,7 @@ import { takeWarmTaskLease } from "./warmTaskLease";
interface Props {
workspaceMode: WorkspaceMode;
+ claudeModelAccess?: string;
selectedRepository?: string | null;
repositories?: string[];
githubIntegrationId?: number;
@@ -71,6 +73,42 @@ describe("useWarmTask", () => {
});
}
+ it.each([false, true])(
+ "releases an unused warm run and permits another warm request (late: %s)",
+ async (late) => {
+ let finishWarm:
+ | ((value: { task_id: string; run_id: string }) => void)
+ | undefined;
+ if (late)
+ mockClient.warmTask.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishWarm = resolve;
+ }),
+ );
+ const { rerender } = renderHook((props: Props) => useWarmTask(props), {
+ initialProps: cloudTyping,
+ });
+ await flushDebounce();
+ rerender({ ...cloudTyping, claudeModelAccess: "own-subscription" });
+ if (finishWarm)
+ await act(async () => {
+ finishWarm?.({ task_id: "task-1", run_id: "run-1" });
+ });
+ await flushDebounce();
+ expect(mockClient.warmTask).toHaveBeenCalledTimes(1);
+ expect(mockClient.cancelTaskRun).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ undefined,
+ true,
+ );
+ rerender(cloudTyping);
+ await flushDebounce();
+ expect(mockClient.warmTask).toHaveBeenCalledTimes(2);
+ },
+ );
+
it("fires a debounced warm when cloud + repo + typing", async () => {
renderHook((props: Props) => useWarmTask(props), {
initialProps: cloudTyping,
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts
index ff3b415166e4..db2947a8e6ed 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useWarmTask.ts
@@ -6,7 +6,11 @@ import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authCl
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { useEffect, useMemo, useRef } from "react";
import { logger } from "../../../shell/logger";
-import { buildWarmTaskLeaseKey, rememberWarmTaskLease } from "./warmTaskLease";
+import {
+ buildWarmTaskLeaseKey,
+ forgetWarmTaskLease,
+ rememberWarmTaskLease,
+} from "./warmTaskLease";
const log = logger.scope("warm-task");
@@ -14,6 +18,7 @@ const WARM_DEBOUNCE_MS = 600;
interface UseWarmTaskOptions {
workspaceMode: WorkspaceMode;
+ claudeModelAccess?: string;
selectedRepository?: string | null;
repositories?: string[];
githubIntegrationId?: number;
@@ -29,6 +34,7 @@ interface UseWarmTaskOptions {
export function useWarmTask({
workspaceMode,
+ claudeModelAccess,
selectedRepository,
repositories,
githubIntegrationId,
@@ -47,6 +53,7 @@ export function useWarmTask({
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastWarmedKeyRef = useRef<string | null>(null);
const latestKeyRef = useRef<string | null>(null);
+ const leaseRef = useRef<{ taskId: string; runId: string } | null>(null);
const isCloud = workspaceMode === "cloud";
const normalizedBranch = branch ?? null;
@@ -72,6 +79,7 @@ export function useWarmTask({
: null;
const eligible =
enabled &&
+ claudeModelAccess !== "own-subscription" &&
isCloud &&
!!client &&
(allowNoRepo || (!!warmRepository && warmGithubIntegrationId !== null)) &&
@@ -91,7 +99,7 @@ export function useWarmTask({
})}`
: null;
useEffect(() => {
- latestKeyRef.current = key;
+ latestKeyRef.current = eligible ? key : null;
const clearDebounce = (): void => {
if (debounceRef.current) {
@@ -102,6 +110,19 @@ export function useWarmTask({
if (!eligible || !key || !client) {
clearDebounce();
+ if (
+ client &&
+ leaseRef.current &&
+ claudeModelAccess === "own-subscription"
+ ) {
+ const lease = leaseRef.current;
+ forgetWarmTaskLease(lease);
+ leaseRef.current = null;
+ lastWarmedKeyRef.current = null;
+ void client
+ .cancelTaskRun(lease.taskId, lease.runId, undefined, true)
+ .catch((error) => log.warn("Could not release warm task", { error }));
+ }
return;
}
if (lastWarmedKeyRef.current === key || debounceRef.current) {
@@ -136,8 +157,21 @@ export function useWarmTask({
: {}),
...(warmCustomImageId ? { custom_image_id: warmCustomImageId } : {}),
})
- .then((warm) => {
+ .then(async (warm) => {
+ if (warm && latestKeyRef.current !== key) {
+ if (lastWarmedKeyRef.current === key) {
+ lastWarmedKeyRef.current = null;
+ }
+ await client.cancelTaskRun(
+ warm.task_id,
+ warm.run_id,
+ undefined,
+ true,
+ );
+ return;
+ }
if (warm && latestKeyRef.current === key) {
+ leaseRef.current = { taskId: warm.task_id, runId: warm.run_id };
rememberWarmTaskLease(
buildWarmTaskLeaseKey({
repository,
@@ -164,6 +198,7 @@ export function useWarmTask({
return clearDebounce;
}, [
eligible,
+ claudeModelAccess,
key,
client,
warmRepository,
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/warmTaskLease.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/warmTaskLease.ts
index 7784b440d758..2fb21bdb085f 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/warmTaskLease.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/warmTaskLease.ts
@@ -33,6 +33,14 @@ export function rememberWarmTaskLease(key: string, lease: WarmTaskLease): void {
currentLease = { key, lease };
}
+export function forgetWarmTaskLease(lease: WarmTaskLease): void {
+ if (
+ currentLease?.lease.taskId === lease.taskId &&
+ currentLease.lease.runId === lease.runId
+ )
+ currentLease = null;
+}
+
export function takeWarmTaskLease(
parts: WarmTaskLeaseKeyParts,
): WarmTaskLease | null {
diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts
index 63a424098f49..2e47635f237b 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
@@ -318,6 +318,7 @@ describe("AgentService", () => {
it.each([
{ action: "login" as const, expected: "'auth' 'login'" },
{ action: "logout" as const, expected: "'auth' 'logout'" },
+ { action: "setup-token" as const, expected: "'setup-token'" },
])(
"describes the claude auth $action terminal",
async ({ action, expected }) => {
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 ea6c3c80643a..391a7b833655 100644
--- a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/agent/schemas.ts
@@ -273,7 +273,7 @@ export type ClaudeSubscriptionStatus = z.infer<
>;
export const claudeAuthTerminalInput = z.object({
- action: z.enum(["login", "logout"]),
+ action: z.enum(["login", "logout", "setup-token"]),
});
export const claudeAuthTerminalOutput = z.object({
diff --git a/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts b/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts
index c89fe23d325e..9ad47b7bd6c3 100644
--- a/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts
@@ -58,6 +58,7 @@ function initializeGitRepo(dir: string): void {
});
execSync("git config user.name 'Test'", { cwd: dir, stdio: "pipe" });
execSync("git config commit.gpgsign false", { cwd: dir, stdio: "pipe" });
+ execSync("git config tag.gpgsign false", { cwd: dir, stdio: "pipe" });
writeFileSync(path.join(dir, "README.md"), "# Test Repo");
execSync("git add . && git commit -m 'Initial commit'", {
cwd: dir,
@@ -109,7 +110,10 @@ async function withTestContext(
fn: (ctx: TestContext) => Promise<void>,
): Promise<void> {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "archive-int-"));
- const repoPath = await createTempRepo();
+ const repoPath =
+ opts.hasWorkspace === false
+ ? path.join(tempDir, "repo")
+ : await createTempRepo();
const worktreeBasePath = path.join(tempDir, "worktrees");
let gitRepoInitialized = false;
@@ -748,7 +752,7 @@ describe("ArchiveService integration", () => {
}));
it("throws when workspace not found for unarchive", () =>
- withTestContext({}, async (ctx) => {
+ withTestContext({ hasWorkspace: false }, async (ctx) => {
await expect(ctx.service.unarchiveTask("nonexistent")).rejects.toThrow(
"Workspace not found",
);
@@ -839,7 +843,7 @@ describe("ArchiveService integration", () => {
}));
it("throws when workspace not found for delete", () =>
- withTestContext({}, async (ctx) => {
+ withTestContext({ hasWorkspace: false }, async (ctx) => {
await expect(
ctx.service.deleteArchivedTask("nonexistent"),
).rejects.toThrow("Workspace not found");
diff --git a/products/desktop/packages/workspace-server/src/services/claude-subscription/schemas.ts b/products/desktop/packages/workspace-server/src/services/claude-subscription/schemas.ts
new file mode 100644
index 000000000000..269f337d8320
--- /dev/null
+++ b/products/desktop/packages/workspace-server/src/services/claude-subscription/schemas.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+
+export const claudeSubscriptionTokenInput = z.object({
+ token: z
+ .string()
+ .trim()
+ .max(4096)
+ .regex(/^sk-ant-oat01-\S{29,}$/),
+});
diff --git a/products/desktop/packages/workspace-server/src/services/secure-store/identifiers.ts b/products/desktop/packages/workspace-server/src/services/secure-store/identifiers.ts
index 41798437b155..19822533b434 100644
--- a/products/desktop/packages/workspace-server/src/services/secure-store/identifiers.ts
+++ b/products/desktop/packages/workspace-server/src/services/secure-store/identifiers.ts
@@ -6,5 +6,5 @@ export interface ISecureStoreService {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
- clear(): void;
+ clear(): void | Promise<void>;
}
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index e0cd95a902da..d36d451af02a 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -216,6 +216,7 @@ TASK_SIGNALS_CLONING_BLOBLESS_FEATURE_FLAG = "task-signals-cloning-blobless"
# an image rebuild.
RTK_DISABLED_FEATURE_FLAG = "tasks-rtk-disabled"
BENJAMIN_FEATURE_FLAG = "task-cloud-run-benjamin-plus"
+CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-claude-own-subscription-cloud"
# Gates whether long-running process_task runs continue-as-new to bound history/replay cost.
CONTINUE_AS_NEW_FEATURE_FLAG = "tasks-cloud-run-continue-as-new"
PR_BABYSIT_SNAPSHOT_FEATURE_FLAG = "tasks-pr-babysit-snapshot"
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 571c31bfe64d..ad28c48d100f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -13,7 +13,10 @@ from uuid import UUID, uuid4
from django.conf import settings
from django.core import signing
-from django.core.exceptions import ValidationError as DjangoValidationError
+from django.core.exceptions import (
+ PermissionDenied,
+ ValidationError as DjangoValidationError,
+)
from django.db import IntegrityError, transaction
from django.db.models import (
Case,
@@ -88,6 +91,7 @@ from products.tasks.backend.logic.services.network_policy import (
MAX_SANDBOX_ALLOWED_DOMAINS,
normalize_requested_domains,
)
+from products.tasks.backend.logic.services.sandbox import get_sandbox_class_for_sandbox_id
from products.tasks.backend.mentions import resolve_mentioned_user_ids
from products.tasks.backend.models import (
MCP_CREDENTIAL_OWNER_STATE_KEY,
@@ -415,6 +419,8 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset(
"ai_stage",
"auto_publish",
"benjamin_enabled",
+ "claude_model_access",
+ "claude_subscription_user_id",
"context_window",
"custom_image_id",
"fast_mode",
@@ -2255,6 +2261,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"provider",
"model",
"reasoning_effort",
+ "claude_model_access",
+ "claude_subscription_user_id",
"rtk_effective",
"benjamin_effective",
"usage_metrics_recorded",
@@ -3947,6 +3955,10 @@ def signal_task_run_user_message(
"""
from temporalio.service import RPCError, RPCStatusCode # noqa: PLC0415 — keep temporalio off the api import path
+ from products.tasks.backend.exceptions import (
+ ComputeBillingLimitError, # noqa: PLC0415 — keep temporalio off the api import path
+ SandboxNotFoundError,
+ )
from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
signal_task_followup_message,
)
@@ -3954,9 +3966,22 @@ def signal_task_run_user_message(
run = _get_visible_run(run_id, task_id, team_id)
if run is None:
return None
- from products.tasks.backend.exceptions import (
- ComputeBillingLimitError, # noqa: PLC0415 — keep temporalio off the api import path
- )
+ if (run.state or {}).get("claude_model_access") == "own-subscription" and (run.state or {}).get(
+ "claude_subscription_user_id"
+ ) != actor_user_id:
+ raise PermissionDenied("Only the user who started this run can use its Claude plan.")
+ if run.is_terminal or (run.state or {}).get("cancel_requested_at"):
+ if not run.is_terminal:
+ raise RuntimeError("Task run is still stopping. Try again shortly.")
+ sandbox_id = (run.state or {}).get("sandbox_id")
+ if sandbox_id:
+ try:
+ sandbox = get_sandbox_class_for_sandbox_id(sandbox_id).get_by_id(sandbox_id)
+ if sandbox.is_running():
+ raise RuntimeError("Task run is still stopping. Try again shortly.")
+ except SandboxNotFoundError:
+ pass
+ return False
from products.tasks.backend.logic.services.compute_quota import get_compute_quota_denial_reason # noqa: PLC0415
if reason := get_compute_quota_denial_reason(run.task):
@@ -4666,6 +4691,7 @@ def bootstrap_task_run(
"fast_mode": fast_mode,
"rtk_enabled": validated_data.get("rtk_enabled"),
"benjamin_enabled": validated_data.get("benjamin_enabled"),
+ "claude_model_access": validated_data.get("claude_model_access"),
}.items():
if value is not None:
extra_state = extra_state or {}
@@ -6506,7 +6532,7 @@ def _warm_sandbox_selection_is_accessible(
def _idling_warm_run_for_task(task: Task) -> TaskRun | None:
"""The task's latest run iff it is an idling pre-warmed Run (non-terminal, awaiting first message)."""
run = task.latest_run
- if run is None or run.is_terminal:
+ if run is None or run.is_terminal or (run.state or {}).get("cancel_requested_at"):
return None
if not (run.state or {}).get("await_user_message"):
return None
@@ -6930,6 +6956,8 @@ def warm_task_resume_sandbox(
return None
previous_state = parse_run_state(previous_run.state)
+ if previous_state.claude_model_access == "own-subscription":
+ return None
resolved_runtime_adapter = runtime_adapter or previous_state.runtime_adapter
resolved_model = model or previous_state.model
resolved_reasoning_effort = reasoning_effort or previous_state.reasoning_effort
@@ -7122,7 +7150,13 @@ def run_task(
internal=task.internal,
)
+ claude_model_access = validated_data.get("claude_model_access")
+ if claude_model_access is None and previous_state is not None:
+ claude_model_access = previous_state.claude_model_access
+
warm_run = _idling_warm_run_for_task(task)
+ if warm_run is not None and claude_model_access == "own-subscription":
+ warm_run = None
if warm_run is not None:
_warm_retry_message_id(warm_retry_token, warm_run)
warm_state = warm_run.state or {}
@@ -7260,6 +7294,7 @@ def run_task(
("initial_permission_mode", initial_permission_mode),
("rtk_enabled", validated_data.get("rtk_enabled")),
("benjamin_enabled", validated_data.get("benjamin_enabled")),
+ ("claude_model_access", claude_model_access),
):
if value is not None:
extra_state = extra_state or {}
@@ -9056,7 +9091,9 @@ def forward_thread_message(
author = message.author
author_name = (author.get_full_name() or author.email) if author else "A teammate"
content = f"[Thread comment from {author_name}] {message.content}"
- signal_result = signal_task_run_user_message(run.id, task.id, team_id, content=content, artifact_ids=[])
+ signal_result = signal_task_run_user_message(
+ run.id, task.id, team_id, content=content, artifact_ids=[], actor_user_id=user_id
+ )
if not signal_result:
return "signal_failed", None
diff --git a/products/tasks/backend/facade/client_provenance.py b/products/tasks/backend/facade/client_provenance.py
index c39d48c2a812..b59050c02e67 100644
--- a/products/tasks/backend/facade/client_provenance.py
+++ b/products/tasks/backend/facade/client_provenance.py
@@ -1,10 +1,24 @@
from rest_framework.request import Request
+from posthog.auth import OAuthAccessTokenAuthentication
from posthog.oauth_provenance import is_interactive_desktop_grant
+from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS
from products.tasks.backend.models import TaskClientProvenance
+def is_sandbox_oauth_request(request: Request) -> bool:
+ authenticator = getattr(request, "successful_authenticator", None)
+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return False
+ token = authenticator.access_token
+ return (
+ token.application is not None
+ and token.application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS
+ and (token.sandbox_task_id is not None or "internal_run:read" in (token.scope or "").split())
+ )
+
+
def get_task_client_provenance(request: Request) -> TaskClientProvenance | None:
if is_interactive_desktop_grant(request):
return TaskClientProvenance.POSTHOG_DESKTOP
diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.py
index 743e087bf1e2..e58b9780baf7 100644
--- a/products/tasks/backend/logic/services/agent_command.py
+++ b/products/tasks/backend/logic/services/agent_command.py
@@ -274,7 +274,8 @@ def send_agent_command(
request_kwargs: dict[str, Any] = {
"json": payload,
"headers": headers,
- "timeout": timeout,
+ "timeout": min(timeout, 5) if method == "credential_response" else timeout,
+ "allow_redirects": method != "credential_response",
"params": query_params or None,
}
diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.py
index 35b3a62df764..941205b9a7da 100644
--- a/products/tasks/backend/logic/services/agent_server_launcher.py
+++ b/products/tasks/backend/logic/services/agent_server_launcher.py
@@ -17,7 +17,7 @@ from typing import TYPE_CHECKING
from django.conf import settings
from products.tasks.backend.constants import POSTHOG_EXEC_PERMISSION_REGEX, SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
-from products.tasks.backend.exceptions import SandboxExecutionError
+from products.tasks.backend.exceptions import ProcessTaskFatalError, SandboxExecutionError
from products.tasks.backend.logic.services.agentsh import (
AGENTSH_DAEMON_PORT,
BASH_ENV_SCRIPT,
@@ -76,8 +76,8 @@ def _session_init_probe_hosts() -> list[str]:
return hosts
-def _start_and_wait_command(command: str) -> str:
- health_command = build_health_check_command(AGENT_SERVER_PORT, AGENT_SERVER_HEALTH_MAX_ATTEMPTS)
+def _start_and_wait_command(command: str, max_attempts: int = AGENT_SERVER_HEALTH_MAX_ATTEMPTS) -> str:
+ health_command = build_health_check_command(AGENT_SERVER_PORT, max_attempts, pid_file="/tmp/agent-server.pid")
return (
f"{command}; launch_status=$?; "
'if [ "$launch_status" -ne 0 ]; then exit "$launch_status"; fi; '
@@ -150,6 +150,7 @@ class AgentServerLaunchMixin(SandboxBase):
benjamin_enabled: bool = False,
peer_messaging: bool = False,
posthog_exec_permission_regex: str | None = None,
+ claude_model_access: str | None = None,
) -> str:
env_prefix = build_agent_runtime_env_prefix(
interaction_origin=interaction_origin,
@@ -171,6 +172,7 @@ class AgentServerLaunchMixin(SandboxBase):
peer_messaging=peer_messaging,
unset_bedrock=self.disable_direct_bedrock,
)
+ subscription_flag = " --claudeSubscription" if claude_model_access == "own-subscription" else ""
create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"
# Only append when opted in: agent-server builds without the option reject unknown
# flags, so default runs (and resumes of old snapshots) must not see it.
@@ -194,7 +196,7 @@ class AgentServerLaunchMixin(SandboxBase):
f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "
f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"
f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{relay_mcp_servers_arg}"
- f"{domains_flag}{repo_ready_flag}{exec_permission_flag}"
+ f"{domains_flag}{repo_ready_flag}{exec_permission_flag}{subscription_flag}"
)
launch_started_at = "export POSTHOG_AGENT_LAUNCH_STARTED_AT_MS=$(date +%s%3N)"
@@ -214,12 +216,12 @@ class AgentServerLaunchMixin(SandboxBase):
if allowed_domains is not None:
return (
f"cd /scripts && {launch_started_prefix}{initialize_env_file} && "
- f"({build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &)"
+ f"({build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} & echo $! > /tmp/agent-server.pid)"
)
else:
return (
f"cd /scripts && {launch_started_prefix}{initialize_env_file} && "
- f"(nohup {server_cmd} > /tmp/agent-server.log 2>&1 &)"
+ f"(nohup {server_cmd} > /tmp/agent-server.log 2>&1 & echo $! > /tmp/agent-server.pid)"
)
def _termination_failure_reason(self) -> str:
@@ -299,6 +301,7 @@ class AgentServerLaunchMixin(SandboxBase):
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
peer_messaging: bool = False,
+ claude_model_access: str | None = None,
) -> int | None:
"""Start the agent-server HTTP server in the sandbox.
@@ -382,11 +385,13 @@ class AgentServerLaunchMixin(SandboxBase):
benjamin_enabled=benjamin_enabled,
peer_messaging=peer_messaging,
posthog_exec_permission_regex=exec_permission_regex,
+ claude_model_access=claude_model_access,
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
- execute_command = _start_and_wait_command(command) if wait_for_health else command
- timeout_seconds = 30 + health_check_timeout_seconds(AGENT_SERVER_HEALTH_MAX_ATTEMPTS) if wait_for_health else 30
+ max_attempts = 300 if claude_model_access == "own-subscription" else AGENT_SERVER_HEALTH_MAX_ATTEMPTS
+ execute_command = _start_and_wait_command(command, max_attempts) if wait_for_health else command
+ timeout_seconds = 30 + health_check_timeout_seconds(max_attempts) if wait_for_health else 30
start_time = time.perf_counter()
launch_result = self.execute(execute_command, timeout_seconds=timeout_seconds)
start_and_health_ms = int((time.perf_counter() - start_time) * 1000)
@@ -394,6 +399,16 @@ class AgentServerLaunchMixin(SandboxBase):
health_duration_ms = _health_duration_ms(launch_result.stdout)
if wait_for_health and health_duration_ms is not None:
diagnostics = self._diagnose_startup_failure(allowed_domains)
+ if (
+ "claude_credential_unavailable" in launch_result.stdout
+ or "claude_credential_unavailable" in diagnostics.get("log", "")
+ ):
+ raise ProcessTaskFatalError(
+ "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
+ {"task_id": task_id, "run_id": run_id},
+ RuntimeError("Claude token unavailable"),
+ capture=False,
+ )
raise SandboxExecutionError(
"Agent-server failed to start",
{
@@ -422,8 +437,11 @@ class AgentServerLaunchMixin(SandboxBase):
return _health_duration_ms(launch_result.stdout)
return None
- def wait_for_agent_server_ready(self, allowed_domains: list[str] | None = None) -> None:
- if self._wait_for_health_check():
+ def wait_for_agent_server_ready(
+ self, allowed_domains: list[str] | None = None, *, claude_model_access: str | None = None
+ ) -> None:
+ max_attempts = 300 if claude_model_access == "own-subscription" else AGENT_SERVER_HEALTH_MAX_ATTEMPTS
+ if self._wait_for_health_check(max_attempts=max_attempts):
if allowed_domains is not None and not self._agentsh_daemon_is_healthy():
raise SandboxExecutionError(
"Failed to verify agentsh network enforcement",
@@ -518,7 +536,9 @@ class AgentServerLaunchMixin(SandboxBase):
self, max_attempts: int = AGENT_SERVER_HEALTH_MAX_ATTEMPTS, poll_interval: float = 0.5
) -> bool:
"""Poll health endpoint until server is ready (single remote call)."""
- return wait_for_health_check(self.execute, self.id, AGENT_SERVER_PORT, max_attempts, poll_interval)
+ return wait_for_health_check(
+ self.execute, self.id, AGENT_SERVER_PORT, max_attempts, poll_interval, pid_file="/tmp/agent-server.pid"
+ )
def _agent_server_is_healthy(self) -> bool:
return wait_for_health_check(self.execute, self.id, AGENT_SERVER_PORT, max_attempts=1, poll_interval=0.0)
@@ -534,8 +554,8 @@ class AgentServerLaunchMixin(SandboxBase):
def _free_agent_server_port(self) -> None:
self.execute(
- "pkill -TERM -f agent-server 2>/dev/null || true; "
- "for _ in $(seq 1 10); do pgrep -f agent-server >/dev/null || break; sleep 0.5; done; "
- "pkill -KILL -f agent-server 2>/dev/null || true",
+ "pkill -TERM -f '[a]gent-server' 2>/dev/null || true; "
+ "for _ in $(seq 1 10); do pgrep -f '[a]gent-server' >/dev/null || break; sleep 0.5; done; "
+ "pkill -KILL -f '[a]gent-server' 2>/dev/null || true",
timeout_seconds=15,
)
diff --git a/products/tasks/backend/logic/services/agentsh.py b/products/tasks/backend/logic/services/agentsh.py
index c3742cc32cfc..5ef06a71a6fa 100644
--- a/products/tasks/backend/logic/services/agentsh.py
+++ b/products/tasks/backend/logic/services/agentsh.py
@@ -334,7 +334,7 @@ if [[ "${{BASH_SOURCE[0]}}" == "$0" ]]; then
exit 0
fi
-unset GH_TOKEN GITHUB_TOKEN
+unset GH_TOKEN GITHUB_TOKEN CLAUDE_CODE_OAUTH_TOKEN CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR
while IFS= read -r -d $'\\0' kv 2>/dev/null; do
case "$kv" in
GH_TOKEN=*|GITHUB_TOKEN=*) export "$kv" ;;
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 1a0bdc8c6045..71bc16a3599a 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -886,6 +886,7 @@ class DockerSandbox(SandboxBase):
benjamin_enabled: bool = False,
peer_messaging: bool = False,
posthog_exec_permission_regex: str | None = None,
+ claude_model_access: str | None = None,
) -> str:
# The host proxy URL (e.g. localhost:8003) is unreachable from inside the container;
# rewrite it the same way POSTHOG_API_URL is for Docker sandboxes.
@@ -910,6 +911,7 @@ class DockerSandbox(SandboxBase):
benjamin_enabled=benjamin_enabled,
peer_messaging=peer_messaging,
)
+ subscription_flag = " --claudeSubscription" if claude_model_access == "own-subscription" else ""
create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"
# Only append when opted in: agent-server builds without the option reject unknown
# flags, so default runs (and resumes of old snapshots) must not see it.
@@ -933,7 +935,7 @@ class DockerSandbox(SandboxBase):
f"{env_prefix}./node_modules/.bin/agent-server --port {AGENT_SERVER_PORT}{repo_flag} "
f"--taskId {shlex.quote(task_id)} --runId {shlex.quote(run_id)} --mode {shlex.quote(mode)}"
f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{relay_mcp_servers_arg}"
- f"{domains_flag}{repo_ready_flag}{exec_permission_flag}"
+ f"{domains_flag}{repo_ready_flag}{exec_permission_flag}{subscription_flag}"
)
# agentsh injects HTTP_PROXY pointing at a per-session egress proxy port; undici
@@ -949,12 +951,12 @@ class DockerSandbox(SandboxBase):
if allowed_domains is not None:
return (
f"cd /scripts && {initialize_env_file} && "
- f"({build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} &)"
+ f"({build_exec_prefix()} {ENV_WRAPPER_SCRIPT} bash -c {shlex.quote(inner)} & echo $! > /tmp/agent-server.pid)"
)
else:
- return f"cd /scripts && {initialize_env_file} && (nohup {server_cmd} > /tmp/agent-server.log 2>&1 &)"
+ return f"cd /scripts && {initialize_env_file} && (nohup {server_cmd} > /tmp/agent-server.log 2>&1 & echo $! > /tmp/agent-server.pid)"
- def _launch_and_check(self, command: str) -> bool:
+ def _launch_and_check(self, command: str, *, max_attempts: int = 20) -> bool:
"""Execute the agent-server command and wait for the health check.
Returns True if the server started successfully, False otherwise.
@@ -963,7 +965,7 @@ class DockerSandbox(SandboxBase):
if result.exit_code != 0:
logger.warning(f"Agent-server process failed to launch in sandbox {self.id}: {result.stderr}")
return False
- return self._wait_for_health_check(max_attempts=20)
+ return self._wait_for_health_check(max_attempts=max_attempts)
def _install_gh_guard(self) -> None:
"""Install the gh PATH shim at runtime so it's present regardless of image age.
@@ -1004,6 +1006,7 @@ class DockerSandbox(SandboxBase):
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
peer_messaging: bool = False,
+ claude_model_access: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
@@ -1084,6 +1087,7 @@ class DockerSandbox(SandboxBase):
benjamin_enabled=benjamin_enabled,
peer_messaging=peer_messaging,
posthog_exec_permission_regex=exec_permission_regex,
+ claude_model_access=claude_model_access,
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
@@ -1098,7 +1102,8 @@ class DockerSandbox(SandboxBase):
)
return
- if self._launch_and_check(command):
+ max_attempts = 300 if claude_model_access == "own-subscription" else 20
+ if self._launch_and_check(command, max_attempts=max_attempts):
logger.info(f"Agent-server started on port {self._host_port}")
return
@@ -1141,8 +1146,9 @@ class DockerSandbox(SandboxBase):
benjamin_enabled=benjamin_enabled,
peer_messaging=peer_messaging,
posthog_exec_permission_regex=exec_permission_regex,
+ claude_model_access=claude_model_access,
)
- if self._launch_and_check(command):
+ if self._launch_and_check(command, max_attempts=max_attempts):
logger.info(f"Agent-server started on port {self._host_port} (without --baseBranch)")
return
@@ -1157,8 +1163,10 @@ class DockerSandbox(SandboxBase):
capture=False,
)
- def wait_for_agent_server_ready(self, allowed_domains: list[str] | None = None) -> None:
- if self._wait_for_health_check(max_attempts=240):
+ def wait_for_agent_server_ready(
+ self, allowed_domains: list[str] | None = None, *, claude_model_access: str | None = None
+ ) -> None:
+ if self._wait_for_health_check(max_attempts=300 if claude_model_access == "own-subscription" else 240):
logger.info(f"Agent-server ready on port {self._host_port}")
return
log_result = self.execute("cat /tmp/agent-server.log 2>/dev/null || echo 'No log file'", timeout_seconds=5)
@@ -1225,7 +1233,9 @@ class DockerSandbox(SandboxBase):
def _wait_for_health_check(self, max_attempts: int = 60, poll_interval: float = 0.5) -> bool:
"""Poll health endpoint until server is ready (single remote call)."""
- return wait_for_health_check(self.execute, self.id, AGENT_SERVER_PORT, max_attempts, poll_interval)
+ return wait_for_health_check(
+ self.execute, self.id, AGENT_SERVER_PORT, max_attempts, poll_interval, pid_file="/tmp/agent-server.pid"
+ )
def read_agent_server_session_init_ms(self) -> int | None:
return self._read_health_session_init_ms(AGENT_SERVER_PORT)
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index 957a0c333dbb..d5554907af86 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -299,7 +299,9 @@ def build_agent_runtime_env_prefix(
"POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN": event_ingest_token,
"POSTHOG_TASK_RUN_SESSION_TOKEN": task_run_session_token,
"POSTHOG_TASK_RUN_EVENT_INGEST_URL": event_ingest_url,
- "POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN": "true" if event_ingest_keep_stream_open else None,
+ "POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN": (
+ "true" if event_ingest_keep_stream_open else "false" if settings.DEBUG and not event_ingest_url else None
+ ),
# Set explicitly in both states: "0" opts the run out, "1" pins auto-detection on
# even if a stale env value survives in a resumed sandbox.
"POSTHOG_RTK": "1" if rtk_enabled else "0",
@@ -571,6 +573,7 @@ class SandboxBase(ABC):
rtk_enabled: bool = True,
benjamin_enabled: bool = False,
peer_messaging: bool = False,
+ claude_model_access: str | None = None,
) -> int | None:
"""Start the agent-server HTTP server in the sandbox.
@@ -583,7 +586,9 @@ class SandboxBase(ABC):
return False
@abstractmethod
- def wait_for_agent_server_ready(self, allowed_domains: list[str] | None = None) -> None: ...
+ def wait_for_agent_server_ready(
+ self, allowed_domains: list[str] | None = None, *, claude_model_access: str | None = None
+ ) -> None: ...
@abstractmethod
def mark_repo_ready(self, repo_ready_file: str) -> None: ...
@@ -744,26 +749,45 @@ def wait_for_health_check(
port: int,
max_attempts: int = 60,
poll_interval: float = 0.5,
+ pid_file: str | None = None,
) -> bool:
"""Poll health endpoint until server is ready (single remote call).
Runs a bash polling loop inside the sandbox so only one round-trip is
needed regardless of how many attempts are required.
"""
- health_script = build_health_check_command(port, max_attempts, poll_interval)
+ health_script = build_health_check_command(port, max_attempts, poll_interval, pid_file)
result = execute(health_script, timeout_seconds=health_check_timeout_seconds(max_attempts, poll_interval))
+ if "claude_credential_unavailable" in result.stdout:
+ from products.tasks.backend.exceptions import ProcessTaskFatalError
+
+ raise ProcessTaskFatalError(
+ "The Claude token did not arrive. Open Desktop and check your token in Settings > Harness. Then start the task again.",
+ {"sandbox_id": sandbox_id},
+ RuntimeError("Claude token unavailable"),
+ capture=False,
+ )
if result.exit_code == 0:
_logger.info(f"Agent-server health check passed in sandbox {sandbox_id} ({result.stdout.strip()})")
return True
return False
-def build_health_check_command(port: int, max_attempts: int = 60, poll_interval: float = 0.5) -> str:
+def build_health_check_command(
+ port: int, max_attempts: int = 60, poll_interval: float = 0.5, pid_file: str | None = None
+) -> str:
+ process_check = (
+ f'if [ -f {shlex.quote(pid_file)} ]; then kill -0 "$(cat {shlex.quote(pid_file)})" 2>/dev/null || exit 1; fi; '
+ if pid_file is not None
+ else ""
+ )
return (
f"for i in $(seq 1 {max_attempts}); do "
- f" body=$(curl -s http://localhost:{port}/health); "
+ f"{process_check}"
+ f" body=$(curl -s --max-time 2 http://localhost:{port}/health); "
" status=$?; "
' if [ "$status" = "0" ]; then '
+ ' case "$body" in *claude_credential_unavailable*) echo "claude_credential_unavailable"; exit 1;; esac; '
" python3 -c '"
"import json, sys; "
"payload = json.loads(sys.argv[1]); "
diff --git a/products/tasks/backend/logic/services/tests/test_agent_command.py b/products/tasks/backend/logic/services/tests/test_agent_command.py
index 593a963242c5..1e34970748d7 100644
--- a/products/tasks/backend/logic/services/tests/test_agent_command.py
+++ b/products/tasks/backend/logic/services/tests/test_agent_command.py
@@ -181,14 +181,15 @@ class TestSendAgentCommand:
@patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
@patch("products.tasks.backend.logic.services.agent_command.requests.post")
- def test_success(self, mock_post, mock_validate):
+ @pytest.mark.parametrize("method", ["user_message", "credential_response"])
+ def test_success(self, mock_post, mock_validate, method):
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.json.return_value = {"jsonrpc": "2.0", "result": "ok"}
mock_post.return_value = mock_resp
task_run = self._make_task_run(sandbox_url="https://sandbox.modal.run/rpc", connect_token="tok")
- result = send_agent_command(task_run, "user_message", params={"message": "hi"})
+ result = send_agent_command(task_run, method, params={"message": "hi"})
assert result.success
assert result.status_code == 200
@@ -196,9 +197,13 @@ class TestSendAgentCommand:
call_kwargs = mock_post.call_args
assert call_kwargs.kwargs["headers"]["Authorization"] == "Bearer tok"
- assert call_kwargs.kwargs["json"]["method"] == "user_message"
+ assert call_kwargs.kwargs["json"]["method"] == method
assert call_kwargs.args[0] == "https://sandbox.modal.run/rpc/command"
+ if method == "credential_response":
+ assert call_kwargs.kwargs["timeout"] == 5
+ assert call_kwargs.kwargs["allow_redirects"] is False
+
@patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
@patch("products.tasks.backend.logic.services.agent_command.requests.post")
def test_appends_command_path_when_missing_trailing_slash(self, mock_post, mock_validate):
diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
index 5a44fbc39acb..3993f3e0f56f 100644
--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py
@@ -698,13 +698,43 @@ class TestModalSandboxAgentServer:
assert expected_env in command
@pytest.mark.parametrize(
- "keep_stream_open, expected_env_present",
+ "claude_model_access, subscription_flag",
[
- (True, True),
- (False, False),
+ ("own-subscription", True),
+ ("posthog-gateway", False),
+ (None, False),
],
)
- def test_start_agent_server_keep_stream_open_env(self, mock_sandbox: Any, keep_stream_open, expected_env_present):
+ def test_start_agent_server_claude_subscription_flag(
+ self, mock_sandbox: Any, claude_model_access, subscription_flag
+ ):
+ mock_sandbox.execute = MagicMock(
+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
+ )
+
+ mock_sandbox.start_agent_server(
+ repository="posthog/posthog",
+ task_id="task-123",
+ run_id="run-456",
+ mode="background",
+ claude_model_access=claude_model_access,
+ )
+
+ command = _agent_server_launch_command(mock_sandbox.execute)
+ assert (" --claudeSubscription" in command) is subscription_flag
+
+ @pytest.mark.parametrize(
+ "keep_stream_open, debug, expected_env_value",
+ [
+ (True, False, "true"),
+ (False, False, None),
+ (False, True, "false"),
+ ],
+ )
+ def test_start_agent_server_keep_stream_open_env(
+ self, mock_sandbox: Any, keep_stream_open, debug, expected_env_value, settings
+ ):
+ settings.DEBUG = debug
mock_sandbox.execute = MagicMock(
return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),
)
@@ -718,8 +748,8 @@ class TestModalSandboxAgentServer:
)
command = _agent_server_launch_command(mock_sandbox.execute)
- if expected_env_present:
- assert "POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN=true" in command
+ if expected_env_value is not None:
+ assert f"POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN={expected_env_value}" in command
else:
assert "POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN" not in command
@@ -774,24 +804,21 @@ class TestModalSandboxAgentServer:
assert error.value.context["health_poll_ms"] == 120000
assert mock_sandbox.supports_combined_agent_server_start_and_health() is True
- def test_wait_for_health_check_passes(self, mock_sandbox: Any):
- mock_sandbox.execute = MagicMock(
- return_value=ExecutionResult(stdout="ok:3", stderr="", exit_code=0, error=None),
- )
-
- result = mock_sandbox._wait_for_health_check()
-
- assert result is True
- assert mock_sandbox.execute.call_count == 1
+ @pytest.mark.parametrize(
+ "exit_code, stdout, expected", [(0, "ok:3", True), (1, "", False), (1, "claude_credential_unavailable", None)]
+ )
+ def test_wait_for_health_check(self, mock_sandbox: Any, exit_code, stdout, expected):
+ from products.tasks.backend.exceptions import ProcessTaskFatalError
- def test_wait_for_health_check_fails(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
- return_value=ExecutionResult(stdout="", stderr="", exit_code=1, error=None),
+ return_value=ExecutionResult(stdout=stdout, stderr="", exit_code=exit_code, error=None),
)
-
- result = mock_sandbox._wait_for_health_check()
-
- assert result is False
+ if expected is None:
+ with pytest.raises(ProcessTaskFatalError) as error:
+ mock_sandbox._wait_for_health_check()
+ assert error.value.non_retryable
+ else:
+ assert mock_sandbox._wait_for_health_check() is expected
assert mock_sandbox.execute.call_count == 1
def test_start_agent_server_skips_relaunch_when_already_healthy(self, mock_sandbox: Any):
@@ -1224,8 +1251,8 @@ class TestModalSandboxAgentServerStartupHelpers:
sandbox._free_agent_server_port()
command = sandbox.execute.call_args_list[0][0][0]
- assert "pkill -TERM -f agent-server" in command
- assert "pkill -KILL -f agent-server" in command
+ assert "pkill -TERM -f '[a]gent-server'" in command
+ assert "pkill -KILL -f '[a]gent-server'" in command
class TestStartupFailureDiagnostics:
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index a2c2964bb584..c8265be2c75c 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -751,6 +751,8 @@ class Task(DeletedMetaFields, models.Model):
state: dict = {} if task.runtime == Task.Runtime.PI else {"mode": mode}
if extra_state:
state.update({k: v for k, v in extra_state.items() if k != "mode"})
+ if state.get("claude_model_access") == "own-subscription":
+ state["claude_subscription_user_id"] = acting_user_id or task.created_by_id
state.setdefault("repositories", task.repositories or ([task.repository] if task.repository else []))
# A workflow task's later runs must keep the connector allowlist selected by the workflow.
if task.origin_product == Task.OriginProduct.WORKFLOW and "config_snapshot" not in state:
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 3eb9d2f83053..f50f1c675425 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -24,6 +24,7 @@ from posthog.security.url_validation import is_url_allowed, resolve_url_hosts_ip
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.api import CHANNEL_INSTRUCTIONS_MAX_BYTES
+from products.tasks.backend.facade.client_provenance import is_sandbox_oauth_request
from products.tasks.backend.facade.contracts import (
ChannelDTO,
ChannelFeedMessageDTO,
@@ -92,6 +93,28 @@ def _is_pi_task_run_request(context: dict[str, Any]) -> bool:
return task_runtime == tasks_facade.TaskRuntime.PI
+def _validate_subscription_caller(attrs: dict[str, Any], context: dict[str, Any]) -> None:
+ request = context.get("request")
+ if request is None:
+ return
+ access = attrs.get("claude_model_access")
+ if access is None and (run_id := attrs.get("resume_from_run_id")):
+ view = context.get("view")
+ kwargs = getattr(view, "kwargs", {})
+ task_id = kwargs.get("parent_lookup_task_id") or kwargs.get("pk")
+ team = context.get("team")
+ if team is not None and task_id is not None:
+ run = tasks_facade.get_task_run_detail(run_id, task_id, team.id)
+ if run is not None:
+ access = run.state.get("claude_model_access")
+ if access == "own-subscription" and not is_sandbox_oauth_request(request):
+ raise serializers.ValidationError(
+ {"claude_model_access": "Open PostHog Desktop to resume this run with your Claude plan."}
+ )
+ if access == "own-subscription" and is_sandbox_oauth_request(request):
+ raise serializers.ValidationError({"claude_model_access": "Only a user can select a Claude subscription."})
+
+
def request_distinct_id(context: dict[str, Any]) -> str | None:
"""The acting user's distinct id, for flag evaluation. `None` when there isn't one."""
user = getattr(context.get("request"), "user", None)
@@ -3165,8 +3188,21 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSer
"for this run."
),
)
+ claude_model_access = serializers.ChoiceField(
+ choices=["posthog-gateway", "own-subscription"],
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox "
+ "request a Claude token from the creating PostHog Desktop at run start; the token is "
+ "sent in flight and never stored on PostHog servers. If omitted or null, resumed runs "
+ "keep their billing choice and new runs use the PostHog gateway."
+ ),
+ )
def validate(self, attrs):
+ _validate_subscription_caller(attrs, self.context)
errors: dict[str, str] = {}
if collision_error := get_relayed_imported_mcp_name_collision_error(attrs):
errors["relayed_mcp_servers"] = collision_error
@@ -3177,6 +3213,8 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSer
pending_user_message = attrs.get("pending_user_message")
pending_user_artifact_ids = attrs.get("pending_user_artifact_ids") or []
+ if attrs.get("claude_model_access") == "own-subscription" and _is_pi_task_run_request(self.context):
+ errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."
if pending_user_message is not None:
trimmed_message = pending_user_message.strip()
attrs["pending_user_message"] = trimmed_message or None
@@ -3356,8 +3394,21 @@ class TaskRunBootstrapCreateRequestSerializer(
"for this run."
),
)
+ claude_model_access = serializers.ChoiceField(
+ choices=["posthog-gateway", "own-subscription"],
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox "
+ "request a Claude token from the creating PostHog Desktop at run start; the token is "
+ "sent in flight and never stored on PostHog servers. If omitted or null, resumed runs "
+ "keep their billing choice and new runs use the PostHog gateway."
+ ),
+ )
def validate(self, attrs):
+ _validate_subscription_caller(attrs, self.context)
errors: dict[str, str] = {}
if collision_error := get_relayed_imported_mcp_name_collision_error(attrs):
errors["relayed_mcp_servers"] = collision_error
@@ -3365,6 +3416,8 @@ class TaskRunBootstrapCreateRequestSerializer(
runtime_adapter = attrs.get("runtime_adapter")
is_pi_task = _is_pi_task_run_request(self.context)
if is_pi_task:
+ if attrs.get("claude_model_access") == "own-subscription":
+ errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."
pi_incompatible_fields = ("runtime_adapter", "context_window", "fast_mode", "initial_permission_mode")
for field in pi_incompatible_fields:
if attrs.get(field) is not None:
@@ -3821,6 +3874,7 @@ class TaskRunCommandRequestSerializer(serializers.Serializer):
"permission_response",
"set_config_option",
"mcp_response",
+ "credential_response",
"pi/rpc",
"queue_get",
"queue_clear",
@@ -3947,6 +4001,22 @@ class TaskRunCommandRequestSerializer(serializers.Serializer):
)
if len(json.dumps(params)) > self.MAX_MCP_RESPONSE_PARAMS_BYTES:
raise serializers.ValidationError({"params": "mcp_response params exceed the 300 KB limit"})
+ elif method == "credential_response":
+ self._require_nonempty_string(params, "requestId")
+ if len(params["requestId"]) > 128:
+ raise serializers.ValidationError({"params": "requestId exceeds the 128 character limit"})
+ if params.get("credential") != "claude_subscription_token":
+ raise serializers.ValidationError({"params": "Unsupported credential"})
+ token = params.get("token")
+ error = params.get("error")
+ if (token is None) == (error is None):
+ raise serializers.ValidationError(
+ {"params": "credential_response requires exactly one of token or error"}
+ )
+ if token is not None and (not isinstance(token, str) or not token.strip() or len(token) > 4096):
+ raise serializers.ValidationError({"params": "token must contain between 1 and 4096 characters"})
+ if error is not None and error not in ("no_token", "store_unavailable"):
+ raise serializers.ValidationError({"params": "Unsupported credential error"})
return attrs
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 7890b4452034..0dacf6d6ee0b 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -76,7 +76,7 @@ from products.tasks.backend.facade.access import (
usage_limit_response,
)
from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_task_usage
-from products.tasks.backend.facade.client_provenance import get_task_client_provenance
+from products.tasks.backend.facade.client_provenance import get_task_client_provenance, is_sandbox_oauth_request
from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceeded
from products.tasks.backend.facade.contracts import TaskAnalysisError
from products.tasks.backend.facade.metrics import (
@@ -1417,15 +1417,6 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(status=status.HTTP_204_NO_CONTENT)
-@extend_schema(tags=["task-runs", "tasks"])
-def is_sandbox_oauth_request(request) -> bool:
- authenticator = request.successful_authenticator
- if not isinstance(authenticator, OAuthAccessTokenAuthentication):
- return False
- application = authenticator.access_token.application
- return application is not None and application.client_id in SANDBOX_OAUTH_APP_CLIENT_IDS
-
-
def _sandbox_bound_task_id(request) -> UUID | None:
if not is_sandbox_oauth_request(request):
return None
@@ -1441,6 +1432,7 @@ def is_sandbox_agent_request(request, task_id: str) -> bool:
_HUMAN_STEERING_COMMAND_METHODS = frozenset({"user_message", "side_question"})
+@extend_schema(tags=["task-runs", "tasks"])
class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
API for managing task runs. Each run represents an execution of a task.
@@ -1540,6 +1532,16 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise NotFound()
return run
+ def _ensure_subscription_owner(self, task_id: str, run_id: str) -> None:
+ run = tasks_facade.get_task_run_detail(run_id, task_id, self.team_id)
+ if run is None:
+ raise NotFound()
+ if (
+ run.state.get("claude_model_access") == "own-subscription"
+ and run.state.get("claude_subscription_user_id") != self._user_id()
+ ):
+ raise PermissionDenied("Only the user who started this run can use its Claude plan.")
+
@validated_request(
responses={
200: OpenApiResponse(response=TaskRunDetailSerializer, description="List of task runs"),
@@ -2710,6 +2712,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def connection_token(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
+ self._ensure_subscription_owner(task_id, pk)
if not tasks_facade.task_exempt_from_code_access(task_id, self.team_id) and (
access_response := code_access_required_response(request, self.organization, task_id=task_id)
):
@@ -2806,6 +2809,16 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def command(self, request, pk=None, **kwargs):
task_id = self._ensure_task_accessible()
method = request.validated_data["method"]
+ if method not in {"cancel", "close", "credential_response"}:
+ self._ensure_subscription_owner(task_id, pk)
+ if method == "credential_response":
+ run = tasks_facade.get_task_run_detail(pk, task_id, self.team_id)
+ if (
+ run is None
+ or is_sandbox_oauth_request(request)
+ or run.state.get("claude_subscription_user_id") != self._user_id()
+ ):
+ raise PermissionDenied("Only the user who started this run can send a Claude token.")
# Steering an analysis run spends model tokens on a task whose generations are excluded
# from the customer's rollup, so these are the reuse path the one-shot rule closes. Cancel
# and the agent's own operations stay open.
@@ -3105,7 +3118,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
json=payload,
headers=headers,
params=params,
- timeout=600,
+ timeout=5 if payload.get("method") == "credential_response" else 600,
+ allow_redirects=payload.get("method") != "credential_response",
)
@validated_request(
diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.md
index 69ff7514c984..37664b15f2cd 100644
--- a/products/tasks/backend/temporal/process_task/README.md
+++ b/products/tasks/backend/temporal/process_task/README.md
@@ -149,6 +149,33 @@ Per-team configuration for sandbox execution: network access level (trusted/full
| GitHub App | Installation access tokens via the team's GitHub integration |
| API permissions | `PostHogFeatureFlagPermission` + `APIScopePermission` on all endpoints |
+### Claude subscription token relay
+
+A run created with `claude_model_access: "own-subscription"` uses the user's Claude plan for model usage.
+Sandbox compute still uses PostHog credits.
+The `posthog-code-claude-own-subscription-cloud` flag controls rollout.
+If the backend cannot confirm that the flag is enabled, an explicitly requested subscription run fails without switching to PostHog billing.
+
+Desktop stores a `claude setup-token` token in its encrypted local store.
+The server records the user who selected subscription billing in protected run state.
+Desktop and the command endpoint check this owner before sending a token.
+Sandbox credentials cannot select subscription billing or inherit it from a resumed run.
+The response uses the authenticated `/command/` proxy, with redirects blocked and a five-second request timeout.
+Subscription runs always use direct event ingest so the request can reach Desktop before session readiness.
+The separate event-ingest rollout flag does not control this path.
+The request metadata can be replayed through the durable event stream; the token is never included in that stream, task state, logs, or analytics.
+If no token arrives within 120 seconds, the run fails with setup instructions.
+
+Subscription runs require the `--claudeSubscription` startup option.
+The launcher checks support before starting the process.
+Subscription health checks have a 155-second command limit, leaving time for setup and diagnostics within the five-minute activity.
+The PID check applies only when the PID file exists, so servers launched before deployment can still pass the health check.
+Continuation inherits the selected billing mode unless the caller explicitly changes it.
+Subscription runs do not reuse prewarmed sessions, because those processes have already selected their credentials.
+
+Keep the flag off while deploying the backend and publishing the sandbox agent build, then enable it for the intended users.
+Desktop and backend use the same flag; a stale client cannot bypass the backend check.
+
## Sandbox providers
| | DockerSandbox | ModalSandbox |
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index a8f780bfd22c..1735a77c0a94 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -2,7 +2,7 @@ import json
import hashlib
from dataclasses import dataclass
from datetime import timedelta
-from typing import Any
+from typing import Any, Literal
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
@@ -19,6 +19,7 @@ from products.tasks.backend.constants import (
AGENT_PEER_MESSAGING_FEATURE_FLAG,
AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,
BENJAMIN_FEATURE_FLAG,
+ CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,
CONTINUE_AS_NEW_FEATURE_FLAG,
DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,
DEV_STACK_IMAGE_NAME,
@@ -40,7 +41,12 @@ from products.tasks.backend.constants import (
vm_sandbox_origin_in_rollout,
vm_sandbox_origin_rollout_percentages,
)
-from products.tasks.backend.exceptions import SandboxNetworkPolicyError, TaskInvalidStateError, TaskRunNotReadyError
+from products.tasks.backend.exceptions import (
+ ProcessTaskFatalError,
+ SandboxNetworkPolicyError,
+ TaskInvalidStateError,
+ TaskRunNotReadyError,
+)
from products.tasks.backend.facade.api import ensure_task_run_session
from products.tasks.backend.feature_flags import is_agent_otel_telemetry_enabled
from products.tasks.backend.logic.services.agentsh import (
@@ -156,6 +162,7 @@ class TaskProcessingContext:
# and out-of-band consumers route deterministically for the run's whole life.
sandbox_backend: str = "modal"
dev_stack_preview_enabled: bool = False
+ claude_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway"
@property
def mode(self) -> str:
@@ -449,6 +456,49 @@ def _is_rtk_enabled(
return True
+def _resolve_claude_model_access(
+ *,
+ task_runtime: str,
+ distinct_id: str | None,
+ organization_id: str,
+ run_id: str,
+ state: dict | None = None,
+) -> Literal["posthog-gateway", "own-subscription"]:
+ if (state or {}).get("claude_model_access") != "own-subscription":
+ return "posthog-gateway"
+ if task_runtime != Task.Runtime.ACP or (state or {}).get("runtime_adapter") not in (None, "claude"):
+ raise ProcessTaskFatalError(
+ "Your Claude plan requires the Claude runtime. Select Claude and try again.",
+ {"run_id": run_id},
+ cause=ValueError("Subscription requested for a non-Claude runtime"),
+ capture=False,
+ )
+ try:
+ enabled = bool(
+ distinct_id
+ and posthoganalytics.feature_enabled(
+ CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,
+ distinct_id=distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ log_with_activity_context("claude_own_subscription_flag_check_failed", run_id=run_id, error=str(e))
+ enabled = False
+ if not enabled:
+ raise ProcessTaskFatalError(
+ "Using your Claude plan for cloud tasks is unavailable. Try again later, "
+ 'or open Claude subscription settings and turn off "Cloud tasks" to use PostHog credits.',
+ {"run_id": run_id},
+ cause=ValueError("Claude subscription rollout unavailable"),
+ capture=False,
+ )
+ return "own-subscription"
+
+
def _is_benjamin_enabled(
*,
distinct_id: str,
@@ -1203,9 +1253,26 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
TaskRun.update_state_atomic(task_run.id, updates=state_updates)
except Exception as e:
log_with_activity_context("run_state_stamp_failed", run_id=run_id, error=str(e))
+ claude_distinct_id: str | None = distinct_id
+ if state.get("claude_model_access") == "own-subscription":
+ subscription_owner_id = state.get("claude_subscription_user_id")
+ claude_distinct_id = (
+ team.all_users_with_access().filter(id=subscription_owner_id).values_list("distinct_id", flat=True).first()
+ if isinstance(subscription_owner_id, int) and not isinstance(subscription_owner_id, bool)
+ else None
+ )
+ claude_model_access = _resolve_claude_model_access(
+ task_runtime=task.runtime,
+ distinct_id=claude_distinct_id,
+ organization_id=organization_id,
+ run_id=run_id,
+ state=state,
+ )
pi_persistent_streaming = task.runtime == Task.Runtime.PI and not is_slack_interaction_state(state)
sandbox_event_ingest_override = state.get("sandbox_event_ingest_enabled")
- if pi_persistent_streaming and not isinstance(sandbox_event_ingest_override, bool):
+ if claude_model_access == "own-subscription" or (
+ pi_persistent_streaming and not isinstance(sandbox_event_ingest_override, bool)
+ ):
sandbox_event_ingest_enabled = True
else:
sandbox_event_ingest_enabled = _is_sandbox_event_ingest_enabled(
@@ -1482,6 +1549,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
custom_image_name=custom_image_name,
rtk_enabled=rtk_enabled,
benjamin_enabled=benjamin_enabled,
+ claude_model_access=claude_model_access,
continue_as_new_enabled=_is_continue_as_new_enabled(
distinct_id=distinct_id,
organization_id=organization_id,
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 7993379abc73..13774c6867c8 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -24,6 +24,7 @@ from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.exceptions import (
OAuthTokenError,
ProcessTaskError,
+ ProcessTaskFatalError,
SandboxExecutionError,
SandboxMissingRepositoryError,
)
@@ -529,6 +530,7 @@ def _invoke_start_agent_server(
wait_for_health: bool = False,
) -> int | None:
try:
+ _enforce_claude_subscription_support(sandbox, ctx)
health_duration_ms = sandbox.start_agent_server(
repository=ctx.repository if len(ctx.repositories) <= 1 else None,
task_id=ctx.task_id,
@@ -558,6 +560,7 @@ def _invoke_start_agent_server(
rtk_enabled=ctx.rtk_enabled,
benjamin_enabled=ctx.benjamin_enabled,
peer_messaging=ctx.peer_messaging_enabled,
+ claude_model_access=ctx.claude_model_access,
)
return health_duration_ms if isinstance(health_duration_ms, int) else None
@@ -582,6 +585,23 @@ def _invoke_start_agent_server(
)
+def _enforce_claude_subscription_support(sandbox: SandboxBase, ctx: TaskProcessingContext) -> None:
+ if ctx.claude_model_access != "own-subscription":
+ return
+ result = sandbox.execute(
+ "grep -q -- --claudeSubscription /scripts/node_modules/.bin/agent-server",
+ timeout_seconds=10,
+ )
+ if result.exit_code != 0:
+ raise ProcessTaskFatalError(
+ "This sandbox build cannot use your Claude plan yet. Start a new task. "
+ 'To use PostHog credits instead, turn off "Use your Claude plan for cloud tasks".',
+ {"task_id": ctx.task_id, "run_id": ctx.run_id},
+ cause=RuntimeError("agent-server lacks --claudeSubscription"),
+ capture=False,
+ )
+
+
def _record_agent_server_launch(sandbox: SandboxBase, ctx: TaskProcessingContext, params: _LaunchParams) -> None:
if params.mcp_configs and params.actor_user_id is not None:
mark_sandbox_mcp_session(sandbox.id, params.actor_user_id)
@@ -736,7 +756,14 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
origin_product=ctx.origin_product,
runtime=runtime,
) as health_timer:
- sandbox.wait_for_agent_server_ready(params.agentsh_domains)
+ sandbox.wait_for_agent_server_ready(
+ params.agentsh_domains,
+ **(
+ {"claude_model_access": ctx.claude_model_access}
+ if ctx.claude_model_access == "own-subscription"
+ else {}
+ ),
+ )
invoke_ms = invoke_timer.elapsed_ms
health_poll_ms = health_timer.elapsed_ms
_record_agent_server_launch(sandbox, ctx, params)
@@ -861,7 +888,14 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
origin_product=ctx.origin_product,
runtime=runtime,
) as health_timer:
- sandbox.wait_for_agent_server_ready(agentsh_domains)
+ sandbox.wait_for_agent_server_ready(
+ agentsh_domains,
+ **(
+ {"claude_model_access": ctx.claude_model_access}
+ if ctx.claude_model_access == "own-subscription"
+ else {}
+ ),
+ )
else:
logger.warning(
"agent_server_readiness_retry_recovery",
@@ -893,7 +927,14 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOu
origin_product=ctx.origin_product,
runtime=runtime,
) as health_timer:
- sandbox.wait_for_agent_server_ready(agentsh_domains)
+ sandbox.wait_for_agent_server_ready(
+ agentsh_domains,
+ **(
+ {"claude_model_access": ctx.claude_model_access}
+ if ctx.claude_model_access == "own-subscription"
+ else {}
+ ),
+ )
_record_agent_server_launch(sandbox, ctx, params)
except Exception:
if attempt > 1:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index 07f5a476b55b..c6e5b5b453ba 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -15,6 +15,7 @@ from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.constants import (
AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,
BENJAMIN_FEATURE_FLAG,
+ CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,
CONTINUE_AS_NEW_FEATURE_FLAG,
DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,
DEV_STACK_IMAGE_NAME,
@@ -29,7 +30,7 @@ from products.tasks.backend.constants import (
vm_sandbox_origin_in_rollout,
vm_sandbox_origin_rollout_percentages,
)
-from products.tasks.backend.exceptions import TaskInvalidStateError, TaskRunNotReadyError
+from products.tasks.backend.exceptions import ProcessTaskFatalError, TaskInvalidStateError, TaskRunNotReadyError
from products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, SandboxEnvironment, Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import (
GetTaskProcessingContextInput,
@@ -45,6 +46,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing
_is_pr_babysit_snapshot_enabled,
_is_rtk_enabled,
_is_sandbox_event_ingest_enabled,
+ _resolve_claude_model_access,
_resolve_modal_vm_sandbox,
_resolve_sandbox_backend,
get_task_processing_context,
@@ -222,11 +224,26 @@ class TestGetTaskProcessingContextActivity:
task.soft_delete()
@pytest.mark.django_db(transaction=True)
- def test_get_task_processing_context_success(self, activity_environment, test_task):
- task_run = test_task.create_run()
+ @pytest.mark.parametrize("subscription", [False, True])
+ def test_get_task_processing_context_success(self, activity_environment, test_task, subscription):
+ owner = User.objects.create_user(
+ email="[email protected]", password=None, first_name="Owner", distinct_id="subscription-owner"
+ )
+ OrganizationMembership.objects.create(organization=test_task.team.organization, user=owner)
+ task_run = test_task.create_run(
+ acting_user_id=owner.id,
+ extra_state={"claude_model_access": "own-subscription"} if subscription else {},
+ )
input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))
- result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",
+ return_value=False,
+ ) as flag:
+ flag.side_effect = lambda key, distinct_id=None, **kwargs: (
+ key == CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG and distinct_id == owner.distinct_id
+ )
+ result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
assert isinstance(result, TaskProcessingContext)
assert result.task_id == str(test_task.id)
@@ -235,6 +252,7 @@ class TestGetTaskProcessingContextActivity:
assert result.github_integration_id == test_task.github_integration_id
assert result.repository == "posthog/posthog-js"
assert result.create_pr is True
+ assert result.claude_model_access == ("own-subscription" if subscription else "posthog-gateway")
@pytest.mark.django_db(transaction=True)
def test_get_task_processing_context_rejects_previous_owner_run(self, activity_environment, test_task):
@@ -908,6 +926,71 @@ class TestGetTaskProcessingContextActivity:
is False
)
+ @pytest.mark.parametrize(
+ "flag_value, state, expected",
+ [
+ (True, {"claude_model_access": "own-subscription"}, "own-subscription"),
+ (True, {"claude_model_access": "posthog-gateway"}, "posthog-gateway"),
+ (True, {}, "posthog-gateway"),
+ ],
+ )
+ def test_claude_model_access_requires_state_ask_and_flag(self, flag_value, state, expected):
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",
+ return_value=flag_value,
+ ) as feature_enabled_mock:
+ assert (
+ _resolve_claude_model_access(
+ task_runtime=Task.Runtime.ACP,
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ state=state,
+ )
+ == expected
+ )
+
+ if state.get("claude_model_access") == "own-subscription":
+ feature_enabled_mock.assert_called_once_with(
+ CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,
+ distinct_id="distinct-id",
+ groups={"organization": "organization-id"},
+ group_properties={"organization": {"id": "organization-id"}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ else:
+ feature_enabled_mock.assert_not_called()
+
+ @pytest.mark.parametrize("flag_value", [False, None, RuntimeError("flag service failed")])
+ def test_claude_model_access_never_changes_requested_billing(self, flag_value: object) -> None:
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",
+ return_value=flag_value,
+ side_effect=flag_value if isinstance(flag_value, Exception) else None,
+ ),
+ pytest.raises(ProcessTaskFatalError, match="Using your Claude plan for cloud tasks is unavailable"),
+ ):
+ _resolve_claude_model_access(
+ task_runtime=Task.Runtime.ACP,
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ state={"claude_model_access": "own-subscription"},
+ )
+
+ @pytest.mark.parametrize("task_runtime,adapter", [(Task.Runtime.ACP, "codex"), (Task.Runtime.PI, None)])
+ def test_claude_subscription_rejects_other_adapters(self, task_runtime: str, adapter: str | None) -> None:
+ with pytest.raises(ProcessTaskFatalError, match="requires the Claude runtime"):
+ _resolve_claude_model_access(
+ task_runtime=task_runtime,
+ distinct_id="distinct-id",
+ organization_id="organization-id",
+ run_id="run-id",
+ state={"claude_model_access": "own-subscription", "runtime_adapter": adapter},
+ )
+
@pytest.mark.parametrize("launched_value", [True, False])
def test_benjamin_launch_persisted_value_pins_later_resolutions(self, launched_value):
with patch(BENJAMIN_PAYLOAD_TARGET) as payload_mock:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 0c11d91dc6ab..c874a6643740 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -1,3 +1,5 @@
+from typing import Literal
+
import pytest
from freezegun import freeze_time
@@ -5,6 +7,7 @@ from django.db import OperationalError
from products.tasks.backend.exceptions import (
OAuthTokenError,
+ ProcessTaskFatalError,
SandboxExecutionError,
SandboxMissingRepositoryError,
SandboxTimeoutError,
@@ -68,6 +71,7 @@ def _context(
network_policy_fingerprint: str | None = None,
use_modal_vm_sandbox: bool = False,
use_modal_network_allowlist: bool = False,
+ claude_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway",
) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
@@ -85,6 +89,7 @@ def _context(
network_policy_fingerprint=network_policy_fingerprint,
use_modal_vm_sandbox=use_modal_vm_sandbox,
use_modal_network_allowlist=use_modal_network_allowlist,
+ claude_model_access=claude_model_access,
_branch=branch,
)
@@ -539,6 +544,32 @@ def test_ensure_repository_on_disk_skips_repo_less_runs(mocker) -> None:
sandbox.execute.assert_not_called()
[email protected]("access,exit_code", [("posthog-gateway", 1), ("own-subscription", 0), ("own-subscription", 1)])
+def test_subscription_compatibility_is_checked_before_launch(mocker, access, exit_code) -> None:
+ sandbox = mocker.Mock()
+ sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=exit_code)
+ params = _LaunchParams(
+ mcp_configs=[],
+ relayed_mcp_servers=[],
+ actor_user_id=None,
+ agentsh_domains=None,
+ protected_base_branch=None,
+ event_ingest_token=None,
+ task_run_session_token=None,
+ event_ingest_url=None,
+ event_ingest_keep_stream_open=False,
+ )
+ context = _context(claude_model_access=access)
+ if access == "own-subscription" and exit_code != 0:
+ with pytest.raises(ProcessTaskFatalError, match="cannot use your Claude plan yet"):
+ _invoke_start_agent_server(sandbox, context, params, repo_ready_file=None)
+ sandbox.start_agent_server.assert_not_called()
+ else:
+ _invoke_start_agent_server(sandbox, context, params, repo_ready_file=None)
+ sandbox.start_agent_server.assert_called_once()
+ assert sandbox.start_agent_server.call_args.kwargs["claude_model_access"] == access
+
+
def test_agent_shadow_flag_uses_server_side_organization_targeting(mocker) -> None:
feature_enabled = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.posthoganalytics.feature_enabled",
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
index 00da8a75351a..28ef2b5183db 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
from products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGE
from products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
from products.tasks.backend.models import INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN
+from products.tasks.backend.temporal.process_task import utils
from products.tasks.backend.temporal.process_task.ai_gateway_token import (
INTERACTIVE_MINTABLE_PRODUCTS,
MINTABLE_PRODUCTS,
@@ -460,6 +461,13 @@ class TestProvisioningBoundaries:
distinct_id="user-1",
)
+ def test_subscription_run_does_not_mint_gateway_credentials(self, mint_settings):
+ ctx = self._ctx()
+ ctx.claude_model_access = "own-subscription"
+ with patch.object(utils, "mint_scoped_token") as mint:
+ assert utils.run_gateway_env_vars(ctx, self._task()) == {}
+ mint.assert_not_called()
+
def test_snapshot_builder_uses_the_shared_derivation(self, mint_settings):
from products.tasks.backend.temporal.process_task import utils
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 2b1db62b1e2b..ffbc7e8b80e6 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -4,7 +4,7 @@ import logging
from collections.abc import Iterable
from dataclasses import dataclass, field
from enum import StrEnum
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Literal, Optional
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -458,6 +458,7 @@ class RunState(BaseModel, extra="allow"):
reasoning_effort: ReasoningEffort | None = None
context_window: str | None = None
fast_mode: bool | None = None
+ claude_model_access: Literal["posthog-gateway", "own-subscription"] | None = None
resume_from_run_id: str | None = None
same_run_resume: bool = False
same_run_resume_idle: bool = False
@@ -1415,6 +1416,8 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:
context that scoped-token minting depends on. `ctx` is the run's
TaskProcessingContext (duck-typed to avoid an import cycle); `task` the Task row.
"""
+ if ctx.claude_model_access == "own-subscription":
+ return {}
return ai_gateway_env_vars(
team_id=ctx.team_id,
origin_product=ctx.origin_product,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 202e0937628a..c262a927b2a6 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -1455,6 +1455,7 @@ class TestTaskAPI(BaseTaskAPITest):
status=TaskRun.Status.IN_PROGRESS,
state={
"mode": "interactive",
+ "claude_model_access": "own-subscription",
"sandbox_connect_token": "secret-token",
"sandbox_url": "https://sandbox.example.com",
"pending_dispatch": {"user_id": self.user.id},
@@ -1471,6 +1472,7 @@ class TestTaskAPI(BaseTaskAPITest):
response.json()["state"],
{
"mode": "interactive",
+ "claude_model_access": "own-subscription",
"slack_artifact_delivery": "canvas_file",
"slack_chart_delivery": True,
},
@@ -3002,6 +3004,7 @@ class TestTaskAPI(BaseTaskAPITest):
("fast_mode", {"fast_mode": True}),
("initial_permission_mode", {"initial_permission_mode": "plan"}),
("reasoning_effort", {"reasoning_effort": "ultracode"}),
+ ("claude_model_access", {"claude_model_access": "own-subscription"}),
]
)
def test_create_run_endpoint_rejects_invalid_configuration_for_pi(
@@ -3517,6 +3520,8 @@ class TestTaskAPI(BaseTaskAPITest):
("rtk_enabled", False),
("benjamin_enabled", True),
("benjamin_enabled", False),
+ ("claude_model_access", "own-subscription"),
+ ("claude_model_access", "posthog-gateway"),
]
)
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
@@ -3531,10 +3536,10 @@ class TestTaskAPI(BaseTaskAPITest):
assert response.status_code == status.HTTP_200_OK
task_run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])
- assert task_run.state[field] is value
+ assert task_run.state[field] == value
mock_workflow.assert_called_once()
- @parameterized.expand([("rtk_enabled",), ("benjamin_enabled",)])
+ @parameterized.expand([("rtk_enabled",), ("benjamin_enabled",), ("claude_model_access",)])
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_omits_agent_toggle_when_not_set(self, field, mock_workflow):
task = self.create_task()
@@ -4297,6 +4302,40 @@ class TestTaskAPI(BaseTaskAPITest):
# Token passed on a BOT resume must not be cached — only USER mode runs use it.
assert get_cached_github_user_token(str(task_run.id)) is None
+ @parameterized.expand(
+ [(None, None), ("own-subscription", "own-subscription"), ("posthog-gateway", "posthog-gateway")]
+ )
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_resume_requires_explicit_claude_billing_choice(
+ self, requested: str | None, expected: str | None, mock_workflow: MagicMock
+ ) -> None:
+ task = self.create_task()
+ previous_run = TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ state={"runtime_adapter": "claude", "claude_model_access": "own-subscription"},
+ )
+ payload = {"mode": "interactive", "resume_from_run_id": str(previous_run.id)}
+ if requested is not None:
+ payload["claude_model_access"] = requested
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/", payload, format="json")
+
+ if expected is None:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "claude_model_access"
+ assert task.runs.count() == 1
+ mock_workflow.assert_not_called()
+ return
+
+ assert response.status_code == status.HTTP_200_OK
+ run = TaskRun.objects.get(id=response.json()["latest_run"]["id"])
+ assert run.state["claude_model_access"] == expected
+ if expected == "own-subscription":
+ assert response.json()["latest_run"]["state"]["claude_subscription_user_id"] == self.user.id
+ mock_workflow.assert_called_once()
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_run_endpoint_resume_rejects_inherited_invalid_reasoning_effort(self, mock_workflow):
task = self.create_task()
@@ -5551,6 +5590,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
status=TaskRun.Status.IN_PROGRESS,
state={
"github_credential_source": "caller_token",
+ "claude_model_access": "own-subscription",
+ "claude_subscription_user_id": self.user.id,
"pr_authorship_mode": "user",
"sandbox_id": "sb-real",
"sandbox_cpu_cores": 2,
@@ -5606,6 +5647,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
{
"state": {
"github_credential_source": "server_integration",
+ "claude_model_access": "posthog-gateway",
+ "claude_subscription_user_id": self.user.id + 1,
"pr_authorship_mode": "bot",
"sandbox_id": "sb-attacker",
"sandbox_cpu_cores": 128,
@@ -5664,6 +5707,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
run.refresh_from_db()
+ assert run.state["claude_model_access"] == "own-subscription"
+ assert run.state["claude_subscription_user_id"] == self.user.id
assert run.state["github_credential_source"] == "caller_token"
assert run.state["pr_authorship_mode"] == "user"
assert "dev_stack_preview" not in run.state
@@ -5714,6 +5759,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
{
"state": {},
"state_remove_keys": [
+ "claude_model_access",
+ "claude_subscription_user_id",
"github_credential_source",
"agent_otel_telemetry_enabled",
"stream_presence_gated",
@@ -5751,6 +5798,8 @@ class TestTaskRunAPI(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
run.refresh_from_db()
+ assert run.state["claude_model_access"] == "own-subscription"
+ assert run.state["claude_subscription_user_id"] == self.user.id
assert run.state["github_credential_source"] == "caller_token" # protected key survives removal
assert run.state["agent_otel_telemetry_enabled"] is False # protected key survives removal
assert run.state["stream_presence_gated"] is True # protected key survives removal
@@ -8088,14 +8137,25 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.content.decode("utf-8").splitlines(), expected_lines)
+ @parameterized.expand([(None,), (True,), (False,)])
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_connection_token_returns_jwt(self):
+ def test_connection_token_returns_jwt(self, subscription_owner):
reset_sandbox_jwt_key_cache()
task = self.create_task()
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ if subscription_owner is not None:
+ run.state = {
+ "claude_model_access": "own-subscription",
+ "claude_subscription_user_id": self.user.id if subscription_owner else self.user.id + 1,
+ }
+ run.save(update_fields=["state"])
response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/connection_token/")
+ if subscription_owner is False:
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertNotIn("token", response.json())
+ return
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
@@ -10754,10 +10814,16 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["error"], "permission_response is not supported for Pi tasks.")
+ @parameterized.expand([(True,), (False,)])
@patch("products.tasks.backend.temporal.client.signal_task_followup_message")
- def test_command_signals_user_message(self, mock_signal_followup):
+ def test_command_signals_user_message(self, subscription_owner_matches, mock_signal_followup):
task = self.create_task()
run = self._create_run_with_sandbox(task)
+ run.state.update(
+ claude_model_access="own-subscription",
+ claude_subscription_user_id=self.user.id if subscription_owner_matches else self.user.id + 1,
+ )
+ run.save(update_fields=["state"])
response = self.client.post(
self._command_url(task, run),
@@ -10765,6 +10831,10 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
format="json",
)
+ if not subscription_owner_matches:
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_signal_followup.assert_not_called()
+ return
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data["jsonrpc"], "2.0")
@@ -11076,13 +11146,40 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
self.assertEqual(response.json()["error"], "Failed to queue user message for task run")
+ @parameterized.expand(
+ [
+ ("workflow_missing", TaskRun.Status.IN_PROGRESS, False, 409),
+ ("stopping", TaskRun.Status.IN_PROGRESS, True, 502),
+ ("cleanup_pending", TaskRun.Status.CANCELLED, True, 502),
+ ("hogland_cleanup_pending", TaskRun.Status.CANCELLED, True, 502),
+ ("cancelled", TaskRun.Status.CANCELLED, False, 409),
+ ("completed", TaskRun.Status.COMPLETED, False, 409),
+ ("failed", TaskRun.Status.FAILED, False, 409),
+ ]
+ )
@patch("products.tasks.backend.temporal.client.signal_task_followup_message")
- def test_command_returns_409_when_user_message_workflow_has_ended(self, mock_signal_followup):
+ @patch("products.tasks.backend.facade.api.get_sandbox_class_for_sandbox_id")
+ def test_command_rejects_user_message_when_run_cannot_accept_it(
+ self, _name, run_status, stopping, expected_status, mock_sandbox_class, mock_signal_followup
+ ):
from temporalio.service import RPCError, RPCStatusCode
- mock_signal_followup.side_effect = RPCError("workflow missing", RPCStatusCode.NOT_FOUND, b"")
task = self.create_task()
run = self._create_run_with_sandbox(task)
+ mock_sandbox_class.return_value.get_by_id.return_value.is_running.return_value = stopping
+ run.status = run_status
+ if stopping:
+ run.state = {**run.state, "cancel_requested_at": django_timezone.now().isoformat()}
+ run.save(update_fields=["status", "state", "updated_at"])
+ if stopping:
+ self._open_sandbox_session(run)
+ if not stopping and not run.is_terminal:
+ mock_signal_followup.side_effect = RPCError("workflow missing", RPCStatusCode.NOT_FOUND, b"")
+
+ if _name == "hogland_cleanup_pending":
+ SandboxSession.objects.for_team(self.team.pk).filter(task_run=run).update(
+ sandbox_backend="hogland", ttl_expires_at=django_timezone.now() - timedelta(minutes=1)
+ )
response = self.client.post(
self._command_url(task, run),
@@ -11090,8 +11187,15 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
- self.assertEqual(response.json()["error"], "Task run workflow has ended")
+ self.assertEqual(response.status_code, expected_status)
+ self.assertEqual(
+ response.json()["error"],
+ "Task run workflow has ended" if expected_status == 409 else "Failed to queue user message for task run",
+ )
+ if stopping or run.is_terminal:
+ mock_signal_followup.assert_not_called()
+ run.refresh_from_db()
+ self.assertNotIn("pending_followup_messages", run.state)
@patch("products.tasks.backend.temporal.client.signal_task_followup_message")
def test_command_returns_502_while_warm_workflow_is_registering(self, mock_signal_followup):
@@ -11633,6 +11737,77 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
self.assertEqual(call_kwargs["json"]["method"], "mcp_response")
self.assertEqual(call_kwargs["json"]["params"]["error"], {"code": -32001, "message": "server process exited"})
+ @parameterized.expand([(True,), (False,)])
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")
+ def test_command_proxies_credential_response_and_never_persists_the_token(self, owner_matches, mock_post):
+ reset_sandbox_jwt_key_cache()
+ token = "sk-ant-oat01-fake-test-token-0000000000000000"
+ self._mock_agent_response(
+ mock_post,
+ {"jsonrpc": "2.0", "id": "req-8", "result": {"acknowledged": True}},
+ )
+
+ task = self.create_task()
+ run = self._create_run_with_sandbox(task)
+ run.state["claude_subscription_user_id"] = self.user.id if owner_matches else self.user.id + 1
+ run.save(update_fields=["state"])
+ state_before = dict(run.state or {})
+
+ with self.assertLogs(level="DEBUG") as captured:
+ response = self.client.post(
+ self._command_url(task, run),
+ {
+ "jsonrpc": "2.0",
+ "method": "credential_response",
+ "params": {
+ "requestId": "cred-1",
+ "credential": "claude_subscription_token",
+ "token": token,
+ },
+ "id": "req-8",
+ },
+ format="json",
+ )
+
+ if not owner_matches:
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_post.assert_not_called()
+ return
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ call_kwargs = mock_post.call_args[1]
+ assert call_kwargs["allow_redirects"] is False
+ assert call_kwargs["timeout"] == 5
+ self.assertEqual(call_kwargs["json"]["method"], "credential_response")
+ self.assertEqual(call_kwargs["json"]["params"]["token"], token)
+ run.refresh_from_db()
+ self.assertEqual(run.state, state_before)
+ for record in captured.records:
+ self.assertNotIn(token, record.getMessage())
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_command_rejects_credential_response_with_token_and_error(self):
+ task = self.create_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ {
+ "jsonrpc": "2.0",
+ "method": "credential_response",
+ "params": {
+ "requestId": "cred-2",
+ "credential": "claude_subscription_token",
+ "token": "sk-ant-oat01-fake-test-token-0000000000000000",
+ "error": "no_token",
+ },
+ "id": "req-9",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def _create_posthog_ai_task(self, created_by: User | None = None):
return Task.objects.create(
team=self.team,
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index 42fade240771..aa7e7f9fa443 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -1399,10 +1399,20 @@ class TestSignalTaskRunUserMessage(TestCase):
with patch("products.tasks.backend.temporal.client.signal_task_followup_message"):
return facade.signal_task_run_user_message(run.id, run.task_id, self.team.id, **{**defaults, **kwargs})
- def test_records_the_message_so_a_reload_can_show_it_before_the_agent_takes_it(self):
+ @parameterized.expand([(None,), (True,), (False,)])
+ def test_records_the_message_so_a_reload_can_show_it_before_the_agent_takes_it(self, subscription_owner):
run = self._run()
-
- self.assertTrue(self._signal(run))
+ if subscription_owner is not None:
+ run.state = {"claude_model_access": "own-subscription", "claude_subscription_user_id": self.user.id}
+ run.save(update_fields=["state"])
+ if subscription_owner is False:
+ with self.assertRaises(facade.PermissionDenied):
+ self._signal(run, actor_user_id=self.user.id + 1)
+ run.refresh_from_db()
+ self.assertNotIn("pending_followup_messages", run.state)
+ return
+
+ self.assertTrue(self._signal(run, actor_user_id=self.user.id))
run.refresh_from_db()
recorded = run.state["pending_followup_messages"]
diff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.py
index cda3705343aa..5781e5ed3b77 100644
--- a/products/tasks/backend/tests/test_presentation_serializers.py
+++ b/products/tasks/backend/tests/test_presentation_serializers.py
@@ -1,4 +1,5 @@
import ipaddress
+from types import SimpleNamespace
from unittest.mock import patch
@@ -6,11 +7,17 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.auth import OAuthAccessTokenAuthentication
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_EU, ARRAY_APP_CLIENT_ID_US
+
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.presentation.serializers import (
TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES,
SandboxEnvironmentWriteSerializer,
TaskRunArtifactUploadSerializer,
+ TaskRunBootstrapCreateRequestSerializer,
+ TaskRunCommandRequestSerializer,
TaskRunCreateRequestSerializer,
TaskRunLivingArtifactCreateRequestSerializer,
TaskWriteSerializer,
@@ -86,6 +93,62 @@ class TestTaskRunLivingArtifactCreateRequestSerializer(SimpleTestCase):
class TestTaskRunCreateRequestSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (TaskRunCreateRequestSerializer, True),
+ (TaskRunCreateRequestSerializer, False),
+ (TaskRunBootstrapCreateRequestSerializer, True),
+ (TaskRunBootstrapCreateRequestSerializer, False),
+ ]
+ )
+ def test_subscription_requires_acp(
+ self,
+ serializer_class: type[TaskRunCreateRequestSerializer] | type[TaskRunBootstrapCreateRequestSerializer],
+ is_pi: bool,
+ ) -> None:
+ serializer = serializer_class(data={"claude_model_access": "own-subscription"})
+ with patch("products.tasks.backend.presentation.serializers._is_pi_task_run_request", return_value=is_pi):
+ assert serializer.is_valid() is not is_pi
+ if is_pi:
+ assert "claude_model_access" in serializer.errors
+
+ @parameterized.expand(
+ [
+ (serializer_class, resume, client_id, sandbox)
+ for serializer_class, resume in [
+ (TaskRunCreateRequestSerializer, False),
+ (TaskRunBootstrapCreateRequestSerializer, False),
+ (TaskRunCreateRequestSerializer, True),
+ ]
+ for client_id in [ARRAY_APP_CLIENT_ID_US, ARRAY_APP_CLIENT_ID_EU]
+ for sandbox in [False, True]
+ ]
+ )
+ def test_subscription_checks_oauth_origin(self, serializer_class, resume, client_id, sandbox) -> None:
+ authenticator = OAuthAccessTokenAuthentication()
+ authenticator.access_token = OAuthAccessToken(
+ application=OAuthApplication(client_id=client_id),
+ scope="task:write internal_run:read" if sandbox else "task:write",
+ )
+ serializer = serializer_class(
+ data={"resume_from_run_id": "00000000-0000-0000-0000-000000000001"}
+ if resume
+ else {"claude_model_access": "own-subscription"},
+ context={
+ "request": SimpleNamespace(successful_authenticator=authenticator),
+ "view": SimpleNamespace(kwargs={"pk": "task-1"}),
+ "team": SimpleNamespace(id=1),
+ },
+ )
+ with patch.object(
+ tasks_facade,
+ "get_task_run_detail",
+ return_value=SimpleNamespace(state={"claude_model_access": "own-subscription"}),
+ ):
+ assert serializer.is_valid() is (not sandbox and not resume), serializer.errors
+ if sandbox or resume:
+ assert "claude_model_access" in serializer.errors
+
@patch(
"posthog.security.url_validation.resolve_host_ips",
return_value={ipaddress.ip_address("93.184.216.34")},
@@ -143,3 +206,26 @@ class TestTaskRunArtifactUploadSerializer(SimpleTestCase):
if not expected_valid:
megabytes = TASK_RUN_ARTIFACT_INLINE_MAX_SIZE_BYTES // (1024 * 1024)
assert f"{megabytes}MB attachment limit" in str(serializer.errors["content"])
+
+
+class TestCredentialResponseSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ({"token": ""},),
+ ({"token": "x" * 4097},),
+ ({"error": "arbitrary error body"},),
+ ({"token": "invented-token", "error": "no_token"},),
+ ({"credential": "unsupported", "token": "invented-token"},),
+ ({"requestId": "x" * 129, "token": "invented-token"},),
+ ]
+ )
+ def test_rejects_invalid_credential_response(self, params: dict[str, str]) -> None:
+ serializer = TaskRunCommandRequestSerializer(
+ data={
+ "jsonrpc": "2.0",
+ "method": "credential_response",
+ "params": {"requestId": "request-1", "credential": "claude_subscription_token", **params},
+ }
+ )
+ assert not serializer.is_valid()
+ assert "params" in serializer.errors
diff --git a/products/tasks/backend/tests/test_warm_facade.py b/products/tasks/backend/tests/test_warm_facade.py
index e3346ecc053b..7c24db0d1368 100644
--- a/products/tasks/backend/tests/test_warm_facade.py
+++ b/products/tasks/backend/tests/test_warm_facade.py
@@ -1548,7 +1548,8 @@ class TestRunTaskWarmActivation(APIBaseTest):
run.refresh_from_db()
assert run.state.get("await_user_message") is True
- def test_context_window_mismatch_does_not_activate_warm_run(self):
+ @parameterized.expand([("context_window", "1m"), ("claude_model_access", "own-subscription")])
+ def test_runtime_selection_mismatch_does_not_activate_warm_run(self, field, value):
task, run = self._warm_run()
with (
patch(f"{FACADE}.signal_task_run_user_message") as mock_signal,
@@ -1562,7 +1563,7 @@ class TestRunTaskWarmActivation(APIBaseTest):
"mode": "interactive",
"branch": "main",
"pending_user_message": "do it",
- "context_window": "1m",
+ field: value,
},
)
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 6d2fe5ee1f3d..a3a0b1e9f5a9 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -2569,6 +2569,17 @@ export const InitialPermissionModeEnumApi = {
Auto: 'auto',
} as const
+/**
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription
+ */
+export type ClaudeModelAccessEnumApi = (typeof ClaudeModelAccessEnumApi)[keyof typeof ClaudeModelAccessEnumApi]
+
+export const ClaudeModelAccessEnumApi = {
+ PosthogGateway: 'posthog-gateway',
+ OwnSubscription: 'own-subscription',
+} as const
+
/**
* Request body for creating a new task run
*/
@@ -2669,6 +2680,11 @@ export interface ClaudeTaskRunCreateSchemaApi {
* @nullable
*/
benjamin_enabled?: boolean | null
+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.
+ *
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription */
+ claude_model_access?: ClaudeModelAccessEnumApi | null
}
/**
@@ -2795,6 +2811,11 @@ export interface CodexTaskRunCreateSchemaApi {
* @nullable
*/
benjamin_enabled?: boolean | null
+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.
+ *
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription */
+ claude_model_access?: ClaudeModelAccessEnumApi | null
}
export interface TaskRunResumeRequestSchemaApi {
@@ -3166,6 +3187,11 @@ export interface TaskRunBootstrapCreateRequestApi {
* @nullable
*/
benjamin_enabled?: boolean | null
+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.
+ *
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription */
+ claude_model_access?: ClaudeModelAccessEnumApi | null
}
/**
@@ -3724,6 +3750,7 @@ export const JsonrpcEnumApi = {
* * `permission_response` - permission_response
* * `set_config_option` - set_config_option
* * `mcp_response` - mcp_response
+ * * `credential_response` - credential_response
* * `pi/rpc` - pi/rpc
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear
@@ -3739,6 +3766,7 @@ export const TaskRunCommandRequestMethodEnumApi = {
PermissionResponse: 'permission_response',
SetConfigOption: 'set_config_option',
McpResponse: 'mcp_response',
+ CredentialResponse: 'credential_response',
PiRpc: 'pi/rpc',
QueueGet: 'queue_get',
QueueClear: 'queue_clear',
@@ -3761,6 +3789,7 @@ export interface TaskRunCommandRequestApi {
* * `permission_response` - permission_response
* * `set_config_option` - set_config_option
* * `mcp_response` - mcp_response
+ * * `credential_response` - credential_response
* * `pi/rpc` - pi/rpc
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 2c0bd2ca86ad..13773b95cab5 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1873,6 +1873,17 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
),
+ claude_model_access: zod
+ .union([
+ zod
+ .enum(['posthog-gateway', 'own-subscription'])
+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
+ ),
})
.describe('Request body for creating a new task run'),
zod
@@ -2026,6 +2037,17 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([
.describe(
'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
),
+ claude_model_access: zod
+ .union([
+ zod
+ .enum(['posthog-gateway', 'own-subscription'])
+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
+ ),
})
.describe('Request body for creating a new task run'),
zod.object({
@@ -2471,6 +2493,17 @@ export const TasksRunsCreateBody = /* @__PURE__ */ zod
.describe(
'Whether the Benjamin-Plus token-efficiency instruction applies to this run. Omitted or null lets the server decide from the feature flag; true or false pins the choice for this run.'
),
+ claude_model_access: zod
+ .union([
+ zod
+ .enum(['posthog-gateway', 'own-subscription'])
+ .describe('\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"
+ ),
})
.describe('Request body for creating a task run without starting execution yet.')
@@ -3085,16 +3118,17 @@ export const TasksRunsCommandCreateBody = /* @__PURE__ */ zod
'permission_response',
'set_config_option',
'mcp_response',
+ 'credential_response',
'pi/rpc',
'queue_get',
'queue_clear',
'side_question',
])
.describe(
- '\* `user_message` - user_message\n\* `cancel` - cancel\n\* `close` - close\n\* `permission_response` - permission_response\n\* `set_config_option` - set_config_option\n\* `mcp_response` - mcp_response\n\* `pi\/rpc` - pi\/rpc\n\* `queue_get` - queue_get\n\* `queue_clear` - queue_clear\n\* `side_question` - side_question'
+ '\* `user_message` - user_message\n\* `cancel` - cancel\n\* `close` - close\n\* `permission_response` - permission_response\n\* `set_config_option` - set_config_option\n\* `mcp_response` - mcp_response\n\* `credential_response` - credential_response\n\* `pi\/rpc` - pi\/rpc\n\* `queue_get` - queue_get\n\* `queue_clear` - queue_clear\n\* `side_question` - side_question'
)
.describe(
- 'Command method to execute on the agent server\n\n\* `user_message` - user_message\n\* `cancel` - cancel\n\* `close` - close\n\* `permission_response` - permission_response\n\* `set_config_option` - set_config_option\n\* `mcp_response` - mcp_response\n\* `pi\/rpc` - pi\/rpc\n\* `queue_get` - queue_get\n\* `queue_clear` - queue_clear\n\* `side_question` - side_question'
+ 'Command method to execute on the agent server\n\n\* `user_message` - user_message\n\* `cancel` - cancel\n\* `close` - close\n\* `permission_response` - permission_response\n\* `set_config_option` - set_config_option\n\* `mcp_response` - mcp_response\n\* `credential_response` - credential_response\n\* `pi\/rpc` - pi\/rpc\n\* `queue_get` - queue_get\n\* `queue_clear` - queue_clear\n\* `side_question` - side_question'
),
params: zod.record(zod.string(), zod.unknown()).optional().describe('Parameters for the command'),
id: zod.unknown().optional().describe('Optional JSON-RPC request ID (string or number)'),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 67cf11734aba..013e33503311 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17343,6 +17343,18 @@ export namespace Schemas {
total_with_tags: number;
}
+ /**
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription
+ */
+ export type ClaudeModelAccessEnum = typeof ClaudeModelAccessEnum[keyof typeof ClaudeModelAccessEnum];
+
+
+ export const ClaudeModelAccessEnum = {
+ PosthogGateway: 'posthog-gateway',
+ OwnSubscription: 'own-subscription',
+ } as const;
+
/**
* * `claude` - claude
*/
@@ -17578,6 +17590,11 @@ export namespace Schemas {
* @nullable
*/
benjamin_enabled?: boolean | null;
+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.
+ *
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription */
+ claude_model_access?: ClaudeModelAccessEnum | null;
}
export type ClickhouseEventProperties = { [key: string]: unknown };
@@ -17988,6 +18005,11 @@ export namespace Schemas {
* @nullable
*/
benjamin_enabled?: boolean | null;
+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.
+ *
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription */
+ claude_model_access?: ClaudeModelAccessEnum | null;
}
export type PropertyGroupOperatorEnum = typeof PropertyGroupOperatorEnum[keyof typeof PropertyGroupOperatorEnum];
@@ -86064,6 +86086,11 @@ export namespace Schemas {
* @nullable
*/
benjamin_enabled?: boolean | null;
+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.
+ *
+ * * `posthog-gateway` - posthog-gateway
+ * * `own-subscription` - own-subscription */
+ claude_model_access?: ClaudeModelAccessEnum | null;
}
export interface TaskRunCancelRequest {
@@ -86089,6 +86116,7 @@ export namespace Schemas {
* * `permission_response` - permission_response
* * `set_config_option` - set_config_option
* * `mcp_response` - mcp_response
+ * * `credential_response` - credential_response
* * `pi/rpc` - pi/rpc
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear
@@ -86104,6 +86132,7 @@ export namespace Schemas {
PermissionResponse: 'permission_response',
SetConfigOption: 'set_config_option',
McpResponse: 'mcp_response',
+ CredentialResponse: 'credential_response',
PiRpc: 'pi/rpc',
QueueGet: 'queue_get',
QueueClear: 'queue_clear',
@@ -86126,6 +86155,7 @@ export namespace Schemas {
* * `permission_response` - permission_response
* * `set_config_option` - set_config_option
* * `mcp_response` - mcp_response
+ * * `credential_response` - credential_response
* * `pi/rpc` - pi/rpc
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear