: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
fix(desktop): prevent app unmount during background access rechecks (#90550)
Adam Leith7eae6e14986d
diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.tsindex 187da21550eb..9e2c7933feea 100644--- a/products/desktop/packages/agent/src/posthog-api.test.ts+++ b/products/desktop/packages/agent/src/posthog-api.test.ts@@ -79,6 +79,31 @@ describe("PostHogAPIClient", () => {expect(mockFetch).toHaveBeenCalledTimes(2);});+ it("does not refresh or retry when the API answers 403", async () => {+ // A 403 is a permission denial a fresh token cannot fix. Forcing a+ // refresh on each one rotates the refresh token and rebuilds the whole+ // desktop session, which unmounts the app into its loading screen.+ const getApiKey = vi.fn().mockResolvedValue("token");+ const refreshApiKey = vi.fn().mockResolvedValue("fresh-token");+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey,+ refreshApiKey,+ projectId: 1,+ });+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 403,+ statusText: "Forbidden",+ json: vi.fn().mockResolvedValue({ detail: "forbidden" }),+ });++ await expect(client.getTaskRun("task-1", "run-1")).rejects.toThrow("[403]");++ expect(refreshApiKey).not.toHaveBeenCalled();+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+// The lookup gates session start, so a stalled socket must degrade to null// rather than hang. The bound is what makes the best-effort catch reachable.it("bounds the user-node lookup and returns null when it times out", async () => {diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex d49ca31e812b..a471f7475ba8 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -132,8 +132,12 @@ export class PostHogAPIClient {return host;}- private isAuthFailure(status: number): boolean {- return status === 401 || status === 403;+ private isTokenRejection(status: number): boolean {+ // 401 means the token is invalid or expired, which a forced refresh+ // fixes. 403 means the credential lacks permission; a refresh from the+ // same grant cannot gain any, and forcing one on every 403 rotates the+ // refresh token and rebuilds the whole desktop session.+ return status === 401;}private async resolveApiKey(forceRefresh = false): Promise<string> {@@ -179,7 +183,7 @@ export class PostHogAPIClient {): Promise<Response> {let response = await this.performRequest(endpoint, options);- if (!response.ok && this.isAuthFailure(response.status)) {+ if (!response.ok && this.isTokenRejection(response.status)) {response = await this.performRequest(endpoint, options, true);}diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.tsindex f04d7b941cfa..847ed6f9443f 100644--- a/products/desktop/packages/core/src/auth/auth.test.ts+++ b/products/desktop/packages/core/src/auth/auth.test.ts@@ -2315,32 +2315,82 @@ describe("AuthService", () => {it.each([{name: "keeps the current result on screen while a refresh for the same account rechecks it",- refreshedAccountKey: "user-1",+ bootAccountKey: "user-1" as string | null,+ refreshedAccountKey: "user-1" as string | null,statusDuringRecheck: "allowed",},{// A failed account lookup is an unknown account, not another one.name: "keeps the current result on screen while a refresh whose account lookup failed rechecks it",+ bootAccountKey: "user-1" as string | null,refreshedAccountKey: null as string | null,statusDuringRecheck: "allowed",},+ {+ // Same on the other side: a boot whose lookup failed must not turn+ // every later refresh into a full-app remount.+ name: "keeps the current result on screen when the boot account lookup failed and a refresh resolves one",+ bootAccountKey: null as string | null,+ refreshedAccountKey: "user-1" as string | null,+ statusDuringRecheck: "allowed",+ },{name: "shows checking while a refresh that lands on another account rechecks",- refreshedAccountKey: "user-2",+ bootAccountKey: "user-1" as string | null,+ refreshedAccountKey: "user-2" as string | null,statusDuringRecheck: "checking",},- ])("$name", async ({ refreshedAccountKey, statusDuringRecheck }) => {+ ])(+ "$name",+ async ({ bootAccountKey, refreshedAccountKey, statusDuringRecheck }) => {+ let release!: () => void;+ const pending = new Promise<Response>((resolve) => {+ release = () => resolve(okBody({ allowed: true, reason: null }));+ });+ stubAuthFetch({ accountKey: bootAccountKey });+ await service.initialize();+ expect(service.getState().desktopAccess.status).toBe("allowed");++ let checks = 0;+ stubAuthFetch({+ accountKey: refreshedAccountKey,+ desktopAccessResponse: () => {+ checks += 1;+ return pending as unknown as Response;+ },+ });+ const refresh = service.refreshAccessToken();+ await vi.waitFor(() => expect(checks).toBe(1));+ expect(service.getState().desktopAccess.status).toBe(+ statusDuringRecheck,+ );++ release();+ await refresh;+ expect(service.getState().desktopAccess.status).toBe("allowed");+ },+ );++ it("keeps the live project and settled access when a refresh rebuild omits the project", async () => {+ // One 4xx or timeout on a per-org or per-team fetch during a token+ // refresh rebuilds the map without the project the app is showing.+ // Adopting the fallback selection then swaps the project and unmounts+ // the whole app. The #88289 test covers the initialize path with no+ // live session; this one covers a refresh over a live session.let release!: () => void;const pending = new Promise<Response>((resolve) => {release = () => resolve(okBody({ allowed: true, reason: null }));});stubAuthFetch();await service.initialize();+ expect(service.getState().currentProjectId).toBe(42);expect(service.getState().desktopAccess.status).toBe("allowed");let checks = 0;stubAuthFetch({- accountKey: refreshedAccountKey,+ orgs: {+ "org-1": { name: "Org 1", projects: [{ id: 7, name: "Project 7" }] },+ },desktopAccessResponse: () => {checks += 1;return pending as unknown as Response;@@ -2348,10 +2398,62 @@ describe("AuthService", () => {});const refresh = service.refreshAccessToken();await vi.waitFor(() => expect(checks).toBe(1));- expect(service.getState().desktopAccess.status).toBe(statusDuringRecheck);+ expect(service.getState().currentProjectId).toBe(42);+ expect(service.getState().desktopAccess.status).toBe("allowed");release();await refresh;+ expect(service.getState().currentProjectId).toBe(42);+ expect(service.getState().desktopAccess.status).toBe("allowed");+ });++ it.each([+ {+ // Dropping an allowed result because the session object rotated+ // mid-check leaves the published state on "checking", which keeps the+ // whole app unmounted until the rotation's own check answers.+ name: "applies an allowed check that finished after a same-identity rotation",+ staleResponse: () => okBody({ allowed: true, reason: null }),+ statusAfterStale: "allowed",+ },+ {+ // A timeout or a rejected old token on the stale check must not+ // publish "error" and unmount the app while the rotation's own+ // healthy check is still pending.+ name: "drops a failed check that finished after a same-identity rotation",+ staleResponse: () =>+ ({+ ok: false,+ status: 500,+ json: vi.fn().mockResolvedValue({}),+ }) as unknown as Response,+ statusAfterStale: "checking",+ },+ ])("$name", async ({ staleResponse, statusAfterStale }) => {+ stubAuthFetch();+ await service.initialize();+ expect(service.getState().desktopAccess.status).toBe("allowed");++ const releases: Array<(response: Response) => void> = [];+ stubAuthFetch({+ desktopAccessResponse: () =>+ new Promise<Response>((resolve) => {+ releases.push(resolve);+ }) as unknown as Response,+ });+ const retry = service.retryDesktopAccess();+ await vi.waitFor(() => expect(releases.length).toBe(1));+ expect(service.getState().desktopAccess.status).toBe("checking");++ const refresh = service.refreshAccessToken();+ await vi.waitFor(() => expect(releases.length).toBe(2));++ releases[0](staleResponse());+ await retry;+ expect(service.getState().desktopAccess.status).toBe(statusAfterStale);++ releases[1](okBody({ allowed: true, reason: null }));+ await refresh;expect(service.getState().desktopAccess.status).toBe("allowed");});diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.tsindex 08037be0f179..7e2e02de5160 100644--- a/products/desktop/packages/core/src/auth/auth.ts+++ b/products/desktop/packages/core/src/auth/auth.ts@@ -845,7 +845,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {: null;const preferredProjectId =options.selectedProjectId ?? lastPrefs?.lastSelectedProjectId ?? null;- const selection = this.reconcileInitialSelection({+ let selection = this.reconcileInitialSelection({orgProjectsMap,currentOrgId,preferredProjectId,@@ -858,6 +858,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {) {selection.currentProjectId = null;}+ selection = this.retainLiveProjectSelection(selection, preferredProjectId);const refreshToken =tokenResponse.refresh_token ?? options.fallbackRefreshToken ?? null;@@ -877,6 +878,30 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {return session;}+ // A background rebuild must not move the app off its live project. Partial+ // map rebuilds omit projects (one per-team or per-org fetch can 4xx or time+ // out), and adopting the fallback selection here replaces or nulls the+ // project, which unmounts the whole app and strands the user elsewhere. The+ // map is picker data; the desktop access check enforces access to the kept+ // project.+ private retainLiveProjectSelection(+ selection: { currentOrgId: string | null; currentProjectId: number | null },+ preferredProjectId: number | null,+ ): { currentOrgId: string | null; currentProjectId: number | null } {+ const liveSession = this.session;+ if (+ !liveSession ||+ liveSession.currentProjectId === null ||+ preferredProjectId !== liveSession.currentProjectId ||+ selection.currentProjectId === liveSession.currentProjectId+ ) {+ return selection;+ }+ return {+ currentProjectId: liveSession.currentProjectId,+ currentOrgId: liveSession.currentOrgId ?? selection.currentOrgId,+ };+ }private async buildOrgProjectsMap(accessToken: string,cloudRegion: CloudRegion,@@ -1283,14 +1308,16 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {private carryDesktopAccessInto(session: InMemorySession): DesktopAccess {const previous = this.state.desktopAccess;const previousAccountKey = this.session?.accountKey ?? null;- // A failed `/api/users/@me/` lookup leaves accountKey null. That is an- // unknown account, not a different one, so it must not flash the loading- // screen. A resolved key that differs is a real account change.- const sameIdentity =+ // A failed `/api/users/@me/` lookup leaves accountKey null on either+ // side. That is an unknown account, not a different one, so it must not+ // flash the loading screen. Only two resolved keys that differ prove the+ // refresh landed on another account.+ const accountChanged =previousAccountKey !== null &&- (session.accountKey === null ||- session.accountKey === previousAccountKey) &&- previous.projectId === session.currentProjectId;+ session.accountKey !== null &&+ session.accountKey !== previousAccountKey;+ const sameIdentity =+ !accountChanged && previous.projectId === session.currentProjectId;if (sameIdentity &&(previous.status === "allowed" || previous.status === "blocked")@@ -1308,7 +1335,31 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {session: InMemorySession,): Promise<void> {const desktopAccess = await this.checkDesktopAccess(session);- if (this.session !== session) return;+ if (this.session !== session) {+ // The session rotated while the check was in flight. The result is+ // scoped to (account, project): when the rotation kept both and nothing+ // newer has answered, an "allowed" result still applies, and dropping+ // it would leave the published state on "checking" until the rotation's+ // own check answers. Only "allowed" may apply from a stale check: every+ // rotation runs its own check, so a stale failure or denial (a timeout+ // on the old request, a rejected old token) must wait for that newer+ // check instead of unmounting the app with a result the newer check+ // will overturn.+ const current = this.session;+ const accountChanged =+ current !== null &&+ current.accountKey !== null &&+ session.accountKey !== null &&+ current.accountKey !== session.accountKey;+ const stillAnswers =+ current !== null &&+ !accountChanged &&+ current.currentProjectId === session.currentProjectId &&+ desktopAccess.status === "allowed" &&+ this.state.desktopAccess.status === "checking" &&+ this.state.desktopAccess.projectId === session.currentProjectId;+ if (!stillAnswers) return;+ }this.updateState({ desktopAccess });}@@ -1553,16 +1604,20 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {: null;const storedSelected =this.authSession.getCurrent()?.selectedProjectId ?? null;- const selection = this.reconcileInitialSelection({- orgProjectsMap: map,- currentOrgId: session.currentOrgId,- preferredProjectId:- session.currentProjectId ??- storedSelected ??- lastPrefs?.lastSelectedProjectId ??- null,- lastSelectedOrgId: lastPrefs?.lastSelectedOrgId ?? null,- });+ const preferredProjectId =+ session.currentProjectId ??+ storedSelected ??+ lastPrefs?.lastSelectedProjectId ??+ null;+ const selection = this.retainLiveProjectSelection(+ this.reconcileInitialSelection({+ orgProjectsMap: map,+ currentOrgId: session.currentOrgId,+ preferredProjectId,+ lastSelectedOrgId: lastPrefs?.lastSelectedOrgId ?? null,+ }),+ preferredProjectId,+ );await this.commitSessionState(session, {orgProjectsMap: map,currentOrgId: selection.currentOrgId,diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsxindex 278a3502a9db..b23eefce578a 100644--- a/products/desktop/packages/ui/src/shell/App.tsx+++ b/products/desktop/packages/ui/src/shell/App.tsx@@ -30,6 +30,10 @@ import { UpdateBanner } from "@posthog/ui/features/sidebar/components/UpdateBannimport { PendingPromptRecovery } from "@posthog/ui/features/task-detail/components/PendingPromptRecovery";import { router } from "@posthog/ui/router/router";import { AppLoadingScreen } from "@posthog/ui/shell/AppLoadingScreen";+import {+ isBackgroundAccessRecheck,+ nextLastAllowedProjectId,+} from "@posthog/ui/shell/desktopAccessGate";import { ErrorBoundary } from "@posthog/ui/shell/ErrorBoundary";import { ensureSession } from "@posthog/ui/shell/firstRun";import { logger } from "@posthog/ui/shell/logger";@@ -67,6 +71,36 @@ function App({ devToolbar }: AppProps) {desktopAccess.projectId === authState.currentProjectId;const hasDesktopAccess =desktopAccessIsCurrent && desktopAccess.status === "allowed";+ // Once the app has shown for a project, a background access recheck for+ // that same project must not unmount it into the loading screen (see+ // isBackgroundAccessRecheck). The ref updates in an effect, so when a+ // "checking" flip renders it still holds the project from the last settled+ // render.+ const lastAllowedProjectRef = useRef<number | null>(null);+ useEffect(() => {+ lastAllowedProjectRef.current = nextLastAllowedProjectId(+ lastAllowedProjectRef.current,+ {+ isAuthenticated,+ currentProjectId: authState.currentProjectId,+ accessIsCurrent: desktopAccessIsCurrent,+ accessStatus: desktopAccess.status,+ },+ );+ }, [+ isAuthenticated,+ authState.currentProjectId,+ desktopAccessIsCurrent,+ desktopAccess.status,+ ]);+ const isRevalidatingAccess =+ desktopAccessIsCurrent &&+ isBackgroundAccessRecheck(+ lastAllowedProjectRef.current,+ authState.currentProjectId,+ desktopAccess.status,+ );+ const settledDesktopAccess = hasDesktopAccess || isRevalidatingAccess;const switchError =selectProjectMutation.isError || switchOrgMutation.isError? "Couldn't switch your selection. Try again."@@ -84,19 +118,20 @@ function App({ devToolbar }: AppProps) {desktopAccessIsCurrent &&["blocked", "error"].includes(desktopAccess.status);const authenticatedClient = useOptionalAuthenticatedClient();- const consent = useOrgConsent(isAuthenticated && hasDesktopAccess);+ const consent = useOrgConsent(isAuthenticated && settledDesktopAccess);const needsConsent =isAuthenticated &&hasCompletedOnboarding &&- hasDesktopAccess &&+ settledDesktopAccess &&consent.status === "resolved" &&!consent.satisfied;const isCheckingAccess =isAuthenticated &&hasCompletedOnboarding &&(!desktopAccessIsCurrent ||- ["unchecked", "checking"].includes(desktopAccess.status) ||- (hasDesktopAccess && consent.status === "loading"));+ (["unchecked", "checking"].includes(desktopAccess.status) &&+ !isRevalidatingAccess) ||+ (settledDesktopAccess && consent.status === "loading"));const { isAdmin: isOrgAdmin } = useIsOrgAdmin();const isAdmin = isOrgAdmin === true;useConsentAnalytics(@@ -115,7 +150,7 @@ function App({ devToolbar }: AppProps) {isBootstrapped &&isAuthenticated &&hasCompletedOnboarding &&- hasDesktopAccess &&+ settledDesktopAccess &&consent.status === "resolved" &&consent.satisfied;const startupIdentity = getAuthIdentity(authState);diff --git a/products/desktop/packages/ui/src/shell/desktopAccessGate.test.ts b/products/desktop/packages/ui/src/shell/desktopAccessGate.test.tsnew file mode 100644index 000000000000..23d29e111f9e--- /dev/null+++ b/products/desktop/packages/ui/src/shell/desktopAccessGate.test.ts@@ -0,0 +1,166 @@+import { describe, expect, it } from "vitest";+import {+ isBackgroundAccessRecheck,+ nextLastAllowedProjectId,+} from "./desktopAccessGate";++describe("desktopAccessGate", () => {+ describe("isBackgroundAccessRecheck", () => {+ it.each([+ {+ name: "recheck of the project the app already showed",+ lastAllowedProjectId: 42,+ currentProjectId: 42,+ accessStatus: "checking" as const,+ expected: true,+ },+ {+ name: "recheck after a project change",+ lastAllowedProjectId: 42,+ currentProjectId: 7,+ accessStatus: "checking" as const,+ expected: false,+ },+ {+ name: "first check with no previously allowed project",+ lastAllowedProjectId: null,+ currentProjectId: 42,+ accessStatus: "checking" as const,+ expected: false,+ },+ {+ name: "settled allowed result",+ lastAllowedProjectId: 42,+ currentProjectId: 42,+ accessStatus: "allowed" as const,+ expected: false,+ },+ {+ name: "settled blocked result",+ lastAllowedProjectId: 42,+ currentProjectId: 42,+ accessStatus: "blocked" as const,+ expected: false,+ },+ {+ name: "settled error result",+ lastAllowedProjectId: 42,+ currentProjectId: 42,+ accessStatus: "error" as const,+ expected: false,+ },+ {+ name: "unchecked state after a reset",+ lastAllowedProjectId: 42,+ currentProjectId: 42,+ accessStatus: "unchecked" as const,+ expected: false,+ },+ ])(+ "$name",+ ({ lastAllowedProjectId, currentProjectId, accessStatus, expected }) => {+ expect(+ isBackgroundAccessRecheck(+ lastAllowedProjectId,+ currentProjectId,+ accessStatus,+ ),+ ).toBe(expected);+ },+ );+ });++ describe("nextLastAllowedProjectId", () => {+ it.each([+ {+ name: "records the project on an allowed result",+ previous: null,+ state: {+ isAuthenticated: true,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "allowed" as const,+ },+ expected: 42,+ },+ {+ name: "clears on a settled blocked result",+ previous: 42,+ state: {+ isAuthenticated: true,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "blocked" as const,+ },+ expected: null,+ },+ {+ name: "clears on a settled error result",+ previous: 42,+ state: {+ isAuthenticated: true,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "error" as const,+ },+ expected: null,+ },+ {+ name: "clears on sign-out",+ previous: 42,+ state: {+ isAuthenticated: false,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "allowed" as const,+ },+ expected: null,+ },+ {+ name: "keeps the marker through a recheck",+ previous: 42,+ state: {+ isAuthenticated: true,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "checking" as const,+ },+ expected: 42,+ },+ {+ name: "keeps the marker while the access record lags a project switch",+ previous: 42,+ state: {+ isAuthenticated: true,+ currentProjectId: 7,+ accessIsCurrent: false,+ accessStatus: "blocked" as const,+ },+ expected: 42,+ },+ ])("$name", ({ previous, state, expected }) => {+ expect(nextLastAllowedProjectId(previous, state)).toBe(expected);+ });++ it("gates a retry from the denial screen instead of mounting the app", () => {+ // allowed -> blocked -> retry publishes "checking" for the same+ // project. Without the clear on "blocked", the retry counts as a+ // background recheck and the whole app mounts before the check answers.+ const afterAllowed = nextLastAllowedProjectId(null, {+ isAuthenticated: true,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "allowed",+ });+ const afterBlocked = nextLastAllowedProjectId(afterAllowed, {+ isAuthenticated: true,+ currentProjectId: 42,+ accessIsCurrent: true,+ accessStatus: "blocked",+ });+ expect(isBackgroundAccessRecheck(afterBlocked, 42, "checking")).toBe(+ false,+ );+ });+ });+});diff --git a/products/desktop/packages/ui/src/shell/desktopAccessGate.ts b/products/desktop/packages/ui/src/shell/desktopAccessGate.tsnew file mode 100644index 000000000000..808e53b4ffd7--- /dev/null+++ b/products/desktop/packages/ui/src/shell/desktopAccessGate.ts@@ -0,0 +1,49 @@+import type { AuthState } from "@posthog/core/auth/schemas";++type DesktopAccessStatus = AuthState["desktopAccess"]["status"];++/**+ * True while the desktop access check re-runs for a project the app already+ * showed with access allowed. Token refreshes and session recovery flip the+ * access status back to "checking"; gating the app on that flip replaces the+ * running app with the full-window loading screen. A first load (no+ * previously allowed project) and a project change still gate, and a settled+ * "blocked" or "error" result still swaps to the access screen.+ */+export function isBackgroundAccessRecheck(+ lastAllowedProjectId: number | null,+ currentProjectId: number | null,+ accessStatus: DesktopAccessStatus,+): boolean {+ return (+ accessStatus === "checking" &&+ lastAllowedProjectId !== null &&+ lastAllowedProjectId === currentProjectId+ );+}++/**+ * The next value of the last-allowed-project marker after an auth state+ * change. The marker holds the project the app already showed with access+ * allowed, which is what lets isBackgroundAccessRecheck keep the app+ * mounted. A settled "blocked" or "error" result ends that grace: the next+ * "checking" for the project is a retry from the denial screen, and the app+ * must not mount before that check answers.+ */+export function nextLastAllowedProjectId(+ previous: number | null,+ state: {+ isAuthenticated: boolean;+ currentProjectId: number | null;+ accessIsCurrent: boolean;+ accessStatus: DesktopAccessStatus;+ },+): number | null {+ if (!state.isAuthenticated) return null;+ if (!state.accessIsCurrent) return previous;+ if (state.accessStatus === "allowed") return state.currentProjectId;+ if (state.accessStatus === "blocked" || state.accessStatus === "error") {+ return null;+ }+ return previous;+}diff --git a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.tsindex e950666a1ff1..aaf23a6e6a41 100644--- a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts+++ b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts@@ -305,6 +305,26 @@ describe("McpProxyService", () => {expect(authServiceMock.authenticatedFetch).toHaveBeenCalledTimes(1);});+ it("does not refresh on a 403 with a generic auth failure body", async () => {+ // A refresh cannot add permissions, and each forced one rotates the+ // refresh token and rebuilds the whole desktop session.+ authServiceMock.authenticatedFetch.mockResolvedValue(+ new Response('{"error":"Invalid API key"}', {+ status: 403,+ headers: { "content-type": "application/json" },+ }),+ );++ await service.start();+ const proxyUrl = service.register("alpha", "https://upstream.example");++ const res = await fetch(proxyUrl, { method: "POST", body: "payload" });++ expect(res.status).toBe(403);+ expect(authServiceMock.refreshAccessToken).not.toHaveBeenCalled();+ expect(authServiceMock.authenticatedFetch).toHaveBeenCalledTimes(1);+ });+it("does not retry when the body looks healthy", async () => {authServiceMock.authenticatedFetch.mockResolvedValue(new Response('{"ok":true}', {diff --git a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.tsindex b3c359c13e8f..662c97b74200 100644--- a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts+++ b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts@@ -330,7 +330,11 @@ export class McpProxyService {if (bodyText.includes('"authentication_failed"')) {return true;}- if (status < 400) return false;+ // Same rule for servers that answer with plain text: only a 401 signals a+ // rejected token. A 403 is a permission denial a refresh cannot fix, and+ // each forced refresh rotates the refresh token and rebuilds the whole+ // desktop session.+ if (status !== 401) return false;return (bodyText.includes("Invalid API key") ||bodyText.includes("Authentication failed")