Skip to content

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

fix(desktop): stop falling back to the retired llm gateway (#118191)

Brandonbba4f29695c4
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.ts
index 0e2510c929f4..4b51d9b1f061 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
@@ -72,6 +72,7 @@ describe("DesktopPiRpcClientFactory", () => {
? "http://127.0.0.1:5678"
: "http://127.0.0.1:1234",
),
+ startGatewaySession: vi.fn(async () => "http://127.0.0.1:1234"),
} as unknown as AuthProxyService;
const policies = [
{
@@ -115,7 +116,12 @@ describe("DesktopPiRpcClientFactory", () => {
mcpApps as unknown as AgentMcpApps,
rootLogger,
{
- getRoute: vi.fn(async () => ({ mode: "legacy" as const, reason: "x" })),
+ getRoute: vi.fn(async () => ({
+ mode: "blocked" as const,
+ reason: "not_rolled_out",
+ detail: "unavailable",
+ status: 403 as const,
+ })),
remint: vi.fn(),
fallBack: vi.fn(),
},
@@ -132,14 +138,15 @@ describe("DesktopPiRpcClientFactory", () => {
},
}),
).resolves.toBe(client);
- expect(authProxy.start).toHaveBeenCalledWith(
- getLlmGatewayUrl(getCloudUrlFromRegion("dev-cloud")),
- {
+ expect(authProxy.startGatewaySession).toHaveBeenCalledWith({
+ projectId: 1,
+ legacyGatewayUrl: getLlmGatewayUrl(getCloudUrlFromRegion("dev-cloud")),
+ headers: {
"x-posthog-property-task_id": "task-1",
"x-posthog-property-$ai_session_id": "task-1",
"X-PostHog-Project-Id": "1",
},
- );
+ });
expect(authProxy.start).toHaveBeenCalledWith("https://app.dev.posthog.dev");
expect(createLocalRuntimeMcpServers).toHaveBeenCalledWith("/workspace");
expect(mcpApps.addServerConfigs).toHaveBeenCalledWith([
@@ -198,9 +205,9 @@ describe("DesktopPiRpcClientFactory", () => {
it.each([
["go", "http://127.0.0.1:1234/session"],
- ["legacy", "http://127.0.0.1:1234/legacy"],
+ ["blocked", "http://127.0.0.1:1234/session"],
] as const)(
- "routes a Pi session to the %s gateway by the source's route",
+ "routes a Pi session on a %s route through the gateway session",
async (mode, expectedBaseUrl) => {
const auth = {
getOAuthCredentials: vi.fn(async () => ({
@@ -227,7 +234,12 @@ describe("DesktopPiRpcClientFactory", () => {
getRoute: vi.fn(async () =>
mode === "go"
? { mode: "go", token: "phe_x", teamId: 7, projectId: 7 }
- : { mode: "legacy", reason: "not_rolled_out" },
+ : {
+ mode: "blocked",
+ reason: "not_rolled_out",
+ detail: "unavailable",
+ status: 403,
+ },
),
remint: vi.fn(),
fallBack: vi.fn(),
@@ -269,17 +281,19 @@ describe("DesktopPiRpcClientFactory", () => {
},
}),
);
- 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",
- },
- });
- }
+ expect(authProxy.start).not.toHaveBeenCalledWith(
+ getLlmGatewayUrl("https://us.posthog.com"),
+ expect.anything(),
+ );
+ 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",
+ },
+ });
},
);
});
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.ts
index a98abbb8a117..7969dd852f8b 100644
--- a/products/desktop/packages/core/src/llm-gateway/gateway-token.test.ts
+++ b/products/desktop/packages/core/src/llm-gateway/gateway-token.test.ts
@@ -3,20 +3,25 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AuthService } from "../auth/auth";
import type { AuthState } from "../auth/schemas";
import {
+ GATEWAY_ACTION_RECHECK_MS,
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_THROTTLED_RECHECK_MS,
GATEWAY_TOKEN_MIN_REFRESH_SKEW_MS,
GATEWAY_TOKEN_REFRESH_SKEW_MS,
+ GATEWAY_TRANSIENT_MAX_RECHECK_MS,
+ GATEWAY_TRANSIENT_RECHECK_MS,
GatewayTokenService,
+ transientRecheckMs,
} 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/`;
+const TRANSIENT = "Couldn't reach PostHog AI. Retrying shortly.";
+const UNAVAILABLE = "PostHog AI isn't available for this project right now.";
+const SIGN_IN = "Sign in to PostHog again to use PostHog AI.";
function minted(token: string, expiresInMs = 3_600_000) {
return {
@@ -126,9 +131,12 @@ describe("GatewayTokenService.getRoute", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-09-23T12:00:00Z"));
+ // Jitter at its ceiling, so a first transient re-check is exactly 30s.
+ vi.spyOn(Math, "random").mockReturnValue(1);
});
afterEach(() => {
vi.useRealTimers();
+ vi.restoreAllMocks();
});
it("mints once and serves the Go route from the cache", async () => {
@@ -174,51 +182,168 @@ describe("GatewayTokenService.getRoute", () => {
200,
{ enabled: false, reason: "unconfigured" },
"unconfigured",
- GATEWAY_LEGACY_RECHECK_MS,
+ 403,
+ UNAVAILABLE,
+ GATEWAY_ACTION_RECHECK_MS,
],
[
200,
{ enabled: false, reason: "not_rolled_out" },
"not_rolled_out",
- GATEWAY_NOT_ROLLED_OUT_RECHECK_MS,
+ 403,
+ UNAVAILABLE,
+ GATEWAY_ACTION_RECHECK_MS,
],
[
403,
{ enabled: false, reason: "desktop_access_blocked" },
"desktop_access_blocked",
- GATEWAY_LEGACY_RECHECK_MS,
+ 403,
+ "PostHog Desktop access is required.",
+ GATEWAY_BLOCKED_RECHECK_MS,
+ ],
+ [
+ 403,
+ { enabled: false, reason: "email_unverified" },
+ "email_unverified",
+ 403,
+ "Verify your email to use PostHog AI.",
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ // Django's billing-limit 429: without its row this would read as throttled.
+ [
+ 429,
+ {
+ type: "billing_limit",
+ code: "organization_deactivated",
+ error: "Organization is deactivated.",
+ },
+ "organization_deactivated",
+ 403,
+ UNAVAILABLE,
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ [
+ 403,
+ { enabled: false, reason: "oauth_required", detail: "Sign in." },
+ "oauth_required",
+ 401,
+ "Sign in.",
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ [
+ 429,
+ { enabled: false, reason: "throttled", detail: "Try later." },
+ "throttled",
+ 429,
+ "Too many PostHog AI sign-in attempts. Try again in a few minutes.",
+ GATEWAY_THROTTLED_RECHECK_MS,
+ ],
+ [
+ 503,
+ { enabled: false, reason: "mint_failed", detail: "mint failed" },
+ "mint_failed",
+ 503,
+ TRANSIENT,
+ GATEWAY_TRANSIENT_RECHECK_MS,
+ ],
+ [
+ 403,
+ { enabled: false, reason: "unauthorized", detail: "Not this project." },
+ "unauthorized",
+ 401,
+ "Not this project.",
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ [
+ 403,
+ { enabled: false, reason: "blocked", detail: "No AI for you." },
+ "blocked",
+ 403,
+ "No AI for you.",
+ GATEWAY_BLOCKED_RECHECK_MS,
+ ],
+ [
+ 403,
+ { enabled: false, reason: "org_deactivated" },
+ "org_deactivated",
+ 403,
+ UNAVAILABLE,
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ [
+ 200,
+ { enabled: false, reason: "credit_state_unknown" },
+ "credit_state_unknown",
+ 503,
+ TRANSIENT,
+ GATEWAY_TRANSIENT_RECHECK_MS,
],
[
402,
{ enabled: false, reason: "payment_required" },
"payment_required",
- GATEWAY_LEGACY_RECHECK_MS,
+ 402,
+ UNAVAILABLE,
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ [
+ 401,
+ { enabled: false, reason: "token_revoked", detail: "Revoked." },
+ "token_revoked",
+ 401,
+ "Revoked.",
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ [
+ 429,
+ { type: "billing_limit", code: "usage_limit_reached" },
+ "usage_limit_reached",
+ 429,
+ "Too many PostHog AI sign-in attempts. Try again in a few minutes.",
+ GATEWAY_THROTTLED_RECHECK_MS,
+ ],
+ [
+ 404,
+ { detail: "Not found." },
+ "http_404",
+ 403,
+ "Not found.",
+ GATEWAY_ACTION_RECHECK_MS,
+ ],
+ // `constructor` is an inherited key, not a table entry.
+ [
+ 403,
+ { enabled: false, reason: "constructor" },
+ "constructor",
+ 403,
+ UNAVAILABLE,
+ GATEWAY_ACTION_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],
+ [503, null, "http_503", 503, TRANSIENT, GATEWAY_TRANSIENT_RECHECK_MS],
])(
- "treats a %s as legacy and re-checks after the negative cache",
- async (status, body, reason, recheckMs) => {
+ "blocks a %s refusal with its reason and re-mints after the re-check",
+ async (status, body, reason, blockedStatus, detail, 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 });
+ expect(await t.service.getRoute()).toEqual({
+ mode: "blocked",
+ reason,
+ detail,
+ status: blockedStatus,
+ });
vi.setSystemTime(Date.now() + recheckMs - 1);
- expect(await t.service.getRoute()).toMatchObject({ mode: "legacy" });
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
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(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 () => {
+ it("serves a known refusal while its re-check is in flight to a caller that will not wait", async () => {
const t = setup();
t.mintResponses.push(() =>
json({ enabled: false, reason: "not_rolled_out" }, 200),
@@ -226,17 +351,16 @@ describe("GatewayTokenService.getRoute", () => {
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();
+ vi.setSystemTime(Date.now() + GATEWAY_ACTION_RECHECK_MS);
+ await t.service.getRoute(42, { awaitRecheck: false });
await vi.waitFor(() => expect(t.mintCalls()).toBe(2));
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
- reason: "not_rolled_out",
- });
+ expect(await t.service.getRoute(42, { awaitRecheck: false })).toMatchObject(
+ { mode: "blocked", reason: "not_rolled_out" },
+ );
});
- it("waits for the re-check when a session start asks for it", async () => {
+ it("waits for a due re-check by default", async () => {
const t = setup();
t.mintResponses.push(() =>
json({ enabled: false, reason: "not_rolled_out" }, 200),
@@ -244,9 +368,9 @@ describe("GatewayTokenService.getRoute", () => {
t.mintResponses.push(() => json(minted("phe_one"), 201));
await t.service.getRoute();
- vi.setSystemTime(Date.now() + GATEWAY_NOT_ROLLED_OUT_RECHECK_MS);
+ vi.setSystemTime(Date.now() + GATEWAY_ACTION_RECHECK_MS);
- expect(await t.service.getRoute(42, { awaitRecheck: true })).toMatchObject({
+ expect(await t.service.getRoute()).toMatchObject({
mode: "go",
token: "phe_one",
});
@@ -254,11 +378,11 @@ describe("GatewayTokenService.getRoute", () => {
it.each([
[
- "a session start on a legacy route",
+ "a caller on a refused route",
{ enabled: false, reason: "not_rolled_out" },
200,
- GATEWAY_NOT_ROLLED_OUT_RECHECK_MS,
- { awaitRecheck: true },
+ GATEWAY_ACTION_RECHECK_MS,
+ {},
],
[
"any caller on a blocked route",
@@ -307,7 +431,7 @@ describe("GatewayTokenService.getRoute", () => {
});
});
- it("treats an exhausted credit bucket as final, not as legacy", async () => {
+ it("treats an exhausted credit bucket as a 402 that only clears on a refill", async () => {
const t = setup();
const sentence =
"Your organization has reached its PostHog Desktop usage limit";
@@ -323,6 +447,7 @@ describe("GatewayTokenService.getRoute", () => {
mode: "blocked",
reason: "credit_bucket_exhausted",
detail: sentence,
+ status: 402,
});
vi.setSystemTime(Date.now() + GATEWAY_BLOCKED_RECHECK_MS - 1);
expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
@@ -335,32 +460,89 @@ describe("GatewayTokenService.getRoute", () => {
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));
+ it("keeps a refusal other than an exhausted bucket when usage reports a refill", async () => {
+ const t = setup();
+ t.mintResponses.push(() =>
+ json({ enabled: false, reason: "throttled" }, 429),
+ );
- expect(await t.service.getRoute()).toEqual({ mode: "legacy", reason });
- },
- );
+ await t.service.getRoute();
+ t.service.clearBlocked();
+
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
+ reason: "throttled",
+ });
+ expect(t.mintCalls()).toBe(1);
+ });
+
+ it("backs off on consecutive transient refusals and resets after a mint", async () => {
+ const t = setup();
+ t.mintResponses.push(() => json(null, 503));
+ t.mintResponses.push(() => json(null, 503));
+ t.mintResponses.push(() => json(minted("phe_one"), 201));
+ t.mintResponses.push(() => json(null, 503));
+ t.mintResponses.push(() => json(minted("phe_two"), 201));
+
+ await t.service.getRoute();
+ vi.setSystemTime(Date.now() + GATEWAY_TRANSIENT_RECHECK_MS);
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
+ expect(t.mintCalls()).toBe(2);
+ vi.setSystemTime(Date.now() + 2 * GATEWAY_TRANSIENT_RECHECK_MS - 1);
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
+ expect(t.mintCalls()).toBe(2);
+ vi.setSystemTime(Date.now() + 1);
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });
+
+ // The mint reset the count, so this wait is 30s.
+ vi.setSystemTime(Date.now() + 3_600_000);
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
+ expect(t.mintCalls()).toBe(4);
+ vi.setSystemTime(Date.now() + GATEWAY_TRANSIENT_RECHECK_MS);
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" });
+ });
+
+ it("backs off when the early refresh fails twice in a row", async () => {
+ const t = setup();
+ // An hourly token refreshes 2 minutes early, leaving room for 30s + 60s.
+ t.mintResponses.push(() => json(minted("phe_one"), 201));
+ t.mintResponses.push(() => json(null, 503));
+ t.mintResponses.push(() => json(null, 503));
+ t.mintResponses.push(() => json(minted("phe_two"), 201));
+
+ await t.service.getRoute();
+ vi.setSystemTime(Date.now() + 3_600_000 - 120_000);
+ await t.service.getRoute();
+ await vi.waitFor(() => expect(t.mintCalls()).toBe(2));
+ // Let the refused refresh settle and schedule its re-check.
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ vi.setSystemTime(Date.now() + GATEWAY_TRANSIENT_RECHECK_MS);
+ await t.service.getRoute();
+ await vi.waitFor(() => expect(t.mintCalls()).toBe(3));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ vi.setSystemTime(Date.now() + 2 * GATEWAY_TRANSIENT_RECHECK_MS - 1_000);
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });
+ expect(t.mintCalls()).toBe(3);
+ vi.setSystemTime(Date.now() + 1_000);
+ await t.service.getRoute();
+ await vi.waitFor(async () =>
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" }),
+ );
+ });
+
+ it("shortens a transient re-check by the jitter draw", async () => {
+ const t = setup();
+ vi.spyOn(Math, "random").mockReturnValue(0);
+ t.mintResponses.push(() => json(null, 503));
+ t.mintResponses.push(() => json(minted("phe_one"), 201));
+
+ await t.service.getRoute();
+ vi.setSystemTime(Date.now() + GATEWAY_TRANSIENT_RECHECK_MS / 2 - 1);
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
+ vi.setSystemTime(Date.now() + 1);
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });
+ });
it("feeds a desktop access denial into the auth state", async () => {
const t = setup();
@@ -369,22 +551,24 @@ describe("GatewayTokenService.getRoute", () => {
json({ enabled: false, reason: "desktop_access_blocked", access }, 403),
);
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "desktop_access_blocked",
});
expect(t.reportDesktopAccessBlocked).toHaveBeenCalledWith(42, access);
});
- it("falls back to legacy when the mint request fails", async () => {
+ it("blocks briefly when the mint request fails", async () => {
const t = setup();
t.mintResponses.push(() => {
throw new Error("offline");
});
expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ mode: "blocked",
reason: "mint_failed",
+ detail: TRANSIENT,
+ status: 503,
});
});
@@ -401,8 +585,8 @@ describe("GatewayTokenService.getRoute", () => {
json({ ...minted("phe_bad"), gateway_url: gatewayUrl }, 201),
);
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "invalid_gateway_url",
});
});
@@ -436,11 +620,11 @@ describe("GatewayTokenService.getRoute", () => {
});
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_ACTION_RECHECK_MS).toBe(600_000);
expect(GATEWAY_BLOCKED_RECHECK_MS).toBe(1_800_000);
+ expect(GATEWAY_THROTTLED_RECHECK_MS).toBe(300_000);
+ expect(GATEWAY_TRANSIENT_RECHECK_MS).toBe(30_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);
@@ -475,12 +659,12 @@ describe("GatewayTokenService.getRoute", () => {
json({ ...minted("phe_one"), expires_at: "soon" }, 201),
);
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "invalid_expiry",
});
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "invalid_expiry",
});
expect(t.mintCalls()).toBe(1);
@@ -508,7 +692,10 @@ describe("GatewayTokenService.getRoute", () => {
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
- expect(await pending).toEqual({ mode: "legacy", reason: "mint_failed" });
+ expect(await pending).toMatchObject({
+ mode: "blocked",
+ reason: "mint_failed",
+ });
});
it("gives up on a mint whose body does not arrive in time", async () => {
@@ -531,8 +718,8 @@ describe("GatewayTokenService.getRoute", () => {
const pending = t.service.getRoute();
await vi.advanceTimersByTimeAsync(GATEWAY_MINT_TIMEOUT_MS);
- expect(await pending).toEqual({
- mode: "legacy",
+ expect(await pending).toMatchObject({
+ mode: "blocked",
reason: "invalid_mint_response",
});
});
@@ -541,8 +728,8 @@ describe("GatewayTokenService.getRoute", () => {
const t = setup();
t.mintResponses.push(() => json({ ...minted("sk-not-phe") }, 201));
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "invalid_mint_response",
});
});
@@ -566,15 +753,21 @@ describe("GatewayTokenService.getRoute", () => {
});
it.each([
- ["a network error", () => Promise.reject(new Error("offline"))],
- ["a 503", () => json(null, 503)],
+ // Non-transient refusals wait for expiry, 59,999ms after the refresh.
+ [
+ "a network error",
+ () => Promise.reject(new Error("offline")),
+ GATEWAY_TRANSIENT_RECHECK_MS,
+ ],
+ ["a 503", () => json(null, 503), GATEWAY_TRANSIENT_RECHECK_MS],
[
"a flag-off refusal",
() => json({ enabled: false, reason: "not_rolled_out" }, 200),
+ 60_000 - 1,
],
])(
"keeps the unexpired token when the early refresh hits %s",
- async (_label, failure) => {
+ async (_label, failure, retryAfterMs) => {
const t = setup();
t.mintResponses.push(() => json(minted("phe_one", 10 * 60_000), 201));
t.mintResponses.push(failure);
@@ -588,7 +781,11 @@ describe("GatewayTokenService.getRoute", () => {
expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });
expect(t.mintCalls()).toBe(2);
- vi.setSystemTime(Date.now() + GATEWAY_REFRESH_RETRY_MS);
+ // A second of slack: only Date is faked, so real milliseconds still pass.
+ vi.setSystemTime(Date.now() + retryAfterMs - 1_000);
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_one" });
+ expect(t.mintCalls()).toBe(2);
+ vi.setSystemTime(Date.now() + 1_000);
await t.service.getRoute();
await vi.waitFor(async () =>
expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" }),
@@ -611,22 +808,26 @@ describe("GatewayTokenService.getRoute", () => {
);
});
- it("answers legacy without minting on a host that cannot reach Go", async () => {
+ it("blocks without minting on a host that cannot reach Go", async () => {
const t = setup({ config: { goEnabled: false } });
expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ mode: "blocked",
reason: "host_unsupported",
+ detail: "PostHog AI helpers aren't available in the web app yet.",
+ status: 403,
});
expect(t.authenticatedFetch).not.toHaveBeenCalled();
});
- it("answers legacy with no selected project", async () => {
+ it("blocks with no selected project", async () => {
const t = setup({ state: baseState({ currentProjectId: null }) });
expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ mode: "blocked",
reason: "no_project",
+ detail: "Select a project to use PostHog AI.",
+ status: 403,
});
});
@@ -656,9 +857,12 @@ describe("GatewayTokenService.remint", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-09-23T12:00:00Z"));
+ // Jitter at its ceiling, so a first transient re-check is exactly 30s.
+ vi.spyOn(Math, "random").mockReturnValue(1);
});
afterEach(() => {
vi.useRealTimers();
+ vi.restoreAllMocks();
});
async function primed() {
@@ -801,37 +1005,47 @@ describe("GatewayTokenService.remint", () => {
).toMatchObject({ token: "phe_two" });
});
- it("falls back to legacy when Go refuses the re-minted token too", async () => {
+ it("blocks briefly 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",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "gateway_unauthorized",
+ status: 503,
});
- vi.setSystemTime(Date.now() + GATEWAY_LEGACY_RECHECK_MS - 1);
- expect(await t.service.getRoute()).toMatchObject({ mode: "legacy" });
+ vi.setSystemTime(Date.now() + GATEWAY_TRANSIENT_RECHECK_MS - 1);
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
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" }),
- );
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_three" });
+ });
+
+ it("schedules a Go 401 block through the jittered backoff", async () => {
+ vi.spyOn(Math, "random").mockReturnValue(0);
+ const t = await primed();
+ t.service.fallBack("phe_one", undefined);
+
+ vi.setSystemTime(Date.now() + GATEWAY_TRANSIENT_RECHECK_MS / 2 - 1);
+ expect(await t.service.getRoute()).toMatchObject({ mode: "blocked" });
+ t.mintResponses.push(() => json(minted("phe_two"), 201));
+ vi.setSystemTime(Date.now() + 1);
+ expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" });
});
- it("falls back only the named project", async () => {
+ it("blocks 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",
+ expect(await t.service.getRoute(43)).toMatchObject({
+ mode: "blocked",
reason: "gateway_unauthorized",
});
expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_one" });
@@ -847,7 +1061,7 @@ describe("GatewayTokenService.remint", () => {
expect(await t.service.getRoute()).toMatchObject({ token: "phe_two" });
});
- it("falls back instead of re-minting on a 401 inside the minimum interval", async () => {
+ it("blocks 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();
@@ -855,8 +1069,8 @@ describe("GatewayTokenService.remint", () => {
expect(
await t.service.remint("unauthorized", "phe_one", undefined),
).toBeNull();
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "gateway_unauthorized",
});
expect(t.mintCalls()).toBe(1);
@@ -945,7 +1159,7 @@ describe("GatewayTokenService identity changes", () => {
expect(t.mintCalls()).toBe(1);
});
- it("answers legacy without minting while signed out", async () => {
+ it("blocks without minting while signed out", async () => {
const t = setup();
t.mintResponses.push(() => json(minted("phe_one"), 201));
await t.service.getRoute();
@@ -953,17 +1167,19 @@ describe("GatewayTokenService identity changes", () => {
t.setState(baseState({ status: "anonymous", currentProjectId: 42 }));
expect(await t.service.getRoute(42)).toEqual({
- mode: "legacy",
+ mode: "blocked",
reason: "signed_out",
+ detail: SIGN_IN,
+ status: 401,
});
expect(t.mintCalls()).toBe(1);
});
- it("answers legacy before any identity exists", async () => {
+ it("blocks before any identity exists", async () => {
const t = setup({ state: baseState({ status: "restoring" }) });
- expect(await t.service.getRoute(42)).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute(42)).toMatchObject({
+ mode: "blocked",
reason: "signed_out",
});
expect(t.mintCalls()).toBe(0);
@@ -1005,8 +1221,8 @@ describe("GatewayTokenService identity changes", () => {
change(t);
release(json(minted("phe_one"), 201));
- expect(await pending).toEqual({
- mode: "legacy",
+ expect(await pending).toMatchObject({
+ mode: "blocked",
reason: "identity_changed",
});
t.setState(baseState());
@@ -1021,8 +1237,8 @@ describe("GatewayTokenService identity changes", () => {
return { accessToken: "pha_x", apiHost: API_HOST };
});
- expect(await t.service.getRoute()).toEqual({
- mode: "legacy",
+ expect(await t.service.getRoute()).toMatchObject({
+ mode: "blocked",
reason: "identity_changed",
});
expect(t.mintCalls()).toBe(0);
@@ -1080,3 +1296,18 @@ describe("GatewayTokenService identity changes", () => {
expect(await t.service.getRoute(42)).toMatchObject({ token: "phe_two" });
});
});
+
+describe("transientRecheckMs", () => {
+ it.each([
+ [1, 1, GATEWAY_TRANSIENT_RECHECK_MS],
+ [1, 0, GATEWAY_TRANSIENT_RECHECK_MS / 2],
+ [2, 1, 2 * GATEWAY_TRANSIENT_RECHECK_MS],
+ [3, 1, 4 * GATEWAY_TRANSIENT_RECHECK_MS],
+ [20, 1, GATEWAY_TRANSIENT_MAX_RECHECK_MS],
+ ])(
+ "waits up to the doubled 30s for failure %i (random %s)",
+ (failures, random, expected) => {
+ expect(transientRecheckMs(failures, random)).toBe(expected);
+ },
+ );
+});
diff --git a/products/desktop/packages/core/src/llm-gateway/gateway-token.ts b/products/desktop/packages/core/src/llm-gateway/gateway-token.ts
index 7ac62213b58a..94543a6524b5 100644
--- a/products/desktop/packages/core/src/llm-gateway/gateway-token.ts
+++ b/products/desktop/packages/core/src/llm-gateway/gateway-token.ts
@@ -1,5 +1,8 @@
import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
-import { validateAiGatewayUrl } from "@posthog/shared";
+import {
+ GATEWAY_TRANSIENT_DETAIL,
+ validateAiGatewayUrl,
+} from "@posthog/shared";
import { inject, injectable } from "inversify";
import type { AuthService } from "../auth/auth";
import { AUTH_SERVICE } from "../auth/auth.module";
@@ -19,6 +22,7 @@ import {
} from "./schemas";
type GoRoute = Extract<GatewayRoute, { mode: "go" }>;
+type BlockedRoute = Extract<GatewayRoute, { mode: "blocked" }>;
/**
* Refresh a tenth of the lifetime before expiry, clamped to these bounds, so
@@ -26,18 +30,162 @@ type GoRoute = Extract<GatewayRoute, { mode: "go" }>;
*/
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;
+/** A refusal the user can clear (verify email, sign in again). */
+export const GATEWAY_ACTION_RECHECK_MS = 10 * 60_000;
export const GATEWAY_BLOCKED_RECHECK_MS = 30 * 60_000;
+export const GATEWAY_THROTTLED_RECHECK_MS = 5 * 60_000;
+export const GATEWAY_TRANSIENT_RECHECK_MS = 30_000;
+export const GATEWAY_TRANSIENT_MAX_RECHECK_MS = 10 * 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;
+const SIGN_IN_DETAIL = "Sign in to PostHog again to use PostHog AI.";
+
+interface RefusalPolicy {
+ status: BlockedRoute["status"];
+ recheckMs: number;
+ /** Used when the server sends no detail; transient refusals always use it. */
+ detail: string;
+ serverDetail: boolean;
+}
+
+const TRANSIENT: RefusalPolicy = {
+ status: 503,
+ recheckMs: GATEWAY_TRANSIENT_RECHECK_MS,
+ detail: GATEWAY_TRANSIENT_DETAIL,
+ serverDetail: false,
+};
+
+const UNAVAILABLE: RefusalPolicy = {
+ status: 403,
+ recheckMs: GATEWAY_ACTION_RECHECK_MS,
+ detail: "PostHog AI isn't available for this project right now.",
+ serverDetail: true,
+};
+
+const REFUSALS: Record<string, RefusalPolicy> = {
+ credit_bucket_exhausted: {
+ status: 402,
+ recheckMs: GATEWAY_BLOCKED_RECHECK_MS,
+ detail: "Your organization has reached its PostHog Desktop usage limit",
+ serverDetail: true,
+ },
+ throttled: {
+ status: 429,
+ recheckMs: GATEWAY_THROTTLED_RECHECK_MS,
+ detail: "Too many PostHog AI sign-in attempts. Try again in a few minutes.",
+ serverDetail: false,
+ },
+ email_unverified: {
+ status: 403,
+ recheckMs: GATEWAY_ACTION_RECHECK_MS,
+ detail: "Verify your email to use PostHog AI.",
+ serverDetail: true,
+ },
+ oauth_required: {
+ status: 401,
+ recheckMs: GATEWAY_ACTION_RECHECK_MS,
+ detail: SIGN_IN_DETAIL,
+ serverDetail: true,
+ },
+ unauthorized: {
+ status: 401,
+ recheckMs: GATEWAY_ACTION_RECHECK_MS,
+ detail: SIGN_IN_DETAIL,
+ serverDetail: true,
+ },
+ signed_out: {
+ status: 401,
+ recheckMs: GATEWAY_ACTION_RECHECK_MS,
+ detail: SIGN_IN_DETAIL,
+ serverDetail: false,
+ },
+ blocked: {
+ status: 403,
+ recheckMs: GATEWAY_BLOCKED_RECHECK_MS,
+ detail: "This account can't use PostHog AI.",
+ serverDetail: true,
+ },
+ desktop_access_blocked: {
+ status: 403,
+ recheckMs: GATEWAY_BLOCKED_RECHECK_MS,
+ detail: "PostHog Desktop access is required.",
+ serverDetail: true,
+ },
+ no_project: {
+ status: 403,
+ recheckMs: GATEWAY_ACTION_RECHECK_MS,
+ detail: "Select a project to use PostHog AI.",
+ serverDetail: false,
+ },
+ // Go sends no CORS headers, so the web host cannot reach it.
+ host_unsupported: {
+ status: 403,
+ recheckMs: GATEWAY_BLOCKED_RECHECK_MS,
+ detail: "PostHog AI helpers aren't available in the web app yet.",
+ serverDetail: false,
+ },
+ unconfigured: UNAVAILABLE,
+ not_rolled_out: UNAVAILABLE,
+ org_deactivated: UNAVAILABLE,
+ organization_deactivated: UNAVAILABLE,
+};
+
+/**
+ * An unlisted reason falls back on the HTTP status: a 4xx keeps the server's
+ * detail, anything else is transient.
+ */
+function policyFor(reason: string, httpStatus?: number): RefusalPolicy {
+ // Own keys only: the reason comes from the response body.
+ if (Object.hasOwn(REFUSALS, reason)) {
+ return REFUSALS[reason];
+ }
+ if (httpStatus === 429) return REFUSALS.throttled;
+ if (httpStatus !== undefined && httpStatus >= 400 && httpStatus < 500) {
+ return {
+ ...UNAVAILABLE,
+ status: httpStatus === 401 || httpStatus === 402 ? httpStatus : 403,
+ };
+ }
+ return TRANSIENT;
+}
+
+export function blockedRoute(
+ reason: string,
+ serverDetail?: string,
+ httpStatus?: number,
+): { route: BlockedRoute; recheckMs: number } {
+ const policy = policyFor(reason, httpStatus);
+ const detail =
+ policy.serverDetail && serverDetail ? serverDetail : policy.detail;
+ return {
+ route: { mode: "blocked", reason, detail, status: policy.status },
+ recheckMs: policy.recheckMs,
+ };
+}
+
+/**
+ * The re-check after the `failures`th transient refusal in a row: doubles from
+ * 30s up to the cap, and jitter only shortens it so clients spread out.
+ */
+export function transientRecheckMs(failures: number, random: number): number {
+ const ceiling = Math.min(
+ GATEWAY_TRANSIENT_RECHECK_MS * 2 ** Math.max(0, failures - 1),
+ GATEWAY_TRANSIENT_MAX_RECHECK_MS,
+ );
+ return Math.round(ceiling * (0.5 + random * 0.5));
+}
+
+function isTransient(route: GatewayRoute): boolean {
+ return route.mode === "blocked" && route.status === 503;
+}
+
interface CacheEntry {
route: GatewayRoute;
recheckAt: number;
+ /** Consecutive transient refusals, reset by any other outcome. */
+ transientFailures: number;
mintedAt: number;
refreshAt: number;
inFlight: Promise<GatewayRoute> | null;
@@ -46,8 +194,8 @@ interface CacheEntry {
/**
* 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.
+ * and never handed to a subprocess. A refusal blocks the project with a reason
+ * until its re-check.
*/
@injectable()
export class GatewayTokenService {
@@ -62,6 +210,7 @@ export class GatewayTokenService {
private routesKey = "";
private readonly log: LlmGatewayLogger;
private readonly now: () => number = () => Date.now();
+ private readonly random: () => number = () => Math.random();
constructor(
@inject(LLM_GATEWAY_HOST)
@@ -81,8 +230,8 @@ export class GatewayTokenService {
}
/**
- * A due legacy re-check runs in the background unless `awaitRecheck` asks
- * to wait (a session start picks its target once).
+ * A due re-check of a blocked route is awaited unless `awaitRecheck` is
+ * false, which serves the blocked route and re-checks in the background.
*/
async getRoute(
projectId?: number | null,
@@ -91,12 +240,12 @@ export class GatewayTokenService {
const resolvedProject =
projectId ?? this.authService.getState().currentProjectId;
if (resolvedProject === null || resolvedProject === undefined) {
- return { mode: "legacy", reason: "no_project" };
+ return blockedRoute("no_project").route;
}
if (!this.config.goEnabled) {
- return { mode: "legacy", reason: "host_unsupported" };
+ return blockedRoute("host_unsupported").route;
}
- if (!this.signedIn) return { mode: "legacy", reason: "signed_out" };
+ if (!this.signedIn) return blockedRoute("signed_out").route;
return this.routeFor(resolvedProject, options);
}
@@ -135,7 +284,7 @@ export class GatewayTokenService {
/**
* Go refused `token` with a 401 and no re-mint can replace it: the project
- * uses the legacy gateway until the re-check.
+ * is blocked until a short re-check mints again.
*/
fallBack(token: string, projectId: number | null | undefined): void {
const resolvedProject =
@@ -143,14 +292,26 @@ export class GatewayTokenService {
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;
+ this.log.warn("Go refused the gateway token; blocking until a re-mint");
+ // 503, not 401: the block clears on a re-mint, and agent SDKs retry a 5xx
+ // but give up on a 401.
+ entry.route = {
+ mode: "blocked",
+ reason: "gateway_unauthorized",
+ detail: "PostHog AI couldn't verify this session. Retrying shortly.",
+ status: 503,
+ };
+ this.scheduleRecheck(entry, entry.route, GATEWAY_TRANSIENT_RECHECK_MS);
}
+ /** Usage reports credit left, which disproves only an exhausted bucket. */
clearBlocked(): void {
for (const [projectId, entry] of this.cache) {
- if (entry.route.mode === "blocked" && !entry.inFlight) {
+ if (
+ entry.route.mode === "blocked" &&
+ entry.route.reason === "credit_bucket_exhausted" &&
+ !entry.inFlight
+ ) {
this.cache.delete(projectId);
}
}
@@ -165,13 +326,12 @@ export class GatewayTokenService {
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.
+ // A known refusal is served while it re-checks only for a caller that
+ // opts out of waiting; a first mint always waits.
const settled =
entry !== undefined &&
- entry.route.mode === "legacy" &&
!isPending(entry.route) &&
- !options.awaitRecheck;
+ options.awaitRecheck === false;
if (entry?.inFlight && entry.route.mode !== "go") {
return settled ? entry.route : entry.inFlight;
}
@@ -202,8 +362,9 @@ export class GatewayTokenService {
if (existing?.inFlight) return existing.inFlight;
const current = keepValidToken ? existing?.route : undefined;
const entry: CacheEntry = existing ?? {
- route: { mode: "legacy", reason: "pending" },
+ route: blockedRoute("pending").route,
recheckAt: 0,
+ transientFailures: 0,
mintedAt: 0,
refreshAt: 0,
inFlight: null,
@@ -214,22 +375,26 @@ export class GatewayTokenService {
const inFlight = this.requestMint(projectId, generation)
.then(({ route, recheckMs }): GatewayRoute => {
if (generation !== this.generation) {
- return { mode: "legacy", reason: "identity_changed" };
+ return blockedRoute("identity_changed").route;
}
+ // An exhausted bucket is final; any other refusal keeps a live token.
if (
current?.mode === "go" &&
- route.mode === "legacy" &&
+ route.mode === "blocked" &&
+ route.reason !== "credit_bucket_exhausted" &&
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;
+ // Past expiry `routeFor` mints regardless, so a long window only
+ // stops early refresh attempts.
+ this.scheduleRecheck(entry, route, recheckMs);
return current;
}
entry.route = route;
- entry.recheckAt = this.now() + recheckMs;
+ this.scheduleRecheck(entry, route, recheckMs);
if (route.mode === "go") {
const lifetime = route.expiresAt - this.now();
entry.refreshAt =
@@ -262,7 +427,7 @@ export class GatewayTokenService {
({ 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");
+ return blockedRoute("identity_changed");
timer = setTimeout(() => timeout.abort(), GATEWAY_MINT_TIMEOUT_MS);
response = await this.host.authenticatedFetch(
`${apiHost}/api/projects/${projectId}/desktop/gateway_token/`,
@@ -280,7 +445,7 @@ export class GatewayTokenService {
timedOut: timeout.signal.aborted,
});
clearTimeout(timer);
- return this.legacy("mint_failed");
+ return blockedRoute("mint_failed");
}
const body: unknown = await response.json().catch(() => null);
@@ -289,37 +454,23 @@ export class GatewayTokenService {
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", {
+ this.log.info("Gateway token not issued", {
status: response.status,
reason,
});
- return this.legacy(reason);
+ return blockedRoute(reason, data.detail, response.status);
}
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");
+ return blockedRoute("invalid_mint_response");
}
const gatewayUrl = validateAiGatewayUrl(minted.data.gateway_url, {
apiHost,
@@ -333,11 +484,11 @@ export class GatewayTokenService {
this.now();
if (!gatewayUrl) {
this.log.warn("Gateway token response named an untrusted gateway");
- return this.legacy("invalid_gateway_url");
+ return blockedRoute("invalid_gateway_url");
}
if (!Number.isFinite(expiresAt)) {
this.log.warn("Gateway token response had an unreadable expiry");
- return this.legacy("invalid_expiry");
+ return blockedRoute("invalid_expiry");
}
return {
route: {
@@ -357,17 +508,19 @@ export class GatewayTokenService {
};
}
- 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 scheduleRecheck(
+ entry: CacheEntry,
+ route: GatewayRoute,
+ recheckMs: number,
+ ): void {
+ if (isTransient(route)) {
+ entry.transientFailures += 1;
+ entry.recheckAt =
+ this.now() + transientRecheckMs(entry.transientFailures, this.random());
+ return;
+ }
+ entry.transientFailures = 0;
+ entry.recheckAt = this.now() + recheckMs;
}
private overrideRoute(projectId: number): GoRoute | null {
@@ -425,5 +578,5 @@ export class GatewayTokenService {
}
function isPending(route: GatewayRoute): boolean {
- return route.mode === "legacy" && route.reason === "pending";
+ return route.mode === "blocked" && route.reason === "pending";
}
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.ts
index 4784521c70e7..8168460321aa 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
@@ -47,7 +47,7 @@ function createService(
.fn()
.mockResolvedValue({ accessToken: "tok", apiHost: API_HOST }),
authenticatedFetch,
- fetch: options.fetch,
+ fetch: options.fetch ?? authenticatedFetch,
};
const endpoints: LlmGatewayEndpoints = {
@@ -58,9 +58,7 @@ function createService(
defaultModel: "claude-default",
};
const gatewayTokens = {
- getRoute: vi
- .fn()
- .mockResolvedValue(options.route ?? { mode: "legacy", reason: "test" }),
+ getRoute: vi.fn().mockResolvedValue(options.route ?? GO_ROUTE),
remint: options.remint ?? vi.fn().mockResolvedValue(null),
fallBack: vi.fn(),
clearBlocked: vi.fn(),
@@ -133,15 +131,6 @@ const CHAT_SUCCESS_BODY = {
usage: { prompt_tokens: 9, completion_tokens: 4, total_tokens: 13 },
};
-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();
@@ -163,61 +152,6 @@ describe("LlmGatewayService.prompt", () => {
});
});
- it("posts to the resolved messages URL with the default model and request body", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(createJsonResponse(SUCCESS_BODY));
- const { service } = createService(fetchMock);
-
- await service.prompt([{ role: "user", content: "hi" }], {
- system: "be terse",
- maxTokens: 256,
- });
-
- const [url, init] = fetchMock.mock.calls[0];
- expect(url).toBe(`${API_HOST}/gateway/v1/messages`);
- expect(init.method).toBe("POST");
- expect(init.headers).toMatchObject({ "X-PostHog-Project-Id": "42" });
- const body = JSON.parse(init.body);
- expect(body.model).toBe("claude-default");
- expect(body.system).toBe("be terse");
- expect(body.max_tokens).toBe(256);
- expect(body.stream).toBe(false);
- });
-
- it("forwards posthogProperties as x-posthog-property-* request headers and skips nulls", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(createJsonResponse(SUCCESS_BODY));
- const { service } = createService(fetchMock);
-
- await service.prompt([{ role: "user", content: "hi" }], {
- posthogProperties: {
- $ai_span_name: "pr_description",
- task_id: 42,
- is_dry_run: false,
- // Null/undefined values are dropped so the gateway doesn't see
- // literal "null" strings on the captured event.
- unused: null,
- skipped: undefined,
- // Newlines and non-ASCII characters are sanitized so no HTTP client
- // (undici, Bun's fetch) rejects the request before it's sent.
- rich: "line one\nline two — done 🎉",
- },
- });
-
- const [, init] = fetchMock.mock.calls[0];
- expect(init.headers).toMatchObject({
- "x-posthog-property-$ai_span_name": "pr_description",
- "x-posthog-property-task_id": "42",
- "x-posthog-property-is_dry_run": "false",
- "x-posthog-property-rich": "line one line two done ",
- });
- expect(init.headers).not.toHaveProperty("x-posthog-property-unused");
- expect(init.headers).not.toHaveProperty("X-PostHog-Span-Name");
- expect(init.headers).not.toHaveProperty("x-posthog-property-skipped");
- });
-
it("throws a typed LlmGatewayError with parsed error fields on non-ok response", async () => {
const fetchMock = vi.fn().mockResolvedValue(
createJsonResponse(
@@ -265,106 +199,6 @@ describe("LlmGatewayService.prompt", () => {
});
});
- it("retries once on the free-tier model when the model gate 403s", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(createJsonResponse(MODEL_GATE_BODY, 403))
- .mockResolvedValueOnce(createJsonResponse(SUCCESS_BODY));
- const { service } = createService(fetchMock);
-
- const result = await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
-
- expect(result.content).toBe("hello world");
- expect(fetchMock).toHaveBeenCalledTimes(2);
- const firstBody = JSON.parse(fetchMock.mock.calls[0][1].body as string);
- const retryBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);
- expect(firstBody.model).toBe("claude-haiku-4-5");
- expect(retryBody.model).toBe("@cf/zai-org/glm-5.2");
- });
-
- it("routes straight to the free-tier model once the org is known unsubscribed", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(createJsonResponse(MODEL_GATE_BODY, 403))
- .mockImplementation(async () => createJsonResponse(SUCCESS_BODY));
- const { service } = createService(fetchMock);
-
- // First call learns "unsubscribed" from the gate's 403.
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
- // Second call must not burn a round trip on the gate.
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
-
- expect(fetchMock).toHaveBeenCalledTimes(3);
- const thirdBody = JSON.parse(fetchMock.mock.calls[2][1].body as string);
- expect(thirdBody.model).toBe("@cf/zai-org/glm-5.2");
- });
-
- it("forgets the learned subscription state when the organization changes", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(createJsonResponse(MODEL_GATE_BODY, 403))
- .mockImplementation(async () => createJsonResponse(SUCCESS_BODY));
- const { service, emitAuthState } = createService(fetchMock);
-
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
- emitAuthState("org-2");
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
-
- const bodyAfterSwitch = JSON.parse(
- fetchMock.mock.calls[2][1].body as string,
- );
- expect(bodyAfterSwitch.model).toBe("claude-haiku-4-5");
- });
-
- it("keeps the learned subscription state across same-org auth changes", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(createJsonResponse(MODEL_GATE_BODY, 403))
- .mockImplementation(async () => createJsonResponse(SUCCESS_BODY));
- const { service, emitAuthState } = createService(fetchMock);
-
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
- emitAuthState("org-1");
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
-
- expect(fetchMock).toHaveBeenCalledTimes(3);
- const bodyAfterRefresh = JSON.parse(
- fetchMock.mock.calls[2][1].body as string,
- );
- expect(bodyAfterRefresh.model).toBe("@cf/zai-org/glm-5.2");
- });
-
- it("does not retry non-gate 403s on the free-tier model", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- createJsonResponse(
- { detail: "Product 'posthog_code' requires OAuth authentication" },
- 403,
- ),
- );
- const { service } = createService(fetchMock);
-
- await expect(
- service.prompt([{ role: "user", content: "hi" }]),
- ).rejects.toMatchObject({ statusCode: 403 });
- expect(fetchMock).toHaveBeenCalledTimes(1);
- });
-
it("throws a timeout LlmGatewayError when the request aborts via the internal timeout", async () => {
const fetchMock = vi.fn((_url: string, init?: RequestInit) => {
return new Promise<Response>((_resolve, reject) => {
@@ -535,24 +369,6 @@ describe("LlmGatewayService.fetchUsage", () => {
expect(usage.ai_credits?.breakdown).toEqual(breakdown);
});
-
- it("feeds code_usage_subscribed into helper model routing", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(
- createJsonResponse({ ...USAGE_BODY, code_usage_subscribed: false }),
- )
- .mockResolvedValue(createJsonResponse(SUCCESS_BODY));
- const { service } = createService(fetchMock);
-
- await service.fetchUsage();
- await service.prompt([{ role: "user", content: "hi" }], {
- model: "claude-haiku-4-5",
- });
-
- const promptBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);
- expect(promptBody.model).toBe("@cf/zai-org/glm-5.2");
- });
});
describe("LlmGatewayService.prompt on the Go gateway", () => {
@@ -988,6 +804,7 @@ describe("LlmGatewayService.prompt on the Go gateway", () => {
mode: "blocked",
reason: "credit_bucket_exhausted",
detail: "Your organization has reached its PostHog Desktop usage limit",
+ status: 402,
},
fetch: goFetch,
});
@@ -999,6 +816,7 @@ describe("LlmGatewayService.prompt on the Go gateway", () => {
expect(error).toMatchObject({
statusCode: 402,
code: "credit_bucket_exhausted",
+ type: "billing_error",
});
expect(classifyGatewayLimitError((error as Error).message)).toBe(
"org_limit",
@@ -1006,6 +824,36 @@ describe("LlmGatewayService.prompt on the Go gateway", () => {
expect(authenticatedFetch).not.toHaveBeenCalled();
expect(goFetch).not.toHaveBeenCalled();
});
+
+ it.each([
+ ["email_unverified", 403, "permission_error"],
+ ["signed_out", 401, "authentication_error"],
+ ["mint_failed", 503, "api_error"],
+ ] as const)(
+ "refuses a helper prompt on a %s block with its status, without legacy",
+ async (reason, status, type) => {
+ const authenticatedFetch = vi.fn();
+ const { service } = createService(authenticatedFetch, {
+ route: { mode: "blocked", reason, detail: "blocked", status },
+ });
+
+ await expect(
+ service.prompt([{ role: "user", content: "hi" }]),
+ ).rejects.toMatchObject({ statusCode: status, code: reason, type });
+ expect(authenticatedFetch).not.toHaveBeenCalled();
+ },
+ );
+
+ it("refuses a helper prompt with a retryable error when the route lookup fails", async () => {
+ const authenticatedFetch = vi.fn();
+ const { service, gatewayTokens } = createService(authenticatedFetch);
+ vi.mocked(gatewayTokens.getRoute).mockRejectedValueOnce(new Error("boom"));
+
+ await expect(
+ service.prompt([{ role: "user", content: "hi" }]),
+ ).rejects.toMatchObject({ statusCode: 503, code: "route_failed" });
+ expect(authenticatedFetch).not.toHaveBeenCalled();
+ });
});
describe("LlmGatewayService.fetchUsage and the blocked route", () => {
diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
index 2909200619f8..549dc49feeec 100644
--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
@@ -2,21 +2,20 @@ import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
import {
aiGatewayDenialCode,
aiGatewayRemintReason,
- classifyGatewayLimitError,
+ GATEWAY_BLOCKED_ERROR_TYPES,
isAnthropicModelId,
} from "@posthog/shared";
import {
buildAiGatewayReservedHeaders,
buildPosthogProjectHeaderRecord,
buildPosthogPropertiesHeaderRecord,
- buildPosthogPropertyHeaderRecord,
type PosthogProperties,
} from "@posthog/shared/posthog-property-headers";
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 { blockedRoute, type GatewayTokenService } from "./gateway-token";
import {
GATEWAY_TOKEN_SERVICE,
LLM_GATEWAY_HOST,
@@ -42,8 +41,7 @@ import {
// the cheapest model rather than the gateway default.
export const HELPER_GATEWAY_MODEL = "claude-haiku-4-5";
-const FREE_TIER_GATEWAY_MODEL = "@cf/zai-org/glm-5.2";
-// The same model in the Go gateway's spelling; Go does not resolve `@cf/`.
+// Go does not resolve the `@cf/` spelling of this model.
const GO_FREE_TIER_GATEWAY_MODEL = "zai-org/glm-5.2";
// The Messages API requires max_tokens; the Go gateway forwards the body as sent.
@@ -124,7 +122,6 @@ export class LlmGatewayService {
authService.on(AuthServiceEvent.StateChanged, (state) => {
if (state.currentOrgId === orgId) return;
orgId = state.currentOrgId;
- this.lastKnownCodeUsageSubscribed = null;
this.legacyUsageOrgs.clear();
});
}
@@ -134,7 +131,6 @@ export class LlmGatewayService {
private readonly log: LlmGatewayLogger;
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>();
@@ -158,47 +154,23 @@ export class LlmGatewayService {
const requested = options.model ?? this.endpoints.defaultModel;
const route = await this.gatewayTokens
.getRoute()
- .catch((): GatewayRoute => ({ mode: "legacy", reason: "route_failed" }));
+ .catch((): GatewayRoute => blockedRoute("route_failed").route);
if (route.mode === "blocked") {
throw new LlmGatewayError(
route.detail,
- "billing_error",
+ GATEWAY_BLOCKED_ERROR_TYPES[route.status],
route.reason,
- 402,
+ route.status,
);
}
- if (route.mode === "go") {
- return this.sendGoPrompt(
- messages,
- {
- ...options,
- model: pickGoModel(route, requested),
- },
- route,
- );
- }
- const model =
- this.lastKnownCodeUsageSubscribed === false
- ? FREE_TIER_GATEWAY_MODEL
- : requested;
- try {
- return await this.sendPrompt(messages, { ...options, model });
- } catch (error) {
- const isModelGate =
- error instanceof LlmGatewayError &&
- error.statusCode === 403 &&
- classifyGatewayLimitError(error.message) === "model_gate";
- if (!isModelGate || model === FREE_TIER_GATEWAY_MODEL) throw error;
- this.lastKnownCodeUsageSubscribed = false;
- this.log.warn("Model gated for free tier, retrying on free-tier model", {
- model,
- fallbackModel: FREE_TIER_GATEWAY_MODEL,
- });
- return await this.sendPrompt(messages, {
+ return this.sendGoPrompt(
+ messages,
+ {
...options,
- model: FREE_TIER_GATEWAY_MODEL,
- });
- }
+ model: pickGoModel(route, requested),
+ },
+ route,
+ );
}
private async sendGoPrompt(
@@ -256,25 +228,6 @@ export class LlmGatewayService {
}
}
- private async sendPrompt(
- messages: LlmMessage[],
- options: SendOptions,
- ): Promise<PromptOutput> {
- const auth = await this.auth.getValidAccessToken();
- 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,
@@ -480,9 +433,6 @@ export class LlmGatewayService {
if (usage.ai_credits && !usage.ai_credits.exhausted) {
this.gatewayTokens.clearBlocked();
}
- if (usage.code_usage_subscribed !== undefined) {
- this.lastKnownCodeUsageSubscribed = usage.code_usage_subscribed;
- }
return usage;
}
diff --git a/products/desktop/packages/core/src/llm-gateway/schemas.ts b/products/desktop/packages/core/src/llm-gateway/schemas.ts
index 4d40f5a922ec..bea40fd8af2b 100644
--- a/products/desktop/packages/core/src/llm-gateway/schemas.ts
+++ b/products/desktop/packages/core/src/llm-gateway/schemas.ts
@@ -1,3 +1,4 @@
+import type { GatewayBlockedStatus } from "@posthog/shared";
import { z } from "zod";
export const llmMessageSchema = z.object({
@@ -104,12 +105,14 @@ export const gatewayTokenRefusalSchema = z.object({
access: z.unknown().optional(),
});
+export type { GatewayBlockedStatus };
+
export type GatewayRoute =
- | { mode: "legacy"; reason: string }
| {
mode: "blocked";
- reason: "credit_bucket_exhausted";
+ reason: string;
detail: string;
+ status: GatewayBlockedStatus;
}
| {
mode: "go";
diff --git a/products/desktop/packages/shared/src/ai-gateway-blocked.ts b/products/desktop/packages/shared/src/ai-gateway-blocked.ts
new file mode 100644
index 000000000000..0fcebdaa9ea9
--- /dev/null
+++ b/products/desktop/packages/shared/src/ai-gateway-blocked.ts
@@ -0,0 +1,18 @@
+/** The HTTP statuses a refused PostHog AI gateway route answers with. */
+export type GatewayBlockedStatus = 401 | 402 | 403 | 429 | 503;
+
+/**
+ * Shared by helper prompts and the agent auth proxy, so agent SDKs classify a
+ * refusal the same way on either path.
+ */
+export const GATEWAY_BLOCKED_ERROR_TYPES: Record<GatewayBlockedStatus, string> =
+ {
+ 401: "authentication_error",
+ 402: "billing_error",
+ 403: "permission_error",
+ 429: "rate_limit_error",
+ 503: "api_error",
+ };
+
+export const GATEWAY_TRANSIENT_DETAIL =
+ "Couldn't reach PostHog AI. Retrying shortly.";
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index c2f65035d9e5..cf6d51b9cc34 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -1,4 +1,5 @@
export * from "@posthog/agent-contracts";
+export * from "./ai-gateway-blocked";
export * from "./analytics-events";
export type { ArchivedTask } from "./archive-domain";
export { withTimeout } from "./async";
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.ts
index 725dd27e4c39..f77e99aa6304 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
@@ -90,7 +90,12 @@ describe("AgentAuthAdapter", () => {
deps.mcpProxy as never,
deps.loggerFactory as never,
{
- getRoute: vi.fn().mockResolvedValue({ mode: "legacy", reason: "x" }),
+ getRoute: vi.fn().mockResolvedValue({
+ mode: "blocked",
+ reason: "x",
+ detail: "x",
+ status: 503,
+ }),
remint: vi.fn(),
fallBack: vi.fn(),
} as never,
@@ -188,37 +193,39 @@ describe("AgentAuthAdapter", () => {
it.each([
[
- "a legacy route",
- vi.fn().mockResolvedValue({ mode: "legacy", reason: "not_rolled_out" }),
+ "a refused route",
+ vi.fn().mockResolvedValue({
+ mode: "blocked",
+ reason: "not_rolled_out",
+ detail: "unavailable",
+ status: 403,
+ }),
],
["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,
- );
- });
+ ])(
+ "keeps a session target on %s, never legacy",
+ 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/session",
+ mode: "go",
+ });
+ expect(authProxy.start).not.toHaveBeenCalled();
+ },
+ );
- it("stays on legacy without a project or a source", async () => {
+ it("stays on legacy without a project", 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");
});
});
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.ts
index 535a5a4c4067..9134487e6d08 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
@@ -1075,42 +1075,41 @@ describe("AuthProxyService gateway sessions", () => {
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"));
+ it("answers a refusal mid-session without reaching the legacy gateway", async () => {
goFetch.mockResolvedValue(new Response("ok"));
const proxyUrl = await session();
await fetch(`${proxyUrl}/v1/messages`, { method: "POST", body: "{}" });
goFetch.mockClear();
source.getRoute.mockResolvedValue({
- mode: "legacy",
+ mode: "blocked",
reason: "not_rolled_out",
+ detail: "PostHog AI isn't available for this project right now.",
+ status: 403,
});
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(res.status).toBe(403);
+ expect(await res.json()).toEqual({
+ error: {
+ type: "permission_error",
+ code: "not_rolled_out",
+ message: "PostHog AI isn't available for this project right now.",
+ },
+ });
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(authFetch).not.toHaveBeenCalled();
+ const changed = logs.filter(
+ ([, message]) => message === "Gateway session route changed",
);
- expect(switched).toEqual([
+ expect(changed).toEqual([
[
"info",
- "Gateway session switched gateway",
- { projectId: 42, from: "go", to: "legacy", reason: "not_rolled_out" },
+ "Gateway session route changed",
+ { projectId: 42, from: "go", to: "blocked", reason: "not_rolled_out" },
],
]);
});
@@ -1148,6 +1147,7 @@ describe("AuthProxyService gateway sessions", () => {
mode: "blocked",
reason: "credit_bucket_exhausted",
detail: "Your organization has reached its PostHog Desktop usage limit",
+ status: 402,
});
const res = await fetch(`${proxyUrl}/v1/messages`, {
@@ -1172,6 +1172,7 @@ describe("AuthProxyService gateway sessions", () => {
mode: "blocked",
reason: "credit_bucket_exhausted",
detail: "limit",
+ status: 402,
});
const res = await fetch(`${proxyUrl}/v1/models`);
@@ -1182,33 +1183,49 @@ describe("AuthProxyService gateway sessions", () => {
);
});
- 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: "{}",
+ const blocked = (reason: string, status: 401 | 402 | 403 | 429 | 503) => () =>
+ Promise.resolve({
+ mode: "blocked" as const,
+ reason,
+ detail: reason,
+ status,
});
- 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" });
+ it.each([
+ [
+ "a failing source",
+ () => Promise.reject(new Error("boom")),
+ 503,
+ "api_error",
+ ],
+ ["a sign-out", blocked("signed_out", 401), 401, "authentication_error"],
+ [
+ "an empty bucket",
+ blocked("credit_bucket_exhausted", 402),
+ 402,
+ "billing_error",
+ ],
+ ["an access refusal", blocked("blocked", 403), 403, "permission_error"],
+ ["a mint throttle", blocked("throttled", 429), 429, "rate_limit_error"],
+ ])(
+ "answers %s with a refusal, never the legacy gateway",
+ async (_label, getRoute, status, type) => {
+ const proxyUrl = await session();
+ source.getRoute.mockImplementation(getRoute);
- const res = await fetch(`${proxyUrl}/v1/messages`, {
- method: "POST",
- body: "{}",
- });
+ const res = await fetch(`${proxyUrl}/v1/messages`, {
+ method: "POST",
+ body: "{}",
+ });
- expect(await res.text()).toBe("legacy");
- expect(goFetch).not.toHaveBeenCalled();
- });
+ expect(res.status).toBe(status);
+ expect(
+ ((await res.json()) as { error: { type: string } }).error.type,
+ ).toBe(type);
+ expect(goFetch).not.toHaveBeenCalled();
+ expect(authFetch).not.toHaveBeenCalled();
+ },
+ );
it("never logs the path token or the query string of a Go request", async () => {
goFetch.mockResolvedValue(new Response("ok"));
@@ -1278,15 +1295,17 @@ describe("AuthProxyService gateway sessions", () => {
expect(res.headers["x-kept"]).toBe("1");
});
- it("strips Connection-named headers on the legacy fallback", async () => {
+ it("strips Connection-named headers on the legacy models listing", async () => {
authFetch.mockResolvedValue(new Response("legacy"));
source.getRoute.mockResolvedValue({
- mode: "legacy",
- reason: "not_rolled_out",
+ mode: "blocked",
+ reason: "credit_bucket_exhausted",
+ detail: "limit",
+ status: 402,
});
const proxyUrl = await session();
- await rawPost(`${proxyUrl}/v1/messages`, {
+ await rawPost(`${proxyUrl}/v1/models`, {
connection: "close, x-hop",
"x-hop": "1",
"x-kept": "1",
@@ -1297,7 +1316,7 @@ describe("AuthProxyService gateway sessions", () => {
expect(init.headers["x-kept"]).toBe("1");
});
- it("refuses an upstream redirect on the legacy fallback", async () => {
+ it("refuses an upstream redirect on the legacy models listing", async () => {
authFetch.mockResolvedValue(
new Response(null, {
status: 302,
@@ -1305,16 +1324,14 @@ describe("AuthProxyService gateway sessions", () => {
}),
);
source.getRoute.mockResolvedValue({
- mode: "legacy",
- reason: "not_rolled_out",
+ mode: "blocked",
+ reason: "credit_bucket_exhausted",
+ detail: "limit",
+ status: 402,
});
const proxyUrl = await session();
- const res = await fetch(`${proxyUrl}/v1/messages`, {
- method: "POST",
- body: "{}",
- redirect: "manual",
- });
+ const res = await fetch(`${proxyUrl}/v1/models`, { 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/gateway-proxy.ts b/products/desktop/packages/workspace-server/src/services/auth-proxy/gateway-proxy.ts
index e65cc44cbfbe..89d744905f98 100644
--- 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.ts
@@ -15,18 +15,11 @@ export async function resolveGatewayProxy(input: {
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
- ) {
+ // The session settles each request's route and answers a refusal itself.
+ if (source && projectId !== null) {
+ await source
+ .getRoute(projectId, { awaitRecheck: input.awaitRecheck ?? true })
+ .catch(() => null);
return {
proxyUrl: await authProxy.startGatewaySession({
projectId,
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.ts
index 55541ac17276..d9d33202441e 100644
--- 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.ts
@@ -4,6 +4,8 @@ import {
aiGatewayDenialCode,
aiGatewayRemintReason,
applyAllowedModels,
+ GATEWAY_BLOCKED_ERROR_TYPES,
+ GATEWAY_TRANSIENT_DETAIL,
serializeError,
} from "@posthog/shared";
import { collapsePropertyHeadersForAiGateway } from "@posthog/shared/posthog-property-headers";
@@ -75,7 +77,10 @@ function isSessionHeader(lower: string): boolean {
/** Serves session targets: Go under a per-request credential, else legacy. */
export class GatewaySessionHandler {
- private readonly modes = new WeakMap<SessionTarget, "go" | "legacy">();
+ private readonly modes = new WeakMap<
+ SessionTarget,
+ GatewayCredential["mode"]
+ >();
constructor(
private readonly deps: {
@@ -144,18 +149,20 @@ export class GatewaySessionHandler {
const credential: GatewayCredential = await this.deps
.source()
.getRoute(target.projectId)
- .catch(() => ({ mode: "legacy", reason: "route_failed" }));
+ .catch(() => ({
+ mode: "blocked",
+ reason: "route_failed",
+ detail: GATEWAY_TRANSIENT_DETAIL,
+ status: 503,
+ }));
if (abort.signal.aborted) return;
this.noteMode(
target,
- credential.mode === "legacy" ? "legacy" : "go",
- credential.mode === "legacy" ? credential.reason : undefined,
+ credential.mode,
+ credential.mode === "blocked" ? 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")
- ) {
+ if (credential.mode === "blocked" && path === "/v1/models") {
this.forwardOnLegacy(
target,
{ path, search, method, body },
@@ -166,8 +173,8 @@ export class GatewaySessionHandler {
return;
}
if (credential.mode === "blocked") {
- jsonError(res, 402, {
- type: "billing_error",
+ jsonError(res, credential.status, {
+ type: GATEWAY_BLOCKED_ERROR_TYPES[credential.status],
code: credential.reason,
message: credential.detail,
});
@@ -191,13 +198,13 @@ export class GatewaySessionHandler {
private noteMode(
target: SessionTarget,
- mode: "go" | "legacy",
+ mode: GatewayCredential["mode"],
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", {
+ this.deps.log.info("Gateway session route changed", {
projectId: target.projectId,
from: previous,
to: mode,
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.ts
index 96253078a63d..ec6521cde6d0 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
@@ -1,3 +1,5 @@
+import type { GatewayBlockedStatus } from "@posthog/shared";
+
export interface AuthProxyAuth {
authenticatedFetch(url: string, init?: RequestInit): Promise<Response>;
}
@@ -5,8 +7,12 @@ 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: "blocked";
+ reason: string;
+ detail: string;
+ status: GatewayBlockedStatus;
+ }
| {
mode: "go";
gatewayUrl: string;