: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): send posthog code traffic to the ai gateway behind a flag (#106214)
Brandonc522b2264bcf
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.tsindex 738373c40845..2489bfb14c53 100644--- a/products/desktop/apps/code/src/main/di/bindings.ts+++ b/products/desktop/apps/code/src/main/di/bindings.ts@@ -74,7 +74,11 @@ import type { NewTaskLinkService } from "@posthog/core/links/new-task-link";import type { OpenTargetLinkService } from "@posthog/core/links/open-target-link";import type { ScoutLinkService } from "@posthog/core/links/scout-link";import type { TaskLinkService } from "@posthog/core/links/task-link";+import type { GatewayTokenService } from "@posthog/core/llm-gateway/gateway-token";import type {+ GATEWAY_TOKEN_HOST,+ GATEWAY_TOKEN_SERVICE,+ GatewayTokenHost,LLM_GATEWAY_HOST,LlmGatewayHost,} from "@posthog/core/llm-gateway/identifiers";@@ -169,8 +173,14 @@ import type {ArchiveFileWatcher,SessionCanceller,} from "@posthog/workspace-server/services/archive/ports";-import type { AUTH_PROXY_AUTH } from "@posthog/workspace-server/services/auth-proxy/identifiers";-import type { AuthProxyAuth } from "@posthog/workspace-server/services/auth-proxy/ports";+import type {+ AUTH_PROXY_AUTH,+ GATEWAY_CREDENTIAL_SOURCE,+} from "@posthog/workspace-server/services/auth-proxy/identifiers";+import type {+ AuthProxyAuth,+ GatewayCredentialSource,+} from "@posthog/workspace-server/services/auth-proxy/ports";import type { ConnectivityService } from "@posthog/workspace-server/services/connectivity/service";import type {ENRICHMENT_AUTH,@@ -396,6 +406,7 @@ export interface MainBindings {// Auth proxy / mcp proxy / mcp relay[AUTH_PROXY_AUTH]: AuthProxyAuth;+ [GATEWAY_CREDENTIAL_SOURCE]: GatewayCredentialSource;[MCP_PROXY_AUTH]: McpProxyAuth;[MCP_RELAY_SERVICE]: McpRelayService;[MCP_RELAY_EXECUTOR]: McpRelayExecutor;@@ -431,6 +442,8 @@ export interface MainBindings {// Llm gateway[LLM_GATEWAY_HOST]: LlmGatewayHost;+ [GATEWAY_TOKEN_HOST]: GatewayTokenHost;+ [GATEWAY_TOKEN_SERVICE]: GatewayTokenService;[MAIN_LLM_GATEWAY_SERVICE]: LlmGatewayService;// Mcp appsdiff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.tsindex 167a89d9bb39..06c823fa04c7 100644--- a/products/desktop/apps/code/src/main/di/container.ts+++ b/products/desktop/apps/code/src/main/di/container.ts@@ -1,5 +1,6 @@import { SETTINGS_BACKUP_FILES } from "@posthog/platform/settings-backup-files";import { ElectronSettingsBackupFiles } from "../platform-adapters/electron-settings-backup-files";+import { desktopGatewayTokenHost } from "../utils/gateway-override";import "reflect-metadata";import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises";@@ -69,11 +70,17 @@ import { NewTaskLinkService } from "@posthog/core/links/new-task-link";import { OpenTargetLinkService } from "@posthog/core/links/open-target-link";import { ScoutLinkService } from "@posthog/core/links/scout-link";import { TaskLinkService } from "@posthog/core/links/task-link";+import type { GatewayTokenService } from "@posthog/core/llm-gateway/gateway-token";import {+ GATEWAY_TOKEN_HOST,+ GATEWAY_TOKEN_SERVICE,LLM_GATEWAY_HOST,LLM_GATEWAY_SERVICE,} from "@posthog/core/llm-gateway/identifiers";-import type { LlmGatewayService } from "@posthog/core/llm-gateway/llm-gateway";+import {+ desktopUsageUrl,+ type LlmGatewayService,+} from "@posthog/core/llm-gateway/llm-gateway";import { llmGatewayModule } from "@posthog/core/llm-gateway/llm-gateway.module";import { MCP_APPS_SERVICE } from "@posthog/core/mcp-apps/identifiers";import { mcpAppsModule } from "@posthog/core/mcp-apps/mcp-apps.module";@@ -164,7 +171,10 @@ import {ARCHIVE_SESSION_CANCELLER,} from "@posthog/workspace-server/services/archive/identifiers";import { authProxyModule } from "@posthog/workspace-server/services/auth-proxy/auth-proxy.module";-import { AUTH_PROXY_AUTH } from "@posthog/workspace-server/services/auth-proxy/identifiers";+import {+ AUTH_PROXY_AUTH,+ GATEWAY_CREDENTIAL_SOURCE,+} from "@posthog/workspace-server/services/auth-proxy/identifiers";import { browserTabsModule } from "@posthog/workspace-server/services/browser-tabs/browser-tabs.module";import { claudeCliSessionsModule } from "@posthog/workspace-server/services/claude-cli-sessions/claude-cli-sessions.module";import { ConnectivityService } from "@posthog/workspace-server/services/connectivity/service";@@ -440,6 +450,9 @@ container.bind(AUTH_PROXY_AUTH).toDynamicValue((ctx) => ({.get<AuthService>(MAIN_AUTH_SERVICE).authenticatedFetch(fetch, url, init),}));+container+ .bind(GATEWAY_CREDENTIAL_SOURCE)+ .toDynamicValue((ctx) => ctx.get<GatewayTokenService>(GATEWAY_TOKEN_SERVICE));container.load(mcpProxyModule);container.bind(MCP_PROXY_AUTH).toDynamicValue((ctx) => {const auth = () => ctx.get<AuthService>(MAIN_AUTH_SERVICE);@@ -560,12 +573,15 @@ container.bind(LLM_GATEWAY_HOST).toDynamicValue((ctx) => {getValidAccessToken: () => auth().getValidAccessToken(),authenticatedFetch: (url: string, init?: RequestInit) =>auth().authenticatedFetch(fetch, url, init),+ fetch: (url: string, init?: RequestInit) => fetch(url, init),messagesUrl: (apiHost: string) =>`${getLlmGatewayUrl(apiHost)}/v1/messages`,- usageUrl: (apiHost: string) => getGatewayUsageUrl(apiHost),+ usageUrl: desktopUsageUrl,+ legacyUsageUrl: (apiHost: string) => getGatewayUsageUrl(apiHost),defaultModel: DEFAULT_GATEWAY_MODEL,};});+container.bind(GATEWAY_TOKEN_HOST).toConstantValue(desktopGatewayTokenHost());container.bind(MAIN_LLM_GATEWAY_SERVICE).toService(LLM_GATEWAY_SERVICE);container.load(mcpAppsModule);container.bind(MAIN_MCP_APPS_SERVICE).toService(MCP_APPS_SERVICE);diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.tsindex 7e8e92012f38..0e2510c929f4 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts@@ -1,12 +1,20 @@import type { PiRpcClient } from "@posthog/agent/pi/rpc-client";import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";import type { RootLogger } from "@posthog/di/logger";+import { ROOT_LOGGER } from "@posthog/di/logger";import { getCloudUrlFromRegion } from "@posthog/shared";+import {+ AGENT_AUTH,+ AGENT_MCP_APPS,+ MCP_SERVER_CONNECTION_SOURCE,+} from "@posthog/workspace-server/services/agent/identifiers";import type {AgentAuth,AgentMcpApps,} from "@posthog/workspace-server/services/agent/ports";import type { AuthProxyService } from "@posthog/workspace-server/services/auth-proxy/auth-proxy";+import { AUTH_PROXY_SERVICE } from "@posthog/workspace-server/services/auth-proxy/identifiers";+import { Container } from "inversify";import { describe, expect, it, vi } from "vitest";import { DesktopPiRpcClientFactory } from "./desktop-pi-rpc-client-factory";@@ -106,6 +114,11 @@ describe("DesktopPiRpcClientFactory", () => {mcpServerSource,mcpApps as unknown as AgentMcpApps,rootLogger,+ {+ getRoute: vi.fn(async () => ({ mode: "legacy" as const, reason: "x" })),+ remint: vi.fn(),+ fallBack: vi.fn(),+ },);await expect(@@ -182,4 +195,107 @@ describe("DesktopPiRpcClientFactory", () => {extensions: ["context-wiki"],});});++ it.each([+ ["go", "http://127.0.0.1:1234/session"],+ ["legacy", "http://127.0.0.1:1234/legacy"],+ ] as const)(+ "routes a Pi session to the %s gateway by the source's route",+ async (mode, expectedBaseUrl) => {+ const auth = {+ getOAuthCredentials: vi.fn(async () => ({+ access: "access-token",+ refresh: null,+ expires: 1,+ region: "us" as const,+ })),+ getState: vi.fn(() => ({ currentProjectId: 7 })),+ getValidAccessToken: vi.fn(async () => ({+ accessToken: "access-token",+ apiHost: "https://us.posthog.com",+ })),+ } as unknown as AgentAuth;+ const authProxy = {+ start: vi.fn(async (url: string) =>+ url === "https://us.posthog.com"+ ? "http://127.0.0.1:5678"+ : "http://127.0.0.1:1234/legacy",+ ),+ startGatewaySession: vi.fn(async () => "http://127.0.0.1:1234/session"),+ } as unknown as AuthProxyService;+ const source = {+ getRoute: vi.fn(async () =>+ mode === "go"+ ? { mode: "go", token: "phe_x", teamId: 7, projectId: 7 }+ : { mode: "legacy", reason: "not_rolled_out" },+ ),+ remint: vi.fn(),+ fallBack: vi.fn(),+ };+ createPiRpcClient.mockReturnValue({} as PiRpcClient);+ const factory = new DesktopPiRpcClientFactory(+ auth,+ authProxy,+ {+ getMcpRuntimeConfiguration: vi.fn(async () => ({+ servers: [],+ policies: [],+ })),+ },+ {+ addServerConfigs: vi.fn(),+ handleDiscovery: vi.fn(async () => {}),+ } as unknown as AgentMcpApps,+ {+ scope: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+ } as unknown as RootLogger,+ source as never,+ );++ await factory.create({ taskContext: { taskId: "task-9", cwd: "/w" } });++ expect(source.getRoute).toHaveBeenCalledWith(7, { awaitRecheck: true });+ expect(createPiRpcClient).toHaveBeenLastCalledWith(+ expect.objectContaining({+ providerOptions: {+ region: "us",+ baseUrl: expectedBaseUrl,+ apiKey: "posthog-code-auth-proxy",+ },+ }),+ );+ if (mode === "go") {+ expect(authProxy.startGatewaySession).toHaveBeenCalledWith({+ projectId: 7,+ legacyGatewayUrl: getLlmGatewayUrl("https://us.posthog.com"),+ headers: {+ "x-posthog-property-task_id": "task-9",+ "x-posthog-property-$ai_session_id": "task-9",+ "X-PostHog-Project-Id": "7",+ },+ });+ }+ },+ );+});++it("refuses to resolve the Pi factory without a gateway credential source", () => {+ const container = new Container();+ for (const token of [+ AGENT_AUTH,+ AUTH_PROXY_SERVICE,+ MCP_SERVER_CONNECTION_SOURCE,+ AGENT_MCP_APPS,+ ROOT_LOGGER,+ ]) {+ container.bind(token).toConstantValue({});+ }+ container.bind(DesktopPiRpcClientFactory).toSelf();++ expect(() => container.get(DesktopPiRpcClientFactory)).toThrow();});diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.tsindex d62945c32cf6..d828165c7d8e 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts@@ -27,8 +27,15 @@ import type {McpServerConnectionSource,} from "@posthog/workspace-server/services/agent/ports";import type { AuthProxyService } from "@posthog/workspace-server/services/auth-proxy/auth-proxy";-import { AUTH_PROXY_SERVICE } from "@posthog/workspace-server/services/auth-proxy/identifiers";-import { AUTH_PROXY_PLACEHOLDER_CREDENTIAL as PROXY_API_KEY } from "@posthog/workspace-server/services/auth-proxy/ports";+import { resolveGatewayProxy } from "@posthog/workspace-server/services/auth-proxy/gateway-proxy";+import {+ AUTH_PROXY_SERVICE,+ GATEWAY_CREDENTIAL_SOURCE,+} from "@posthog/workspace-server/services/auth-proxy/identifiers";+import {+ type GatewayCredentialSource,+ AUTH_PROXY_PLACEHOLDER_CREDENTIAL as PROXY_API_KEY,+} from "@posthog/workspace-server/services/auth-proxy/ports";import type { PiRpcClientFactory } from "@posthog/workspace-server/services/pi-session/identifiers";import { inject, injectable } from "inversify";@@ -42,6 +49,9 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {private readonly mcpServerSource: McpServerConnectionSource,@inject(AGENT_MCP_APPS) private readonly mcpApps: AgentMcpApps,@inject(ROOT_LOGGER) private readonly rootLogger: RootLogger,+ // Required: an unbound source would silently keep Pi on legacy.+ @inject(GATEWAY_CREDENTIAL_SOURCE)+ private readonly gatewaySource: GatewayCredentialSource,) {}async create(@@ -153,18 +163,21 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {}}- private getProxyUrl(+ private async getProxyUrl(region: CloudRegion,projectId: number,taskId: string,): Promise<string> {- const gatewayUrl = getLlmGatewayUrl(getCloudUrlFromRegion(region));- return this.authProxy.start(- gatewayUrl,- buildPosthogScopedPropertyHeaderRecord(+ const { proxyUrl } = await resolveGatewayProxy({+ authProxy: this.authProxy,+ source: this.gatewaySource,+ legacyGatewayUrl: getLlmGatewayUrl(getCloudUrlFromRegion(region)),+ projectId,+ headers: buildPosthogScopedPropertyHeaderRecord({ task_id: taskId, $ai_session_id: taskId },projectId,),- );+ });+ return proxyUrl;}}diff --git a/products/desktop/apps/code/src/main/utils/gateway-override.test.ts b/products/desktop/apps/code/src/main/utils/gateway-override.test.tsnew file mode 100644index 000000000000..67a19ff2a507--- /dev/null+++ b/products/desktop/apps/code/src/main/utils/gateway-override.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import {+ desktopGatewayTokenHost,+ takeGatewayOverride,+} from "./gateway-override";++describe("takeGatewayOverride", () => {+ it("returns the override and removes both variables from the env", () => {+ const env: NodeJS.ProcessEnv = {+ POSTHOG_CODE_AI_GATEWAY_URL: "http://localhost:3308/v1",+ POSTHOG_CODE_AI_GATEWAY_TOKEN: "phe_dev",+ OTHER: "kept",+ };++ expect(takeGatewayOverride(env)).toEqual({+ url: "http://localhost:3308",+ token: "phe_dev",+ });+ expect(env).toEqual({ OTHER: "kept" });+ });++ it.each([+ [{ POSTHOG_CODE_AI_GATEWAY_URL: "http://localhost:3308" }],+ [{ POSTHOG_CODE_AI_GATEWAY_TOKEN: "phe_dev" }],+ [+ {+ POSTHOG_CODE_AI_GATEWAY_URL: "http://gateway.example",+ POSTHOG_CODE_AI_GATEWAY_TOKEN: "phe_dev",+ },+ ],+ [+ {+ POSTHOG_CODE_AI_GATEWAY_URL: "https://gateway.example",+ POSTHOG_CODE_AI_GATEWAY_TOKEN: "phe_dev",+ },+ ],+ ])(+ "ignores an incomplete, plain-http or unlisted override and still deletes it",+ (vars) => {+ const env: NodeJS.ProcessEnv = { ...vars };++ expect(takeGatewayOverride(env)).toBeNull();+ expect(env).toEqual({});+ },+ );+});++describe("desktopGatewayTokenHost", () => {+ it("enables the Go gateway and takes the override", () => {+ const env: NodeJS.ProcessEnv = {+ POSTHOG_CODE_AI_GATEWAY_URL: "http://localhost:3308",+ POSTHOG_CODE_AI_GATEWAY_TOKEN: "phe_dev",+ };++ expect(desktopGatewayTokenHost(env)).toEqual({+ goEnabled: true,+ override: { url: "http://localhost:3308", token: "phe_dev" },+ });+ expect(env).toEqual({});+ });++ it("enables the Go gateway without an override", () => {+ expect(desktopGatewayTokenHost({})).toEqual({+ goEnabled: true,+ override: null,+ });+ });+});diff --git a/products/desktop/apps/code/src/main/utils/gateway-override.ts b/products/desktop/apps/code/src/main/utils/gateway-override.tsnew file mode 100644index 000000000000..c5eb04f8cbf5--- /dev/null+++ b/products/desktop/apps/code/src/main/utils/gateway-override.ts@@ -0,0 +1,31 @@+import type {+ GatewayTokenHost,+ GatewayTokenOverride,+} from "@posthog/core/llm-gateway/identifiers";+import { validateAiGatewayUrl } from "@posthog/shared";++const URL_VAR = "POSTHOG_CODE_AI_GATEWAY_URL";+const TOKEN_VAR = "POSTHOG_CODE_AI_GATEWAY_TOKEN";++/**+ * Reads the dev Go gateway override once and deletes it from the env, since+ * every child process (the Claude CLI included) inherits the whole env.+ */+export function takeGatewayOverride(+ env: NodeJS.ProcessEnv = process.env,+): GatewayTokenOverride | null {+ const rawUrl = env[URL_VAR];+ const token = env[TOKEN_VAR];+ delete env[URL_VAR];+ delete env[TOKEN_VAR];+ if (!rawUrl || !token) return null;+ const url = rawUrl.trim().replace(/\/v1\/?$/, "");+ const origin = validateAiGatewayUrl(url, { allowLoopback: true });+ return origin ? { url: origin, token } : null;+}++export function desktopGatewayTokenHost(+ env: NodeJS.ProcessEnv = process.env,+): GatewayTokenHost {+ return { goEnabled: true, override: takeGatewayOverride(env) };+}diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.tsindex 902e2f21f9b0..aa1638b98a04 100644--- a/products/desktop/apps/web/src/web-container.ts+++ b/products/desktop/apps/web/src/web-container.ts@@ -92,11 +92,16 @@ import {} from "@posthog/core/integrations/identifiers";import { RepositoriesService } from "@posthog/core/integrations/repositoriesService";import {+ GATEWAY_TOKEN_HOST,+ type GatewayTokenHost,LLM_GATEWAY_HOST,LLM_GATEWAY_SERVICE,type LlmGatewayHost,} from "@posthog/core/llm-gateway/identifiers";-import type { LlmGatewayService } from "@posthog/core/llm-gateway/llm-gateway";+import {+ desktopUsageUrl,+ type LlmGatewayService,+} from "@posthog/core/llm-gateway/llm-gateway";import { llmGatewayModule } from "@posthog/core/llm-gateway/llm-gateway.module";import {GITHUB_CONNECT_CLIENT as ONBOARDING_GITHUB_CONNECT_CLIENT,@@ -410,6 +415,7 @@ interface WebBindings {[TITLE_GENERATOR_LOGGER]: TitleGeneratorLogger;[LLM_GATEWAY_SERVICE]: LlmGatewayService;[LLM_GATEWAY_HOST]: LlmGatewayHost;+ [GATEWAY_TOKEN_HOST]: GatewayTokenHost;[FILE_WATCHER_CLIENT]: FileWatcherClient;[GIT_INTERACTION_SERVICE]: GitInteractionService;[GIT_WRITE_CLIENT]: IGitWriteClient;@@ -790,10 +796,16 @@ container.bind(LLM_GATEWAY_HOST).toDynamicValue((ctx) => {),messagesUrl: (apiHost: string) =>`${getLlmGatewayUrl(apiHost)}/v1/messages`,- usageUrl: (apiHost: string) => getGatewayUsageUrl(apiHost),+ usageUrl: desktopUsageUrl,+ legacyUsageUrl: (apiHost: string) => getGatewayUsageUrl(apiHost),defaultModel: DEFAULT_GATEWAY_MODEL,};});+// The Go gateway sends no CORS headers and the web host has no loopback+// proxy, so helper prompts stay on the legacy gateway here.+container+ .bind(GATEWAY_TOKEN_HOST)+ .toConstantValue({ goEnabled: false, override: null });// ── File watcher (TaskDetail's useRepoFileWatcher) ──// Watches a local repo for changes; there is none on web. The consumer gatesdiff --git a/products/desktop/packages/agent/src/gateway-models.test.ts b/products/desktop/packages/agent/src/gateway-models.test.tsindex e243cf025308..1056ecaece8a 100644--- a/products/desktop/packages/agent/src/gateway-models.test.ts+++ b/products/desktop/packages/agent/src/gateway-models.test.ts@@ -107,3 +107,64 @@ describe("gateway models cache", () => {expect(cached[0]?.allowed).toBe(false);});});++describe("Go gateway model entries", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const goEntries = [+ { id: "claude-opus-5", object: "model", owned_by: "anthropic" },+ { id: "gpt-6-sol", object: "model", owned_by: "openai" },+ ];++ it("reads entries without marks from a slugless URL as allowed", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(JSON.stringify({ object: "list", data: goEntries }), {+ status: 200,+ }),+ );++ const models = await fetchModelsList({+ gatewayUrl: "http://127.0.0.1:4100/go-slugless",+ authToken: "posthog-code-auth-proxy",+ });++ expect(fetchMock.mock.calls[0]?.[0]).toBe(+ "http://127.0.0.1:4100/go-slugless/v1/models",+ );+ expect(models).toEqual([+ expect.objectContaining({ id: "claude-opus-5", allowed: true }),+ expect.objectContaining({ id: "gpt-6-sol", allowed: true }),+ ]);+ });++ it("keeps the proxy's marks on Go entries", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response(+ JSON.stringify({+ object: "list",+ data: [+ {+ ...goEntries[0],+ allowed: false,+ restriction_reason: "paid_plan_required",+ },+ { ...goEntries[1], allowed: true, restriction_reason: null },+ ],+ }),+ { status: 200 },+ ),+ );++ const models = await fetchGatewayModels({+ gatewayUrl: "http://127.0.0.1:4100/go-marked",+ authToken: "posthog-code-auth-proxy",+ });++ expect(models.map((m) => [m.id, m.allowed])).toEqual([+ ["claude-opus-5", false],+ ["gpt-6-sol", true],+ ]);+ });+});diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.tsindex 93f5ba465cbd..d899e87c53f6 100644--- a/products/desktop/packages/core/src/auth/auth.test.ts+++ b/products/desktop/packages/core/src/auth/auth.test.ts@@ -524,6 +524,62 @@ describe("AuthService", () => {expect(response.status).toBe(200);});+ it("applies a desktop access denial reported by another endpoint", async () => {+ seedStoredSession({ selectedProjectId: 42 });+ stubAuthFetch();+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());+ await service.initialize();++ service.reportDesktopAccessBlocked(99, {+ allowed: false,+ reason: "startup_plan",+ });+ expect(service.getState().desktopAccess.status).not.toBe("blocked");+ service.reportDesktopAccessBlocked(42, {+ allowed: false,+ reason: "startup_plan",+ });++ expect(service.getState().desktopAccess).toEqual({+ projectId: 42,+ status: "blocked",+ reason: "startup_plan",+ });+ });++ it("changes the session epoch on a sign-in over a live session only", async () => {+ seedStoredSession({ selectedProjectId: 42 });+ stubAuthFetch();+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());+ await service.initialize();+ const first = service.getSessionEpoch();+ expect(first).not.toBeNull();++ await service.refreshAccessToken();+ expect(service.getSessionEpoch()).toBe(first);++ let finishFlow: (value: unknown) => void = () => undefined;+ oauthFlow.startFlow.mockReturnValueOnce(+ new Promise((resolve) => {+ finishFlow = resolve;+ }),+ );+ const pending = service.login("us");+ await service.refreshAccessToken().catch(() => undefined);+ expect(service.getSessionEpoch()).toBe(first);+ finishFlow(mockTokenResponse());+ await pending;+ expect(service.getSessionEpoch()).not.toBe(first);+ const second = service.getSessionEpoch();++ oauthFlow.startFlow.mockResolvedValue(mockTokenResponse());+ await service.login("us");+ expect(service.getSessionEpoch()).not.toBe(second);++ await service.logout();+ expect(service.getSessionEpoch()).toBeNull();+ });+it("requires scope reauthentication when the stored scope version is stale", async () => {seedStoredSession({refreshToken: "refresh-token",diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.tsindex d996a3d3efc9..755e08e8d02e 100644--- a/products/desktop/packages/core/src/auth/auth.ts+++ b/products/desktop/packages/core/src/auth/auth.ts@@ -111,6 +111,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {private refreshPromise: Promise<InMemorySession> | null = null;private impersonationExpiryTimer: ReturnType<typeof setTimeout> | null = null;private sessionGeneration = 0;+ private sessionEpoch = 0;// A refresh already refused, keyed to the session generation so every teardown// invalidates it. `until: null` is a proven-dead token, a timestamp is a pause.private refusedRefresh: {@@ -155,6 +156,28 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {getState(): AuthState {return { ...this.state };}+ reportDesktopAccessBlocked(projectId: number, access: unknown): void {+ if (this.state.currentProjectId !== projectId) return;+ const parsed = desktopAccessResponseSchema.safeParse(access);+ if (!parsed.success || parsed.data.allowed) return;+ this.updateState({+ desktopAccess: {+ projectId,+ status: "blocked",+ reason: parsed.data.reason,+ },+ });+ }+ getCachedAccountKey(): string | null {+ return this.session?.accountKey ?? null;+ }+ /**+ * Changes with every sign-in, including one that replaces a live session+ * without signing out first; token refreshes keep it. Null when signed out.+ */+ getSessionEpoch(): number | null {+ return this.session ? this.sessionEpoch : null;+ }async getAccountKey(): Promise<string | null> {const generation = this.sessionGeneration;const { apiHost } = await this.getValidAccessToken();@@ -1148,11 +1171,12 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {cloudRegion: region,selectedProjectId: this.state.currentProjectId,});- await this.syncAuthenticatedSession(session, sessionGeneration);+ await this.syncAuthenticatedSession(session, sessionGeneration, true);}private async syncAuthenticatedSession(session: InMemorySession,sessionGeneration: number,+ signIn = false,): Promise<boolean> {if (this.sessionGeneration !== sessionGeneration) {return false;@@ -1178,6 +1202,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {}this.persistProjectPreference(session);const desktopAccess = this.carryDesktopAccessInto(session);+ if (signIn) this.sessionEpoch += 1;this.session = session;this.scheduleImpersonationExpiry(session);this.updateState({diff --git a/products/desktop/packages/core/src/llm-gateway/gateway-token.test.ts b/products/desktop/packages/core/src/llm-gateway/gateway-token.test.tsnew file mode 100644index 000000000000..a98abbb8a117--- /dev/null+++ b/products/desktop/packages/core/src/llm-gateway/gateway-token.test.ts@@ -0,0 +1,1082 @@+import type { RootLogger } from "@posthog/di/logger";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AuthService } from "../auth/auth";+import type { AuthState } from "../auth/schemas";+import {+ GATEWAY_BLOCKED_RECHECK_MS,+ GATEWAY_LEGACY_RECHECK_MS,+ GATEWAY_MINT_TIMEOUT_MS,+ GATEWAY_NOT_ROLLED_OUT_RECHECK_MS,+ GATEWAY_REFRESH_RETRY_MS,+ GATEWAY_REMINT_MIN_INTERVAL_MS,+ GATEWAY_TOKEN_MIN_REFRESH_SKEW_MS,+ GATEWAY_TOKEN_REFRESH_SKEW_MS,+ GatewayTokenService,+} from "./gateway-token";+import type { GatewayTokenHost, LlmGatewayHost } from "./identifiers";++const API_HOST = "https://us.posthog.com";+const MINT_URL = `${API_HOST}/api/projects/42/desktop/gateway_token/`;++function minted(token: string, expiresInMs = 3_600_000) {+ return {+ enabled: true,+ token,+ expires_at: new Date(Date.now() + expiresInMs).toISOString(),+ cap_usd: "200",+ gateway_url: "https://ai-gateway.us.posthog.com",+ product: "posthog_code",+ team_id: 7,+ plan: "paid",+ allowed_models: ["claude-opus-5"],+ product_models: ["claude-opus-5", "gpt-6-sol"],+ };+}++function json(body: unknown, status: number): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function baseState(overrides: Partial<AuthState> = {}): AuthState {+ return {+ status: "authenticated",+ bootstrapComplete: true,+ cloudRegion: "us",+ orgProjectsMap: {},+ currentOrgId: "org-1",+ currentProjectId: 42,+ desktopAccess: { projectId: 42, status: "allowed", reason: null },+ needsScopeReauth: false,+ sessionType: "persistent",+ sessionExpiresAt: null,+ ...overrides,+ };+}++function setup(+ options: { config?: Partial<GatewayTokenHost>; state?: AuthState } = {},+) {+ let state = options.state ?? baseState();+ let accountKey: string | null = "user-1";+ let sessionEpoch: number | null = 1;+ const listeners: Array<(state: AuthState) => void> = [];+ const reportDesktopAccessBlocked = vi.fn();+ const authService = {+ getState: () => state,+ on: (_event: string, listener: (state: AuthState) => void) => {+ listeners.push(listener);+ },+ getCachedAccountKey: () => accountKey,+ getSessionEpoch: () => sessionEpoch,+ reportDesktopAccessBlocked,+ } as unknown as AuthService;++ const mintResponses: Array<+ (init?: RequestInit) => Response | Promise<Response>+ > = [];+ const authenticatedFetch = vi.fn(async (url: string, init?: RequestInit) => {+ const next = mintResponses.shift();+ if (!next) throw new Error(`unexpected fetch ${url}`);+ return next(init);+ });+ const host: LlmGatewayHost = {+ getValidAccessToken: vi+ .fn()+ .mockResolvedValue({ accessToken: "pha_x", apiHost: API_HOST }),+ authenticatedFetch,+ messagesUrl: () => "",+ usageUrl: () => "",+ legacyUsageUrl: () => "",+ defaultModel: "m",+ };+ const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const logger = { ...log, scope: () => log } as unknown as RootLogger;+ const service = new GatewayTokenService(+ host,+ { goEnabled: true, override: null, ...options.config },+ authService,+ logger,+ );+ const mintCalls = () =>+ authenticatedFetch.mock.calls.filter(([url]) => url === MINT_URL).length;+ return {+ service,+ host,+ mintResponses,+ authenticatedFetch,+ mintCalls,+ reportDesktopAccessBlocked,+ setAccountKey(next: string | null) {+ accountKey = next;+ },+ setSessionEpoch(next: number | null) {+ sessionEpoch = next;+ },+ setState(next: AuthState) {+ state = next;+ for (const listener of listeners) listener(next);+ },+ };+}++describe("GatewayTokenService.getRoute", () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date("2026-09-23T12:00:00Z"));+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("mints once and serves the Go route from the cache", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));++ const first = await t.service.getRoute();+ const second = await t.service.getRoute(42);++ expect(first).toMatchObject({+ mode: "go",+ gatewayUrl: "https://ai-gateway.us.posthog.com",+ token: "phe_one",+ teamId: 7,+ plan: "paid",+ allowedModels: ["claude-opus-5"],+ productModels: ["claude-opus-5", "gpt-6-sol"],+ projectId: 42,+ source: "mint",+ });+ expect(second).toBe(first);+ expect(t.mintCalls()).toBe(1);+ const [, init] = t.authenticatedFetch.mock.calls[0];+ expect(init?.method).toBe("POST");+ expect(init?.redirect).toBe("error");+ });++ it("shares one in-flight mint between concurrent callers", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));++ const [a, b] = await Promise.all([+ t.service.getRoute(),+ t.service.getRoute(),+ ]);++ expect(a).toEqual(b);+ expect(t.mintCalls()).toBe(1);+ });++ it.each([+ [+ 200,+ { enabled: false, reason: "unconfigured" },+ "unconfigured",+ GATEWAY_LEGACY_RECHECK_MS,+ ],+ [+ 200,+ { enabled: false, reason: "not_rolled_out" },+ "not_rolled_out",+ GATEWAY_NOT_ROLLED_OUT_RECHECK_MS,+ ],+ [+ 403,+ { enabled: false, reason: "desktop_access_blocked" },+ "desktop_access_blocked",+ GATEWAY_LEGACY_RECHECK_MS,+ ],+ [+ 402,+ { enabled: false, reason: "payment_required" },+ "payment_required",+ GATEWAY_LEGACY_RECHECK_MS,+ ],+ [404, { detail: "Not found." }, "http_404", GATEWAY_LEGACY_RECHECK_MS],+ [429, { detail: "org deactivated" }, "http_429", GATEWAY_LEGACY_RECHECK_MS],+ [503, null, "http_503", GATEWAY_LEGACY_RECHECK_MS],+ ])(+ "treats a %s as legacy and re-checks after the negative cache",+ async (status, body, reason, recheckMs) => {+ const t = setup();+ t.mintResponses.push(() => json(body, status));+ t.mintResponses.push(() => json(minted("phe_one"), 201));++ expect(await t.service.getRoute()).toEqual({ mode: "legacy", reason });+ vi.setSystemTime(Date.now() + recheckMs - 1);+ expect(await t.service.getRoute()).toMatchObject({ mode: "legacy" });+ expect(t.mintCalls()).toBe(1);+ vi.setSystemTime(Date.now() + 2);+ expect(await t.service.getRoute()).toEqual({ mode: "legacy", reason });+ expect(t.mintCalls()).toBe(2);+ await vi.waitFor(async () =>+ expect(await t.service.getRoute()).toMatchObject({ mode: "go" }),+ );+ expect(t.mintCalls()).toBe(2);+ },+ );++ it("serves a known refusal to callers while its re-check is in flight", async () => {+ const t = setup();+ t.mintResponses.push(() =>+ json({ enabled: false, reason: "not_rolled_out" }, 200),+ );+ t.mintResponses.push(() => new Promise<Response>(() => undefined));++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + GATEWAY_NOT_ROLLED_OUT_RECHECK_MS);+ await t.service.getRoute();+ await vi.waitFor(() => expect(t.mintCalls()).toBe(2));++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "not_rolled_out",+ });+ });++ it("waits for the re-check when a session start asks for it", async () => {+ const t = setup();+ t.mintResponses.push(() =>+ json({ enabled: false, reason: "not_rolled_out" }, 200),+ );+ t.mintResponses.push(() => json(minted("phe_one"), 201));++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + GATEWAY_NOT_ROLLED_OUT_RECHECK_MS);++ expect(await t.service.getRoute(42, { awaitRecheck: true })).toMatchObject({+ mode: "go",+ token: "phe_one",+ });+ });++ it.each([+ [+ "a session start on a legacy route",+ { enabled: false, reason: "not_rolled_out" },+ 200,+ GATEWAY_NOT_ROLLED_OUT_RECHECK_MS,+ { awaitRecheck: true },+ ],+ [+ "any caller on a blocked route",+ { enabled: false, reason: "credit_bucket_exhausted" },+ 402,+ GATEWAY_BLOCKED_RECHECK_MS,+ {},+ ],+ ])(+ "joins a re-check already in flight for %s",+ async (_label, refusal, status, recheckMs, options) => {+ const t = setup();+ t.mintResponses.push(() => json(refusal, status));+ let release: (response: Response) => void = () => undefined;+ t.mintResponses.push(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + recheckMs);+ void t.service.getRoute(42, { awaitRecheck: false });+ await vi.waitFor(() => expect(t.mintCalls()).toBe(2));+ const joined = t.service.getRoute(42, options);+ release(json(minted("phe_one"), 201));++ expect(await joined).toMatchObject({ mode: "go", token: "phe_one" });+ },+ );++ it("waits for a due blocked re-check instead of refusing again", async () => {+ const t = setup();+ t.mintResponses.push(() =>+ json({ enabled: false, reason: "credit_bucket_exhausted" }, 402),+ );+ t.mintResponses.push(() => json(minted("phe_one"), 201));++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + GATEWAY_BLOCKED_RECHECK_MS);++ expect(await t.service.getRoute()).toMatchObject({+ mode: "go",+ token: "phe_one",+ });+ });++ it("treats an exhausted credit bucket as final, not as legacy", async () => {+ const t = setup();+ const sentence =+ "Your organization has reached its PostHog Desktop usage limit";+ t.mintResponses.push(() =>+ json(+ { enabled: false, reason: "credit_bucket_exhausted", detail: sentence },+ 402,+ ),+ );+ t.mintResponses.push(() => json(minted("phe_one"), 201));++ expect(await t.service.getRoute()).toEqual({+ mode: "blocked",+ reason: "credit_bucket_exhausted",+ detail: sentence,+ });+ vi.setSystemTime(Date.now() + GATEWAY_BLOCKED_RECHECK_MS - 1);+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });+ expect(+ await t.service.remint("unauthorized", "phe_none", undefined),+ ).toBeNull();+ expect(t.mintCalls()).toBe(1);++ t.service.clearBlocked();+ expect(await t.service.getRoute()).toMatchObject({ mode: "go" });+ });++ it.each([+ [403, { enabled: false, reason: "email_unverified" }, "email_unverified"],+ [+ 403,+ {+ detail: "Organization is deactivated.",+ code: "organization_deactivated",+ },+ "organization_deactivated",+ ],+ [429, { enabled: false, reason: "throttled" }, "throttled"],+ [+ 503,+ { enabled: false, reason: "desktop_access_unavailable" },+ "desktop_access_unavailable",+ ],+ [503, { enabled: false, reason: "mint_failed" }, "mint_failed"],+ ])(+ "keeps a %s refusal on legacy with its reason",+ async (status, body, reason) => {+ const t = setup();+ t.mintResponses.push(() => json(body, status));++ expect(await t.service.getRoute()).toEqual({ mode: "legacy", reason });+ },+ );++ it("feeds a desktop access denial into the auth state", async () => {+ const t = setup();+ const access = { allowed: false, reason: "startup_plan" };+ t.mintResponses.push(() =>+ json({ enabled: false, reason: "desktop_access_blocked", access }, 403),+ );++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "desktop_access_blocked",+ });+ expect(t.reportDesktopAccessBlocked).toHaveBeenCalledWith(42, access);+ });++ it("falls back to legacy when the mint request fails", async () => {+ const t = setup();+ t.mintResponses.push(() => {+ throw new Error("offline");+ });++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "mint_failed",+ });+ });++ it.each([+ "https://evil.example",+ "https://llm.posthog.com",+ "http://ai-gateway.us.posthog.com",+ "http://localhost:3308",+ "https://ai-gateway.us.posthog.com/v1",+ "https://ai-gateway.dev.posthog.dev",+ ])("refuses a token naming %s", async (gatewayUrl) => {+ const t = setup();+ t.mintResponses.push(() =>+ json({ ...minted("phe_bad"), gateway_url: gatewayUrl }, 201),+ );++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "invalid_gateway_url",+ });+ });++ it("reads the token's lifetime against the server clock", async () => {+ const t = setup();+ // The local clock runs 10 minutes ahead of the server.+ const serverNow = Date.now() - 10 * 60_000;+ t.mintResponses.push(+ () =>+ new Response(+ JSON.stringify({+ ...minted("phe_one"),+ expires_at: new Date(serverNow + 5 * 60_000).toISOString(),+ }),+ {+ status: 201,+ headers: { date: new Date(serverNow).toUTCString() },+ },+ ),+ );++ const route = await t.service.getRoute();++ expect(route).toMatchObject({ token: "phe_one" });+ expect((route as { expiresAt: number }).expiresAt).toBeGreaterThan(+ Date.now() + 4 * 60_000,+ );+ expect(await t.service.getRoute()).toBe(route);+ expect(t.mintCalls()).toBe(1);+ });++ it("pins the re-check, re-mint and refresh windows", () => {+ expect(GATEWAY_LEGACY_RECHECK_MS).toBe(600_000);+ expect(GATEWAY_NOT_ROLLED_OUT_RECHECK_MS).toBe(1_800_000);+ expect(GATEWAY_BLOCKED_RECHECK_MS).toBe(1_800_000);+ expect(GATEWAY_REMINT_MIN_INTERVAL_MS).toBe(5_000);+ expect(GATEWAY_REFRESH_RETRY_MS).toBe(30_000);+ expect(GATEWAY_TOKEN_REFRESH_SKEW_MS).toBe(120_000);+ expect(GATEWAY_TOKEN_MIN_REFRESH_SKEW_MS).toBe(30_000);+ expect(GATEWAY_MINT_TIMEOUT_MS).toBe(15_000);+ });++ it.each([+ ["a 2-minute", 2 * 60_000, 30_000],+ ["a 5-minute", 5 * 60_000, 30_000],+ ["a 10-minute", 10 * 60_000, 60_000],+ ["an hourly", 60 * 60_000, 120_000],+ ])(+ "refreshes %s token a tenth of its lifetime early, within bounds",+ async (_label, lifetimeMs, skewMs) => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one", lifetimeMs), 201));+ t.mintResponses.push(() => json(minted("phe_two", lifetimeMs), 201));+ const start = Date.now();++ await t.service.getRoute();+ vi.setSystemTime(start + lifetimeMs - skewMs - 1);+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });+ expect(t.mintCalls()).toBe(1);+ vi.setSystemTime(start + lifetimeMs - skewMs + 1);+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });+ await vi.waitFor(() => expect(t.mintCalls()).toBe(2));+ },+ );++ it("rejects a 201 whose expiry is not a date", async () => {+ const t = setup();+ t.mintResponses.push(() =>+ json({ ...minted("phe_one"), expires_at: "soon" }, 201),+ );++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "invalid_expiry",+ });+ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "invalid_expiry",+ });+ expect(t.mintCalls()).toBe(1);+ });++ it("gives up on a mint that does not answer in time", async () => {+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });+ const t = setup();+ t.mintResponses.push(+ (init) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () =>+ reject(new Error("aborted")),+ );+ }),+ );++ const pending = t.service.getRoute();+ await vi.advanceTimersByTimeAsync(GATEWAY_MINT_TIMEOUT_MS - 1);+ let settled = false;+ void pending.then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);+ await vi.advanceTimersByTimeAsync(1);++ expect(await pending).toEqual({ mode: "legacy", reason: "mint_failed" });+ });++ it("gives up on a mint whose body does not arrive in time", async () => {+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });+ const t = setup();+ t.mintResponses.push(+ (init) =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ init?.signal?.addEventListener("abort", () =>+ controller.error(new Error("aborted")),+ );+ },+ }),+ { status: 201 },+ ),+ );++ const pending = t.service.getRoute();+ await vi.advanceTimersByTimeAsync(GATEWAY_MINT_TIMEOUT_MS);++ expect(await pending).toEqual({+ mode: "legacy",+ reason: "invalid_mint_response",+ });+ });++ it("rejects a 201 that does not match the contract", async () => {+ const t = setup();+ t.mintResponses.push(() => json({ ...minted("sk-not-phe") }, 201));++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "invalid_mint_response",+ });+ });++ it("refreshes in the background inside the skew and blocks once expired", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one", 10 * 60_000), 201));+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ t.mintResponses.push(() => json(minted("phe_three"), 201));++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + 10 * 60_000 - 60_000 + 1);+ const during = await t.service.getRoute();+ expect(during).toMatchObject({ token: "phe_one" });+ await vi.waitFor(async () =>+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" }),+ );++ vi.setSystemTime(Date.now() + 3_600_000 + 1);+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_three" });+ });++ it.each([+ ["a network error", () => Promise.reject(new Error("offline"))],+ ["a 503", () => json(null, 503)],+ [+ "a flag-off refusal",+ () => json({ enabled: false, reason: "not_rolled_out" }, 200),+ ],+ ])(+ "keeps the unexpired token when the early refresh hits %s",+ async (_label, failure) => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one", 10 * 60_000), 201));+ t.mintResponses.push(failure);+ t.mintResponses.push(() => json(minted("phe_two"), 201));++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + 10 * 60_000 - 60_000 + 1);+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });+ await vi.waitFor(() => expect(t.mintCalls()).toBe(2));+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });+ expect(t.mintCalls()).toBe(2);++ vi.setSystemTime(Date.now() + GATEWAY_REFRESH_RETRY_MS);+ await t.service.getRoute();+ await vi.waitFor(async () =>+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" }),+ );+ },+ );++ it("replaces the unexpired token when the early refresh finds the bucket empty", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one", 10 * 60_000), 201));+ t.mintResponses.push(() =>+ json({ enabled: false, reason: "credit_bucket_exhausted" }, 402),+ );++ await t.service.getRoute();+ vi.setSystemTime(Date.now() + 10 * 60_000 - 60_000 + 1);+ await t.service.getRoute();+ await vi.waitFor(async () =>+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" }),+ );+ });++ it("answers legacy without minting on a host that cannot reach Go", async () => {+ const t = setup({ config: { goEnabled: false } });++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "host_unsupported",+ });+ expect(t.authenticatedFetch).not.toHaveBeenCalled();+ });++ it("answers legacy with no selected project", async () => {+ const t = setup({ state: baseState({ currentProjectId: null }) });++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "no_project",+ });+ });++ it("uses the dev override without minting", async () => {+ const t = setup({+ config: {+ override: { url: "http://localhost:3308", token: "phe_dev" },+ },+ });++ expect(await t.service.getRoute()).toMatchObject({+ mode: "go",+ gatewayUrl: "http://localhost:3308",+ token: "phe_dev",+ source: "override",+ allowedModels: null,+ productModels: [],+ });+ expect(+ await t.service.remint("unauthorized", "phe_dev", undefined),+ ).toBeNull();+ expect(t.authenticatedFetch).not.toHaveBeenCalled();+ });+});++describe("GatewayTokenService.remint", () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date("2026-09-23T12:00:00Z"));+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ async function primed() {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ await t.service.getRoute();+ vi.setSystemTime(Date.now() + GATEWAY_REMINT_MIN_INTERVAL_MS);+ return t;+ }++ it("dedupes concurrent 401 re-mints into one mint", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));++ const [a, b] = await Promise.all([+ t.service.remint("unauthorized", "phe_one", undefined),+ t.service.remint("unauthorized", "phe_one", undefined),+ ]);++ expect(a).toMatchObject({ token: "phe_two" });+ expect(b).toMatchObject({ token: "phe_two" });+ expect(t.mintCalls()).toBe(2);+ });++ it("returns the current route when another caller already replaced the token", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.remint("unauthorized", "phe_one", undefined);++ const again = await t.service.remint("unauthorized", "phe_one", undefined);++ expect(again).toMatchObject({ token: "phe_two" });+ expect(t.mintCalls()).toBe(2);+ });++ it("re-mints once per token for token_cap_exceeded", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));++ expect(+ await t.service.remint("token_cap_exceeded", "phe_one", undefined),+ ).toMatchObject({+ token: "phe_two",+ });+ vi.setSystemTime(Date.now() + GATEWAY_REMINT_MIN_INTERVAL_MS);+ t.mintResponses.push(() => json(minted("phe_three"), 201));+ expect(+ await t.service.remint("token_cap_exceeded", "phe_two", undefined),+ ).toMatchObject({+ token: "phe_three",+ });+ expect(+ await t.service.remint("token_cap_exceeded", "phe_two", undefined),+ ).toMatchObject({+ token: "phe_three",+ });+ expect(t.mintCalls()).toBe(3);+ });++ it("refuses a second cap re-mint for the same token", async () => {+ const t = await primed();+ t.mintResponses.push(() =>+ json({ enabled: false, reason: "not_rolled_out" }, 200),+ );++ expect(+ await t.service.remint("token_cap_exceeded", "phe_one", undefined),+ ).toBeNull();+ // Past the minimum interval, so only the per-token rule refuses.+ vi.setSystemTime(Date.now() + GATEWAY_REMINT_MIN_INTERVAL_MS);+ expect(+ await t.service.remint("token_cap_exceeded", "phe_one", undefined),+ ).toBeNull();+ expect(t.mintCalls()).toBe(2);+ });++ it("returns null when the identity changes while a re-mint waits on a mint", async () => {+ const t = await primed();+ let release: (response: Response) => void = () => undefined;+ t.mintResponses.push(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );++ const pending = t.service.remint("unauthorized", "phe_one", undefined);+ await vi.waitFor(() => expect(t.mintCalls()).toBe(2));+ t.setAccountKey("user-2");+ t.setState(baseState({ currentOrgId: "org-2" }));+ release(json(minted("phe_two"), 201));++ expect(await pending).toBeNull();+ t.mintResponses.push(() => json(minted("phe_three"), 201));+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_three" });+ });++ it("does not re-mint once signed out", async () => {+ const t = await primed();+ t.setState(baseState({ status: "anonymous", currentProjectId: null }));++ expect(await t.service.remint("unauthorized", "phe_one", 42)).toBeNull();+ expect(t.mintCalls()).toBe(1);+ });++ it("still re-mints for the same account after a project switch", async () => {+ const t = await primed();+ t.setState(baseState({ currentProjectId: 43 }));+ t.mintResponses.push(() => json(minted("phe_two"), 201));++ expect(await t.service.remint("unauthorized", "phe_one", 42)).toMatchObject(+ { token: "phe_two" },+ );+ });++ it("still re-mints on a 401 for a token a routine mint issued", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.remint("token_cap_exceeded", "phe_one", undefined);+ vi.setSystemTime(Date.now() + GATEWAY_REMINT_MIN_INTERVAL_MS);+ t.mintResponses.push(() => json(minted("phe_three"), 201));++ expect(+ await t.service.remint("unauthorized", "phe_two", undefined),+ ).toMatchObject({ token: "phe_three" });+ });++ it("keeps the cap re-mint when the minimum interval skips it", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ await t.service.getRoute();++ expect(+ await t.service.remint("token_cap_exceeded", "phe_one", undefined),+ ).toBeNull();+ vi.setSystemTime(Date.now() + GATEWAY_REMINT_MIN_INTERVAL_MS);+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ expect(+ await t.service.remint("token_cap_exceeded", "phe_one", undefined),+ ).toMatchObject({ token: "phe_two" });+ });++ it("falls back to legacy when Go refuses the re-minted token too", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.remint("unauthorized", "phe_one", undefined);++ t.service.fallBack("phe_two", undefined);++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "gateway_unauthorized",+ });+ vi.setSystemTime(Date.now() + GATEWAY_LEGACY_RECHECK_MS - 1);+ expect(await t.service.getRoute()).toMatchObject({ mode: "legacy" });+ expect(t.mintCalls()).toBe(2);+ t.mintResponses.push(() => json(minted("phe_three"), 201));+ vi.setSystemTime(Date.now() + 1);+ await t.service.getRoute();+ await vi.waitFor(async () =>+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_three" }),+ );+ });++ it("falls back only the named project", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_other"), 201));+ expect(await t.service.getRoute(43)).toMatchObject({ token: "phe_other" });++ t.service.fallBack("phe_other", 43);++ expect(await t.service.getRoute(43)).toEqual({+ mode: "legacy",+ reason: "gateway_unauthorized",+ });+ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_one" });+ });++ it("ignores a fallback for a token that is no longer current", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.remint("unauthorized", "phe_one", undefined);++ t.service.fallBack("phe_one", 42);++ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" });+ });++ it("falls back instead of re-minting on a 401 inside the minimum interval", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ await t.service.getRoute();++ expect(+ await t.service.remint("unauthorized", "phe_one", undefined),+ ).toBeNull();+ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "gateway_unauthorized",+ });+ expect(t.mintCalls()).toBe(1);+ });++ it("serves the newer token to a 401 on an older one inside the minimum interval", async () => {+ const t = await primed();+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.remint("token_cap_exceeded", "phe_one", undefined);++ expect(+ await t.service.remint("unauthorized", "phe_one", undefined),+ ).toMatchObject({ token: "phe_two" });+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" });+ });+});++describe("GatewayTokenService identity changes", () => {+ it.each([+ ["project", { currentProjectId: 43 }],+ ["organization", { currentOrgId: "org-2" }],+ ["region", { cloudRegion: "eu" as const }],+ ])("drops cached tokens when the %s changes", async (_label, change) => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.getRoute(42);++ t.setState(baseState(change));+ t.setState(baseState());++ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });+ });++ it("drops cached tokens when the account changes", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.getRoute(42);++ t.setAccountKey("user-2");+ t.setState(baseState());++ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });+ });++ it("drops cached tokens on a sign-in over a live session when the account lookup failed", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.getRoute(42);++ t.setAccountKey(null);+ t.setSessionEpoch(2);+ t.setState(baseState());++ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });+ });++ it("drops cached tokens when the session type changes", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ await t.service.getRoute(42);++ t.setState(baseState({ sessionType: "impersonated" }));++ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });+ });++ it("keeps tokens across unrelated state updates", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ await t.service.getRoute();++ t.setState(+ baseState({+ desktopAccess: { projectId: 42, status: "checking", reason: null },+ }),+ );+ t.setAccountKey(null);+ t.setState(baseState({ status: "restoring" }));+ t.setState(baseState());++ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });+ expect(t.mintCalls()).toBe(1);+ });++ it("answers legacy without minting while signed out", async () => {+ const t = setup();+ t.mintResponses.push(() => json(minted("phe_one"), 201));+ await t.service.getRoute();++ t.setState(baseState({ status: "anonymous", currentProjectId: 42 }));++ expect(await t.service.getRoute(42)).toEqual({+ mode: "legacy",+ reason: "signed_out",+ });+ expect(t.mintCalls()).toBe(1);+ });++ it("answers legacy before any identity exists", async () => {+ const t = setup({ state: baseState({ status: "restoring" }) });++ expect(await t.service.getRoute(42)).toEqual({+ mode: "legacy",+ reason: "signed_out",+ });+ expect(t.mintCalls()).toBe(0);+ });++ describe("discards a mint that lands for an older identity", () => {+ it.each([+ [+ "a sign-out",+ (t: ReturnType<typeof setup>) =>+ t.setState(+ baseState({ status: "anonymous", currentProjectId: null }),+ ),+ ],+ [+ "an account switch",+ (t: ReturnType<typeof setup>) => {+ t.setAccountKey("user-2");+ t.setState(baseState());+ },+ ],+ [+ "a region switch",+ (t: ReturnType<typeof setup>) =>+ t.setState(baseState({ cloudRegion: "eu" })),+ ],+ ])("after %s", async (_label, change) => {+ const t = setup();+ let release: (response: Response) => void = () => undefined;+ t.mintResponses.push(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );++ const pending = t.service.getRoute(42);+ await vi.waitFor(() => expect(t.mintCalls()).toBe(1));+ change(t);+ release(json(minted("phe_one"), 201));++ expect(await pending).toEqual({+ mode: "legacy",+ reason: "identity_changed",+ });+ t.setState(baseState());+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });+ });++ it("skips the mint request when the identity changes while reading the OAuth token", async () => {+ const t = setup();+ vi.mocked(t.host.getValidAccessToken).mockImplementationOnce(async () => {+ t.setState(baseState({ status: "anonymous", currentProjectId: null }));+ return { accessToken: "pha_x", apiHost: API_HOST };+ });++ expect(await t.service.getRoute()).toEqual({+ mode: "legacy",+ reason: "identity_changed",+ });+ expect(t.mintCalls()).toBe(0);+ });++ it("does not report a desktop access denial for another identity", async () => {+ const t = setup();+ t.mintResponses.push(() => {+ t.setAccountKey("user-2");+ t.setState(baseState());+ return json({ enabled: false, reason: "desktop_access_blocked" }, 403);+ });++ await t.service.getRoute();+ expect(t.reportDesktopAccessBlocked).not.toHaveBeenCalled();+ });+ });++ it("hands a mint that raced a failed account lookup to its caller", async () => {+ const t = setup();+ let release: (response: Response) => void = () => undefined;+ t.mintResponses.push(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );++ const pending = t.service.getRoute(42);+ await vi.waitFor(() => expect(t.mintCalls()).toBe(1));+ t.setAccountKey(null);+ t.setState(baseState({ currentOrgId: null }));+ release(json(minted("phe_one"), 201));++ expect(await pending).toMatchObject({ mode: "go", token: "phe_one" });+ });++ it("hands a mint that raced a project switch to its caller without caching it", async () => {+ const t = setup();+ let release: (response: Response) => void = () => undefined;+ t.mintResponses.push(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );++ const pending = t.service.getRoute(42);+ await vi.waitFor(() => expect(t.mintCalls()).toBe(1));+ t.setState(baseState({ currentProjectId: 43 }));+ release(json(minted("phe_one"), 201));++ expect(await pending).toMatchObject({ mode: "go", token: "phe_one" });+ t.mintResponses.push(() => json(minted("phe_two"), 201));+ expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });+ });+});diff --git a/products/desktop/packages/core/src/llm-gateway/gateway-token.ts b/products/desktop/packages/core/src/llm-gateway/gateway-token.tsnew file mode 100644index 000000000000..7ac62213b58a--- /dev/null+++ b/products/desktop/packages/core/src/llm-gateway/gateway-token.ts@@ -0,0 +1,429 @@+import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";+import { validateAiGatewayUrl } from "@posthog/shared";+import { inject, injectable } from "inversify";+import type { AuthService } from "../auth/auth";+import { AUTH_SERVICE } from "../auth/auth.module";+import { AuthServiceEvent, type AuthState } from "../auth/schemas";+import {+ GATEWAY_TOKEN_HOST,+ type GatewayTokenHost,+ LLM_GATEWAY_HOST,+ type LlmGatewayHost,+ type LlmGatewayLogger,+} from "./identifiers";+import {+ type GatewayRemintReason,+ type GatewayRoute,+ gatewayTokenMintedSchema,+ gatewayTokenRefusalSchema,+} from "./schemas";++type GoRoute = Extract<GatewayRoute, { mode: "go" }>;++/**+ * Refresh a tenth of the lifetime before expiry, clamped to these bounds, so+ * short tokens do not spend the per-user mint throttle.+ */+export const GATEWAY_TOKEN_REFRESH_SKEW_MS = 2 * 60_000;+export const GATEWAY_TOKEN_MIN_REFRESH_SKEW_MS = 30_000;+export const GATEWAY_LEGACY_RECHECK_MS = 10 * 60_000;+/** `not_rolled_out` changes only with the flag, so it is re-checked less often. */+export const GATEWAY_NOT_ROLLED_OUT_RECHECK_MS = 30 * 60_000;+export const GATEWAY_BLOCKED_RECHECK_MS = 30 * 60_000;+export const GATEWAY_REMINT_MIN_INTERVAL_MS = 5_000;+export const GATEWAY_REFRESH_RETRY_MS = 30_000;++export const GATEWAY_MINT_TIMEOUT_MS = 15_000;++interface CacheEntry {+ route: GatewayRoute;+ recheckAt: number;+ mintedAt: number;+ refreshAt: number;+ inFlight: Promise<GatewayRoute> | null;+ capReminted: Set<string>;+}++/**+ * Holds the app's `phe_` Go gateway token per project, minted through Django+ * and never handed to a subprocess. A refusal routes to the legacy gateway,+ * except an exhausted credit bucket, which is final.+ */+@injectable()+export class GatewayTokenService {+ private readonly cache = new Map<number, CacheEntry>();+ // Bumped on sign-out and on an account or region switch; a mint started+ // under an older value is never cached or returned.+ private generation = 0;+ private signedIn = false;+ private region: string | null = null;+ private account: string | null = null;+ private epoch: number | null = null;+ private routesKey = "";+ private readonly log: LlmGatewayLogger;+ private readonly now: () => number = () => Date.now();++ constructor(+ @inject(LLM_GATEWAY_HOST)+ private readonly host: LlmGatewayHost,+ @inject(GATEWAY_TOKEN_HOST)+ private readonly config: GatewayTokenHost,+ @inject(AUTH_SERVICE)+ private readonly authService: AuthService,+ @inject(ROOT_LOGGER)+ logger: RootLogger,+ ) {+ this.log = logger.scope("gateway-token");+ this.handleAuthState(authService.getState());+ authService.on(AuthServiceEvent.StateChanged, (state) =>+ this.handleAuthState(state),+ );+ }++ /**+ * A due legacy re-check runs in the background unless `awaitRecheck` asks+ * to wait (a session start picks its target once).+ */+ async getRoute(+ projectId?: number | null,+ options: { awaitRecheck?: boolean } = {},+ ): Promise<GatewayRoute> {+ const resolvedProject =+ projectId ?? this.authService.getState().currentProjectId;+ if (resolvedProject === null || resolvedProject === undefined) {+ return { mode: "legacy", reason: "no_project" };+ }+ if (!this.config.goEnabled) {+ return { mode: "legacy", reason: "host_unsupported" };+ }+ if (!this.signedIn) return { mode: "legacy", reason: "signed_out" };+ return this.routeFor(resolvedProject, options);+ }++ async remint(+ reason: GatewayRemintReason,+ staleToken: string,+ projectId: number | null | undefined,+ ): Promise<GatewayRoute | null> {+ const resolvedProject =+ projectId ?? this.authService.getState().currentProjectId;+ if (resolvedProject === null || resolvedProject === undefined) return null;+ if (this.config.override) return null;+ if (!this.signedIn) return null;+ const entry = this.cache.get(resolvedProject);+ if (entry?.inFlight) {+ const route = await entry.inFlight;+ return route.mode === "go" && route.token !== staleToken ? route : null;+ }+ if (entry?.route.mode === "go" && entry.route.token !== staleToken) {+ return entry.route;+ }+ if (entry?.route.mode === "blocked" && this.now() < entry.recheckAt) {+ return null;+ }+ if (reason === "token_cap_exceeded" && entry?.capReminted.has(staleToken)) {+ return null;+ }+ if (entry && this.now() - entry.mintedAt < GATEWAY_REMINT_MIN_INTERVAL_MS) {+ if (reason === "unauthorized") this.fallBack(staleToken, resolvedProject);+ return null;+ }+ if (reason === "token_cap_exceeded") entry?.capReminted.add(staleToken);+ const route = await this.mint(resolvedProject);+ return route.mode === "go" ? route : null;+ }++ /**+ * Go refused `token` with a 401 and no re-mint can replace it: the project+ * uses the legacy gateway until the re-check.+ */+ fallBack(token: string, projectId: number | null | undefined): void {+ const resolvedProject =+ projectId ?? this.authService.getState().currentProjectId;+ if (resolvedProject === null || resolvedProject === undefined) return;+ const entry = this.cache.get(resolvedProject);+ if (entry?.route.mode !== "go" || entry.route.token !== token) return;+ this.log.warn("Go refused the gateway token; using the legacy gateway");+ entry.route = { mode: "legacy", reason: "gateway_unauthorized" };+ entry.recheckAt = this.now() + GATEWAY_LEGACY_RECHECK_MS;+ }++ clearBlocked(): void {+ for (const [projectId, entry] of this.cache) {+ if (entry.route.mode === "blocked" && !entry.inFlight) {+ this.cache.delete(projectId);+ }+ }+ }++ private routeFor(+ projectId: number,+ options: { awaitRecheck?: boolean },+ ): Promise<GatewayRoute> | GatewayRoute {+ const override = this.overrideRoute(projectId);+ if (override) return override;++ const entry = this.cache.get(projectId);+ const now = this.now();+ // A known legacy refusal is served while it re-checks; a first mint or a+ // blocked route (a hard 402 once its window passes) waits.+ const settled =+ entry !== undefined &&+ entry.route.mode === "legacy" &&+ !isPending(entry.route) &&+ !options.awaitRecheck;+ if (entry?.inFlight && entry.route.mode !== "go") {+ return settled ? entry.route : entry.inFlight;+ }+ if (entry?.route.mode === "go") {+ const { expiresAt } = entry.route;+ if (now < entry.refreshAt) return entry.route;+ if (now < expiresAt) {+ if (now >= entry.recheckAt) {+ void this.mint(projectId, true).catch(() => undefined);+ }+ return entry.route;+ }+ return this.mint(projectId);+ }+ if (entry && now < entry.recheckAt) return entry.route;+ if (settled) {+ void this.mint(projectId).catch(() => undefined);+ return entry.route;+ }+ return this.mint(projectId);+ }++ private mint(+ projectId: number,+ keepValidToken = false,+ ): Promise<GatewayRoute> {+ const existing = this.cache.get(projectId);+ if (existing?.inFlight) return existing.inFlight;+ const current = keepValidToken ? existing?.route : undefined;+ const entry: CacheEntry = existing ?? {+ route: { mode: "legacy", reason: "pending" },+ recheckAt: 0,+ mintedAt: 0,+ refreshAt: 0,+ inFlight: null,+ capReminted: new Set(),+ };+ entry.mintedAt = this.now();+ const generation = this.generation;+ const inFlight = this.requestMint(projectId, generation)+ .then(({ route, recheckMs }): GatewayRoute => {+ if (generation !== this.generation) {+ return { mode: "legacy", reason: "identity_changed" };+ }+ if (+ current?.mode === "go" &&+ route.mode === "legacy" &&+ this.now() < current.expiresAt+ ) {+ this.log.warn(+ "Gateway token refresh failed; keeping the current token",+ { reason: route.reason },+ );+ entry.recheckAt = this.now() + GATEWAY_REFRESH_RETRY_MS;+ return current;+ }+ entry.route = route;+ entry.recheckAt = this.now() + recheckMs;+ if (route.mode === "go") {+ const lifetime = route.expiresAt - this.now();+ entry.refreshAt =+ route.expiresAt -+ Math.min(+ GATEWAY_TOKEN_REFRESH_SKEW_MS,+ Math.max(GATEWAY_TOKEN_MIN_REFRESH_SKEW_MS, lifetime / 10),+ );+ }+ return route;+ })+ .finally(() => {+ entry.inFlight = null;+ });+ entry.inFlight = inFlight;+ this.cache.set(projectId, entry);+ return inFlight;+ }++ private async requestMint(+ projectId: number,+ generation: number,+ ): Promise<{ route: GatewayRoute; recheckMs: number }> {+ let apiHost: string;+ let response: Response;+ // Covers the mint request and its body, not the OAuth token read.+ const timeout = new AbortController();+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ ({ apiHost } = await this.host.getValidAccessToken());+ // The OAuth token read above may already belong to the next identity.+ if (generation !== this.generation)+ return this.legacy("identity_changed");+ timer = setTimeout(() => timeout.abort(), GATEWAY_MINT_TIMEOUT_MS);+ response = await this.host.authenticatedFetch(+ `${apiHost}/api/projects/${projectId}/desktop/gateway_token/`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: "{}",+ redirect: "error",+ signal: timeout.signal,+ },+ );+ } catch (error) {+ this.log.warn("Gateway token mint failed", {+ error: error instanceof Error ? error.message : String(error),+ timedOut: timeout.signal.aborted,+ });+ clearTimeout(timer);+ return this.legacy("mint_failed");+ }++ const body: unknown = await response.json().catch(() => null);+ clearTimeout(timer);+ if (response.status !== 201) {+ const refusal = gatewayTokenRefusalSchema.safeParse(body);+ const data = refusal.success ? refusal.data : {};+ const reason = data.reason ?? data.code ?? `http_${response.status}`;+ // Final: the legacy gateway refuses the same user, so no fallback.+ if (response.status === 402 && reason === "credit_bucket_exhausted") {+ this.log.info("Gateway token refused: credit bucket exhausted");+ return {+ route: {+ mode: "blocked",+ reason: "credit_bucket_exhausted",+ detail:+ data.detail ??+ "Your organization has reached its PostHog Desktop usage limit",+ },+ recheckMs: GATEWAY_BLOCKED_RECHECK_MS,+ };+ }+ if (+ reason === "desktop_access_blocked" &&+ generation === this.generation+ ) {+ this.authService.reportDesktopAccessBlocked?.(projectId, data.access);+ }+ this.log.info("Gateway token not issued; using the legacy gateway", {+ status: response.status,+ reason,+ });+ return this.legacy(reason);+ }++ const minted = gatewayTokenMintedSchema.safeParse(body);+ if (!minted.success) {+ this.log.warn("Gateway token response did not match the contract");+ return this.legacy("invalid_mint_response");+ }+ const gatewayUrl = validateAiGatewayUrl(minted.data.gateway_url, {+ apiHost,+ });+ // Read against the server's clock, so a skewed local clock neither+ // expires a fresh token nor keeps a dead one.+ const serverNow = Date.parse(response.headers.get("date") ?? "");+ const expiresAt =+ Date.parse(minted.data.expires_at) -+ (Number.isFinite(serverNow) ? serverNow : this.now()) ++ this.now();+ if (!gatewayUrl) {+ this.log.warn("Gateway token response named an untrusted gateway");+ return this.legacy("invalid_gateway_url");+ }+ if (!Number.isFinite(expiresAt)) {+ this.log.warn("Gateway token response had an unreadable expiry");+ return this.legacy("invalid_expiry");+ }+ return {+ route: {+ mode: "go",+ gatewayUrl,+ token: minted.data.token,+ expiresAt,+ capUsd: minted.data.cap_usd,+ allowedModels: minted.data.allowed_models,+ productModels: minted.data.product_models,+ plan: minted.data.plan,+ projectId,+ teamId: minted.data.team_id,+ source: "mint",+ },+ recheckMs: 0,+ };+ }++ private legacy(reason: string): {+ route: GatewayRoute;+ recheckMs: number;+ } {+ return {+ route: { mode: "legacy", reason },+ recheckMs:+ reason === "not_rolled_out"+ ? GATEWAY_NOT_ROLLED_OUT_RECHECK_MS+ : GATEWAY_LEGACY_RECHECK_MS,+ };+ }++ private overrideRoute(projectId: number): GoRoute | null {+ const override = this.config.override;+ if (!override) return null;+ return {+ mode: "go",+ gatewayUrl: override.url,+ token: override.token,+ expiresAt: Number.POSITIVE_INFINITY,+ capUsd: "",+ allowedModels: null,+ productModels: [],+ plan: "paid",+ projectId,+ teamId: projectId,+ source: "override",+ };+ }++ private handleAuthState(state: AuthState): void {+ if (state.status === "anonymous") {+ if (this.signedIn) this.generation += 1;+ this.signedIn = false;+ this.account = null;+ this.epoch = null;+ this.cache.clear();+ return;+ }+ if (state.status !== "authenticated") return;+ // A null account is a failed lookup, not a different account; the+ // session epoch still catches a sign-in over a live session.+ const account = this.authService.getCachedAccountKey?.() ?? null;+ const epoch = this.authService.getSessionEpoch?.() ?? null;+ const identityChanged =+ !this.signedIn ||+ state.cloudRegion !== this.region ||+ (epoch !== null && this.epoch !== null && epoch !== this.epoch) ||+ (account !== null && this.account !== null && account !== this.account);+ if (account !== null) this.account = account;+ if (epoch !== null) this.epoch = epoch;+ const routesKey = JSON.stringify([+ state.currentOrgId,+ state.currentProjectId,+ state.sessionType,+ ]);+ if (identityChanged) {+ this.generation += 1;+ this.signedIn = true;+ this.region = state.cloudRegion;+ }+ if (identityChanged || routesKey !== this.routesKey) this.cache.clear();+ this.routesKey = routesKey;+ }+}++function isPending(route: GatewayRoute): boolean {+ return route.mode === "legacy" && route.reason === "pending";+}diff --git a/products/desktop/packages/core/src/llm-gateway/identifiers.ts b/products/desktop/packages/core/src/llm-gateway/identifiers.tsindex 5d671254e5cd..f1e7a7d3233e 100644--- a/products/desktop/packages/core/src/llm-gateway/identifiers.ts+++ b/products/desktop/packages/core/src/llm-gateway/identifiers.ts@@ -1,14 +1,21 @@export const LLM_GATEWAY_SERVICE = Symbol.for("posthog.core.llmGatewayService");export const LLM_GATEWAY_HOST = Symbol.for("posthog.core.llmGatewayHost");+export const GATEWAY_TOKEN_SERVICE = Symbol.for(+ "posthog.core.gatewayTokenService",+);+export const GATEWAY_TOKEN_HOST = Symbol.for("posthog.core.gatewayTokenHost");export interface LlmGatewayAuth {getValidAccessToken(): Promise<{ accessToken: string; apiHost: string }>;authenticatedFetch(url: string, init?: RequestInit): Promise<Response>;+ /** Unauthenticated fetch for Go gateway calls, which carry their own bearer. */+ fetch?(url: string, init?: RequestInit): Promise<Response>;}export interface LlmGatewayEndpoints {messagesUrl(apiHost: string): string;- usageUrl(apiHost: string): string;+ usageUrl(apiHost: string, projectId: number): string;+ legacyUsageUrl(apiHost: string): string;defaultModel: string;}@@ -20,3 +27,14 @@ export interface LlmGatewayLogger {warn(message: string, ...args: unknown[]): void;error(message: string, ...args: unknown[]): void;}++export interface GatewayTokenOverride {+ url: string;+ token: string;+}++export interface GatewayTokenHost {+ /** False on hosts that cannot reach the Go gateway (the web host has no CORS path). */+ goEnabled: boolean;+ override: GatewayTokenOverride | null;+}diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.module.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.module.tsindex cb4fb83045b5..689c746f4006 100644--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.module.ts+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.module.ts@@ -1,7 +1,9 @@import { ContainerModule } from "inversify";-import { LLM_GATEWAY_SERVICE } from "./identifiers";+import { GatewayTokenService } from "./gateway-token";+import { GATEWAY_TOKEN_SERVICE, LLM_GATEWAY_SERVICE } from "./identifiers";import { LlmGatewayService } from "./llm-gateway";export const llmGatewayModule = new ContainerModule(({ bind }) => {+ bind(GATEWAY_TOKEN_SERVICE).to(GatewayTokenService).inSingletonScope();bind(LLM_GATEWAY_SERVICE).to(LlmGatewayService).inSingletonScope();});diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.tsindex a3f5354f6b79..88e788ecec93 100644--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts@@ -1,5 +1,7 @@+import { classifyGatewayLimitError } from "@posthog/shared";import { beforeEach, describe, expect, it, vi } from "vitest";import type { AuthService } from "../auth/auth";+import type { GatewayTokenService } from "./gateway-token";import type {LlmGatewayAuth,LlmGatewayEndpoints,@@ -7,6 +9,7 @@ import type {LlmGatewayLogger,} from "./identifiers";import { LlmGatewayError, LlmGatewayService } from "./llm-gateway";+import type { GatewayRoute } from "./schemas";const API_HOST = "https://app.example.com";@@ -17,21 +20,51 @@ function createJsonResponse(data: unknown, status = 200): Response {});}+const GO_ROUTE: Extract<GatewayRoute, { mode: "go" }> = {+ mode: "go",+ gatewayUrl: "https://ai-gateway.us.posthog.com",+ token: "phe_one",+ expiresAt: Date.now() + 3_600_000,+ capUsd: "200",+ allowedModels: ["claude-haiku-4-5", "claude-default"],+ productModels: ["claude-haiku-4-5", "claude-default"],+ plan: "paid",+ projectId: 42,+ teamId: 7,+ source: "mint",+};+function createService(authenticatedFetch: LlmGatewayAuth["authenticatedFetch"],+ options: {+ route?: GatewayRoute;+ remint?: GatewayTokenService["remint"];+ fetch?: LlmGatewayAuth["fetch"];+ } = {},) {const auth: LlmGatewayAuth = {getValidAccessToken: vi.fn().mockResolvedValue({ accessToken: "tok", apiHost: API_HOST }),authenticatedFetch,+ fetch: options.fetch,};const endpoints: LlmGatewayEndpoints = {messagesUrl: (host) => `${host}/gateway/v1/messages`,- usageUrl: (host) => `${host}/gateway/usage`,+ usageUrl: (host, projectId) =>+ `${host}/api/projects/${projectId}/desktop/usage/`,+ legacyUsageUrl: (host) => `${host}/gateway/usage`,defaultModel: "claude-default",};+ const gatewayTokens = {+ getRoute: vi+ .fn()+ .mockResolvedValue(options.route ?? { mode: "legacy", reason: "test" }),+ remint: options.remint ?? vi.fn().mockResolvedValue(null),+ fallBack: vi.fn(),+ clearBlocked: vi.fn(),+ } as unknown as GatewayTokenService;const host: LlmGatewayHost = { ...auth, ...endpoints };@@ -60,8 +93,20 @@ function createService(}};- const service = new LlmGatewayService(host, logger, authService);- return { service, auth, endpoints, log, emitAuthState };+ const service = new LlmGatewayService(+ host,+ logger,+ authService,+ gatewayTokens,+ );+ return {+ service,+ auth,+ endpoints,+ log,+ emitAuthState,+ gatewayTokens,+ };}const SUCCESS_BODY = {@@ -74,6 +119,15 @@ const SUCCESS_BODY = {usage: { input_tokens: 12, output_tokens: 7 },};+const MODEL_GATE_BODY = {+ error: {+ message:+ "Model 'claude-haiku-4-5' needs a paid PostHog plan. Models available on the free tier: @cf/zai-org/glm-5.2. Add a payment method to your organization to unlock all models. (rate_limit)",+ type: "permission_error",+ code: "model_gate",+ },+};+describe("LlmGatewayService.prompt", () => {beforeEach(() => {vi.useRealTimers();@@ -196,16 +250,6 @@ describe("LlmGatewayService.prompt", () => {});});- // The free-tier model gate's 403 body, as the gateway serves it.- const MODEL_GATE_BODY = {- error: {- message:- "Model 'claude-haiku-4-5' needs a paid PostHog plan. Models available on the free tier: @cf/zai-org/glm-5.2. Add a payment method to your organization to unlock all models. (rate_limit)",- type: "permission_error",- code: "model_gate",- },- };-it("retries once on the free-tier model when the model gate 403s", async () => {const fetchMock = vi.fn()@@ -342,7 +386,7 @@ describe("LlmGatewayService.fetchUsage", () => {is_rate_limited: false,};- it("returns the schema-parsed usage payload", async () => {+ it("returns the schema-parsed usage payload from Django", async () => {const fetchMock = vi.fn().mockResolvedValue(createJsonResponse(USAGE_BODY));const { service } = createService(fetchMock);@@ -350,9 +394,62 @@ describe("LlmGatewayService.fetchUsage", () => {expect(usage.product).toBe("code");expect(usage.sustained.used_percent).toBe(10);- expect(fetchMock).toHaveBeenCalledWith(`${API_HOST}/gateway/usage`, {- headers: { "X-PostHog-Project-Id": "42" },- });+ expect(fetchMock).toHaveBeenCalledWith(+ `${API_HOST}/api/projects/42/desktop/usage/`,+ { headers: { "X-PostHog-Project-Id": "42" } },+ );+ });++ it("falls back to the legacy usage URL once per org after a 404", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(createJsonResponse({ detail: "nope" }, 404))+ .mockImplementation(async () => createJsonResponse(USAGE_BODY));+ const { service } = createService(fetchMock);++ await service.fetchUsage();+ await service.fetchUsage();++ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([+ `${API_HOST}/api/projects/42/desktop/usage/`,+ `${API_HOST}/gateway/usage`,+ `${API_HOST}/gateway/usage`,+ ]);+ });++ it("re-probes Django after the organization changes", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(createJsonResponse({}, 404))+ .mockImplementation(async () => createJsonResponse(USAGE_BODY));+ const { service, emitAuthState } = createService(fetchMock);++ await service.fetchUsage();+ emitAuthState("org-2");+ await service.fetchUsage();++ expect(fetchMock.mock.calls.at(-1)?.[0]).toBe(+ `${API_HOST}/api/projects/42/desktop/usage/`,+ );+ });++ it("strips the Django body's extra is_pro field", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ createJsonResponse({+ ...USAGE_BODY,+ product: "posthog_code",+ is_pro: false,+ ai_credits: { exhausted: false, used_usd: 1.5, limit_usd: 100 },+ code_usage_subscribed: true,+ billing_period_end: "2026-10-01T00:00:00Z",+ }),+ );+ const { service } = createService(fetchMock);++ const usage = await service.fetchUsage();++ expect(usage).not.toHaveProperty("is_pro");+ expect(usage.billing_period_end).toBe("2026-10-01T00:00:00Z");});it("throws a usage_error LlmGatewayError on non-ok response", async () => {@@ -442,3 +539,322 @@ describe("LlmGatewayService.fetchUsage", () => {expect(promptBody.model).toBe("@cf/zai-org/glm-5.2");});});++describe("LlmGatewayService.prompt on the Go gateway", () => {+ it("posts to the Go gateway with the session token and a properties blob", async () => {+ const authenticatedFetch = vi.fn();+ const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));+ const { service } = createService(authenticatedFetch, {+ route: GO_ROUTE,+ fetch: goFetch,+ });++ await service.prompt([{ role: "user", content: "hi" }], {+ model: "claude-haiku-4-5",+ posthogProperties: { ai_stage: "title", $ai_span_name: "title" },+ });++ expect(authenticatedFetch).not.toHaveBeenCalled();+ const [url, init] = goFetch.mock.calls[0];+ expect(url).toBe("https://ai-gateway.us.posthog.com/v1/messages");+ expect(init.redirect).toBe("error");+ expect(init.headers.Authorization).toBe("Bearer phe_one");+ expect(init.headers).not.toHaveProperty("X-PostHog-Project-Id");+ expect(JSON.parse(init.headers["X-PostHog-Properties"])).toEqual({+ ai_stage: "title",+ ai_product: "posthog_code",+ team_id: 7,+ });+ expect(JSON.parse(init.body).model).toBe("claude-haiku-4-5");+ });++ it("picks the free-tier model from the pin without a round trip", async () => {+ const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));+ const { service } = createService(vi.fn(), {+ route: {+ ...GO_ROUTE,+ plan: "free",+ allowedModels: ["zai-org/glm-5.3", "@cf/zai-org/glm-5.2"],+ },+ fetch: goFetch,+ });++ await service.prompt([{ role: "user", content: "hi" }], {+ model: "claude-haiku-4-5",+ });++ expect(goFetch).toHaveBeenCalledTimes(1);+ expect(JSON.parse(goFetch.mock.calls[0][1].body).model).toBe(+ "@cf/zai-org/glm-5.2",+ );+ });++ it("falls back to the first allowed model when the free model is not pinned", async () => {+ const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));+ const { service } = createService(vi.fn(), {+ route: { ...GO_ROUTE, plan: "free", allowedModels: ["zai-org/glm-5.3"] },+ fetch: goFetch,+ });++ await service.prompt([{ role: "user", content: "hi" }]);++ expect(JSON.parse(goFetch.mock.calls[0][1].body).model).toBe(+ "zai-org/glm-5.3",+ );+ });++ it.each([+ [+ "a 401",+ createJsonResponse({ error: { message: "bad token" } }, 401),+ "unauthorized",+ ],+ [+ "a token cap 402",+ new Response(+ JSON.stringify({+ type: "error",+ error: { type: "billing_error", message: "admission rejected" },+ }),+ {+ status: 402,+ headers: { "X-PostHog-Denial": "token_cap_exceeded" },+ },+ ),+ "token_cap_exceeded",+ ],+ ])("re-mints once and retries after %s", async (_label, refusal, reason) => {+ const goFetch = vi+ .fn()+ .mockResolvedValueOnce(refusal)+ .mockResolvedValue(createJsonResponse(SUCCESS_BODY));+ const remint = vi.fn().mockResolvedValue({ ...GO_ROUTE, token: "phe_two" });+ const { service } = createService(vi.fn(), {+ route: GO_ROUTE,+ fetch: goFetch,+ remint,+ });++ const result = await service.prompt([{ role: "user", content: "hi" }]);++ expect(result.content).toBe("hello world");+ expect(remint).toHaveBeenCalledWith(reason, "phe_one", 42);+ expect(goFetch.mock.calls[1][1].headers.Authorization).toBe(+ "Bearer phe_two",+ );+ });++ it("surfaces a cap refusal after a 401 re-mint without trying legacy", async () => {+ const goFetch = vi+ .fn()+ .mockResolvedValueOnce(new Response("{}", { status: 401 }))+ .mockResolvedValueOnce(+ new Response("{}", {+ status: 402,+ headers: { "X-PostHog-Denial": "token_cap_exceeded" },+ }),+ );+ const remint = vi.fn().mockResolvedValue({ ...GO_ROUTE, token: "phe_two" });+ const legacyFetch = vi.fn();+ const { service, gatewayTokens } = createService(legacyFetch, {+ route: GO_ROUTE,+ fetch: goFetch,+ remint,+ });++ await expect(+ service.prompt([{ role: "user", content: "hi" }]),+ ).rejects.toMatchObject({ statusCode: 402 });+ expect(remint).toHaveBeenCalledTimes(1);+ expect(legacyFetch).not.toHaveBeenCalled();+ expect(gatewayTokens.fallBack).not.toHaveBeenCalled();+ });++ it("surfaces the original refusal when the re-mint rejects", async () => {+ const goFetch = vi+ .fn()+ .mockResolvedValueOnce(+ createJsonResponse({ error: { message: "bad token" } }, 401),+ );+ const remint = vi.fn().mockRejectedValue(new Error("mint exploded"));+ const { service } = createService(vi.fn(), {+ route: GO_ROUTE,+ fetch: goFetch,+ remint,+ });++ await expect(+ service.prompt([{ role: "user", content: "hi" }]),+ ).rejects.toMatchObject({ name: "LlmGatewayError", statusCode: 401 });+ expect(goFetch).toHaveBeenCalledTimes(1);+ });++ it("keeps the requested model when the pin is null or empty", async () => {+ for (const allowedModels of [null, []]) {+ const goFetch = vi+ .fn()+ .mockResolvedValue(createJsonResponse(SUCCESS_BODY));+ const { service } = createService(vi.fn(), {+ route: { ...GO_ROUTE, allowedModels },+ fetch: goFetch,+ });++ await service.prompt([{ role: "user", content: "hi" }], {+ model: "claude-haiku-4-5",+ });++ expect(JSON.parse(goFetch.mock.calls[0][1].body).model).toBe(+ "claude-haiku-4-5",+ );+ }+ });++ it.each([+ [401, "unauthorized", true],+ [402, "token_cap_exceeded", false],+ ] as const)(+ "surfaces a 401 on the token re-minted after a %s, falling back only for a 401 pair",+ async (firstStatus, reason, fallsBack) => {+ const refusal = (status: number) =>+ new Response("{}", {+ status,+ headers:+ status === 402 ? { "X-PostHog-Denial": "token_cap_exceeded" } : {},+ });+ const goFetch = vi+ .fn()+ .mockResolvedValueOnce(refusal(firstStatus))+ .mockResolvedValueOnce(refusal(401));+ const remint = vi+ .fn()+ .mockResolvedValue({ ...GO_ROUTE, token: "phe_two" });+ const legacyFetch = vi.fn();+ const { service, gatewayTokens } = createService(legacyFetch, {+ route: GO_ROUTE,+ fetch: goFetch,+ remint,+ });++ await expect(+ service.prompt([{ role: "user", content: "hi" }]),+ ).rejects.toMatchObject({ statusCode: 401 });+ expect(goFetch).toHaveBeenCalledTimes(2);+ expect(remint).toHaveBeenCalledWith(reason, "phe_one", 42);+ expect(remint).toHaveBeenCalledTimes(1);+ expect(legacyFetch).not.toHaveBeenCalled();+ if (fallsBack) {+ expect(gatewayTokens.fallBack).toHaveBeenCalledWith("phe_two", 42);+ } else {+ expect(gatewayTokens.fallBack).not.toHaveBeenCalled();+ }+ },+ );++ it("does not retry an org spend refusal and does not use the legacy model-gate retry", async () => {+ const goFetch = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ error: {+ code: "credit_bucket_exhausted",+ message: "limit reached",+ },+ }),+ { status: 402 },+ ),+ );+ const remint = vi.fn();+ const { service } = createService(vi.fn(), {+ route: GO_ROUTE,+ fetch: goFetch,+ remint,+ });++ await expect(+ service.prompt([{ role: "user", content: "hi" }]),+ ).rejects.toMatchObject({+ statusCode: 402,+ code: "credit_bucket_exhausted",+ });+ expect(remint).not.toHaveBeenCalled();+ expect(goFetch).toHaveBeenCalledTimes(1);+ });++ it("surfaces the second refusal when the re-mint yields nothing", async () => {+ const goFetch = vi+ .fn()+ .mockResolvedValue(+ createJsonResponse({ error: { message: "bad" } }, 401),+ );+ const { service } = createService(vi.fn(), {+ route: GO_ROUTE,+ fetch: goFetch,+ remint: vi.fn().mockResolvedValue(null),+ });++ await expect(+ service.prompt([{ role: "user", content: "hi" }]),+ ).rejects.toMatchObject({ statusCode: 401 });+ expect(goFetch).toHaveBeenCalledTimes(1);+ });++ it("refuses a helper prompt while the credit bucket is exhausted, without legacy", async () => {+ const authenticatedFetch = vi.fn();+ const goFetch = vi.fn();+ const { service } = createService(authenticatedFetch, {+ route: {+ mode: "blocked",+ reason: "credit_bucket_exhausted",+ detail: "Your organization has reached its PostHog Desktop usage limit",+ },+ fetch: goFetch,+ });++ const error = await service+ .prompt([{ role: "user", content: "hi" }])+ .catch((e: unknown) => e);++ expect(error).toMatchObject({+ statusCode: 402,+ code: "credit_bucket_exhausted",+ });+ expect(classifyGatewayLimitError((error as Error).message)).toBe(+ "org_limit",+ );+ expect(authenticatedFetch).not.toHaveBeenCalled();+ expect(goFetch).not.toHaveBeenCalled();+ });+});++describe("LlmGatewayService.fetchUsage and the blocked route", () => {+ it.each([+ [false, 1],+ [true, 0],+ ])(+ "clears a blocked route when exhausted is %s",+ async (exhausted, calls) => {+ const fetchMock = vi.fn().mockResolvedValue(+ createJsonResponse({+ product: "posthog_code",+ user_id: 1,+ sustained: {+ used_percent: 0,+ reset_at: "2026-01-01T00:00:00Z",+ exceeded: false,+ },+ burst: {+ used_percent: 0,+ reset_at: "2026-01-01T00:00:00Z",+ exceeded: false,+ },+ is_rate_limited: exhausted,+ ai_credits: { exhausted, used_usd: 1, limit_usd: 2 },+ }),+ );+ const { service, gatewayTokens } = createService(fetchMock);++ await service.fetchUsage();++ expect(gatewayTokens.clearBlocked).toHaveBeenCalledTimes(calls);+ },+ );+});diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.tsindex 1e618ae06c59..a45be7bb8ea4 100644--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts@@ -1,7 +1,12 @@import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";-import { classifyGatewayLimitError } from "@posthog/shared";+import {+ aiGatewayDenialCode,+ aiGatewayRemintReason,+ classifyGatewayLimitError,+} from "@posthog/shared";import {buildPosthogProjectHeaderRecord,+ buildPosthogPropertiesHeaderRecord,buildPosthogPropertyHeaderRecord,type PosthogProperties,} from "@posthog/shared/posthog-property-headers";@@ -9,7 +14,9 @@ import { inject, injectable } from "inversify";import type { AuthService } from "../auth/auth";import { AUTH_SERVICE } from "../auth/auth.module";import { AuthServiceEvent } from "../auth/schemas";+import type { GatewayTokenService } from "./gateway-token";import {+ GATEWAY_TOKEN_SERVICE,LLM_GATEWAY_HOST,type LlmGatewayAuth,type LlmGatewayEndpoints,@@ -20,6 +27,7 @@ import {type AnthropicErrorResponse,type AnthropicMessagesRequest,type AnthropicMessagesResponse,+ type GatewayRoute,type LlmMessage,type PromptOutput,type UsageOutput,@@ -32,6 +40,32 @@ export const HELPER_GATEWAY_MODEL = "claude-haiku-4-5";const FREE_TIER_GATEWAY_MODEL = "@cf/zai-org/glm-5.2";+type GoRoute = Extract<GatewayRoute, { mode: "go" }>;++export function desktopUsageUrl(apiHost: string, projectId: number): string {+ return `${apiHost}/api/projects/${projectId}/desktop/usage/`;+}++type SendOptions = {+ system?: string;+ maxTokens?: number;+ model: string;+ signal?: AbortSignal;+ timeoutMs?: number;+ posthogProperties?: PosthogProperties;+};++// The Go gateway's model for a helper prompt, picked from the token's pin+// so a free-tier token never spends a round trip on a refused model.+function pickGoModel(route: GoRoute, requested: string): string {+ const allowed = route.allowedModels;+ if (allowed === null || allowed.includes(requested)) return requested;+ if (route.plan === "free" && allowed.includes(FREE_TIER_GATEWAY_MODEL)) {+ return FREE_TIER_GATEWAY_MODEL;+ }+ return allowed[0] ?? requested;+}+export class LlmGatewayError extends Error {constructor(message: string,@@ -53,6 +87,8 @@ export class LlmGatewayService {logger: RootLogger,@inject(AUTH_SERVICE)authService: AuthService,+ @inject(GATEWAY_TOKEN_SERVICE)+ private readonly gatewayTokens: GatewayTokenService,) {this.auth = host;this.endpoints = host;@@ -63,6 +99,7 @@ export class LlmGatewayService {if (state.currentOrgId === orgId) return;orgId = state.currentOrgId;this.lastKnownCodeUsageSubscribed = null;+ this.legacyUsageOrgs.clear();});}@@ -72,6 +109,8 @@ export class LlmGatewayService {private readonly authService: AuthService;private lastKnownCodeUsageSubscribed: boolean | null = null;+ // Orgs whose server has no Django usage endpoint yet (a 404 once).+ private readonly legacyUsageOrgs = new Set<string>();async prompt(messages: LlmMessage[],@@ -91,6 +130,27 @@ export class LlmGatewayService {} = {},): Promise<PromptOutput> {const requested = options.model ?? this.endpoints.defaultModel;+ const route = await this.gatewayTokens+ .getRoute()+ .catch((): GatewayRoute => ({ mode: "legacy", reason: "route_failed" }));+ if (route.mode === "blocked") {+ throw new LlmGatewayError(+ route.detail,+ "billing_error",+ route.reason,+ 402,+ );+ }+ if (route.mode === "go") {+ return this.sendGoPrompt(+ messages,+ {+ ...options,+ model: pickGoModel(route, requested),+ },+ route,+ );+ }const model =this.lastKnownCodeUsageSubscribed === false? FREE_TIER_GATEWAY_MODEL@@ -115,28 +175,81 @@ export class LlmGatewayService {}}- private async sendPrompt(+ private async sendGoPrompt(messages: LlmMessage[],- options: {- system?: string;- maxTokens?: number;- model: string;- signal?: AbortSignal;- timeoutMs?: number;- posthogProperties?: PosthogProperties;- },+ options: SendOptions,+ route: GoRoute,): Promise<PromptOutput> {- const {- system,- maxTokens,- model,- signal,- timeoutMs = 60_000,- posthogProperties,- } = options;+ const send = (current: GoRoute) =>+ this.executePrompt(+ messages,+ options,+ `${current.gatewayUrl}/v1/messages`,+ (url, init) =>+ (this.auth.fetch ?? fetch)(url, {+ ...init,+ redirect: "error",+ headers: {+ ...(init.headers as Record<string, string>),+ Authorization: `Bearer ${current.token}`,+ },+ }),+ buildPosthogPropertiesHeaderRecord({+ ...options.posthogProperties,+ ai_product: "posthog_code",+ team_id: current.teamId,+ }),+ );+ try {+ return await send(route);+ } catch (error) {+ const reason = remintReason(error);+ if (!reason) throw error;+ const fresh = await this.gatewayTokens+ .remint(reason, route.token, route.projectId)+ .catch(() => null);+ if (!fresh || fresh.mode !== "go") throw error;+ try {+ return await send(fresh);+ } catch (retryError) {+ if (+ reason === "unauthorized" &&+ remintReason(retryError) === "unauthorized"+ ) {+ this.gatewayTokens.fallBack(fresh.token, fresh.projectId);+ }+ throw retryError;+ }+ }+ }+ private async sendPrompt(+ messages: LlmMessage[],+ options: SendOptions,+ ): Promise<PromptOutput> {const auth = await this.auth.getValidAccessToken();- const messagesUrl = this.endpoints.messagesUrl(auth.apiHost);+ return this.executePrompt(+ messages,+ options,+ this.endpoints.messagesUrl(auth.apiHost),+ (url, init) => this.auth.authenticatedFetch(url, init),+ {+ ...this.projectScopeHeaders(),+ ...(options.posthogProperties+ ? buildPosthogPropertyHeaderRecord(options.posthogProperties)+ : {}),+ },+ );+ }++ private async executePrompt(+ messages: LlmMessage[],+ options: SendOptions,+ messagesUrl: string,+ fetchImpl: (url: string, init: RequestInit) => Promise<Response>,+ extraHeaders: Record<string, string>,+ ): Promise<PromptOutput> {+ const { system, maxTokens, model, signal, timeoutMs = 60_000 } = options;const requestBody: AnthropicMessagesRequest = {model,@@ -170,15 +283,12 @@ export class LlmGatewayService {const headers: Record<string, string> = {"Content-Type": "application/json",- ...this.projectScopeHeaders(),- ...(posthogProperties- ? buildPosthogPropertyHeaderRecord(posthogProperties)- : {}),+ ...extraHeaders,};let response: Response;try {- response = await this.auth.authenticatedFetch(messagesUrl, {+ response = await fetchImpl(messagesUrl, {method: "POST",headers,body: JSON.stringify(requestBody),@@ -214,10 +324,14 @@ export class LlmGatewayService {typeof errorData?.detail === "string" ? errorData.detail : undefined;const errorMessage =errorData?.error?.message ||+ (typeof errorData?.message === "string" ? errorData.message : "") ||detail ||`HTTP ${response.status}: ${response.statusText}`;const errorType = errorData?.error?.type || "unknown_error";- const errorCode = errorData?.error?.code;+ const errorCode = aiGatewayDenialCode(+ response.headers.get("x-posthog-denial"),+ errorData,+ );this.log.error("LLM gateway request failed", {status: response.status,@@ -258,15 +372,28 @@ export class LlmGatewayService {async fetchUsage(): Promise<UsageOutput> {const auth = await this.auth.getValidAccessToken();- const usageUrl = this.endpoints.usageUrl(auth.apiHost);+ const { currentOrgId, currentProjectId } = this.authService.getState();+ const useLegacy =+ currentProjectId === null ||+ (currentOrgId !== null && this.legacyUsageOrgs.has(currentOrgId));+ const usageUrl = useLegacy+ ? this.endpoints.legacyUsageUrl(auth.apiHost)+ : this.endpoints.usageUrl(auth.apiHost, currentProjectId);- this.log.debug("Fetching usage from gateway", { url: usageUrl });+ this.log.debug("Fetching usage", { url: usageUrl });let response: Response;try {response = await this.auth.authenticatedFetch(usageUrl, {headers: this.projectScopeHeaders(),});+ if (!useLegacy && response.status === 404) {+ if (currentOrgId !== null) this.legacyUsageOrgs.add(currentOrgId);+ response = await this.auth.authenticatedFetch(+ this.endpoints.legacyUsageUrl(auth.apiHost),+ { headers: this.projectScopeHeaders() },+ );+ }} catch (err) {this.log.warn("Usage fetch network error", {error: err instanceof Error ? err.message : String(err),@@ -285,6 +412,9 @@ export class LlmGatewayService {}const usage = usageOutput.parse(await response.json());+ if (usage.ai_credits && !usage.ai_credits.exhausted) {+ this.gatewayTokens.clearBlocked();+ }if (usage.code_usage_subscribed !== undefined) {this.lastKnownCodeUsageSubscribed = usage.code_usage_subscribed;}@@ -297,3 +427,8 @@ export class LlmGatewayService {);}}++function remintReason(error: unknown) {+ if (!(error instanceof LlmGatewayError)) return null;+ return aiGatewayRemintReason(error.statusCode, error.code);+}diff --git a/products/desktop/packages/core/src/llm-gateway/schemas.ts b/products/desktop/packages/core/src/llm-gateway/schemas.tsindex 7935aa0d0aa2..97c8207229aa 100644--- a/products/desktop/packages/core/src/llm-gateway/schemas.ts+++ b/products/desktop/packages/core/src/llm-gateway/schemas.ts@@ -53,8 +53,58 @@ export interface AnthropicErrorResponse {type: string;code?: string;};+ /** The Go gateway's flat envelope. */+ code?: unknown;+ message?: unknown;detail?: unknown;}+export const gatewayTokenMintedSchema = z.object({+ enabled: z.literal(true),+ token: z.string().startsWith("phe_"),+ expires_at: z.string(),+ cap_usd: z.string(),+ gateway_url: z.string(),+ product: z.string(),+ team_id: z.number(),+ plan: z.enum(["paid", "free"]),+ allowed_models: z.array(z.string()),+ product_models: z.array(z.string()),+});+export type GatewayTokenMinted = z.infer<typeof gatewayTokenMintedSchema>;++export const gatewayTokenRefusalSchema = z.object({+ enabled: z.literal(false).optional(),+ reason: z.string().optional(),+ /** DRF permission refusals carry the reason here instead. */+ code: z.string().optional(),+ detail: z.string().optional(),+ access: z.unknown().optional(),+});++export type GatewayRoute =+ | { mode: "legacy"; reason: string }+ | {+ mode: "blocked";+ reason: "credit_bucket_exhausted";+ detail: string;+ }+ | {+ mode: "go";+ gatewayUrl: string;+ token: string;+ /** Epoch ms. */+ expiresAt: number;+ capUsd: string;+ allowedModels: string[] | null;+ productModels: string[];+ plan: "paid" | "free";+ projectId: number;+ teamId: number;+ source: "mint" | "override";+ };++export type GatewayRemintReason = "unauthorized" | "token_cap_exceeded";+export type { UsageOutput } from "../usage/schemas";export { usageOutput } from "../usage/schemas";diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 2c2fc7ea046c..e5d565e35cd9 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -2844,6 +2844,7 @@ export class SessionService {execution_type: "local",initial_mode: executionMode,adapter,+ ...(result.gatewayMode && { gateway_mode: result.gatewayMode }),});if (initialPrompt?.length) {diff --git a/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.test.ts b/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.test.tsindex 2302ee5ad961..834c703d6f87 100644--- a/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.test.ts+++ b/products/desktop/packages/harness/src/extensions/posthog-provider/model-catalog.test.ts@@ -211,6 +211,38 @@ describe("resolvePosthogPiModelCatalog", () => {},);+ it("reads Go-shaped entries through the proxy and honours its marks", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ object: "list",+ data: [+ { id: "claude-opus-5", owned_by: "anthropic" },+ {+ id: "gpt-6-sol",+ owned_by: "openai",+ allowed: false,+ restriction_reason: "paid_plan_required",+ },+ ],+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const models = await fetchPosthogPiModelCatalog(+ "http://127.0.0.1:4100/session-token",+ "us",+ "posthog-code-auth-proxy",+ 42,+ );++ expect(fetchMock.mock.calls[0]?.[0]).toBe(+ "http://127.0.0.1:4100/session-token/v1/models",+ );+ expect(models.map((model) => model.id)).toEqual(["claude-opus-5"]);+ });+it("uses fallback models without fetching while offline", async () => {process.env.PI_OFFLINE = "1";const fetch = vi.fn();diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex edb724ffc514..3dc89c355707 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -144,6 +144,7 @@ export interface TaskRunStartedProperties {model?: string;initial_mode?: string;adapter?: string;+ gateway_mode?: "legacy" | "go";}export interface TaskRunCompletedProperties {diff --git a/products/desktop/packages/shared/src/cloud-task-models.test.ts b/products/desktop/packages/shared/src/cloud-task-models.test.tsindex 318f2126ade4..aaaedc8cdea3 100644--- a/products/desktop/packages/shared/src/cloud-task-models.test.ts+++ b/products/desktop/packages/shared/src/cloud-task-models.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it } from "vitest";import {adapterForModelId,+ applyAllowedModels,buildCloudTaskConfigOptions,buildProviderModelGroups,compareModelsForPicker,@@ -418,3 +419,82 @@ describe("getCloudTaskGatewayUrl with a custom cloud", () => {);});});++describe("applyAllowedModels", () => {+ const goBody = {+ object: "list",+ data: [+ { id: "claude-opus-5", owned_by: "anthropic" },+ { id: "gpt-6-sol", owned_by: "openai" },+ { id: "internal-only", owned_by: "anthropic" },+ { id: "glm", aliases: ["@cf/zai-org/glm-5.2"], owned_by: "cloudflare" },+ ],+ };++ it("keeps product models and marks the ones outside the pin", () => {+ const result = applyAllowedModels(goBody, {+ productModels: ["claude-opus-5", "gpt-6-sol", "@cf/zai-org/glm-5.2"],+ allowedModels: ["@cf/zai-org/glm-5.2"],+ }) as { object: string; data: Array<Record<string, unknown>> };++ expect(result.object).toBe("list");+ expect(+ result.data.map((m) => [m.id, m.allowed, m.restriction_reason]),+ ).toEqual([+ ["claude-opus-5", false, "paid_plan_required"],+ ["gpt-6-sol", false, "paid_plan_required"],+ ["glm", true, null],+ ]);+ });++ it("marks every kept entry allowed only when the pin is null", () => {+ const result = applyAllowedModels(goBody, {+ productModels: [],+ allowedModels: null,+ }) as { data: Array<Record<string, unknown>> };+ expect(result.data).toHaveLength(4);+ expect(result.data.every((m) => m.allowed === true)).toBe(true);+ });++ it("marks no entry allowed when the pin is empty", () => {+ const result = applyAllowedModels(goBody, {+ productModels: [],+ allowedModels: [],+ }) as { data: Array<Record<string, unknown>> };+ expect(result.data).toHaveLength(4);+ expect(result.data.every((m) => m.allowed === false)).toBe(true);+ });++ it("feeds normalizeGatewayModelsResponse the marks it reads", () => {+ const models = normalizeGatewayModelsResponse(+ applyAllowedModels(goBody, {+ productModels: ["claude-opus-5"],+ allowedModels: ["gpt-6-sol"],+ }),+ );+ expect(models).toEqual([+ expect.objectContaining({+ id: "claude-opus-5",+ allowed: false,+ restriction_reason: "paid_plan_required",+ }),+ ]);+ });++ it("handles bare arrays and leaves unknown shapes alone", () => {+ expect(+ applyAllowedModels([{ id: "a" }, { id: "b" }, "junk"], {+ productModels: ["a"],+ allowedModels: ["a"],+ }),+ ).toEqual([{ id: "a", allowed: true, restriction_reason: null }]);+ expect(+ applyAllowedModels(+ { error: "x" },+ { productModels: [], allowedModels: [] },+ ),+ ).toEqual({+ error: "x",+ });+ });+});diff --git a/products/desktop/packages/shared/src/cloud-task-models.ts b/products/desktop/packages/shared/src/cloud-task-models.tsindex 8875e4d70554..70e9fa64353f 100644--- a/products/desktop/packages/shared/src/cloud-task-models.ts+++ b/products/desktop/packages/shared/src/cloud-task-models.ts@@ -496,3 +496,64 @@ export function buildCloudTaskConfigOptions(return configOptions;}++export const PAID_PLAN_REQUIRED_REASON = "paid_plan_required";++export interface AllowedModelsPin {+ /** The desktop product's model list; empty keeps every entry. */+ productModels: readonly string[];+ /** What the token can call; null (the dev override) allows every entry. */+ allowedModels: readonly string[] | null;+}++function modelNames(entry: Record<string, unknown>): string[] {+ const names = typeof entry.id === "string" ? [entry.id] : [];+ if (Array.isArray(entry.aliases)) {+ for (const alias of entry.aliases) {+ if (typeof alias === "string") names.push(alias);+ }+ }+ return names;+}++/**+ * Filters the Go gateway's unfiltered `/v1/models` body to the desktop product+ * list and marks `allowed` from the token's pin, keeping the response shape.+ */+export function applyAllowedModels(+ body: unknown,+ pin: AllowedModelsPin,+): unknown {+ const product = new Set(pin.productModels);+ const allowed = pin.allowedModels && new Set(pin.allowedModels);+ const rewrite = (entries: unknown[]): unknown[] =>+ entries.flatMap((entry) => {+ if (!entry || typeof entry !== "object") return [];+ const record = entry as Record<string, unknown>;+ const names = modelNames(record);+ if (names.length === 0) return [];+ if (product.size > 0 && !names.some((name) => product.has(name))) {+ return [];+ }+ const isAllowed =+ allowed === null || names.some((name) => allowed.has(name));+ return [+ {+ ...record,+ allowed: isAllowed,+ restriction_reason: isAllowed ? null : PAID_PLAN_REQUIRED_REASON,+ },+ ];+ });++ if (Array.isArray(body)) return rewrite(body);+ if (!body || typeof body !== "object") return body;+ const response = body as GatewayModelsResponse & Record<string, unknown>;+ if (Array.isArray(response.data)) {+ return { ...response, data: rewrite(response.data) };+ }+ if (Array.isArray(response.models)) {+ return { ...response, models: rewrite(response.models) };+ }+ return body;+}diff --git a/products/desktop/packages/shared/src/custom-cloud.test.ts b/products/desktop/packages/shared/src/custom-cloud.test.tsindex ab6dcac02c0c..2590ee5bd624 100644--- a/products/desktop/packages/shared/src/custom-cloud.test.ts+++ b/products/desktop/packages/shared/src/custom-cloud.test.ts@@ -5,6 +5,7 @@ import {isCredentialOriginAllowed,isCustomCloudHost,normalizeCustomCloud,+ validateAiGatewayUrl,} from "./custom-cloud";describe("custom cloud", () => {@@ -28,6 +29,15 @@ describe("custom cloud", () => {});});+ it("accepts plain http on an IPv6 loopback", () => {+ expect(+ normalizeCustomCloud({+ url: "http://[::1]:8000",+ oauthClientId: "local",+ })?.url,+ ).toBe("http://[::1]:8000");+ });+it.each([{ name: "no input", url: undefined },{ name: "an empty URL", url: " " },@@ -249,3 +259,69 @@ describe("isCredentialOriginAllowed", () => {).toBe(false);});});++describe("validateAiGatewayUrl", () => {+ afterEach(() => configureCustomCloud(null));++ it.each([+ "https://ai-gateway.us.posthog.com",+ "https://ai-gateway.eu.posthog.com/",+ "https://ai-gateway.us.posthog.com:443",+ "https://ai-gateway.dev.posthog.dev",+ "https://AI-GATEWAY.US.POSTHOG.COM.",+ ])("accepts %s", (raw) => {+ expect(validateAiGatewayUrl(raw)).toBe(+ new URL(raw).origin.replace(/\.$/, ""),+ );+ });++ it.each([+ "http://ai-gateway.us.posthog.com",+ "https://evil.example",+ "https://evilposthog.com",+ "https://us.posthog.com",+ "https://llm.posthog.com",+ "https://attacker.github.io",+ "https://ai-gateway.us.posthog.com.evil.example",+ "https://x-ai-gateway.us.posthog.com.evil.example",+ "https://1.2.3.4",+ "https://ai-gateway.us.posthog.com:8443",+ "https://ai-gateway.us.posthog.com/v1",+ "https://ai-gateway.us.posthog.com?x=1",+ "https://user:[email protected]",+ "http://localhost:3308",+ "https://127.0.0.1:3308",+ "not a url",+ ])("rejects %s", (raw) => {+ expect(validateAiGatewayUrl(raw)).toBeNull();+ });++ it("accepts loopback only under the dev override", () => {+ expect(+ validateAiGatewayUrl("http://localhost:3308", { allowLoopback: true }),+ ).toBe("http://localhost:3308");+ expect(+ validateAiGatewayUrl("http://[::1]:3308", { allowLoopback: true }),+ ).toBe("http://[::1]:3308");+ expect(validateAiGatewayUrl("http://[::1]:3308")).toBeNull();+ expect(+ validateAiGatewayUrl("https://gateway.example", { allowLoopback: true }),+ ).toBeNull();+ });++ it.each([+ ["https://us.posthog.com", "https://ai-gateway.dev.posthog.dev"],+ ["https://app.dev.posthog.dev", "https://ai-gateway.us.posthog.com"],+ ["http://localhost:8000", "https://ai-gateway.us.posthog.com"],+ ])("refuses a gateway outside the domain of %s", (apiHost, raw) => {+ expect(validateAiGatewayUrl(raw, { apiHost })).toBeNull();+ });++ it.each([+ ["https://us.posthog.com", "https://ai-gateway.us.posthog.com"],+ ["https://eu.posthog.com", "https://ai-gateway.eu.posthog.com"],+ ["https://app.dev.posthog.dev", "https://ai-gateway.dev.posthog.dev"],+ ])("accepts a gateway in the domain of %s", (apiHost, raw) => {+ expect(validateAiGatewayUrl(raw, { apiHost })).toBe(raw);+ });+});diff --git a/products/desktop/packages/shared/src/custom-cloud.ts b/products/desktop/packages/shared/src/custom-cloud.tsindex d37940e8c0d6..c9754ca2d9a7 100644--- a/products/desktop/packages/shared/src/custom-cloud.ts+++ b/products/desktop/packages/shared/src/custom-cloud.ts@@ -110,6 +110,13 @@ export function getCustomCloud(): CustomCloud | null {return configured ?? fromEnv();}+/** Go ai-gateway hosts a mint or the dev override may name. */+const AI_GATEWAY_HOSTS = new Set([+ "ai-gateway.us.posthog.com",+ "ai-gateway.eu.posthog.com",+ "ai-gateway.dev.posthog.dev",+]);+const POSTHOG_DOMAINS = ["posthog.com", "posthog.dev"];function postHogDomain(host: string): string | undefined {@@ -170,3 +177,39 @@ export function isCredentialOriginAllowed(postHogDomain(targetHost) === domain);}++/**+ * The origin of a Go gateway URL, or null unless it is a bare https origin on+ * the ai-gateway allowlist with the default port. Loopback passes only with+ * `allowLoopback` (the dev override). With `apiHost`, the gateway must share+ * its PostHog domain, so a prod bearer never reaches a dev host or the reverse.+ */+export function validateAiGatewayUrl(+ raw: string,+ options: { allowLoopback?: boolean; apiHost?: string } = {},+): string | null {+ const parsed = safeUrl(raw.trim());+ if (!parsed) return null;+ if (parsed.username || parsed.password) return null;+ if (+ parsed.search ||+ parsed.hash ||+ parsed.pathname.replace(/\/+$/, "") !== ""+ ) {+ return null;+ }+ const host = parsed.hostname.replace(/\.+$/, "").toLowerCase();+ const origin = `${parsed.protocol}//${canonicalHost(parsed)}`;+ if (isLoopbackHost(host)) {+ const httpish = parsed.protocol === "https:" || parsed.protocol === "http:";+ return options.allowLoopback && httpish ? origin : null;+ }+ if (parsed.protocol !== "https:" || !AI_GATEWAY_HOSTS.has(host)) return null;+ if (parsed.port !== "") return null;+ if (options.apiHost !== undefined) {+ const api = safeUrl(options.apiHost);+ const apiHost = api?.hostname.replace(/\.+$/, "").toLowerCase() ?? "";+ if (postHogDomain(apiHost) !== postHogDomain(host)) return null;+ }+ return origin;+}diff --git a/products/desktop/packages/shared/src/errors.test.ts b/products/desktop/packages/shared/src/errors.test.tsindex fcd2a16804d0..25d517551170 100644--- a/products/desktop/packages/shared/src/errors.test.ts+++ b/products/desktop/packages/shared/src/errors.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vitest";import {+ aiGatewayDenialCode,+ aiGatewayRemintReason,classifyGatewayLimitError,classifyPromptFailure,getErrorMessage,@@ -155,6 +157,61 @@ describe("classifyGatewayLimitError", () => {).toBe("model_gate");});+ it.each([+ [+ 'API Error: 402 {"error":{"code":"credit_bucket_exhausted","message":"Your organization has reached its PostHog Desktop usage limit"}}',+ "org_limit",+ ],+ [+ 'API Error: 402 {"error":{"code":"token_cap_exceeded","message":"admission rejected"}}',+ "org_limit",+ ],+ ['{"code":"cap_exceeded","message":"admission rejected"}', "org_limit"],+ ['{"code":"insufficient_credits","message":"x"}', "org_limit"],+ ["budget_exceeded:team", "org_limit"],+ ["API Error: 402 admission rejected", "org_limit"],+ [+ 'API Error: 403 {"error":{"code":"model_not_allowed","message":"model not allowed for this credential"}}',+ "model_gate",+ ],+ ['{"code":"effort_not_allowed"}', "model_gate"],+ ["API Error: 400 router rejected request", "model_gate"],+ [+ 'API Error: 403 {"type":"error","error":{"type":"permission_error","message":"reasoning effort not allowed for this credential"}}',+ "model_gate",+ ],+ [+ 'API Error: 403 {"type":"error","error":{"type":"permission_error","message":"this credential requires an explicit reasoning effort"}}',+ "model_gate",+ ],+ [+ 'API Error: 402 {"type":"error","error":{"type":"billing_error","message":"admission rejected"}}',+ "org_limit",+ ],+ ])("classifies Go gateway refusal %j as %s", (message, expected) => {+ expect(classifyGatewayLimitError(message)).toBe(expected);+ });++ it.each([+ "API Error: 503 router rejected request",+ "API Error: 500 router rejected request",+ "API Error: 500 admission rejected",+ "API Error: 401 admission rejected",+ "API Error: 500 reasoning effort not allowed for this credential",+ "router rejected request",+ "admission rejected",+ ])("does not read Go outage or auth prose %j as a limit", (message) => {+ expect(classifyGatewayLimitError(message)).toBeNull();+ });++ it("prefers a Go model refusal over the admission fallback", () => {+ expect(+ classifyGatewayLimitError(+ 'admission rejected {"code":"model_not_allowed"}',+ ),+ ).toBe("model_gate");+ });+it.each(["Rate limit exceeded","Rate limit exceeded: Product rate limit exceeded",@@ -165,6 +222,62 @@ describe("classifyGatewayLimitError", () => {});});+describe("aiGatewayDenialCode", () => {+ it.each([+ [+ "the header over the body",+ "token_cap_exceeded:team",+ '{"error":{"code":"cap_exceeded"}}',+ "token_cap_exceeded",+ ],+ [+ "the body's error.code without a header",+ null,+ '{"error":{"code":"cap_exceeded"}}',+ "cap_exceeded",+ ],+ [+ "a top-level code",+ undefined,+ { code: "insufficient_credits" },+ "insufficient_credits",+ ],+ [+ "nothing from an Anthropic-dialect body",+ null,+ '{"type":"error","error":{"type":"x","message":"y"}}',+ undefined,+ ],+ [+ "a padded header",+ " token_cap_exceeded :team",+ null,+ "token_cap_exceeded",+ ],+ [+ "error.code over a top-level code",+ null,+ '{"code":"cap_exceeded","error":{"code":"token_cap_exceeded"}}',+ "token_cap_exceeded",+ ],+ ["nothing from a non-JSON body", "", "<html>", undefined],+ ])("reads %s", (_label, header, body, expected) => {+ expect(aiGatewayDenialCode(header, body)).toBe(expected);+ });+});++describe("aiGatewayRemintReason", () => {+ it.each([+ [401, undefined, "unauthorized"],+ [402, "token_cap_exceeded", "token_cap_exceeded"],+ [402, "cap_exceeded", null],+ [402, undefined, null],+ [403, "token_cap_exceeded", null],+ ] as const)("maps %s %s to %s", (status, code, expected) => {+ expect(aiGatewayRemintReason(status, code)).toBe(expected);+ });+});+describe("classifyPromptFailure", () => {it.each([["Rate limit exceeded", undefined, "usage_limit", false],@@ -212,6 +325,14 @@ describe("isFatalSessionError", () => {).toBe(false);});+ it("does not treat the auth proxy's body-size refusal as fatal", () => {+ expect(+ isFatalSessionError(+ 'Internal error: API Error: 413 {"error":{"type":"request_too_large","message":"request body too large"}}',+ ),+ ).toBe(false);+ });+it("does not treat a rate-limit error as fatal even if a fatal phrase is present", () => {expect(isFatalSessionError("process exited", "rate limit exceeded")).toBe(false,diff --git a/products/desktop/packages/shared/src/errors.ts b/products/desktop/packages/shared/src/errors.tsindex ec9665eb89e8..c2b2e0741f15 100644--- a/products/desktop/packages/shared/src/errors.ts+++ b/products/desktop/packages/shared/src/errors.ts@@ -80,6 +80,18 @@ export type GatewayLimitCause =| "org_limit";const MODEL_GATE_CODE_REGEX = /"code"\s*:\s*"model_gate"/;+const AI_GATEWAY_MODEL_GATE_REGEX =+ /\b(?:model_not_allowed|effort_not_allowed)\b/i;+const AI_GATEWAY_ORG_LIMIT_REGEX =+ /\b(?:cap_exceeded|token_cap_exceeded|insufficient_credits|credit_bucket_exhausted|budget_exceeded)\b/i;+// Go writes these phrases for outages and auth failures too, so they count+// only after the refusal's own status.+const AI_GATEWAY_ROUTER_REFUSAL_REGEX =+ /\b400\b[\s\S]*router rejected request/i;+const AI_GATEWAY_ADMISSION_REFUSAL_REGEX = /\b402\b[\s\S]*admission rejected/i;+// Anthropic-dialect bodies carry no code, only this fixed 403 text.+const AI_GATEWAY_PIN_REFUSAL_REGEX =+ /\b403\b[\s\S]*(?:not allowed for this credential|this credential requires an explicit reasoning effort)/i;const MODEL_UNAVAILABLE_REASON_REGEX = /"reason"\s*:\s*"model_not_available"/;const MODEL_GATE_PATTERNS = ["needs a paid posthog plan"] as const;@@ -179,10 +191,57 @@ export function classifyGatewayLimitError() {return "model_unavailable";}- if (matchesRegex(MODEL_GATE_CODE_REGEX) || matches(MODEL_GATE_PATTERNS)) {+ if (+ matchesRegex(MODEL_GATE_CODE_REGEX) ||+ matches(MODEL_GATE_PATTERNS) ||+ matchesRegex(AI_GATEWAY_MODEL_GATE_REGEX) ||+ matchesRegex(AI_GATEWAY_PIN_REFUSAL_REGEX) ||+ matchesRegex(AI_GATEWAY_ROUTER_REFUSAL_REGEX)+ ) {return "model_gate";}- if (matches(ORG_LIMIT_PATTERNS)) return "org_limit";+ if (+ matches(ORG_LIMIT_PATTERNS) ||+ matchesRegex(AI_GATEWAY_ORG_LIMIT_REGEX) ||+ matchesRegex(AI_GATEWAY_ADMISSION_REFUSAL_REGEX)+ ) {+ return "org_limit";+ }+ return null;+}++export function aiGatewayDenialCode(+ denialHeader: string | null | undefined,+ body: unknown,+): string | undefined {+ const fromHeader = denialHeader?.split(":")[0]?.trim();+ if (fromHeader) return fromHeader;+ let parsed = body;+ if (typeof body === "string") {+ try {+ parsed = JSON.parse(body);+ } catch {+ return undefined;+ }+ }+ if (!parsed || typeof parsed !== "object") return undefined;+ const envelope = parsed as { code?: unknown; error?: { code?: unknown } };+ const candidate = envelope.error?.code ?? envelope.code;+ return typeof candidate === "string" ? candidate : undefined;+}++/**+ * Whether a fresh Go token can fix a refusal: a 401, or a 402 for the token's+ * own cap (the org's limits are refused again after a re-mint).+ */+export function aiGatewayRemintReason(+ status: number | undefined,+ denialCode: string | undefined,+): "unauthorized" | "token_cap_exceeded" | null {+ if (status === 401) return "unauthorized";+ if (status === 402 && denialCode === "token_cap_exceeded") {+ return "token_cap_exceeded";+ }return null;}diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 60fd17bd0ded..78f072f44cdd 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -74,7 +74,9 @@ export {serializeCloudPrompt,} from "./cloud-prompt";export {+ type AllowedModelsPin,adapterForModelId,+ applyAllowedModels,buildCloudTaskConfigOptions,buildProviderModelGroups,type CloudTaskConfigOption,@@ -99,6 +101,7 @@ export {isModalModelId,isOpenAIModel,normalizeGatewayModelsResponse,+ PAID_PLAN_REQUIRED_REASON,pickAllowedModel,} from "./cloud-task-models";export {@@ -109,6 +112,7 @@ export {isCredentialOriginAllowed,isCustomCloudHost,normalizeCustomCloud,+ validateAiGatewayUrl,} from "./custom-cloud";export {buildLoopDeeplink,@@ -152,6 +156,8 @@ export {} from "./domain-types";export * from "./enrichment";export {+ aiGatewayDenialCode,+ aiGatewayRemintReason,classifyGatewayLimitError,classifyPromptFailure,type GatewayLimitCause,diff --git a/products/desktop/packages/shared/src/posthog-property-headers.test.ts b/products/desktop/packages/shared/src/posthog-property-headers.test.tsindex 69d6d11fc46b..eecb1dfc15ce 100644--- a/products/desktop/packages/shared/src/posthog-property-headers.test.ts+++ b/products/desktop/packages/shared/src/posthog-property-headers.test.ts@@ -9,6 +9,7 @@ import {buildPosthogPropertyHeaderRecord,buildPosthogScopedPropertyHeaderLines,buildPosthogScopedPropertyHeaderRecord,+ collapsePropertyHeadersForAiGateway,} from "./posthog-property-headers";describe("PostHog project headers", () => {@@ -379,3 +380,110 @@ describe("buildPosthogPropertiesHeaderLines", () => {expect(buildPosthogPropertiesHeaderLines({ ai_stage: null })).toBe("");});});++describe("collapsePropertyHeadersForAiGateway", () => {+ it("folds per-property headers into one blob and keeps other headers", () => {+ const out = collapsePropertyHeadersForAiGateway(+ {+ "content-type": "application/json",+ "x-posthog-property-task_id": "t1",+ "x-posthog-property-ai_stage": "chat",+ },+ { ai_product: "posthog_code", team_id: 7 },+ );+ expect(out["content-type"]).toBe("application/json");+ expect(+ Object.keys(out).some((k) => k.startsWith("x-posthog-property-")),+ ).toBe(false);+ expect(JSON.parse(out["X-PostHog-Properties"])).toEqual({+ task_id: "t1",+ ai_stage: "chat",+ ai_product: "posthog_code",+ team_id: 7,+ });+ });++ it("lets trusted values win over the client's headers and inbound blob", () => {+ const out = collapsePropertyHeadersForAiGateway(+ {+ "x-posthog-property-team_id": "999",+ "X-PostHog-Properties": JSON.stringify({ ai_product: "wizard", a: 1 }),+ },+ { ai_product: "posthog_code", team_id: 7 },+ );+ expect(JSON.parse(out["X-PostHog-Properties"])).toEqual({+ a: 1,+ ai_product: "posthog_code",+ team_id: 7,+ });+ });++ it("lifts $ai_session_id into the session header", () => {+ const out = collapsePropertyHeadersForAiGateway(+ { "x-posthog-property-$ai_session_id": "task-1" },+ { ai_product: "posthog_code", team_id: 7 },+ );+ expect(out["X-PostHog-Session-Id"]).toBe("task-1");+ expect(JSON.parse(out["X-PostHog-Properties"])).not.toHaveProperty(+ "$ai_session_id",+ );+ });++ it("keeps the trusted keys when the client's values overflow the cap", () => {+ const out = collapsePropertyHeadersForAiGateway(+ {+ "x-posthog-property-a": "x".repeat(5000),+ "x-posthog-property-b": "y".repeat(5000),+ },+ { ai_product: "posthog_code", team_id: 7 },+ );+ const blob = JSON.parse(out["X-PostHog-Properties"]);+ expect(blob.ai_product).toBe("posthog_code");+ expect(blob.team_id).toBe(7);+ });++ it("falls back to the trusted keys alone when non-string values overflow", () => {+ const blob = JSON.stringify(+ Object.fromEntries(Array.from({ length: 2000 }, (_, i) => [`m${i}`, i])),+ );+ const out = collapsePropertyHeadersForAiGateway(+ { "x-posthog-properties": blob },+ { ai_product: "posthog_code", team_id: 7 },+ );+ expect(JSON.parse(out["X-PostHog-Properties"])).toEqual({+ ai_product: "posthog_code",+ team_id: 7,+ });+ });++ it("drops client keys that sanitize to a trusted key", () => {+ const out = collapsePropertyHeadersForAiGateway(+ {+ "x-posthog-properties": JSON.stringify({+ ai_product: "x",+ team_id: 1,+ "ai_prod\u00fcct": "evil",+ "team_\u0001id": 999,+ other: "kept",+ }),+ },+ { ai_product: "posthog_code", team_id: 7 },+ );+ expect(JSON.parse(out["X-PostHog-Properties"])).toEqual({+ other: "kept",+ ai_product: "posthog_code",+ team_id: 7,+ });+ });++ it("ignores an inbound blob that is not a JSON object", () => {+ const out = collapsePropertyHeadersForAiGateway(+ { "x-posthog-properties": "not json" },+ { ai_product: "posthog_code", team_id: 7 },+ );+ expect(JSON.parse(out["X-PostHog-Properties"])).toEqual({+ ai_product: "posthog_code",+ team_id: 7,+ });+ });+});diff --git a/products/desktop/packages/shared/src/posthog-property-headers.ts b/products/desktop/packages/shared/src/posthog-property-headers.tsindex 7bb92ae24dca..4ece01873a17 100644--- a/products/desktop/packages/shared/src/posthog-property-headers.ts+++ b/products/desktop/packages/shared/src/posthog-property-headers.ts@@ -221,3 +221,83 @@ export function buildPosthogPropertiesHeaderLines(.map(([key, value]) => `${key}: ${value}`).join("\n");}++/**+ * Session id header the Go gateway reads; the blob cannot carry it because+ * {@link buildPosthogPropertiesBlob} drops `$` keys.+ */+export const POSTHOG_SESSION_ID_HEADER = "X-PostHog-Session-Id";++const PROPERTY_HEADER_PREFIX = "x-posthog-property-";++function parsePropertiesBlob(raw: string): PosthogProperties {+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return {};+ }+ const properties: PosthogProperties = {};+ for (const [key, value] of Object.entries(parsed)) {+ if (+ typeof value === "string" ||+ typeof value === "number" ||+ typeof value === "boolean"+ ) {+ properties[key] = value;+ }+ }+ return properties;+ } catch {+ return {};+ }+}++export function collapsePropertyHeadersForAiGateway(+ headers: Record<string, string>,+ trusted: PosthogProperties,+): Record<string, string> {+ const out: Record<string, string> = {};+ const fromHeaders: PosthogProperties = {};+ let fromBlob: PosthogProperties = {};+ let sessionId: string | undefined;+ for (const [key, value] of Object.entries(headers)) {+ const lower = key.toLowerCase();+ if (lower.startsWith(PROPERTY_HEADER_PREFIX)) {+ fromHeaders[lower.slice(PROPERTY_HEADER_PREFIX.length)] = value;+ } else if (lower === POSTHOG_PROPERTIES_HEADER.toLowerCase()) {+ fromBlob = parsePropertiesBlob(value);+ } else if (lower === POSTHOG_SESSION_ID_HEADER.toLowerCase()) {+ sessionId = value;+ } else {+ out[key] = value;+ }+ }++ // A client key that sanitizes to a trusted key would overwrite it inside+ // the blob builder, so it is dropped here.+ const trustedKeys = new Set(Object.keys(trusted).map(sanitizeHeaderValue));+ const client = Object.fromEntries(+ Object.entries({ ...fromBlob, ...fromHeaders }).filter(+ ([key]) => !trustedKeys.has(sanitizeHeaderValue(key)),+ ),+ );+ const merged = { ...client, ...trusted };+ let blob = buildPosthogPropertiesBlob(merged);+ const kept = blob ? parsePropertiesBlob(blob) : {};+ const lostTrusted = Object.entries(trusted).some(+ ([key, value]) =>+ value !== null &&+ value !== undefined &&+ !key.startsWith("$") &&+ !(key in kept),+ );+ if (lostTrusted) blob = buildPosthogPropertiesBlob(trusted);+ if (blob) out[POSTHOG_PROPERTIES_HEADER] = blob;++ const session = sessionId ?? merged.$ai_session_id;+ if (session !== null && session !== undefined && session !== "") {+ const value = sanitizeHeaderValue(String(session));+ if (value) out[POSTHOG_SESSION_ID_HEADER] = value;+ }+ return out;+}diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex f20aae25a7c7..de186a9bf2f5 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -920,6 +920,32 @@ describe("SessionService", () => {);});+ it("records the session's gateway mode on the start event", async () => {+ const { track } = await import("@posthog/ui/shell/posthogAnalyticsImpl");+ const service = getSessionService();+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);+ mockBuildAuthenticatedClient.mockReturnValue({+ ...mockAuthenticatedClient,+ createTaskRun: vi.fn().mockResolvedValue({ id: "run-789" }),+ appendTaskRunLog: vi.fn(),+ });+ mockTrpcAgent.start.mutate.mockResolvedValue({+ channel: "test-channel",+ configOptions: [],+ gatewayMode: "go",+ });++ await service.connectToTask({+ task: createMockTask(),+ repoPath: "/repo",+ });++ expect(track).toHaveBeenCalledWith(+ "Task run started",+ expect.objectContaining({ gateway_mode: "go" }),+ );+ });+it("starts Claude with the access selected for the task", async () => {const service = getSessionService();mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);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.tsindex 309d87a66041..d8800f890968 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@@ -225,7 +225,10 @@ function createMockDependencies() {gatewayAuthToken: vi.fn().mockResolvedValue("gateway-token"),gatewayPublishToken: vi.fn().mockResolvedValue("gateway-token"),gatewayProjectId: vi.fn().mockReturnValue(1),- ensureGatewayProxy: vi.fn().mockResolvedValue("http://127.0.0.1:9999"),+ ensureGatewayProxy: vi.fn().mockResolvedValue({+ proxyUrl: "http://127.0.0.1:9999",+ mode: "legacy",+ }),configureProcessEnv: vi.fn().mockResolvedValue(undefined),createPosthogConfig: vi.fn((credentials) => ({apiUrl: credentials.apiHost,@@ -481,6 +484,20 @@ describe("AgentService", () => {});});+ it("lists models from the legacy gateway when the proxy cannot start", async () => {+ deps.agentAuthAdapter.ensureGatewayProxy.mockRejectedValueOnce(+ new Error("PostHog session ended"),+ );++ await service.getPreviewConfigOptions("https://us.posthog.com", "claude");++ expect(fetchGatewayModels).toHaveBeenCalledWith({+ gatewayUrl: "https://gateway.example.com",+ authToken: "gateway-token",+ projectId: 1,+ });+ });+it("includes Modal models in Claude preview options", async () => {vi.mocked(fetchGatewayModels).mockResolvedValueOnce([{@@ -506,8 +523,15 @@ describe("AgentService", () => {"claude",);- expect(fetchGatewayModels).toHaveBeenCalledWith(- expect.objectContaining({ projectId: 1 }),+ expect(fetchGatewayModels).toHaveBeenCalledWith({+ gatewayUrl: "http://127.0.0.1:9999",+ authToken: "gateway-token",+ projectId: 1,+ });+ expect(deps.agentAuthAdapter.ensureGatewayProxy).toHaveBeenCalledWith(+ "https://us.posthog.com",+ 1,+ { awaitRecheck: false },);const modelOption = options.find((option) => option.id === "model");expect(modelOption).toMatchObject({@@ -937,6 +961,21 @@ describe("AgentService", () => {);});+ it("pins the session to the gateway mode chosen at start", async () => {+ deps.agentAuthAdapter.ensureGatewayProxy.mockResolvedValueOnce({+ proxyUrl: "http://127.0.0.1:9998",+ mode: "go",+ });++ const session = await service.startSession(baseSessionParams);++ expect(deps.agentAuthAdapter.ensureGatewayProxy).toHaveBeenCalledWith(+ baseSessionParams.apiHost,+ baseSessionParams.projectId,+ );+ expect(session?.gatewayMode).toBe("go");+ });+it("passes reasoning effort to local Codex startup options", async () => {await service.startSession({...baseSessionParams,diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex 2eea179e78e1..5541e89031c4 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -376,6 +376,7 @@ interface ManagedSession {steering?: string;/** Adapter's negotiated side-question capability from initialize (`_meta.posthog.sideQuestion`). */sideQuestion?: boolean;+ gatewayMode: "legacy" | "go";/** Tracks in-flight MCP tool calls (toolCallId → toolKey) for cancellation */inFlightMcpToolCalls: Map<string, string>;/** Count of "/btw" side questions awaiting a response, so the idle timer does not reap the session mid-answer. */@@ -1046,9 +1047,11 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {}const channel = `agent-event:${taskRunId}`;- const proxyUrl = await this.agentAuthAdapter.ensureGatewayProxy(+ const gatewayProxy = await this.agentAuthAdapter.ensureGatewayProxy(credentials.apiHost,+ credentials.projectId,);+ const proxyUrl = gatewayProxy.proxyUrl;// The wiki mount only needs the auth adapter, so it runs alongside the// env configuration instead of serializing another round-trip before it.const [, contextWiki] = await Promise.all([@@ -1455,6 +1458,7 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {configOptions,steering,sideQuestion,+ gatewayMode: gatewayProxy.mode,inFlightMcpToolCalls: new Map(),pendingSideQuestions: 0,mcpToolApprovals: toolApprovals,@@ -2471,6 +2475,7 @@ For git operations while detached:configOptions: session.configOptions,steering: session.steering,sideQuestion: session.sideQuestion,+ gatewayMode: session.gatewayMode,};}@@ -2669,26 +2674,57 @@ For git operations while detached:}async getPiModelCatalog(apiHost: string, region: CloudRegion) {- const gatewayUrl = getLlmGatewayUrl(apiHost);+ const models = await this.catalogueSource(apiHost);return fetchPosthogPiModelCatalog(- gatewayUrl,+ models.gatewayUrl,region,- (await this.agentAuthAdapter.gatewayAuthToken()) ?? undefined,- this.agentAuthAdapter.gatewayProjectId() ?? undefined,+ models.authToken,+ models.projectId,);}+ /**+ * Where the pickers read `/v1/models`: through the proxy for the selected+ * project, so Go's list gets the same filter and marks a session sees.+ */+ private async catalogueSource(apiHost: string): Promise<{+ gatewayUrl: string;+ authToken: string | undefined;+ projectId: number | undefined;+ }> {+ const projectId = this.agentAuthAdapter.gatewayProjectId();+ const authToken =+ (await this.agentAuthAdapter.gatewayAuthToken()) ?? undefined;+ if (projectId !== null) {+ try {+ // The pickers keep no mode, so a due re-check runs in the background.+ const proxy = await this.agentAuthAdapter.ensureGatewayProxy(+ apiHost,+ projectId,+ { awaitRecheck: false },+ );+ return { gatewayUrl: proxy.proxyUrl, authToken, projectId };+ } catch (err) {+ this.log.warn("Gateway proxy unavailable for the model catalogue", {+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ return {+ gatewayUrl: getLlmGatewayUrl(apiHost),+ authToken,+ projectId: projectId ?? undefined,+ };+ }+async getPreviewConfigOptions(apiHost: string,adapter: Adapter = "claude",allHarnessModels = false,): Promise<SessionConfigOption[]> {- const gatewayUrl = getLlmGatewayUrl(apiHost);- const gatewayModels = await fetchGatewayModels({- gatewayUrl,- authToken: (await this.agentAuthAdapter.gatewayAuthToken()) ?? undefined,- projectId: this.agentAuthAdapter.gatewayProjectId() ?? undefined,- });+ const gatewayModels = await fetchGatewayModels(+ await this.catalogueSource(apiHost),+ );const configOptions = buildCloudTaskConfigOptions(gatewayModels,adapter,diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.tsindex 7ce03933856e..725dd27e4c39 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts@@ -9,7 +9,11 @@ vi.mock("@posthog/agent/posthog-api", () => ({vi.stubGlobal("fetch", mockFetch);import { configureCustomCloud } from "@posthog/shared";+import { Container } from "inversify";+import { AUTH_PROXY_SERVICE } from "../auth-proxy/identifiers";+import { MCP_PROXY_SERVICE } from "../mcp-proxy/identifiers";import { AgentAuthAdapter } from "./auth-adapter";+import { AGENT_AUTH, AGENT_LOGGER } from "./identifiers";const baseCredentials = {apiHost: "https://app.posthog.com",@@ -85,13 +89,139 @@ describe("AgentAuthAdapter", () => {deps.authProxy as never,deps.mcpProxy as never,deps.loggerFactory as never,+ {+ getRoute: vi.fn().mockResolvedValue({ mode: "legacy", reason: "x" }),+ remint: vi.fn(),+ fallBack: vi.fn(),+ } as never,);});+ it("refuses to resolve without a gateway credential source", () => {+ const container = new Container();+ container.bind(AGENT_AUTH).toConstantValue(deps.authService);+ container.bind(AUTH_PROXY_SERVICE).toConstantValue(deps.authProxy);+ container.bind(MCP_PROXY_SERVICE).toConstantValue(deps.mcpProxy);+ container.bind(AGENT_LOGGER).toConstantValue(deps.loggerFactory);+ container.bind(AgentAuthAdapter).toSelf();++ expect(() => container.get(AgentAuthAdapter)).toThrow();+ });+afterEach(() => {vi.restoreAllMocks();});+ describe("ensureGatewayProxy", () => {+ function withSource(getRoute: ReturnType<typeof vi.fn>) {+ const authProxy = {+ start: vi.fn().mockResolvedValue("http://127.0.0.1:9999/legacy"),+ startGatewaySession: vi+ .fn()+ .mockResolvedValue("http://127.0.0.1:9999/session"),+ };+ const source = { getRoute, remint: vi.fn(), fallBack: vi.fn() };+ const withGo = new AgentAuthAdapter(+ deps.authService as never,+ authProxy as never,+ deps.mcpProxy as never,+ deps.loggerFactory as never,+ source as never,+ );+ return { withGo, authProxy };+ }++ it("gives a blocked org a session target that answers the usage limit", async () => {+ const { withGo, authProxy } = withSource(+ vi.fn().mockResolvedValue({+ mode: "blocked",+ reason: "credit_bucket_exhausted",+ detail: "limit",+ }),+ );++ const result = await withGo.ensureGatewayProxy(+ "https://app.posthog.com",+ 1,+ );++ expect(result.mode).toBe("go");+ expect(authProxy.startGatewaySession).toHaveBeenCalled();+ expect(authProxy.start).not.toHaveBeenCalled();+ });++ it("uses a Go session target when the project has a session token", async () => {+ const getRoute = vi+ .fn()+ .mockResolvedValue({ mode: "go", token: "phe_x" });+ const { withGo, authProxy } = withSource(getRoute);++ const result = await withGo.ensureGatewayProxy(+ "https://app.posthog.com",+ 1,+ );++ expect(getRoute).toHaveBeenCalledWith(1, { awaitRecheck: true });+ expect(result).toEqual({+ proxyUrl: "http://127.0.0.1:9999/session",+ mode: "go",+ });+ expect(authProxy.startGatewaySession).toHaveBeenCalledWith({+ projectId: 1,+ legacyGatewayUrl: "https://gateway.example.com",+ headers: undefined,+ });+ });++ it("lets a caller skip waiting on a due re-check", async () => {+ const getRoute = vi+ .fn()+ .mockResolvedValue({ mode: "go", token: "phe_x" });+ const { withGo } = withSource(getRoute);++ await withGo.ensureGatewayProxy("https://app.posthog.com", 1, {+ awaitRecheck: false,+ });++ expect(getRoute).toHaveBeenCalledWith(1, { awaitRecheck: false });+ });++ it.each([+ [+ "a legacy route",+ vi.fn().mockResolvedValue({ mode: "legacy", reason: "not_rolled_out" }),+ ],+ ["a failing source", vi.fn().mockRejectedValue(new Error("boom"))],+ ])("falls back to the legacy target on %s", async (_label, getRoute) => {+ const { withGo, authProxy } = withSource(getRoute);++ const result = await withGo.ensureGatewayProxy(+ "https://app.posthog.com",+ 1,+ );++ expect(result).toEqual({+ proxyUrl: "http://127.0.0.1:9999/legacy",+ mode: "legacy",+ });+ expect(authProxy.start).toHaveBeenCalledWith(+ "https://gateway.example.com",+ undefined,+ );+ });++ it("stays on legacy without a project or a source", async () => {+ const { withGo } = withSource(vi.fn());++ expect(+ (await withGo.ensureGatewayProxy("https://app.posthog.com", null)).mode,+ ).toBe("legacy");+ expect(+ (await adapter.ensureGatewayProxy("https://app.posthog.com", 1)).mode,+ ).toBe("legacy");+ });+ });+describe("getCurrentCredentials", () => {it("returns the auth host and selected project", async () => {deps.authService.getState.mockReturnValue({ currentProjectId: 42 });diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.tsindex 4d0e5415fa24..7954ef5bf326 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts@@ -12,7 +12,15 @@ import {import { POSTHOG_PROJECT_ID_HEADER } from "@posthog/shared/posthog-property-headers";import { inject, injectable } from "inversify";import type { AuthProxyService } from "../auth-proxy/auth-proxy";-import { AUTH_PROXY_SERVICE } from "../auth-proxy/identifiers";+import {+ type ResolvedGatewayProxy,+ resolveGatewayProxy,+} from "../auth-proxy/gateway-proxy";+import {+ AUTH_PROXY_SERVICE,+ GATEWAY_CREDENTIAL_SOURCE,+} from "../auth-proxy/identifiers";+import type { GatewayCredentialSource } from "../auth-proxy/ports";import { MCP_PROXY_SERVICE } from "../mcp-proxy/identifiers";import type { McpProxyService } from "../mcp-proxy/mcp-proxy";import { AGENT_AUTH, AGENT_LOGGER } from "./identifiers";@@ -84,6 +92,9 @@ export class AgentAuthAdapter {private readonly mcpProxy: McpProxyService,@inject(AGENT_LOGGER)loggerFactory: AgentLogger,+ // Required: an unbound source would silently keep every session on legacy.+ @inject(GATEWAY_CREDENTIAL_SOURCE)+ private readonly gatewaySource: GatewayCredentialSource,) {this.log = loggerFactory.scope("agent-auth-adapter");}@@ -227,8 +238,18 @@ export class AgentAuthAdapter {};}- async ensureGatewayProxy(apiHost: string): Promise<string> {- return this.authProxy.start(getLlmGatewayUrl(apiHost));+ async ensureGatewayProxy(+ apiHost: string,+ projectId: number | null,+ options: { awaitRecheck?: boolean } = {},+ ): Promise<ResolvedGatewayProxy> {+ return resolveGatewayProxy({+ authProxy: this.authProxy,+ source: this.gatewaySource,+ legacyGatewayUrl: getLlmGatewayUrl(apiHost),+ projectId,+ awaitRecheck: options.awaitRecheck,+ });}/**diff --git a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts b/products/desktop/packages/workspace-server/src/services/agent/schemas.tsindex 7b574ab88865..357f7b9257fe 100644--- a/products/desktop/packages/workspace-server/src/services/agent/schemas.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/schemas.ts@@ -154,6 +154,7 @@ export const sessionResponseSchema = z.object({// (`_meta.posthog.sideQuestion`): true means the adapter can answer a// one-shot "/btw" question forked off the live transcript.sideQuestion: z.boolean().optional(),+ gatewayMode: z.enum(["legacy", "go"]).optional(),});export type SessionResponse = z.infer<typeof sessionResponseSchema>;diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.tsindex 31b73a41b144..535a5a4c4067 100644--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.test.ts@@ -2,7 +2,11 @@ import http from "node:http";import type { RootLogger } from "@posthog/di/logger";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { AuthProxyService, MAX_BODY_BYTES, PROXY_TIMEOUTS } from "./auth-proxy";-import type { AuthProxyAuth } from "./ports";+import type {+ AuthProxyAuth,+ GatewayCredential,+ GatewayCredentialSource,+} from "./ports";type AuthMock = {authenticatedFetch: ReturnType<typeof vi.fn>;@@ -444,3 +448,875 @@ function rawRequest(url: string): Promise<number> {req.end();});}++type GoCredential = Extract<GatewayCredential, { mode: "go" }>;++function goCredential(overrides: Partial<GoCredential> = {}): GoCredential {+ return {+ mode: "go",+ gatewayUrl: "https://ai-gateway.us.posthog.com",+ token: "phe_one",+ teamId: 7,+ projectId: 42,+ allowedModels: ["claude-opus-5"],+ productModels: ["claude-opus-5", "gpt-6-sol"],+ ...overrides,+ };+}++describe("AuthProxyService gateway sessions", () => {+ let authFetch: ReturnType<typeof vi.fn>;+ let goFetch: ReturnType<+ typeof vi.fn<(url: string, init: RequestInit) => Promise<Response>>+ >;+ let source: {+ getRoute: ReturnType<typeof vi.fn>;+ remint: ReturnType<typeof vi.fn>;+ fallBack: ReturnType<typeof vi.fn>;+ };+ let logs: unknown[][];+ let service: AuthProxyService;++ beforeEach(() => {+ authFetch = vi.fn();+ goFetch = vi.fn<(url: string, init: RequestInit) => Promise<Response>>();+ logs = [];+ source = {+ getRoute: vi.fn().mockResolvedValue(goCredential()),+ remint: vi.fn().mockResolvedValue(null),+ fallBack: vi.fn(),+ };+ const record =+ (level: string) =>+ (...args: unknown[]) =>+ logs.push([level, ...args]);+ const scoped = {+ debug: record("debug"),+ info: record("info"),+ warn: record("warn"),+ error: record("error"),+ };+ const logger = { ...scoped, scope: () => scoped } as unknown as RootLogger;+ service = new AuthProxyService(+ { authenticatedFetch: authFetch } as AuthProxyAuth,+ logger,+ source as unknown as GatewayCredentialSource,+ goFetch,+ );+ });++ afterEach(async () => {+ await service.stop();+ });++ function callInit(index: number) {+ return goFetch.mock.calls[index]?.[1] as unknown as {+ headers: Record<string, string>;+ body: Buffer;+ redirect: string;+ };+ }++ async function session(projectId = 42): Promise<string> {+ return service.startGatewaySession({+ projectId,+ legacyGatewayUrl: "https://gateway.us.posthog.com/posthog_code",+ });+ }++ it("forwards with the session token through plain fetch, never authenticatedFetch", async () => {+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages?beta=true`, {+ method: "POST",+ headers: {+ authorization: "Bearer posthog-code-auth-proxy",+ "x-api-key": "posthog-code-auth-proxy",+ cookie: "session=abc",+ "content-type": "application/json",+ },+ body: "{}",+ });++ expect(res.status).toBe(200);+ expect(authFetch).not.toHaveBeenCalled();+ const url = goFetch.mock.calls[0]?.[0];+ const init = callInit(0);+ expect(url).toBe("https://ai-gateway.us.posthog.com/v1/messages?beta=true");+ expect(init.redirect).toBe("manual");+ expect(init.headers.authorization).toBe("Bearer phe_one");+ expect(init.headers).not.toHaveProperty("x-api-key");+ expect(init.headers).not.toHaveProperty("cookie");+ expect(init.headers["content-type"]).toBe("application/json");+ expect(Buffer.from(init.body).toString()).toBe("{}");+ });++ it("collapses property headers, trusts only its own team, and drops legacy-only headers", async () => {+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();++ await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ headers: {+ "x-posthog-property-task_id": "t1",+ "x-posthog-property-team_id": "999",+ "x-posthog-property-$ai_session_id": "task-1",+ "X-PostHog-Project-Id": "999",+ "x-posthog-use-bedrock-fallback": "true",+ "x-posthog-flag-bedrock-llm-gateway": "test",+ "x-posthog-privacy-mode": "true",+ "X-PostHog-User": "distinct-1",+ "anthropic-version": "2023-06-01",+ "anthropic-auth-token": "leak",+ "x-stainless-os": "MacOS",+ "x-posthog-service-tier": "priority",+ },+ body: "{}",+ });++ const headers = callInit(0).headers;+ expect(JSON.parse(headers["X-PostHog-Properties"])).toEqual({+ task_id: "t1",+ team_id: 7,+ ai_product: "posthog_code",+ });+ expect(headers["X-PostHog-Session-Id"]).toBe("task-1");+ expect(headers["x-posthog-user"]).toBe("distinct-1");+ expect(headers["anthropic-version"]).toBe("2023-06-01");+ expect(headers["x-stainless-os"]).toBe("MacOS");+ expect(headers["x-posthog-service-tier"]).toBe("priority");+ for (const dropped of [+ "x-posthog-project-id",+ "x-posthog-use-bedrock-fallback",+ "x-posthog-flag-bedrock-llm-gateway",+ "x-posthog-privacy-mode",+ "anthropic-auth-token",+ "x-posthog-property-task_id",+ ]) {+ expect(headers).not.toHaveProperty(dropped);+ }+ });++ it("strips a leading product slug from the path", async () => {+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();++ await fetch(`${proxyUrl}/posthog_code/v1/chat/completions`, {+ method: "POST",+ body: "{}",+ });++ expect(goFetch.mock.calls[0]?.[0]).toBe(+ "https://ai-gateway.us.posthog.com/v1/chat/completions",+ );+ });++ it.each([+ "/v1/usage/posthog_code",+ "/internal/teams/2/reported-spend",+ "/v1/tokens",+ ])("refuses %s before any fetch", async (path) => {+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}${path}`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(404);+ expect(goFetch).not.toHaveBeenCalled();+ });++ it.each([+ [+ "a 401",+ () => new Response('{"error":"expired"}', { status: 401 }),+ "unauthorized",+ ],+ [+ "a token cap 402 by header",+ () =>+ new Response('{"error":{"message":"admission rejected"}}', {+ status: 402,+ headers: { "X-PostHog-Denial": "token_cap_exceeded" },+ }),+ "token_cap_exceeded",+ ],+ [+ "a token cap 402 by body code",+ () =>+ new Response(+ '{"error":{"code":"token_cap_exceeded","message":"admission rejected"}}',+ {+ status: 402,+ },+ ),+ "token_cap_exceeded",+ ],+ ])("re-mints once and retries after %s", async (_label, refusal, reason) => {+ goFetch+ .mockResolvedValueOnce(refusal())+ .mockResolvedValue(new Response("second"));+ source.remint.mockResolvedValue(goCredential({ token: "phe_two" }));+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: '{"a":1}',+ });++ expect(await res.text()).toBe("second");+ expect(source.remint).toHaveBeenCalledWith(reason, "phe_one", 42);+ expect(source.remint).toHaveBeenCalledTimes(1);+ expect(source.getRoute).toHaveBeenCalledTimes(1);+ expect(goFetch).toHaveBeenCalledTimes(2);+ expect(callInit(1).headers.authorization).toBe("Bearer phe_two");+ expect(Buffer.from(callInit(1).body).toString()).toBe('{"a":1}');+ });++ it("forwards the refusal untouched when the re-mint gives nothing", async () => {+ goFetch.mockResolvedValue(+ new Response('{"error":{"code":"token_cap_exceeded"}}', {+ status: 402,+ headers: { "X-PostHog-Denial": "token_cap_exceeded" },+ }),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(402);+ expect(res.headers.get("x-posthog-denial")).toBe("token_cap_exceeded");+ expect(await res.text()).toBe('{"error":{"code":"token_cap_exceeded"}}');+ expect(goFetch).toHaveBeenCalledTimes(1);+ });++ it("does not re-mint for an org spend refusal", async () => {+ goFetch.mockResolvedValue(+ new Response(+ '{"error":{"code":"credit_bucket_exhausted","message":"limit"}}',+ {+ status: 402,+ headers: {+ "X-PostHog-Denial": "credit_bucket_exhausted:posthog_code_credits",+ },+ },+ ),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(402);+ expect(await res.text()).toContain("credit_bucket_exhausted");+ expect(source.remint).not.toHaveBeenCalled();+ });++ it("never retries once response headers are on the wire", async () => {+ goFetch.mockResolvedValue(+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode("data: one\n\n"));+ controller.error(new Error("upstream reset"));+ },+ }),+ { status: 200, headers: { "content-type": "text/event-stream" } },+ ),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });+ await res.text().catch(() => "");++ expect(res.status).toBe(200);+ expect(goFetch).toHaveBeenCalledTimes(1);+ expect(source.remint).not.toHaveBeenCalled();+ });++ it("filters /v1/models to the product list and marks the pin", async () => {+ goFetch.mockResolvedValue(+ new Response(+ JSON.stringify({+ object: "list",+ data: [+ { id: "claude-opus-5" },+ { id: "gpt-6-sol" },+ { id: "internal-model" },+ ],+ }),+ { status: 200, headers: { "content-type": "application/json" } },+ ),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/models`);+ const body = (await res.json()) as { data: unknown[] };++ expect(body.data).toEqual([+ { id: "claude-opus-5", allowed: true, restriction_reason: null },+ {+ id: "gpt-6-sol",+ allowed: false,+ restriction_reason: "paid_plan_required",+ },+ ]);+ });++ it("strips cookies and auth challenges from the response", async () => {+ goFetch.mockResolvedValue(+ new Response("ok", {+ headers: {+ "set-cookie": "a=b",+ "www-authenticate": "Bearer",+ "x-posthog-trace-id": "trace",+ },+ }),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.headers.get("set-cookie")).toBeNull();+ expect(res.headers.get("www-authenticate")).toBeNull();+ expect(res.headers.get("x-posthog-trace-id")).toBe("trace");+ });++ it("strips cookies and auth challenges from a rewritten model list", async () => {+ goFetch.mockResolvedValue(+ new Response('{"data":[]}', {+ headers: { "set-cookie": "a=b", "www-authenticate": "Bearer" },+ }),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/models`);++ expect(res.status).toBe(200);+ expect(res.headers.get("set-cookie")).toBeNull();+ expect(res.headers.get("www-authenticate")).toBeNull();+ });++ it("turns an upstream redirect into a 502", async () => {+ goFetch.mockResolvedValue(+ new Response(null, {+ status: 302,+ headers: { location: "https://evil.example" },+ }),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ redirect: "manual",+ });++ expect(res.status).toBe(502);+ expect(res.headers.get("location")).toBeNull();+ });++ it("refuses a body over the cap with a size error the classifier knows", async () => {+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: Buffer.alloc(MAX_BODY_BYTES + 1, 97),+ });++ expect(res.status).toBe(413);+ expect(await res.text()).toContain("request body too large");+ expect(goFetch).not.toHaveBeenCalled();+ });++ it("pins the session timeouts", () => {+ expect(PROXY_TIMEOUTS).toEqual({+ bodyMs: 60_000,+ headersMs: 600_000,+ bufferedBodyMs: 30_000,+ });+ });++ describe("with short timeouts", () => {+ const saved = { ...PROXY_TIMEOUTS };+ afterEach(() => {+ Object.assign(PROXY_TIMEOUTS, saved);+ });++ it("answers 502 and logs an error when Go sends no headers in time", async () => {+ PROXY_TIMEOUTS.headersMs = 100;+ goFetch.mockImplementation(+ (_url, init) =>+ new Promise<Response>((_resolve, reject) => {+ init.signal?.addEventListener("abort", () =>+ reject(new Error("aborted")),+ );+ }),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(502);+ const errors = logs.filter(([level]) => level === "error");+ expect(errors).toEqual([+ [+ "error",+ "Gateway session forward error",+ expect.objectContaining({ timedOut: true }),+ ],+ ]);+ expect(logs.some(([level]) => level === "debug")).toBe(false);+ });++ it.each([+ ["a 401 refusal", "/v1/messages", 401],+ ["the model list", "/v1/models", 200],+ ])(+ "answers 502 when %s body stalls after headers",+ async (_label, path, status) => {+ PROXY_TIMEOUTS.bufferedBodyMs = 100;+ goFetch.mockImplementation(+ async (_url, init) =>+ new Response(+ new ReadableStream<Uint8Array>({+ start(controller) {+ init.signal?.addEventListener("abort", () =>+ controller.error(new Error("aborted")),+ );+ controller.enqueue(new TextEncoder().encode("{"));+ },+ }),+ { status, headers: { "content-type": "application/json" } },+ ),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}${path}`, {+ method: path === "/v1/models" ? "GET" : "POST",+ body: path === "/v1/models" ? undefined : "{}",+ });++ expect(res.status).toBe(502);+ expect(source.remint).not.toHaveBeenCalled();+ expect(logs).toContainEqual([+ "error",+ "Gateway session forward error",+ expect.objectContaining({ timedOut: true }),+ ]);+ },+ );++ it("keeps streaming past the headers timeout once headers arrive", async () => {+ PROXY_TIMEOUTS.headersMs = 50;+ // Like real fetch, the body errors once the request signal aborts.+ goFetch.mockImplementation(+ async (_url, init) =>+ new Response(+ new ReadableStream<Uint8Array>({+ async start(controller) {+ init.signal?.addEventListener("abort", () =>+ controller.error(new Error("aborted")),+ );+ controller.enqueue(new TextEncoder().encode("data: one\n\n"));+ await new Promise((resolve) => setTimeout(resolve, 150));+ controller.enqueue(new TextEncoder().encode("data: two\n\n"));+ controller.close();+ },+ }),+ { status: 200, headers: { "content-type": "text/event-stream" } },+ ),+ );+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(await res.text()).toBe("data: one\n\ndata: two\n\n");+ });++ it("answers 408 when the request body stalls", async () => {+ PROXY_TIMEOUTS.bodyMs = 100;+ const proxyUrl = new URL(await session());+ const status = await new Promise<number>((resolve, reject) => {+ const req = http.request(+ {+ host: proxyUrl.hostname,+ port: proxyUrl.port,+ path: `${proxyUrl.pathname}/v1/messages`,+ method: "POST",+ headers: { "content-length": "100" },+ },+ (res) => {+ resolve(res.statusCode ?? 0);+ res.resume();+ req.destroy();+ },+ );+ req.on("error", reject);+ req.write("{");+ });++ expect(status).toBe(408);+ expect(goFetch).not.toHaveBeenCalled();+ });+ });++ it.each([+ [401, true],+ [402, false],+ ])(+ "forwards a 401 on the token re-minted after a %s, falling back only for a 401 pair",+ async (firstStatus, fallsBack) => {+ goFetch+ .mockResolvedValueOnce(+ new Response("first", {+ status: firstStatus,+ headers:+ firstStatus === 402+ ? { "X-PostHog-Denial": "token_cap_exceeded" }+ : {},+ }),+ )+ .mockResolvedValueOnce(new Response("second", { status: 401 }));+ source.remint.mockResolvedValue(goCredential({ token: "phe_two" }));+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(401);+ expect(await res.text()).toBe("second");+ expect(goFetch).toHaveBeenCalledTimes(2);+ expect(source.remint).toHaveBeenCalledTimes(1);+ expect(authFetch).not.toHaveBeenCalled();+ if (fallsBack) {+ expect(source.fallBack).toHaveBeenCalledWith("phe_two", 42);+ } else {+ expect(source.fallBack).not.toHaveBeenCalled();+ }+ },+ );++ it("does not fall back when the re-minted token hits its cap", async () => {+ goFetch+ .mockResolvedValueOnce(new Response("first", { status: 401 }))+ .mockResolvedValueOnce(+ new Response("second", {+ status: 402,+ headers: { "X-PostHog-Denial": "token_cap_exceeded" },+ }),+ );+ source.remint.mockResolvedValue(goCredential({ token: "phe_two" }));+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(402);+ expect(source.fallBack).not.toHaveBeenCalled();+ });++ it("does not fall back when the re-minted token succeeds", async () => {+ goFetch+ .mockResolvedValueOnce(new Response("first", { status: 401 }))+ .mockResolvedValueOnce(new Response("second", { status: 200 }));+ source.remint.mockResolvedValue(goCredential({ token: "phe_two" }));+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(await res.text()).toBe("second");+ expect(source.fallBack).not.toHaveBeenCalled();+ });++ it("binds each project to its own URL and team", async () => {+ goFetch.mockImplementation(async () => new Response("ok"));+ source.getRoute.mockImplementation(async (projectId: number) =>+ goCredential({ teamId: projectId + 1000, projectId }),+ );+ const first = await session(1);+ const second = await session(2);++ expect(first).not.toBe(second);+ await fetch(`${second}/v1/messages`, {+ method: "POST",+ headers: { "X-PostHog-Project-Id": "1" },+ body: "{}",+ });++ expect(source.getRoute).toHaveBeenCalledWith(2);+ const headers = callInit(0).headers;+ expect(JSON.parse(headers["X-PostHog-Properties"]).team_id).toBe(1002);+ });++ it("stays on the legacy gateway when the source falls back mid-session", async () => {+ authFetch.mockResolvedValue(new Response("legacy"));+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();+ await fetch(`${proxyUrl}/v1/messages`, { method: "POST", body: "{}" });+ goFetch.mockClear();+ source.getRoute.mockResolvedValue({+ mode: "legacy",+ reason: "not_rolled_out",+ });++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ headers: {+ authorization: "Bearer posthog-code-auth-proxy",+ "x-api-key": "posthog-code-auth-proxy",+ },+ body: "{}",+ });++ expect(await res.text()).toBe("legacy");+ await fetch(`${proxyUrl}/v1/messages`, { method: "POST", body: "{}" });+ expect(goFetch).not.toHaveBeenCalled();+ const [url, init] = authFetch.mock.calls[0];+ expect(url).toBe("https://gateway.us.posthog.com/posthog_code/v1/messages");+ expect(init.headers["x-posthog-project-id"]).toBe("42");+ expect(init.headers.authorization).toBeUndefined();+ expect(init.headers["x-api-key"]).toBeUndefined();+ const switched = logs.filter(+ ([, message]) => message === "Gateway session switched gateway",+ );+ expect(switched).toEqual([+ [+ "info",+ "Gateway session switched gateway",+ { projectId: 42, from: "go", to: "legacy", reason: "not_rolled_out" },+ ],+ ]);+ });++ it("sends nothing upstream when the client hangs up while a token is minted", async () => {+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();+ let resolveRoute: (credential: GoCredential) => void = () => undefined;+ source.getRoute.mockImplementation(+ () =>+ new Promise<GoCredential>((resolve) => {+ resolveRoute = resolve;+ }),+ );+ const clientAbort = new AbortController();++ const request = fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ signal: clientAbort.signal,+ }).catch(() => undefined);+ await vi.waitFor(() => expect(source.getRoute).toHaveBeenCalled());+ clientAbort.abort();+ await request;+ await new Promise((resolve) => setTimeout(resolve, 50));+ resolveRoute(goCredential());+ await new Promise((resolve) => setTimeout(resolve, 50));++ expect(goFetch).not.toHaveBeenCalled();+ });++ it("replays the mint's usage-limit sentence when the bucket is empty", async () => {+ const proxyUrl = await session();+ source.getRoute.mockResolvedValue({+ mode: "blocked",+ reason: "credit_bucket_exhausted",+ detail: "Your organization has reached its PostHog Desktop usage limit",+ });++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(res.status).toBe(402);+ const body = (await res.json()) as {+ error: { code: string; message: string };+ };+ expect(body.error.code).toBe("credit_bucket_exhausted");+ expect(body.error.message).toBe(+ "Your organization has reached its PostHog Desktop usage limit",+ );+ });++ it("still lists models on the legacy gateway while blocked", async () => {+ authFetch.mockResolvedValue(new Response('{"data":[]}'));+ const proxyUrl = await session();+ source.getRoute.mockResolvedValue({+ mode: "blocked",+ reason: "credit_bucket_exhausted",+ detail: "limit",+ });++ const res = await fetch(`${proxyUrl}/v1/models`);++ expect(res.status).toBe(200);+ expect(authFetch.mock.calls[0][0]).toBe(+ "https://gateway.us.posthog.com/posthog_code/v1/models",+ );+ });++ it("falls back to the legacy gateway when the source fails", async () => {+ authFetch.mockResolvedValue(new Response("legacy"));+ source.getRoute.mockRejectedValue(new Error("boom"));+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(await res.text()).toBe("legacy");+ expect(goFetch).not.toHaveBeenCalled();+ });++ it("keeps serving a session target after sign-out, on the legacy route", async () => {+ authFetch.mockResolvedValue(new Response("legacy"));+ const proxyUrl = await session();+ source.getRoute.mockResolvedValue({ mode: "legacy", reason: "signed_out" });++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ });++ expect(await res.text()).toBe("legacy");+ expect(goFetch).not.toHaveBeenCalled();+ });++ it("never logs the path token or the query string of a Go request", async () => {+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();++ await fetch(`${proxyUrl}/v1/messages?beta=true&secret=q`, {+ method: "POST",+ body: "{}",+ });+ await fetch(`${proxyUrl}/v1/not-allowed`);+ goFetch.mockRejectedValueOnce(new Error("boom"));+ await fetch(`${proxyUrl}/v1/messages?secret=q`, {+ method: "POST",+ body: "{}",+ });++ const text = JSON.stringify(logs);+ expect(logs.length).toBeGreaterThan(0);+ expect(text).not.toContain(new URL(proxyUrl).pathname.slice(1));+ expect(text).not.toContain("secret=q");+ });++ function rawPost(+ url: string,+ headers: http.OutgoingHttpHeaders,+ ): Promise<http.IncomingMessage> {+ return new Promise((resolve, reject) => {+ const req = http.request(+ url,+ { method: "POST", headers, agent: false },+ (res) => {+ res.resume();+ res.on("end", () => resolve(res));+ },+ );+ req.on("error", reject);+ req.end("{}");+ });+ }++ it("drops request headers the Connection value names, even allowlisted ones", async () => {+ goFetch.mockResolvedValue(new Response("ok"));+ const proxyUrl = await session();++ await rawPost(`${proxyUrl}/v1/messages`, {+ connection: "close, x-stainless-os",+ "x-stainless-os": "MacOS",+ "x-stainless-arch": "arm64",+ });++ const headers = callInit(0).headers;+ expect(headers).not.toHaveProperty("x-stainless-os");+ expect(headers["x-stainless-arch"]).toBe("arm64");+ });++ it("strips response headers the Connection value names", async () => {+ goFetch.mockResolvedValue(+ new Response("ok", {+ headers: { connection: "x-hop", "x-hop": "1", "x-kept": "1" },+ }),+ );+ const proxyUrl = await session();++ const res = await rawPost(`${proxyUrl}/v1/messages`, {});++ expect(res.headers["x-hop"]).toBeUndefined();+ expect(res.headers["x-kept"]).toBe("1");+ });++ it("strips Connection-named headers on the legacy fallback", async () => {+ authFetch.mockResolvedValue(new Response("legacy"));+ source.getRoute.mockResolvedValue({+ mode: "legacy",+ reason: "not_rolled_out",+ });+ const proxyUrl = await session();++ await rawPost(`${proxyUrl}/v1/messages`, {+ connection: "close, x-hop",+ "x-hop": "1",+ "x-kept": "1",+ });++ const [, init] = authFetch.mock.calls[0];+ expect(init.headers).not.toHaveProperty("x-hop");+ expect(init.headers["x-kept"]).toBe("1");+ });++ it("refuses an upstream redirect on the legacy fallback", async () => {+ authFetch.mockResolvedValue(+ new Response(null, {+ status: 302,+ headers: { location: "https://evil.example" },+ }),+ );+ source.getRoute.mockResolvedValue({+ mode: "legacy",+ reason: "not_rolled_out",+ });+ const proxyUrl = await session();++ const res = await fetch(`${proxyUrl}/v1/messages`, {+ method: "POST",+ body: "{}",+ redirect: "manual",+ });++ expect(res.status).toBe(502);+ expect(res.headers.get("location")).toBeNull();+ });+});diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.tsindex c42260fd314c..a07a13efbef1 100644--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/auth-proxy.ts@@ -6,85 +6,99 @@ import {type ScopedLogger,} from "@posthog/di/logger";import { serializeError } from "@posthog/shared";-import { inject, injectable } from "inversify";-import { hopByHop } from "../proxy-stream/hop-by-hop";+import { inject, injectable, optional } from "inversify";import {type StreamProgress,streamBodyToResponse,} from "../proxy-stream/proxy-stream";-import { AUTH_PROXY_AUTH } from "./identifiers";-import type { AuthProxyAuth } from "./ports";--type Body = Buffer<ArrayBuffer>;--const STRIPPED_REQUEST_HEADERS = new Set([- "authorization",- "x-api-key",- "api-key",- "anthropic-auth-token",- "proxy-authorization",- "content-length",- "transfer-encoding",- "cookie",-]);--const STRIPPED_RESPONSE_HEADERS = new Set([- "transfer-encoding",- "content-encoding",- "content-length",- "set-cookie",- "www-authenticate",-]);--export const MAX_BODY_BYTES = 16 * 1024 * 1024;-export const PROXY_TIMEOUTS = {- bodyMs: 60_000,- // Non-streaming calls can run for minutes before the first byte, so this- // only catches a wedged connection.- headersMs: 10 * 60_000,-};+import {+ type FetchLike,+ GatewaySessionHandler,+ type SessionTarget,+} from "./gateway-session";+import {+ AUTH_PROXY_AUTH,+ AUTH_PROXY_FETCH,+ GATEWAY_CREDENTIAL_SOURCE,+} from "./identifiers";+import type { AuthProxyAuth, GatewayCredentialSource } from "./ports";+import {+ jsonError,+ PROXY_TIMEOUTS,+ readBody,+ responseHeaders,+ strippedRequestHeaders,+} from "./proxy-http";++export { MAX_BODY_BYTES, PROXY_TIMEOUTS } from "./proxy-http";++interface LegacyTarget {+ kind: "legacy";+ gatewayUrl: string;+ headers: Record<string, string>;+}++type ProxyTarget = LegacyTarget | SessionTarget;@injectable()export class AuthProxyService {private server: http.Server | null = null;private port: number | null = null;private listenPromise: Promise<void> | null = null;- private readonly targetByToken = new Map<- string,- { gatewayUrl: string; headers: Record<string, string> }- >();+ private readonly targetByToken = new Map<string, ProxyTarget>();private readonly tokenByTarget = new Map<string, string>();private readonly log: ScopedLogger;+ private readonly sessions: GatewaySessionHandler;constructor(@inject(AUTH_PROXY_AUTH)private readonly auth: AuthProxyAuth,@inject(ROOT_LOGGER)rootLogger: RootLogger,+ @inject(GATEWAY_CREDENTIAL_SOURCE)+ @optional()+ private readonly source?: GatewayCredentialSource,+ @inject(AUTH_PROXY_FETCH)+ @optional()+ fetchImpl?: FetchLike,) {this.log = rootLogger.scope("auth-proxy");+ this.sessions = new GatewaySessionHandler({+ log: this.log,+ fetchImpl: fetchImpl ?? ((url, init) => fetch(url, init)),+ source: () => this.requireSource(),+ forwardLegacy: (url, options, res, abort) =>+ this.forwardRequest(url, options, res, abort),+ });}async start(gatewayUrl: string,headers: Record<string, string> = {},): Promise<string> {- const targetKey = JSON.stringify([+ return this.register(["legacy", gatewayUrl], {+ kind: "legacy",gatewayUrl,- Object.entries(headers).sort(([left], [right]) =>- left.localeCompare(right),- ),- ]);- let token = this.tokenByTarget.get(targetKey);- if (!token) {- token = randomBytes(32).toString("base64url");- this.tokenByTarget.set(targetKey, token);- this.targetByToken.set(token, { gatewayUrl, headers: { ...headers } });- }-- await this.ensureListening();+ headers: { ...headers },+ });+ }- return this.getProxyUrl(token);+ /**+ * The bearer and gateway URL resolve per request, so a refreshed token never+ * changes the loopback URL the CLI holds.+ */+ async startGatewaySession(input: {+ projectId: number;+ legacyGatewayUrl: string;+ headers?: Record<string, string>;+ }): Promise<string> {+ this.requireSource();+ return this.register(["session", input.projectId, input.legacyGatewayUrl], {+ kind: "session",+ projectId: input.projectId,+ legacyGatewayUrl: input.legacyGatewayUrl,+ headers: { ...(input.headers ?? {}) },+ });}getProxyUrl(token: string): string {@@ -98,6 +112,28 @@ export class AuthProxyService {return this.server !== null && this.port !== null;}+ private async register(+ identity: unknown[],+ target: ProxyTarget,+ ): Promise<string> {+ const targetKey = JSON.stringify([+ ...identity,+ Object.entries(target.headers).sort(([left], [right]) =>+ left.localeCompare(right),+ ),+ ]);+ let token = this.tokenByTarget.get(targetKey);+ if (!token) {+ token = randomBytes(32).toString("base64url");+ this.tokenByTarget.set(targetKey, token);+ this.targetByToken.set(token, target);+ }++ await this.ensureListening();++ return this.getProxyUrl(token);+ }+private ensureListening(): Promise<void> {if (this.port) {return Promise.resolve();@@ -158,6 +194,17 @@ export class AuthProxyService {return;}+ if (target.kind === "session") {+ void this.sessions.handle(+ target,+ match?.[2] ?? "/",+ incomingUrl.search,+ req,+ res,+ );+ return;+ }+const base = target.gatewayUrl.endsWith("/")? target.gatewayUrl: `${target.gatewayUrl}/`;@@ -193,14 +240,9 @@ export class AuthProxyService {}const headers: Record<string, string> = {};- const requestHopByHop = hopByHop(req.headers.connection);+ const stripped = strippedRequestHeaders(req.headers.connection);for (const [key, value] of Object.entries(req.headers)) {- const name = key.toLowerCase();- if (- name === "host" ||- requestHopByHop.has(name) ||- STRIPPED_REQUEST_HEADERS.has(name)- ) {+ if (stripped.has(key.toLowerCase())) {continue;}if (typeof value === "string") {@@ -309,16 +351,7 @@ export class AuthProxyService {return;}- const responseHeaders: Record<string, string> = {};- const responseHopByHop = hopByHop(response.headers.get("connection"));- response.headers.forEach((value: string, key: string) => {- const name = key.toLowerCase();- if (STRIPPED_RESPONSE_HEADERS.has(name) || responseHopByHop.has(name))- return;- responseHeaders[key] = value;- });-- res.writeHead(response.status, responseHeaders);+ res.writeHead(response.status, responseHeaders(response));await streamBodyToResponse(response.body, res, progress);@@ -366,53 +399,11 @@ export class AuthProxyService {res.end("Proxy error");}}-}-function jsonError(- res: http.ServerResponse,- status: number,- error: Record<string, string>,- extraHeaders: Record<string, string> = {},-): void {- if (res.headersSent) {- res.end();- return;+ private requireSource(): GatewayCredentialSource {+ if (!this.source) {+ throw new Error("Gateway sessions need a credential source");+ }+ return this.source;}- res.writeHead(status, {- "content-type": "application/json",- ...extraHeaders,- });- res.end(JSON.stringify({ error }));-}--function readBody(- req: http.IncomingMessage,-): Promise<Body | "too_large" | "timeout" | "aborted"> {- return new Promise((resolve) => {- const chunks: Buffer[] = [];- let size = 0;- let settled = false;- const finish = (result: Body | "too_large" | "timeout" | "aborted") => {- if (settled) return;- settled = true;- clearTimeout(timer);- req.off("data", onData);- // Drain the rest so the socket can carry the error response.- if (typeof result === "string") req.resume();- resolve(result);- };- const timer = setTimeout(() => finish("timeout"), PROXY_TIMEOUTS.bodyMs);- const onData = (chunk: Buffer) => {- size += chunk.byteLength;- if (size > MAX_BODY_BYTES) {- finish("too_large");- return;- }- chunks.push(chunk);- };- req.on("data", onData);- req.on("end", () => finish(Buffer.concat(chunks)));- req.on("error", () => finish("aborted"));- req.on("aborted", () => finish("aborted"));- });}diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-proxy.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-proxy.tsnew file mode 100644index 000000000000..e65cc44cbfbe--- /dev/null+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-proxy.ts@@ -0,0 +1,43 @@+import type { AuthProxyService } from "./auth-proxy";+import type { GatewayCredentialSource } from "./ports";++export interface ResolvedGatewayProxy {+ proxyUrl: string;+ mode: "legacy" | "go";+}++export async function resolveGatewayProxy(input: {+ authProxy: AuthProxyService;+ source: GatewayCredentialSource | undefined;+ legacyGatewayUrl: string;+ projectId: number | null;+ headers?: Record<string, string>;+ awaitRecheck?: boolean;+}): Promise<ResolvedGatewayProxy> {+ const { authProxy, source, legacyGatewayUrl, projectId, headers } = input;+ const route =+ source && projectId !== null+ ? await source+ .getRoute(projectId, { awaitRecheck: input.awaitRecheck ?? true })+ .catch(() => null)+ : null;+ // A blocked org still gets a session target, which answers with the+ // usage-limit refusal until the bucket refills.+ if (+ (route?.mode === "go" || route?.mode === "blocked") &&+ projectId !== null+ ) {+ return {+ proxyUrl: await authProxy.startGatewaySession({+ projectId,+ legacyGatewayUrl,+ headers,+ }),+ mode: "go",+ };+ }+ return {+ proxyUrl: await authProxy.start(legacyGatewayUrl, headers),+ mode: "legacy",+ };+}diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-session.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-session.tsnew file mode 100644index 000000000000..55541ac17276--- /dev/null+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-session.ts@@ -0,0 +1,420 @@+import type http from "node:http";+import type { ScopedLogger } from "@posthog/di/logger";+import {+ aiGatewayDenialCode,+ aiGatewayRemintReason,+ applyAllowedModels,+ serializeError,+} from "@posthog/shared";+import { collapsePropertyHeadersForAiGateway } from "@posthog/shared/posthog-property-headers";+import {+ type StreamProgress,+ streamBodyToResponse,+} from "../proxy-stream/proxy-stream";+import type {+ GatewayCredential,+ GatewayCredentialSource,+ GatewayRemintReason,+} from "./ports";+import {+ type Body,+ jsonError,+ PROXY_TIMEOUTS,+ readBody,+ responseHeaders,+ strippedRequestHeaders,+} from "./proxy-http";++type GoCredential = Extract<GatewayCredential, { mode: "go" }>;++export type FetchLike = (url: string, init: RequestInit) => Promise<Response>;++export interface SessionTarget {+ kind: "session";+ projectId: number;+ legacyGatewayUrl: string;+ headers: Record<string, string>;+}++const SESSION_PATHS = new Set([+ "/v1/messages",+ "/v1/messages/count_tokens",+ "/v1/chat/completions",+ "/v1/responses",+ "/v1/models",+]);++const SESSION_HEADERS = new Set([+ "accept",+ "content-type",+ "user-agent",+ "traceparent",+ "tracestate",+ "x-posthog-user",+ "x-posthog-provider",+ "x-posthog-service-tier",+ "x-posthog-trace-id",+ "x-posthog-properties",+ "x-posthog-session-id",+]);+const SESSION_HEADER_PREFIXES = [+ "anthropic-",+ "openai-",+ "x-stainless-",+ "x-posthog-property-",+];+const SESSION_DROPPED_HEADERS = new Set(["anthropic-auth-token"]);++function isSessionHeader(lower: string): boolean {+ return (+ !SESSION_DROPPED_HEADERS.has(lower) &&+ (SESSION_HEADERS.has(lower) ||+ SESSION_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix)))+ );+}++/** Serves session targets: Go under a per-request credential, else legacy. */+export class GatewaySessionHandler {+ private readonly modes = new WeakMap<SessionTarget, "go" | "legacy">();++ constructor(+ private readonly deps: {+ log: ScopedLogger;+ fetchImpl: FetchLike;+ source: () => GatewayCredentialSource;+ forwardLegacy: (+ url: URL,+ options: RequestInit,+ res: http.ServerResponse,+ abort: AbortController,+ ) => Promise<void>;+ },+ ) {}++ async handle(+ target: SessionTarget,+ subPath: string,+ search: string,+ req: http.IncomingMessage,+ res: http.ServerResponse,+ ): Promise<void> {+ // Attached before any await so a hang-up while the body is read or a+ // token is minted still cancels the upstream call.+ const abort = new AbortController();+ res.on("close", () => {+ if (!res.writableEnded) abort.abort();+ });+ const path = subPath.replace(/^\/posthog_code(?=\/|$)/, "") || "/";+ if (!SESSION_PATHS.has(path)) {+ this.deps.log.warn(+ "Rejected gateway session request outside the allowlist",+ {+ method: req.method,+ },+ );+ req.resume();+ jsonError(res, 404, { type: "not_found_error", message: "Not found" });+ return;+ }++ const method = req.method ?? "GET";+ let body: Body | undefined;+ if (method !== "GET" && method !== "HEAD") {+ const read = await readBody(req);+ if (read === "too_large") {+ // Worded to match the "request body too large" size-error pattern.+ jsonError(+ res,+ 413,+ { type: "request_too_large", message: "request body too large" },+ { connection: "close" },+ );+ return;+ }+ if (read === "timeout" || read === "aborted") {+ jsonError(res, 408, {+ type: "timeout_error",+ message: "request body not received",+ });+ return;+ }+ body = read;+ }++ const credential: GatewayCredential = await this.deps+ .source()+ .getRoute(target.projectId)+ .catch(() => ({ mode: "legacy", reason: "route_failed" }));+ if (abort.signal.aborted) return;+ this.noteMode(+ target,+ credential.mode === "legacy" ? "legacy" : "go",+ credential.mode === "legacy" ? credential.reason : undefined,+ );+ // Listing models is read-only, so a blocked org still sees the picker.+ if (+ credential.mode === "legacy" ||+ (credential.mode === "blocked" && path === "/v1/models")+ ) {+ this.forwardOnLegacy(+ target,+ { path, search, method, body },+ req,+ res,+ abort,+ );+ return;+ }+ if (credential.mode === "blocked") {+ jsonError(res, 402, {+ type: "billing_error",+ code: credential.reason,+ message: credential.detail,+ });+ return;+ }++ await this.forward(+ target,+ credential,+ {+ path,+ search,+ method,+ headers: this.headers(req, target, credential),+ body,+ },+ res,+ abort,+ );+ }++ private noteMode(+ target: SessionTarget,+ mode: "go" | "legacy",+ reason: string | undefined,+ ): void {+ const previous = this.modes.get(target);+ this.modes.set(target, mode);+ if (previous === undefined || previous === mode) return;+ this.deps.log.info("Gateway session switched gateway", {+ projectId: target.projectId,+ from: previous,+ to: mode,+ reason,+ });+ }++ private headers(+ req: http.IncomingMessage,+ target: SessionTarget,+ credential: GoCredential,+ ): Record<string, string> {+ const forwarded: Record<string, string> = {};+ const stripped = strippedRequestHeaders(req.headers.connection);+ for (const [key, value] of Object.entries(req.headers)) {+ const lower = key.toLowerCase();+ if (+ typeof value === "string" &&+ !stripped.has(lower) &&+ isSessionHeader(lower)+ ) {+ forwarded[lower] = value;+ }+ }+ for (const [key, value] of Object.entries(target.headers)) {+ const lower = key.toLowerCase();+ if (isSessionHeader(lower)) forwarded[lower] = value;+ }+ return collapsePropertyHeadersForAiGateway(forwarded, {+ ai_product: "posthog_code",+ team_id: credential.teamId,+ });+ }++ private async forward(+ target: SessionTarget,+ initial: GoCredential,+ request: {+ path: string;+ search: string;+ method: string;+ headers: Record<string, string>;+ body: Body | undefined;+ },+ res: http.ServerResponse,+ abort: AbortController,+ ): Promise<void> {+ const startedAt = Date.now();+ const progress: StreamProgress = { bytesWritten: 0 };+ let status = 0;+ let timedOut = false;+ const withDeadline = async <T>(+ ms: number,+ run: () => Promise<T>,+ ): Promise<T> => {+ const timer = setTimeout(() => {+ timedOut = true;+ abort.abort();+ }, ms);+ try {+ return await run();+ } finally {+ clearTimeout(timer);+ }+ };+ const send = (credential: GoCredential): Promise<Response> =>+ withDeadline(PROXY_TIMEOUTS.headersMs, () =>+ this.deps.fetchImpl(+ `${credential.gatewayUrl}${request.path}${request.search}`,+ {+ method: request.method,+ headers: {+ ...request.headers,+ authorization: `Bearer ${credential.token}`,+ },+ body: request.body,+ redirect: "manual",+ signal: abort.signal,+ },+ ),+ );+ const buffered = <T>(read: () => Promise<T>): Promise<T> =>+ withDeadline(PROXY_TIMEOUTS.bufferedBodyMs, read);++ try {+ let credential = initial;+ let response = await send(credential);+ // Retried only here, before any byte reaches the client.+ const refusal = await remintReason(response, buffered);+ let bufferedBody = refusal.body;+ if (refusal.reason) {+ const source = this.deps.source();+ const fresh = await source+ .remint(refusal.reason, credential.token, target.projectId)+ .catch(() => null);+ if (fresh?.mode === "go") {+ credential = fresh;+ response = await send(credential);+ bufferedBody = null;+ if (response.status === 401 && refusal.reason === "unauthorized") {+ source.fallBack(credential.token, target.projectId);+ }+ }+ }+ status = response.status;++ if (status >= 300 && status < 400) {+ void response.body?.cancel().catch(() => {});+ jsonError(res, 502, {+ type: "api_error",+ message: "Unexpected redirect from the PostHog gateway",+ });+ return;+ }++ if (request.path === "/v1/models" && response.ok) {+ const body = await buffered(() => response.json());+ const models = applyAllowedModels(body, credential);+ res.writeHead(status, {+ ...responseHeaders(response),+ "content-type": "application/json",+ });+ res.end(JSON.stringify(models));+ return;+ }++ res.writeHead(status, responseHeaders(response));+ if (bufferedBody !== null) {+ res.end(bufferedBody);+ } else {+ await streamBodyToResponse(response.body, res, progress);+ }++ this.deps.log.info("Gateway session forward completed", {+ path: request.path,+ method: request.method,+ status,+ durationMs: Date.now() - startedAt,+ bytesStreamed: progress.bytesWritten,+ });+ } catch (err) {+ const context = {+ path: request.path,+ durationMs: Date.now() - startedAt,+ bytesStreamed: progress.bytesWritten,+ };+ if (abort.signal.aborted && !timedOut) {+ this.deps.log.debug(+ "Upstream fetch aborted after client disconnect",+ context,+ );+ } else {+ this.deps.log.error("Gateway session forward error", {+ ...context,+ method: request.method,+ status,+ headersSent: res.headersSent,+ timedOut,+ errorDetail: serializeError(err),+ });+ }+ if (!res.headersSent) {+ jsonError(res, 502, { type: "api_error", message: "Proxy error" });+ return;+ }+ res.end();+ }+ }++ private forwardOnLegacy(+ target: SessionTarget,+ request: {+ path: string;+ search: string;+ method: string;+ body: Body | undefined;+ },+ req: http.IncomingMessage,+ res: http.ServerResponse,+ abort: AbortController,+ ): void {+ const { path, search, method, body } = request;+ const base = target.legacyGatewayUrl.replace(/\/+$/, "");+ const url = new URL(`${base}${path}${search}`);+ const headers: Record<string, string> = {};+ const stripped = strippedRequestHeaders(req.headers.connection);+ for (const [key, value] of Object.entries(req.headers)) {+ const lower = key.toLowerCase();+ if (stripped.has(lower) || typeof value !== "string") {+ continue;+ }+ headers[lower] = value;+ }+ for (const [key, value] of Object.entries(target.headers)) {+ headers[key.toLowerCase()] = value;+ }+ headers["x-posthog-project-id"] = String(target.projectId);+ void this.deps.forwardLegacy(+ url,+ { method, headers, body, signal: abort.signal },+ res,+ abort,+ );+ }+}++async function remintReason(+ response: Response,+ buffered: (read: () => Promise<string>) => Promise<string>,+): Promise<{ reason: GatewayRemintReason | null; body: string | null }> {+ if (response.status !== 401 && response.status !== 402) {+ return { reason: null, body: null };+ }+ const body = await buffered(() => response.text());+ const code = aiGatewayDenialCode(+ response.headers.get("x-posthog-denial"),+ body,+ );+ return { reason: aiGatewayRemintReason(response.status, code), body };+}diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/identifiers.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/identifiers.tsindex 389054c9d9a2..361a71f809cc 100644--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/identifiers.ts+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/identifiers.ts@@ -2,3 +2,7 @@ export const AUTH_PROXY_SERVICE = Symbol.for("posthog.workspace.authProxyService",);export const AUTH_PROXY_AUTH = Symbol.for("posthog.workspace.authProxyAuth");+export const GATEWAY_CREDENTIAL_SOURCE = Symbol.for(+ "posthog.workspace.gatewayCredentialSource",+);+export const AUTH_PROXY_FETCH = Symbol.for("posthog.workspace.authProxyFetch");diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.tsindex 6c60c084bcd6..96253078a63d 100644--- a/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/ports.ts@@ -3,3 +3,31 @@ export interface AuthProxyAuth {}export const AUTH_PROXY_PLACEHOLDER_CREDENTIAL = "posthog-code-auth-proxy";++export type GatewayCredential =+ | { mode: "legacy"; reason: string }+ | { mode: "blocked"; reason: "credit_bucket_exhausted"; detail: string }+ | {+ mode: "go";+ gatewayUrl: string;+ token: string;+ teamId: number;+ projectId: number;+ allowedModels: string[] | null;+ productModels: string[];+ };++export type GatewayRemintReason = "unauthorized" | "token_cap_exceeded";++export interface GatewayCredentialSource {+ getRoute(+ projectId: number,+ options?: { awaitRecheck?: boolean },+ ): Promise<GatewayCredential>;+ remint(+ reason: GatewayRemintReason,+ staleToken: string,+ projectId: number,+ ): Promise<GatewayCredential | null>;+ fallBack(token: string, projectId: number): void;+}diff --git a/products/desktop/packages/workspace-server/src/services/auth-proxy/proxy-http.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/proxy-http.tsnew file mode 100644index 000000000000..9a0d72a5d5d4--- /dev/null+++ b/products/desktop/packages/workspace-server/src/services/auth-proxy/proxy-http.ts@@ -0,0 +1,107 @@+import type http from "node:http";+import { hopByHop } from "../proxy-stream/hop-by-hop";++export type Body = Buffer<ArrayBuffer>;++export const STRIPPED_REQUEST_HEADERS = new Set([+ "authorization",+ "x-api-key",+ "api-key",+ "anthropic-auth-token",+ "proxy-authorization",+ "content-length",+ "transfer-encoding",+ "cookie",+]);++export const STRIPPED_RESPONSE_HEADERS = new Set([+ "transfer-encoding",+ "content-encoding",+ "content-length",+ "set-cookie",+ "www-authenticate",+]);++export const MAX_BODY_BYTES = 16 * 1024 * 1024;+export const PROXY_TIMEOUTS = {+ bodyMs: 60_000,+ // Non-streaming calls can run for minutes before the first byte; the ALB in+ // front of the gateway closes at 300s, so this only catches a wedged connection.+ headersMs: 10 * 60_000,+ // A buffered refusal or model list is small, so a stall here is a fault.+ bufferedBodyMs: 30_000,+};++/** Request header names never forwarded upstream, given the inbound Connection value. */+export function strippedRequestHeaders(+ connection: string | string[] | undefined,+): Set<string> {+ return new Set([+ "host",+ ...STRIPPED_REQUEST_HEADERS,+ ...hopByHop(connection),+ ]);+}++export function jsonError(+ res: http.ServerResponse,+ status: number,+ error: Record<string, string>,+ extraHeaders: Record<string, string> = {},+): void {+ if (res.headersSent) {+ res.end();+ return;+ }+ res.writeHead(status, {+ "content-type": "application/json",+ ...extraHeaders,+ });+ res.end(JSON.stringify({ error }));+}++export function responseHeaders(+ response: Response,+ stripped: ReadonlySet<string> = STRIPPED_RESPONSE_HEADERS,+): Record<string, string> {+ const hop = hopByHop(response.headers.get("connection"));+ const headers: Record<string, string> = {};+ response.headers.forEach((value: string, key: string) => {+ const name = key.toLowerCase();+ if (stripped.has(name) || hop.has(name)) return;+ headers[key] = value;+ });+ return headers;+}++export function readBody(+ req: http.IncomingMessage,+): Promise<Body | "too_large" | "timeout" | "aborted"> {+ return new Promise((resolve) => {+ const chunks: Buffer[] = [];+ let size = 0;+ let settled = false;+ const finish = (result: Body | "too_large" | "timeout" | "aborted") => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ req.off("data", onData);+ // Drain the rest so the socket can carry the error response.+ if (typeof result === "string") req.resume();+ resolve(result);+ };+ const timer = setTimeout(() => finish("timeout"), PROXY_TIMEOUTS.bodyMs);+ const onData = (chunk: Buffer) => {+ size += chunk.byteLength;+ if (size > MAX_BODY_BYTES) {+ finish("too_large");+ return;+ }+ chunks.push(chunk);+ };+ req.on("data", onData);+ req.on("end", () => finish(Buffer.concat(chunks)));+ req.on("error", () => finish("aborted"));+ req.on("aborted", () => finish("aborted"));+ });+}diff --git a/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.test.ts b/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.test.tsindex c2836222dee6..13b5ea56e2b7 100644--- a/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.test.ts+++ b/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.test.ts@@ -1,3 +1,4 @@+import { EventEmitter } from "node:events";import http from "node:http";import { afterEach, describe, expect, it, vi } from "vitest";import { type StreamProgress, streamBodyToResponse } from "./proxy-stream";@@ -126,4 +127,29 @@ describe("streamBodyToResponse", () => {expect(progress.bytesWritten).toBe(0);});+ it("returns and cancels the body when the response was already destroyed", async () => {+ let cancelled = false;+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ controller.enqueue(new TextEncoder().encode("data\n\n"));+ },+ cancel() {+ cancelled = true;+ },+ });+ // A response whose client left before the copy started: "close" is gone.+ const res = Object.assign(new EventEmitter(), {+ destroyed: true,+ write: vi.fn(() => false),+ end: vi.fn(),+ }) as unknown as http.ServerResponse;++ const outcome = await Promise.race([+ streamBodyToResponse(body, res).then(() => "returned"),+ new Promise((resolve) => setTimeout(() => resolve("hung"), 200)),+ ]);++ expect(outcome).toBe("returned");+ await vi.waitFor(() => expect(cancelled).toBe(true));+ });});diff --git a/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.ts b/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.tsindex 38db9cde8dab..11febc4cf8d3 100644--- a/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.ts+++ b/products/desktop/packages/workspace-server/src/services/proxy-stream/proxy-stream.ts@@ -36,6 +36,11 @@ export async function streamBodyToResponse(void reader.cancel().catch(() => {});});while (true) {+ // "close" never fires again on an already-destroyed response.+ if (res.destroyed) {+ void reader.cancel().catch(() => {});+ return;+ }const { done, value } = await reader.read();if (done) {res.end();