: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): stop the app reloading when a Codex session fails to init (#89805)
Charles Vienb209e4511fc8
diff --git a/products/desktop/packages/api-client/src/fetcher.ts b/products/desktop/packages/api-client/src/fetcher.tsindex bc061a3030fd..9315cd279764 100644--- a/products/desktop/packages/api-client/src/fetcher.ts+++ b/products/desktop/packages/api-client/src/fetcher.ts@@ -35,6 +35,24 @@ export function requestErrorStatus(error: unknown): number | undefined {return error instanceof ApiRequestError ? error.status : undefined;}+// A 403 is a rejected token only when its body's `code` says so. A permission+// denial shares `type: "authentication_error"` but carries+// `code: "permission_denied"`, and a fresh token cannot fix it.+export async function isAuthFailureResponse(+ response: Response,+): Promise<boolean> {+ if (response.status === 401) return true;+ if (response.status !== 403) return false;+ try {+ const body = (await response.clone().json()) as {+ code?: string;+ } | null;+ return body?.code === "authentication_failed";+ } catch {+ return false;+ }+}+export const buildApiFetcher: (config: ApiFetcherConfig,) => Parameters<typeof createApiClient>[0] = (config) => {@@ -92,28 +110,11 @@ export const buildApiFetcher: (}};- const isAuthFailure = async (response: Response): Promise<boolean> => {- if (response.status === 401) return true;- if (response.status !== 403) return false;- try {- const body = (await response.clone().json()) as {- code?: string;- type?: string;- } | null;- return (- body?.code === "authentication_failed" ||- body?.type === "authentication_error"- );- } catch {- return false;- }- };-return {fetch: async (input) => {let response = await makeRequest(input, await config.getAccessToken());- if (!response.ok && (await isAuthFailure(response))) {+ if (!response.ok && (await isAuthFailureResponse(response))) {try {response = await makeRequest(input,diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.tsindex 3f0894860318..752fd9fad9a4 100644--- a/products/desktop/packages/core/src/auth/auth.test.ts+++ b/products/desktop/packages/core/src/auth/auth.test.ts@@ -153,7 +153,8 @@ describe("AuthService", () => {const stubAuthFetch = (options: {- accountKey?: string;+ /** `null` makes the account lookup fail, as a transient 5xx would. */+ accountKey?: string | null;currentOrgId?: string;orgs?: Record<string,@@ -163,7 +164,8 @@ describe("AuthService", () => {redeemInviteCodeResponse?: () => Response;} = {},) => {- const accountKey = options.accountKey ?? "user-1";+ const accountKey =+ options.accountKey === undefined ? "user-1" : options.accountKey;const currentOrgId = options.currentOrgId ?? "org-1";const orgs = options.orgs ?? {"org-1": { name: "Org 1", projects: [{ id: 42, name: "Project 42" }] },@@ -175,6 +177,13 @@ describe("AuthService", () => {const url = typeof input === "string" ? input : input.url;if (url.includes("/api/users/@me/")) {+ if (accountKey === null) {+ return {+ ok: false,+ status: 500,+ json: vi.fn().mockResolvedValue({}),+ } as unknown as Response;+ }return {ok: true,json: vi.fn().mockResolvedValue({@@ -406,6 +415,46 @@ describe("AuthService", () => {expect(oauthFlow.refreshToken).not.toHaveBeenCalled();});+ it.each([+ { name: "a 401", status: 401, body: null, refreshes: true },+ {+ name: "a 403 that reports an authentication failure",+ status: 403,+ body: { type: "authentication_error", code: "authentication_failed" },+ refreshes: true,+ },+ {+ name: "a 403 permission denial",+ status: 403,+ body: {+ type: "authentication_error",+ code: "permission_denied",+ detail: "You do not have permission to perform this action.",+ },+ refreshes: false,+ },+ ])(+ "refreshes the token and retries on $name only when the token was rejected",+ async ({ status, body, refreshes }) => {+ seedStoredSession({ selectedProjectId: 42 });+ stubAuthFetch();+ oauthFlow.refreshToken.mockResolvedValue(mockTokenResponse());+ await service.initialize();+ oauthFlow.refreshToken.mockClear();+ vi.mocked(fetch).mockResolvedValueOnce(+ new Response(body === null ? null : JSON.stringify(body), { status }),+ );++ const response = await service.authenticatedFetch(+ fetch,+ "https://us.posthog.com/api/restricted/",+ );++ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(refreshes ? 1 : 0);+ expect(response.ok).toBe(refreshes);+ },+ );+it("requires scope reauthentication when the stored scope version is stale", async () => {seedStoredSession({refreshToken: "refresh-token",@@ -2298,6 +2347,76 @@ describe("AuthService", () => {});});+ it.each([+ {+ name: "keeps the current result on screen while a refresh for the same account rechecks it",+ refreshedAccountKey: "user-1",+ 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",+ refreshedAccountKey: null as string | null,+ statusDuringRecheck: "allowed",+ },+ {+ name: "shows checking while a refresh that lands on another account rechecks",+ refreshedAccountKey: "user-2",+ statusDuringRecheck: "checking",+ },+ ])("$name", async ({ refreshedAccountKey, statusDuringRecheck }) => {+ let release!: () => void;+ const pending = new Promise<Response>((resolve) => {+ release = () => resolve(okBody({ allowed: true, reason: null }));+ });+ stubAuthFetch();+ 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 current result while a commit that leaves the project alone rechecks it", async () => {+ // Background org recovery commits the project it already had. Publishing+ // "checking" there unmounts the whole app after it finished loading.+ let release!: () => void;+ const pending = new Promise<Response>((resolve) => {+ release = () => resolve(okBody({ allowed: true, reason: null }));+ });+ stubAuthFetch();+ await service.initialize();+ expect(service.getState().desktopAccess.status).toBe("allowed");++ let checks = 0;+ stubAuthFetch({+ desktopAccessResponse: () => {+ checks += 1;+ return pending as unknown as Response;+ },+ });+ const selection = service.selectProject(42);+ await vi.waitFor(() => expect(checks).toBe(1));+ expect(service.getState().desktopAccess.status).toBe("allowed");++ release();+ await selection;+ expect(service.getState().desktopAccess.status).toBe("allowed");+ });+it("rechecks access after selecting an eligible project", async () => {const orgs = {"org-1": {diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.tsindex 90e02e5a9d33..c6501710a513 100644--- a/products/desktop/packages/core/src/auth/auth.ts+++ b/products/desktop/packages/core/src/auth/auth.ts@@ -1,3 +1,4 @@+import { isAuthFailureResponse } from "@posthog/api-client/fetcher";import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";import {type IPowerManager,@@ -251,7 +252,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {return response;}- if (response.status === 401 || response.status === 403) {+ if (await isAuthFailureResponse(response)) {const refreshedAuth = await this.refreshAccessToken();response = await this.executeAuthenticatedFetch(fetchImpl,@@ -453,17 +454,14 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {if (this.sessionGeneration !== sessionGeneration) {return;}+ const desktopAccess = this.carryDesktopAccessInto(nextSession);this.session = nextSession;this.persistProjectPreference(nextSession);this.updateState({orgProjectsMap: next.orgProjectsMap,currentOrgId: next.currentOrgId,currentProjectId: next.currentProjectId,- desktopAccess: {- projectId: next.currentProjectId,- status: "checking",- reason: null,- },+ desktopAccess,});await this.updateDesktopAccessFromSession(nextSession);}@@ -1127,6 +1125,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {return false;}this.persistProjectPreference(session);+ const desktopAccess = this.carryDesktopAccessInto(session);this.session = session;this.scheduleImpersonationExpiry(session);this.updateState({@@ -1136,11 +1135,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {orgProjectsMap: session.orgProjectsMap,currentOrgId: session.currentOrgId,currentProjectId: session.currentProjectId,- desktopAccess: {- projectId: session.currentProjectId,- status: "checking",- reason: null,- },+ desktopAccess,needsScopeReauth: false,sessionType: session.sessionType,sessionExpiresAt: session.accessTokenExpiresAt,@@ -1306,6 +1301,32 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {sessionEndReason: partial.sessionEndReason ?? null,});}++ // Resetting to "checking" on every refresh would unmount the whole app.+ 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 =+ previousAccountKey !== null &&+ (session.accountKey === null ||+ session.accountKey === previousAccountKey) &&+ previous.projectId === session.currentProjectId;+ if (+ sameIdentity &&+ (previous.status === "allowed" || previous.status === "blocked")+ ) {+ return previous;+ }+ return {+ projectId: session.currentProjectId,+ status: "checking",+ reason: null,+ };+ }+private async updateDesktopAccessFromSession(session: InMemorySession,): Promise<void> {diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.tsindex 9c7dfabdae78..2736284bf28d 100644--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.test.ts@@ -1,5 +1,12 @@import { existsSync, readFileSync, statSync } from "node:fs";-import { mkdir, mkdtemp, readlink, rm, writeFile } from "node:fs/promises";+import {+ mkdir,+ mkdtemp,+ readlink,+ rm,+ symlink,+ writeFile,+} from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -182,24 +189,63 @@ describe("prepareCodexHome", () => {expect(existsSync(path.join(homeB, "skills", "query-data"))).toBe(true);});- it("cleanupCodexHome removes the run's dir and is a no-op when absent", async () => {+ it("cleanupCodexHome drops what prepare built but keeps codex's thread rollouts", async () => {await createSkill(bundledSkillsDir, "query-data");+ const codexConfigDir = path.join(testHome.dir, ".codex");+ await mkdir(codexConfigDir, { recursive: true });+ await writeFile(+ path.join(codexConfigDir, "config.toml"),+ 'model = "gpt-5-codex"\n',+ );const codexHome = await prepareCodexHome({appDataPath,taskRunId,bundledSkillsDir,log: noopLog,});- expect(existsSync(codexHome)).toBe(true);+ const rollout = path.join(+ codexHome,+ "sessions",+ "2026",+ "08",+ "26",+ "rollout-2026-08-26T17-14-19-thread-1.jsonl",+ );+ await mkdir(path.dirname(rollout), { recursive: true });+ await writeFile(rollout, "{}\n");await cleanupCodexHome(appDataPath, taskRunId);- expect(existsSync(codexHome)).toBe(false);- expect(existsSync(getCodexHomeDir(appDataPath, taskRunId))).toBe(false);- // Second call on a now-absent dir must not throw.+ expect(existsSync(path.join(codexHome, "skills"))).toBe(false);+ expect(existsSync(path.join(codexHome, "config.toml"))).toBe(false);+ expect(existsSync(rollout)).toBe(true);+ });++ // Windows needs elevated rights to create a directory symlink.+ it.skipIf(process.platform === "win32")(+ "cleanupCodexHome unlinks a run home that is a link instead of emptying its target",+ async () => {+ const victim = path.join(root, "victim");+ await mkdir(victim, { recursive: true });+ await writeFile(path.join(victim, "keep.txt"), "keep me\n");+ const codexHome = getCodexHomeDir(appDataPath, taskRunId);+ await mkdir(path.dirname(codexHome), { recursive: true });+ await symlink(victim, codexHome, "dir");++ await cleanupCodexHome(appDataPath, taskRunId);++ expect(existsSync(codexHome)).toBe(false);+ expect(existsSync(path.join(victim, "keep.txt"))).toBe(true);+ },+ );++ it("cleanupCodexHome is a no-op when the run's dir was never created", async () => {await expect(- cleanupCodexHome(appDataPath, taskRunId),+ cleanupCodexHome(appDataPath, "never-prepared"),).resolves.toBeUndefined();+ expect(existsSync(getCodexHomeDir(appDataPath, "never-prepared"))).toBe(+ false,+ );});it("rejects an unsafe taskRunId instead of escaping the codex-home dir", async () => {diff --git a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts b/products/desktop/packages/workspace-server/src/services/agent/codex-home.tsindex beec0f703eba..dd88ea144e84 100644--- a/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/codex-home.ts@@ -25,17 +25,36 @@ export function getCodexHomeDir(}/**- * Removes a task run's private CODEX_HOME. Safe for any adapter — a no-op when- * the directory was never created.+ * Empties a task run's private CODEX_HOME except `sessions/`, the thread+ * rollouts `thread/resume` needs after the app relaunches. Safe for any+ * adapter — a no-op when the directory was never created.*/export async function cleanupCodexHome(appDataPath: string,taskRunId: string,): Promise<void> {- await fs.promises.rm(getCodexHomeDir(appDataPath, taskRunId), {- recursive: true,- force: true,- });+ const codexHome = getCodexHomeDir(appDataPath, taskRunId);+ // `readdir` resolves through a link, so deleting entry by entry would empty+ // whatever a link at this path points at. Remove the link itself instead.+ const stats = await fs.promises.lstat(codexHome).catch(() => null);+ if (stats === null) return;+ if (!stats.isDirectory()) {+ await fs.promises.rm(codexHome, { recursive: true, force: true });+ return;+ }+ let entries: string[];+ try {+ entries = await fs.promises.readdir(codexHome);+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry === "sessions") continue;+ await fs.promises.rm(path.join(codexHome, entry), {+ recursive: true,+ force: true,+ });+ }}/**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 6ca0d6afc47c..e950666a1ff1 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@@ -281,6 +281,30 @@ describe("McpProxyService", () => {expect(authServiceMock.authenticatedFetch).toHaveBeenCalledTimes(1);});+ it("does not refresh on a permission denial", async () => {+ // Permission denials share `type: "authentication_error"` with rejected+ // tokens; only a rejected token can be fixed by refreshing.+ authServiceMock.authenticatedFetch.mockResolvedValue(+ new Response(+ JSON.stringify({+ type: "authentication_error",+ code: "permission_denied",+ detail: "You do not have permission to perform this action.",+ }),+ { 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 bee677d32ad5..b3c359c13e8f 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@@ -324,10 +324,10 @@ export class McpProxyService {}private isAuthErrorBody(bodyText: string, status: number): boolean {- if (- bodyText.includes('"authentication_failed"') ||- bodyText.includes('"authentication_error"')- ) {+ // Only a rejected token carries `authentication_failed`. A permission denial+ // shares `type: "authentication_error"` but carries `code: "permission_denied"`,+ // and a fresh token cannot fix it, so it must not trigger a refresh.+ if (bodyText.includes('"authentication_failed"')) {return true;}if (status < 400) return false;