:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): enforce project-scoped desktop access (#87165)
Jonathan Mieloo5d54be62c320
diff --git a/products/desktop/apps/code/scripts/quick-ask-e2e.mts b/products/desktop/apps/code/scripts/quick-ask-e2e.mtsindex 61b71c947429..efaddf28d0c6 100644--- a/products/desktop/apps/code/scripts/quick-ask-e2e.mts+++ b/products/desktop/apps/code/scripts/quick-ask-e2e.mts@@ -157,7 +157,7 @@ await page.addInitScript(`orgProjectsMap: {},currentOrgId: "org-1",currentProjectId: 2,- hasCodeAccess: true,+ desktopAccess: { projectId: 2, status: "allowed", reason: null },needsScopeReauth: false,sessionType: "desktop",sessionExpiresAt: null,diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.tsindex 498d276f4ba9..5d289af94e09 100644--- a/products/desktop/packages/core/src/auth/auth.test.ts+++ b/products/desktop/packages/core/src/auth/auth.test.ts@@ -159,9 +159,8 @@ describe("AuthService", () => {string,{ name: string; projects: { id: number; name: string }[] }>;- // Overrides the /api/code/invites/check-access/ response (defaults to- // granting access). May throw to simulate a network error.- checkAccess?: () => Response;+ desktopAccessResponse?: (url: string) => Response;+ redeemInviteCodeResponse?: () => Response;} = {},) => {const accountKey = options.accountKey ?? "user-1";@@ -197,12 +196,19 @@ describe("AuthService", () => {} as unknown as Response;}- if (options.checkAccess) {- return options.checkAccess();+ if (+ url.includes("/api/code/invites/redeem/") &&+ options.redeemInviteCodeResponse+ ) {+ return options.redeemInviteCodeResponse();+ }++ if (options.desktopAccessResponse) {+ return options.desktopAccessResponse(url);}return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -247,7 +253,7 @@ describe("AuthService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: null,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,sessionType: null,sessionExpiresAt: null,@@ -416,7 +422,7 @@ describe("AuthService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: 123,- hasCodeAccess: null,+ desktopAccess: { projectId: 123, status: "unchecked", reason: null },needsScopeReauth: true,sessionType: null,sessionExpiresAt: null,@@ -461,7 +467,7 @@ describe("AuthService", () => {},currentOrgId: "org-1",currentProjectId: 42,- hasCodeAccess: true,+ desktopAccess: { projectId: 42, status: "allowed", reason: null },needsScopeReauth: false,});@@ -857,6 +863,108 @@ describe("AuthService", () => {expect(preferencePort.get("user-1", "us")?.lastSelectedProjectId).toBe(99);});+ it("does not restore a session when logout races with an OAuth login", async () => {+ let releaseOAuthFlow = (): void => {};+ oauthFlow.startFlow.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseOAuthFlow = () =>+ resolve(+ mockTokenResponse({+ accessToken: "initial-access-token",+ refreshToken: "initial-refresh-token",+ }),+ );+ }),+ );+ stubAuthFetch();+ await service.initialize();++ const login = service.login("us");+ await new Promise((resolve) => setTimeout(resolve, 0));+ await service.logout();+ releaseOAuthFlow();+ await login;++ expect(service.getState().status).toBe("anonymous");+ expect(sessionPort.getCurrent()).toBeNull();+ });++ it("does not restore a stored session when logout races with refresh", async () => {+ seedStoredSession();+ let releaseRefresh = (): void => {};+ oauthFlow.refreshToken.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseRefresh = () => resolve(mockTokenResponse());+ }),+ );+ stubAuthFetch();++ const initialize = service.initialize();+ await new Promise((resolve) => setTimeout(resolve, 0));+ await service.logout();+ releaseRefresh();+ await initialize;++ expect(service.getState().status).toBe("anonymous");+ expect(sessionPort.getCurrent()).toBeNull();+ });++ it("does not restore a session when logout races with a project selection", async () => {+ const orgs = {+ "org-1": {+ name: "Org 1",+ projects: [+ { id: 42, name: "Project 42" },+ { id: 84, name: "Project 84" },+ ],+ },+ };+ oauthFlow.startFlow.mockResolvedValue(+ mockTokenResponse({+ accessToken: "initial-access-token",+ refreshToken: "initial-refresh-token",+ }),+ );+ stubAuthFetch({ orgs });++ let releaseEncryption = (): void => {};+ let deferEncrypt = false;+ const gatedCipher: IAuthTokenCipher = {+ encrypt: (plaintext) =>+ deferEncrypt+ ? new Promise<string>((resolve) => {+ releaseEncryption = () => resolve(plaintext);+ })+ : Promise.resolve(plaintext),+ decrypt: (encrypted) => Promise.resolve(encrypted),+ };+ service = new AuthService(+ preferencePort,+ sessionPort,+ oauthFlow as unknown as IAuthOAuthFlowService,+ connectivity,+ gatedCipher,+ mockPowerManager as unknown as IPowerManager,+ mockLogger,+ null,+ );+ service.init();+ await service.initialize();+ await service.login("us");++ deferEncrypt = true;+ const selection = service.selectProject(84);+ await new Promise((resolve) => setTimeout(resolve, 0));+ await service.logout();+ releaseEncryption();+ await selection;++ expect(service.getState().status).toBe("anonymous");+ expect(sessionPort.getCurrent()).toBeNull();+ });+it("restores the selected project after app restart while logged out", async () => {const orgs = {"org-1": {@@ -1216,7 +1324,7 @@ describe("AuthService", () => {return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1279,7 +1387,7 @@ describe("AuthService", () => {return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1333,7 +1441,7 @@ describe("AuthService", () => {return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1383,7 +1491,7 @@ describe("AuthService", () => {return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1485,7 +1593,7 @@ describe("AuthService", () => {}return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1570,7 +1678,7 @@ describe("AuthService", () => {}return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1719,7 +1827,7 @@ describe("AuthService", () => {return {ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),+ json: vi.fn().mockResolvedValue({ allowed: true, reason: null }),} as unknown as Response;}) as unknown as typeof fetch,);@@ -1856,69 +1964,11 @@ describe("AuthService", () => {});});- describe("redeemInviteCode uses authenticatedFetch", () => {- it("retries on 401 via authenticatedFetch", async () => {- oauthFlow.startFlow.mockResolvedValue(- mockTokenResponse({- accessToken: "initial-token",- refreshToken: "refresh-token",- }),- );- oauthFlow.refreshToken.mockResolvedValue(- mockTokenResponse({- accessToken: "refreshed-token",- refreshToken: "new-refresh-token",- }),- );-- let redeemCallCount = 0;- vi.stubGlobal(- "fetch",- vi.fn(async (input: string | Request) => {- const url = typeof input === "string" ? input : input.url;-- if (url.includes("/api/users/@me/")) {- return {- ok: true,- json: vi.fn().mockResolvedValue({ uuid: "user-1" }),- } as unknown as Response;- }-- if (url.includes("/invites/redeem/")) {- redeemCallCount++;- if (redeemCallCount === 1) {- return {- ok: false,- status: 401,- json: () => Promise.resolve({}),- } as unknown as Response;- }- return {- ok: true,- status: 200,- json: () => Promise.resolve({ success: true }),- } as unknown as Response;- }-- return {- ok: true,- json: vi.fn().mockResolvedValue({ has_access: true }),- } as unknown as Response;- }) as unknown as typeof fetch,- );-- await service.login("us");- const state = await service.redeemInviteCode("test-code");-- expect(state.hasCodeAccess).toBe(true);- expect(redeemCallCount).toBe(2);- });- });-- describe("code access resilience", () => {+ describe("desktop access", () => {const okBody = (body: unknown): Response =>({ok: true,+ status: 200,json: vi.fn().mockResolvedValue(body),}) as unknown as Response;@@ -1934,86 +1984,143 @@ describe("AuthService", () => {it.each([{- name: "grants access when the server reports has_access true",- checkAccess: () => okBody({ has_access: true }),- expected: true,+ name: "allows an eligible project",+ payload: { allowed: true, reason: null },+ status: "allowed",+ reason: null,},{- name: "denies access when the server explicitly reports no access",- checkAccess: () => okBody({ has_access: false }),- expected: false,+ name: "preserves a legacy access denial",+ payload: { allowed: false, reason: null },+ status: "blocked",+ reason: null,},{- name: "stays indeterminate when the check throws",- checkAccess: () => {- throw new Error("network down");- },- expected: null,+ name: "blocks a Startup project",+ payload: { allowed: false, reason: "startup_plan" },+ status: "blocked",+ reason: "startup_plan",},{- name: "stays indeterminate on a 2xx response without a has_access flag",- checkAccess: () => okBody({}),- expected: null,+ name: "blocks a project with prepaid credits",+ payload: { allowed: false, reason: "prepaid_credits" },+ status: "blocked",+ reason: "prepaid_credits",},- ])("$name", async ({ checkAccess, expected }) => {- stubAuthFetch({ checkAccess });+ {+ name: "shows an error for a malformed response",+ payload: {},+ status: "error",+ reason: null,+ },+ ] as const)("$name", async ({ payload, status, reason }) => {+ stubAuthFetch({ desktopAccessResponse: () => okBody(payload) });await service.initialize();- const state = service.getState();- expect(state.status).toBe("authenticated");- expect(state.hasCodeAccess).toBe(expected);+ expect(service.getState().desktopAccess).toEqual({+ projectId: 42,+ status,+ reason,+ });});- it.each([- {- name: "a network error",- fail: (): Response => {+ it("shows an error when the access request fails", async () => {+ stubAuthFetch({+ desktopAccessResponse: () => {throw new Error("network down");},- },- {- name: "a 401",- fail: (): Response =>- ({- ok: false,- status: 401,- json: vi.fn().mockResolvedValue({}),- }) as unknown as Response,- },- ])(- "keeps a confirmed grant when a later check hits $name",- async ({ fail }) => {- let shouldFail = false;- stubAuthFetch({- checkAccess: () =>- shouldFail ? fail() : okBody({ has_access: true }),- });+ });- await service.initialize();- expect(service.getState().hasCodeAccess).toBe(true);+ await service.initialize();- shouldFail = true;- await service.refreshAccessToken();+ expect(service.getState().desktopAccess).toEqual({+ projectId: 42,+ status: "error",+ reason: null,+ });+ });- expect(service.getState().hasCodeAccess).toBe(true);- },- );+ it("retries after a technical failure", async () => {+ let available = false;+ stubAuthFetch({+ desktopAccessResponse: () => {+ if (!available) throw new Error("network down");+ return okBody({ allowed: true, reason: null });+ },+ });++ await service.initialize();+ expect(service.getState().desktopAccess.status).toBe("error");++ available = true;+ const state = await service.retryDesktopAccess();++ expect(state.desktopAccess).toEqual({+ projectId: 42,+ status: "allowed",+ reason: null,+ });+ });- it("recovers within the retry loop when a later attempt succeeds", async () => {- let attempts = 0;+ it("rechecks access after redeeming a legacy invite code", async () => {+ let redeemed = false;stubAuthFetch({- checkAccess: () => {- attempts += 1;- if (attempts === 1) throw new Error("transient");- return okBody({ has_access: true });+ redeemInviteCodeResponse: () => {+ redeemed = true;+ return okBody({ success: true });},+ desktopAccessResponse: () =>+ okBody(+ redeemed+ ? { allowed: true, reason: null }+ : { allowed: false, reason: null },+ ),});await service.initialize();+ expect(service.getState().desktopAccess.status).toBe("blocked");- expect(service.getState().hasCodeAccess).toBe(true);- expect(attempts).toBeGreaterThanOrEqual(2);+ const state = await service.redeemInviteCode("test-code");++ expect(state.desktopAccess).toEqual({+ projectId: 42,+ status: "allowed",+ reason: null,+ });+ });++ it("rechecks access after selecting an eligible project", async () => {+ const orgs = {+ "org-1": {+ name: "Org 1",+ projects: [+ { id: 1, name: "Blocked" },+ { id: 2, name: "Allowed" },+ ],+ },+ };+ oauthFlow.refreshToken.mockResolvedValue(+ mockTokenResponse({ scopedOrgs: ["org-1"] }),+ );+ stubAuthFetch({+ orgs,+ desktopAccessResponse: (url) =>+ url.includes("/projects/2/")+ ? okBody({ allowed: true, reason: null })+ : okBody({ allowed: false, reason: "startup_plan" }),+ });++ await service.initialize();+ expect(service.getState().desktopAccess.status).toBe("blocked");++ const state = await service.selectProject(2);++ expect(state.desktopAccess).toEqual({+ projectId: 2,+ status: "allowed",+ reason: null,+ });});});});diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.tsindex 5f3fc4cd1647..1fdd07ad5891 100644--- a/products/desktop/packages/core/src/auth/auth.ts+++ b/products/desktop/packages/core/src/auth/auth.ts@@ -32,6 +32,8 @@ import {type AuthServiceEvents,type AuthState,type AuthTokenResponse,+ type DesktopAccess,+ desktopAccessResponseSchema,findOrgForProject,flattenProjectIds,type OrgProjects,@@ -83,7 +85,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {orgProjectsMap: {},currentOrgId: null,currentProjectId: null,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,sessionType: null,sessionExpiresAt: null,@@ -93,6 +95,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {private initializePromise: Promise<void> | null = null;private refreshPromise: Promise<InMemorySession> | null = null;private impersonationExpiryTimer: ReturnType<typeof setTimeout> | null = null;+ private sessionGeneration = 0;// Serializes session-state commits so overlapping selections can't// interleave across async encryption (see commitSessionState).private commitChain: Promise<void> = Promise.resolve();@@ -128,18 +131,24 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {return { ...this.state };}async login(region: CloudRegion): Promise<AuthState> {+ this.sessionGeneration += 1;+ const sessionGeneration = this.sessionGeneration;await this.authenticateWithFlow(() => this.oauthFlow.startFlow(region),region,"OAuth flow failed",+ sessionGeneration,);return this.getState();}async signup(region: CloudRegion): Promise<AuthState> {+ this.sessionGeneration += 1;+ const sessionGeneration = this.sessionGeneration;await this.authenticateWithFlow(() => this.oauthFlow.startSignupFlow(region),region,"Signup failed",+ sessionGeneration,);return this.getState();}@@ -263,13 +272,25 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {throw new Error(data.error || "Failed to redeem invite code");}- this.updateState({ hasCodeAccess: true });+ return this.retryDesktopAccess();+ }+ async retryDesktopAccess(): Promise<AuthState> {+ await this.initialize();+ const session = await this.ensureValidSession();+ this.updateState({+ desktopAccess: {+ projectId: session.currentProjectId,+ status: "checking",+ reason: null,+ },+ });+ await this.updateDesktopAccessFromSession(session);return this.getState();}async selectProject(projectId: number): Promise<AuthState> {await this.initialize();- const session = this.requireSession();+ const session = await this.ensureValidSession();if (!flattenProjectIds(session.orgProjectsMap).includes(projectId)) {throw new Error("Invalid project selection");@@ -297,7 +318,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {async switchOrg(orgId: string): Promise<AuthState> {await this.initialize();- const session = this.requireSession();+ const session = await this.ensureValidSession();if (!session.orgProjectsMap[orgId]) {throw new Error("Invalid organization");@@ -371,8 +392,9 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {// interleave across async encryption and clobber a newer one. The chain// swallows rejections so one failure doesn't wedge later commits; the// returned promise still rejects for the caller.+ const sessionGeneration = this.sessionGeneration;const run = this.commitChain.then(() =>- this.applyCommittedSession(prevSession, next),+ this.applyCommittedSession(prevSession, next, sessionGeneration),);this.commitChain = run.catch(() => {});return run;@@ -384,7 +406,12 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {currentOrgId: string | null;currentProjectId: number | null;},+ sessionGeneration: number,): Promise<void> {+ if (this.sessionGeneration !== sessionGeneration) {+ return;+ }+const nextSession: InMemorySession = {...prevSession,orgProjectsMap: next.orgProjectsMap,@@ -398,20 +425,35 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {// published state only after it resolves, so a rejection leaves every// layer on the prior session.if (nextSession.refreshToken) {- await this.persistSession({- refreshToken: nextSession.refreshToken,- cloudRegion: nextSession.cloudRegion,- selectedProjectId: next.currentProjectId,- });+ const persisted = await this.persistSession(+ {+ refreshToken: nextSession.refreshToken,+ cloudRegion: nextSession.cloudRegion,+ selectedProjectId: next.currentProjectId,+ },+ () => this.sessionGeneration === sessionGeneration,+ );+ if (!persisted) {+ return;+ }}+ if (this.sessionGeneration !== sessionGeneration) {+ return;+ }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,+ },});+ await this.updateDesktopAccessFromSession(nextSession);}private async patchCurrentOrganization(orgId: string): Promise<void> {const { apiHost } = await this.getValidAccessToken();@@ -453,6 +495,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {async logout(): Promise<AuthState> {const { cloudRegion, currentProjectId } = this.state;+ this.sessionGeneration += 1;this.authSession.clearCurrent();this.clearImpersonationExpiryTimer();this.session = null;@@ -540,7 +583,11 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {orgProjectsMap: {},currentOrgId: null,currentProjectId: storedSession.selectedProjectId,- hasCodeAccess: null,+ desktopAccess: {+ projectId: storedSession.selectedProjectId,+ status: "unchecked",+ reason: null,+ },needsScopeReauth: false,});}@@ -594,6 +641,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {// concurrent callers dedupe onto one refresh. Resolving the stored session// (now async) must happen INSIDE refreshAndSync, else two callers both// refresh and burn the rotating token twice.+ const sessionGeneration = this.sessionGeneration;const refreshAndSync = async (): Promise<InMemorySession> => {const sessionInput = await this.getSessionInputForRefresh();let session: InMemorySession;@@ -614,7 +662,13 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {}throw error;}- await this.syncAuthenticatedSession(session);+ const synchronized = await this.syncAuthenticatedSession(+ session,+ sessionGeneration,+ );+ if (!synchronized) {+ throw new NotAuthenticatedError();+ }return session;};@@ -676,6 +730,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {if (result.errorCode === "auth_error") {this.logger.warn("Refresh token rejected by server, forcing logout");+ this.sessionGeneration += 1;this.authSession.clearCurrent();this.session = null;this.setAnonymousState({@@ -971,6 +1026,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {}>,region: CloudRegion,fallbackError: string,+ sessionGeneration: number,): Promise<void> {const result = await runFlow();if (!result.success || !result.data) {@@ -981,22 +1037,35 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {cloudRegion: region,selectedProjectId: this.state.currentProjectId,});- await this.syncAuthenticatedSession(session);+ await this.syncAuthenticatedSession(session, sessionGeneration);}private async syncAuthenticatedSession(session: InMemorySession,- ): Promise<void> {- this.persistProjectPreference(session);+ sessionGeneration: number,+ ): Promise<boolean> {+ if (this.sessionGeneration !== sessionGeneration) {+ return false;+ }if (session.refreshToken) {- await this.persistSession({- refreshToken: session.refreshToken,- cloudRegion: session.cloudRegion,- selectedProjectId: session.currentProjectId,- });+ const persisted = await this.persistSession(+ {+ refreshToken: session.refreshToken,+ cloudRegion: session.cloudRegion,+ selectedProjectId: session.currentProjectId,+ },+ () => this.sessionGeneration === sessionGeneration,+ );+ if (!persisted) {+ return false;+ }} else {this.authSession.clearCurrent();}+ if (this.sessionGeneration !== sessionGeneration) {+ return false;+ }+ this.persistProjectPreference(session);this.session = session;this.scheduleImpersonationExpiry(session);this.updateState({@@ -1006,30 +1075,50 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {orgProjectsMap: session.orgProjectsMap,currentOrgId: session.currentOrgId,currentProjectId: session.currentProjectId,+ desktopAccess: {+ projectId: session.currentProjectId,+ status: "checking",+ reason: null,+ },needsScopeReauth: false,sessionType: session.sessionType,sessionExpiresAt: session.accessTokenExpiresAt,sessionEndReason: null,});- await this.updateCodeAccessFromSession();+ await this.updateDesktopAccessFromSession(session);+ if (+ this.sessionGeneration !== sessionGeneration ||+ this.session !== session+ ) {+ return false;+ }if (session.orgProjectsIncomplete) {void this.refreshOrgProjects();}+ return true;}- private async persistSession(input: {- refreshToken: string;- cloudRegion: CloudRegion;- selectedProjectId: number | null;- }): Promise<void> {+ private async persistSession(+ input: {+ refreshToken: string;+ cloudRegion: CloudRegion;+ selectedProjectId: number | null;+ },+ shouldSave: () => boolean = () => true,+ ): Promise<boolean> {const priorSelected =this.authSession.getCurrent()?.selectedProjectId ?? null;+ const refreshTokenEncrypted = await this.cipher.encrypt(input.refreshToken);+ if (!shouldSave()) {+ return false;+ }this.authSession.saveCurrent({- refreshTokenEncrypted: await this.cipher.encrypt(input.refreshToken),+ refreshTokenEncrypted,cloudRegion: input.cloudRegion,selectedProjectId: input.selectedProjectId ?? priorSelected,scopeVersion: OAUTH_SCOPE_VERSION,});+ return true;}private persistProjectPreference(session: InMemorySession): void {if (!session.accountKey || session.currentProjectId === null) {@@ -1128,12 +1217,6 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {return { accountKey: null, currentOrgId: null, orgNames: {} };}}- private requireSession(): InMemorySession {- if (!this.session) {- throw new NotAuthenticatedError();- }- return this.session;- }private setAnonymousState(partial: Pick<Partial<AuthState>,@@ -1151,97 +1234,77 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {orgProjectsMap: {},currentOrgId: null,currentProjectId: partial.currentProjectId ?? null,- hasCodeAccess: null,+ desktopAccess: {+ projectId: partial.currentProjectId ?? null,+ status: "unchecked",+ reason: null,+ },needsScopeReauth: partial.needsScopeReauth ?? false,sessionType: null,sessionExpiresAt: null,sessionEndReason: partial.sessionEndReason ?? null,});}- private async updateCodeAccessFromSession(): Promise<void> {- if (!this.session) {- this.updateState({ hasCodeAccess: null });- return;- }-- const hasAccess = await this.checkCodeAccess(this.session);+ private async updateDesktopAccessFromSession(+ session: InMemorySession,+ ): Promise<void> {+ const desktopAccess = await this.checkDesktopAccess(session);+ if (this.session !== session) return;+ this.updateState({ desktopAccess });+ }- if (hasAccess !== null) {- this.updateState({ hasCodeAccess: hasAccess });- return;+ private async checkDesktopAccess(+ session: InMemorySession,+ ): Promise<DesktopAccess> {+ const projectId = session.currentProjectId;+ if (projectId === null) {+ return { projectId, status: "error", reason: null };}- // Indeterminate: a transient/unauthorized failure isn't proof the invite- // was revoked, so keep the prior value and let the next sync re-check.- this.logger.warn(- "Code access check was inconclusive; keeping previous value",- { hasCodeAccess: this.state.hasCodeAccess },- );- }+ if (!this.connectivity.getStatus().isOnline) {+ return { projectId, status: "error", reason: null };+ }- /**- * Resolves Code invite access. Only a 2xx response with an explicit boolean- * `has_access` is authoritative; everything else (offline, network error,- * non-2xx, malformed body) is indeterminate, retried with backoff, then- * returned as `null` so the caller keeps the prior value. Uses the synced- * token directly rather than `authenticatedFetch`, which would re-enter the- * refresh flow this runs inside and deadlock.- */- private async checkCodeAccess(- session: InMemorySession,- ): Promise<boolean | null> {- const url = `${getCloudUrlFromRegion(session.cloudRegion)}/api/code/invites/check-access/`;+ const url = `${getCloudUrlFromRegion(session.cloudRegion)}/api/projects/${projectId}/desktop/access/`;- for (- let attempt = 0;- attempt < AuthService.CODE_ACCESS_MAX_ATTEMPTS;- attempt++- ) {- if (!this.connectivity.getStatus().isOnline) {- return null;- }+ try {+ const response = await this.executeAuthenticatedFetch(+ fetch,+ url,+ {},+ session.accessToken,+ );- try {- const response = await this.executeAuthenticatedFetch(- fetch,- url,- {},- session.accessToken,+ if (response.ok) {+ const result = desktopAccessResponseSchema.safeParse(+ await response.json().catch(() => null),);-- if (response.ok) {- const data = (await response.json().catch(() => null)) as {- has_access?: unknown;- } | null;- if (data && typeof data.has_access === "boolean") {- return data.has_access;+ if (result.success) {+ if (result.data.allowed) {+ return { projectId, status: "allowed", reason: null };}- this.logger.warn("Code access response missing has_access flag", {- status: response.status,- });- } else {- this.logger.warn("Code access check returned non-OK status", {- status: response.status,- });+ return {+ projectId,+ status: "blocked",+ reason: result.data.reason,+ };}- } catch (error) {- this.logger.warn("Code access check request failed", {- error,- attempt,+ this.logger.warn("Desktop access response was invalid", {+ status: response.status,+ });+ } else {+ this.logger.warn("Desktop access check returned non-OK status", {+ status: response.status,});}-- const isLastAttempt =- attempt === AuthService.CODE_ACCESS_MAX_ATTEMPTS - 1;- if (isLastAttempt) break;- await sleepWithBackoff(attempt, AuthService.REFRESH_BACKOFF);+ } catch (error) {+ this.logger.warn("Desktop access check request failed", { error });}- return null;+ return { projectId, status: "error", reason: null };}private static readonly REFRESH_MAX_ATTEMPTS = 3;private static readonly ORG_FETCH_MAX_ATTEMPTS = 3;- private static readonly CODE_ACCESS_MAX_ATTEMPTS = 3;private static readonly ORG_RECOVERY_MAX_ATTEMPTS = 5;private static readonly REFRESH_BACKOFF: BackoffOptions = {initialDelayMs: 1_000,@@ -1298,6 +1361,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {}private endImpersonatedSession(session: InMemorySession): void {+ this.sessionGeneration += 1;this.clearImpersonationExpiryTimer();this.session = null;this.setAnonymousState({diff --git a/products/desktop/packages/core/src/auth/schemas.ts b/products/desktop/packages/core/src/auth/schemas.tsindex 5318136b0f84..2e6567697fa1 100644--- a/products/desktop/packages/core/src/auth/schemas.ts+++ b/products/desktop/packages/core/src/auth/schemas.ts@@ -71,6 +71,49 @@ export function pickInitialProjectId(args: {return allProjectIds[0] ?? null;}+export const desktopAccessReasonSchema = z.enum([+ "startup_plan",+ "prepaid_credits",+]);+export type DesktopAccessReason = z.infer<typeof desktopAccessReasonSchema>;++export const desktopAccessResponseSchema = z.union([+ z.object({ allowed: z.literal(true), reason: z.null() }),+ z.object({+ allowed: z.literal(false),+ reason: desktopAccessReasonSchema.nullable(),+ }),+]);++export const desktopAccessSchema = z.discriminatedUnion("status", [+ z.object({+ projectId: z.number().nullable(),+ status: z.literal("unchecked"),+ reason: z.null(),+ }),+ z.object({+ projectId: z.number().nullable(),+ status: z.literal("checking"),+ reason: z.null(),+ }),+ z.object({+ projectId: z.number(),+ status: z.literal("allowed"),+ reason: z.null(),+ }),+ z.object({+ projectId: z.number(),+ status: z.literal("blocked"),+ reason: desktopAccessReasonSchema.nullable(),+ }),+ z.object({+ projectId: z.number().nullable(),+ status: z.literal("error"),+ reason: z.null(),+ }),+]);+export type DesktopAccess = z.infer<typeof desktopAccessSchema>;+export const authStateSchema = z.object({status: authStatusSchema,bootstrapComplete: z.boolean(),@@ -78,7 +121,7 @@ export const authStateSchema = z.object({orgProjectsMap: orgProjectsMapSchema,currentOrgId: z.string().nullable(),currentProjectId: z.number().nullable(),- hasCodeAccess: z.boolean().nullable(),+ desktopAccess: desktopAccessSchema,needsScopeReauth: z.boolean(),sessionType: z.enum(["persistent", "impersonated"]).nullable(),sessionExpiresAt: z.number().nullable(),diff --git a/products/desktop/packages/core/src/onboarding/steps.test.ts b/products/desktop/packages/core/src/onboarding/steps.test.tsindex 5d9bd14e9d44..23f419a4ffd5 100644--- a/products/desktop/packages/core/src/onboarding/steps.test.ts+++ b/products/desktop/packages/core/src/onboarding/steps.test.ts@@ -12,7 +12,6 @@ import {} from "./steps";const allSteps = {- hasCodeAccess: false,hasImportableConfig: true,hasGithubIntegration: undefined,projectCount: 2,@@ -20,22 +19,6 @@ const allSteps = {};describe("computeActiveSteps", () => {- it("drops invite-code when the user already has code access", () => {- expect(- computeActiveSteps({ ...allSteps, hasCodeAccess: true }),- ).not.toContain("invite-code");- });-- it("keeps invite-code when access is unknown or false", () => {- expect(computeActiveSteps(allSteps)).toEqual(ONBOARDING_STEPS);- expect(computeActiveSteps({ ...allSteps, hasCodeAccess: null })).toEqual(- ONBOARDING_STEPS,- );- expect(- computeActiveSteps({ ...allSteps, hasCodeAccess: undefined }),- ).toEqual(ONBOARDING_STEPS);- });-it("drops import-config when there is no importable config", () => {expect(computeActiveSteps({ ...allSteps, hasImportableConfig: false }),@@ -69,7 +52,7 @@ describe("computeActiveSteps", () => {it("includes consent from the sampled requirement", () => {expect(ONBOARDING_STEPS.indexOf("consent")).toBe(- ONBOARDING_STEPS.indexOf("invite-code") + 1,+ ONBOARDING_STEPS.indexOf("project-select") + 1,);expect(computeActiveSteps({ ...allSteps, consentRequired: undefined }),@@ -82,7 +65,6 @@ describe("computeActiveSteps", () => {describe("nearestActiveStep", () => {const withoutConditionals = computeActiveSteps({- hasCodeAccess: true,hasImportableConfig: false,hasGithubIntegration: undefined,projectCount: 2,@@ -99,7 +81,6 @@ describe("nearestActiveStep", () => {// import-config vanished under the user: continue forward to select-repo,// not back to welcome (the regression that reset onboarding mid-flow).{ removed: "import-config", expected: "select-repo" },- { removed: "invite-code", expected: "consent" },])("moves forward to $expected when $removed drops out",({ removed, expected }) => {@@ -121,7 +102,6 @@ describe("nearestActiveStep", () => {describe("step navigation", () => {const steps = computeActiveSteps({- hasCodeAccess: true,hasImportableConfig: true,hasGithubIntegration: undefined,projectCount: 2,diff --git a/products/desktop/packages/core/src/onboarding/steps.ts b/products/desktop/packages/core/src/onboarding/steps.tsindex 9525bca608f3..acd992ef48a4 100644--- a/products/desktop/packages/core/src/onboarding/steps.ts+++ b/products/desktop/packages/core/src/onboarding/steps.ts@@ -1,7 +1,6 @@export type OnboardingStep =| "welcome"| "project-select"- | "invite-code"| "consent"| "connect-github"| "install-cli"@@ -11,7 +10,6 @@ export type OnboardingStep =export const ONBOARDING_STEPS: OnboardingStep[] = ["welcome","project-select",- "invite-code","consent","connect-github","install-cli",@@ -28,7 +26,6 @@ export interface DetectedRepo {}export function computeActiveSteps(options: {- hasCodeAccess: boolean | null | undefined;hasImportableConfig: boolean;/** Undefined while the integrations query is loading; the step only drops on a confirmed connection. */hasGithubIntegration: boolean | undefined;@@ -38,7 +35,6 @@ export function computeActiveSteps(options: {}): OnboardingStep[] {return ONBOARDING_STEPS.filter((step) => {if (step === "project-select" && options.projectCount === 1) return false;- if (step === "invite-code" && options.hasCodeAccess === true) return false;if (step === "consent" && options.consentRequired === false) return false;if (step === "import-config" && !options.hasImportableConfig) return false;if (step === "install-cli" && options.hasGithubIntegration === true) {diff --git a/products/desktop/packages/host-router/src/routers/auth.router.ts b/products/desktop/packages/host-router/src/routers/auth.router.tsindex 1b344439cb8d..5c9144df239c 100644--- a/products/desktop/packages/host-router/src/routers/auth.router.ts+++ b/products/desktop/packages/host-router/src/routers/auth.router.ts@@ -80,6 +80,12 @@ export const authRouter = router({ctx.container.get<AuthService>(AUTH_SERVICE).redeemInviteCode(input.code),),+ retryDesktopAccess: publicProcedure+ .output(authStateSchema)+ .mutation(async ({ ctx }) =>+ ctx.container.get<AuthService>(AUTH_SERVICE).retryDesktopAccess(),+ ),+logout: publicProcedure.output(authStateSchema).mutation(async ({ ctx }) => {return ctx.container.get<AuthService>(AUTH_SERVICE).logout();}),diff --git a/products/desktop/packages/shared/src/links.ts b/products/desktop/packages/shared/src/links.tsindex 27e965bfca35..4770b0054ecb 100644--- a/products/desktop/packages/shared/src/links.ts+++ b/products/desktop/packages/shared/src/links.ts@@ -4,5 +4,6 @@ export const EXTERNAL_LINKS = {ghInstall: "https://cli.github.com/",gitInstall: "https://git-scm.com/downloads",privacy: "https://posthog.com/privacy",+ talkToHuman: "https://posthog.com/talk-to-a-human",website: "https://posthog.com/desktop",} as const;diff --git a/products/desktop/packages/ui/src/features/auth/authUiStateStore.ts b/products/desktop/packages/ui/src/features/auth/authUiStateStore.tsindex 4bec9f32ca06..e938826f3f83 100644--- a/products/desktop/packages/ui/src/features/auth/authUiStateStore.ts+++ b/products/desktop/packages/ui/src/features/auth/authUiStateStore.ts@@ -3,15 +3,12 @@ import { create } from "zustand";interface AuthUiStateStoreState {authMode: "login" | "signup";- inviteCode: string;selectedRegion: CloudRegion | null;staleRegion: CloudRegion | null;}interface AuthUiStateStoreActions {setAuthMode: (mode: "login" | "signup") => void;- setInviteCode: (inviteCode: string) => void;- resetInviteCode: () => void;setSelectedRegion: (region: CloudRegion | null) => void;setStaleRegion: (region: CloudRegion | null) => void;clearStaleRegion: () => void;@@ -21,13 +18,10 @@ type AuthUiStateStore = AuthUiStateStoreState & AuthUiStateStoreActions;export const useAuthUiStateStore = create<AuthUiStateStore>((set) => ({authMode: "login",- inviteCode: "",selectedRegion: null,staleRegion: null,setAuthMode: (authMode) => set({ authMode }),- setInviteCode: (inviteCode) => set({ inviteCode }),- resetInviteCode: () => set({ inviteCode: "" }),setSelectedRegion: (selectedRegion) => set({ selectedRegion }),setStaleRegion: (region) => set({ staleRegion: region }),clearStaleRegion: () => set({ staleRegion: null }),diff --git a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsx b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsxnew file mode 100644index 000000000000..bd85c14a7e6b--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsx@@ -0,0 +1,62 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { fn } from "storybook/test";+import { DesktopAccessScreen } from "./DesktopAccessScreen";++const meta = {+ title: "Auth/Desktop access",+ component: DesktopAccessScreen,+ parameters: { layout: "fullscreen" },+ args: {+ access: { projectId: 1, status: "blocked", reason: "startup_plan" },+ orgProjectsMap: {+ "org-1": {+ orgName: "Example organization",+ projects: [+ { id: 1, name: "Website" },+ { id: 2, name: "Mobile app" },+ ],+ },+ "org-2": {+ orgName: "Second organization",+ projects: [{ id: 3, name: "Product" }],+ },+ },+ currentOrgId: "org-1",+ currentProjectId: 1,+ isSwitching: false,+ isRetrying: false,+ isRedeemingInviteCode: false,+ isLoggingOut: false,+ switchError: null,+ redemptionError: null,+ onSelectOrganization: fn(),+ onSelectProject: fn(),+ onRedeemInviteCode: fn(),+ onRetry: fn(),+ onLogout: fn(),+ onOpenSupport: fn(),+ },+} satisfies Meta<typeof DesktopAccessScreen>;++export default meta;+type Story = StoryObj<typeof meta>;++export const StartupProgram: Story = {};++export const PrepaidCredits: Story = {+ args: {+ access: { projectId: 1, status: "blocked", reason: "prepaid_credits" },+ },+};++export const LegacyInviteCode: Story = {+ args: {+ access: { projectId: 1, status: "blocked", reason: null },+ },+};++export const TechnicalError: Story = {+ args: {+ access: { projectId: 1, status: "error", reason: null },+ },+};diff --git a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsx b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsxnew file mode 100644index 000000000000..d3f78862d1ab--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsx@@ -0,0 +1,148 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { DesktopAccessScreen } from "./DesktopAccessScreen";++const orgProjectsMap = {+ "org-1": {+ orgName: "First organization",+ projects: [+ { id: 1, name: "Website" },+ { id: 2, name: "Mobile app" },+ ],+ },+ "org-2": {+ orgName: "Second organization",+ projects: [{ id: 3, name: "Product" }],+ },+};++function renderScreen(+ access:+ | {+ projectId: number;+ status: "blocked";+ reason: "startup_plan" | "prepaid_credits" | null;+ }+ | { projectId: number; status: "error"; reason: null },+) {+ const onSelectOrganization = vi.fn();+ const onSelectProject = vi.fn();+ const onRedeemInviteCode = vi.fn();+ const onRetry = vi.fn();+ const onLogout = vi.fn();+ const onOpenSupport = vi.fn();+ const result = render(+ <DesktopAccessScreen+ access={access}+ orgProjectsMap={orgProjectsMap}+ currentOrgId="org-1"+ currentProjectId={1}+ isSwitching={false}+ isRetrying={false}+ isRedeemingInviteCode={false}+ isLoggingOut={false}+ switchError={null}+ redemptionError={null}+ onSelectOrganization={onSelectOrganization}+ onSelectProject={onSelectProject}+ onRedeemInviteCode={onRedeemInviteCode}+ onRetry={onRetry}+ onLogout={onLogout}+ onOpenSupport={onOpenSupport}+ />,+ );+ return {+ ...result,+ onSelectOrganization,+ onSelectProject,+ onRedeemInviteCode,+ onRetry,+ onLogout,+ onOpenSupport,+ };+}++describe("DesktopAccessScreen", () => {+ it.each([+ ["startup_plan", "Organizations in the Startup or YC program"],+ ["prepaid_credits", "[email protected]"],+ ] as const)("renders the %s reason", (reason, expectedCopy) => {+ renderScreen({ projectId: 1, status: "blocked", reason });++ expect(screen.getByText(new RegExp(expectedCopy))).toBeInTheDocument();+ expect(screen.getByText("First organization")).toBeInTheDocument();+ expect(screen.getByText("Website")).toBeInTheDocument();+ });++ it("preserves invite-code redemption for a legacy denial", async () => {+ const user = userEvent.setup();+ const { onRedeemInviteCode } = renderScreen({+ projectId: 1,+ status: "blocked",+ reason: null,+ });++ expect(screen.getByText("Enter your invite code")).toBeInTheDocument();+ await user.type(screen.getByLabelText("Invite code"), "INVITE");+ await user.click(screen.getByText("Redeem invite code"));++ expect(onRedeemInviteCode).toHaveBeenCalledWith("INVITE");+ });++ it.each([+ [{ projectId: 1, status: "error", reason: null }, "Try again"],+ [+ { projectId: 1, status: "blocked", reason: "startup_plan" },+ "Check again",+ ],+ ] as const)("rechecks access for %s", async (access, buttonLabel) => {+ const user = userEvent.setup();+ const { onRetry } = renderScreen(access);++ await user.click(screen.getByText(buttonLabel));++ expect(onRetry).toHaveBeenCalledOnce();+ });++ it("lets the user select another project", async () => {+ const user = userEvent.setup();+ const { container, onSelectProject } = renderScreen({+ projectId: 1,+ status: "blocked",+ reason: "startup_plan",+ });+ const trigger = container.querySelector(+ '[data-attr="desktop-access-project-switcher"]',+ );+ expect(trigger).not.toBeNull();++ await user.click(trigger as HTMLElement);+ await user.click(await screen.findByText("Mobile app"));++ expect(onSelectProject).toHaveBeenCalledWith(2);+ });++ it("lets the user select another organization and log out", async () => {+ const user = userEvent.setup();+ const { container, onSelectOrganization, onLogout, onOpenSupport } =+ renderScreen({+ projectId: 1,+ status: "blocked",+ reason: "prepaid_credits",+ });+ const trigger = container.querySelector(+ '[data-attr="desktop-access-organization-switcher"]',+ );+ expect(trigger).not.toBeNull();++ await user.click(trigger as HTMLElement);+ await user.click(await screen.findByText("Second organization"));+ await user.click(screen.getByText("Get support"));+ await user.click(screen.getByText("Log out"));++ expect(onSelectOrganization).toHaveBeenCalledWith("org-2");+ expect(onOpenSupport).toHaveBeenCalledOnce();+ expect(onLogout).toHaveBeenCalledOnce();+ });+});diff --git a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsx b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsxnew file mode 100644index 000000000000..f58c8765e750--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsx@@ -0,0 +1,380 @@+import {+ ArrowClockwise,+ CaretDown,+ Coins,+ Key,+ RocketLaunch,+ SignOut,+ WarningCircle,+} from "@phosphor-icons/react";+import type { DesktopAccess, OrgProjectsMap } from "@posthog/core/auth/schemas";+import {+ Button,+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxTrigger,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Field,+ FieldLabel,+ Input,+ Spinner,+} from "@posthog/quill";+import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";+import {+ FIELD_CONTENT_CLASS,+ FIELD_TRIGGER_CLASS,+} from "@posthog/ui/styles/fieldTrigger";+import { useMemo, useRef, useState } from "react";++interface OrganizationOption {+ id: string;+ name: string;+}++interface ProjectOption {+ id: number;+ name: string;+}++const BLOCKED_CONTENT = {+ startup_plan: {+ icon: <RocketLaunch />,+ title: "Desktop isn't available for this organization",+ description:+ "Organizations in the Startup or YC program can't use PostHog Desktop. Select another organization to continue.",+ },+ prepaid_credits: {+ icon: <Coins />,+ title: "Desktop isn't available with prepaid credits",+ description:+ "Organizations with pending or active prepaid credits can't use PostHog Desktop. Select another organization to continue. To discuss access, contact your PostHog account executive. If you don't have one, email [email protected].",+ },+} as const;++interface DesktopAccessScreenProps {+ access: DesktopAccess;+ orgProjectsMap: OrgProjectsMap;+ currentOrgId: string | null;+ currentProjectId: number | null;+ isSwitching: boolean;+ isRetrying: boolean;+ isRedeemingInviteCode: boolean;+ isLoggingOut: boolean;+ switchError: string | null;+ redemptionError: string | null;+ onSelectOrganization: (organizationId: string) => void;+ onSelectProject: (projectId: number) => void;+ onRedeemInviteCode: (inviteCode: string) => void;+ onRetry: () => void;+ onLogout: () => void;+ onOpenSupport: () => void;+}++export function DesktopAccessScreen({+ access,+ orgProjectsMap,+ currentOrgId,+ currentProjectId,+ isSwitching,+ isRetrying,+ isRedeemingInviteCode,+ isLoggingOut,+ switchError,+ redemptionError,+ onSelectOrganization,+ onSelectProject,+ onRedeemInviteCode,+ onRetry,+ onLogout,+ onOpenSupport,+}: DesktopAccessScreenProps) {+ const [organizationOpen, setOrganizationOpen] = useState(false);+ const [projectOpen, setProjectOpen] = useState(false);+ const [inviteCode, setInviteCode] = useState("");+ const organizationAnchorRef = useRef<HTMLButtonElement>(null);+ const projectAnchorRef = useRef<HTMLButtonElement>(null);++ const organizations = useMemo<OrganizationOption[]>(+ () =>+ Object.entries(orgProjectsMap)+ .map(([id, organization]) => ({ id, name: organization.orgName }))+ .sort((first, second) => first.name.localeCompare(second.name)),+ [orgProjectsMap],+ );+ const projects = useMemo<ProjectOption[]>(+ () =>+ (currentOrgId+ ? (orgProjectsMap[currentOrgId]?.projects ?? [])+ : []+ ).toSorted((first, second) => first.name.localeCompare(second.name)),+ [currentOrgId, orgProjectsMap],+ );+ const selectedOrganization =+ organizations.find((organization) => organization.id === currentOrgId) ??+ null;+ const selectedProject =+ projects.find((project) => project.id === currentProjectId) ?? null;+ const controlsDisabled =+ isSwitching || isRedeemingInviteCode || access.status === "checking";+ const isLegacyAccessRequired =+ access.status === "blocked" && access.reason === null;++ const blockedContent = access.reason+ ? BLOCKED_CONTENT[access.reason]+ : {+ icon: <Key />,+ title: "Enter your invite code",+ description:+ "This organization needs an invite code to use PostHog Desktop. Enter one below or select another organization.",+ };+ const isTechnicalError = access.status === "error";+ const icon = isTechnicalError ? <WarningCircle /> : blockedContent?.icon;+ const title = isTechnicalError+ ? "Couldn't check Desktop access"+ : blockedContent?.title;+ const description = isTechnicalError+ ? "Try again, or select another organization or project."+ : blockedContent?.description;++ const footerRight = (+ <Button+ variant="link-muted"+ size="sm"+ loading={isLoggingOut}+ disabled={+ isLoggingOut || isSwitching || isRetrying || isRedeemingInviteCode+ }+ onClick={onLogout}+ data-attr="desktop-access-logout"+ >+ <SignOut />+ Log out+ </Button>+ );++ return (+ <FullScreenLayout footerRight={footerRight} onOpenSupport={onOpenSupport}>+ <div className="h-full overflow-y-auto px-8 py-20">+ <div className="flex min-h-full items-center justify-center">+ <Empty className="w-full max-w-xl">+ <EmptyHeader>+ <EmptyMedia variant="icon">{icon}</EmptyMedia>+ <EmptyTitle>{title}</EmptyTitle>+ <EmptyDescription>{description}</EmptyDescription>+ </EmptyHeader>+ <EmptyContent className="w-full max-w-md gap-4">+ {isLegacyAccessRequired && (+ <form+ className="flex w-full flex-col gap-2"+ onSubmit={(event) => {+ event.preventDefault();+ onRedeemInviteCode(inviteCode.trim());+ }}+ >+ <Field>+ <FieldLabel htmlFor="desktop-access-invite-code">+ Invite code+ </FieldLabel>+ <Input+ id="desktop-access-invite-code"+ value={inviteCode}+ onChange={(event) =>+ setInviteCode(event.currentTarget.value)+ }+ disabled={isRedeemingInviteCode || isSwitching}+ autoComplete="off"+ />+ </Field>+ {redemptionError && (+ <p role="alert" className="text-destructive text-sm">+ {redemptionError}+ </p>+ )}+ <Button+ type="submit"+ variant="primary"+ loading={isRedeemingInviteCode}+ disabled={+ isRedeemingInviteCode ||+ isSwitching ||+ inviteCode.trim().length === 0+ }+ data-attr="desktop-access-redeem-invite-code"+ >+ Redeem invite code+ </Button>+ </form>+ )}++ <div className="flex w-full flex-col gap-4">+ <Field className="min-w-0">+ <FieldLabel htmlFor="desktop-access-organization">+ Organization+ </FieldLabel>+ <Combobox<OrganizationOption>+ items={organizations}+ value={selectedOrganization}+ onValueChange={(value) => {+ if (value && value.id !== currentOrgId) {+ onSelectOrganization(value.id);+ }+ setOrganizationOpen(false);+ }}+ open={organizationOpen}+ onOpenChange={setOrganizationOpen}+ itemToStringLabel={(organization) => organization.name}+ itemToStringValue={(organization) => organization.id}+ disabled={controlsDisabled}+ >+ <ComboboxTrigger+ nativeButton+ render={+ <button+ ref={organizationAnchorRef}+ id="desktop-access-organization"+ type="button"+ className={FIELD_TRIGGER_CLASS}+ data-attr="desktop-access-organization-switcher"+ >+ <span className="min-w-0 flex-1 truncate text-left">+ {selectedOrganization?.name ??+ "Select organization"}+ </span>+ {isSwitching ? (+ <Spinner />+ ) : (+ <CaretDown+ size={14}+ className="shrink-0 text-muted"+ />+ )}+ </button>+ }+ />+ <ComboboxContent+ anchor={organizationAnchorRef}+ side="bottom"+ align="start"+ sideOffset={4}+ className={FIELD_CONTENT_CLASS}+ >+ <ComboboxInput+ placeholder="Search organizations..."+ showTrigger={false}+ />+ <ComboboxEmpty>No organizations found.</ComboboxEmpty>+ <ComboboxList>+ {(organization: OrganizationOption) => (+ <ComboboxItem+ key={organization.id}+ value={organization}+ >+ {organization.name}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </Field>++ <Field className="min-w-0">+ <FieldLabel htmlFor="desktop-access-project">+ Project+ </FieldLabel>+ <Combobox<ProjectOption>+ items={projects}+ value={selectedProject}+ onValueChange={(value) => {+ if (value && value.id !== currentProjectId) {+ onSelectProject(value.id);+ }+ setProjectOpen(false);+ }}+ open={projectOpen}+ onOpenChange={setProjectOpen}+ itemToStringLabel={(project) => project.name}+ itemToStringValue={(project) => String(project.id)}+ disabled={controlsDisabled}+ >+ <ComboboxTrigger+ nativeButton+ render={+ <button+ ref={projectAnchorRef}+ id="desktop-access-project"+ type="button"+ className={FIELD_TRIGGER_CLASS}+ data-attr="desktop-access-project-switcher"+ >+ <span className="min-w-0 flex-1 truncate text-left">+ {selectedProject?.name ?? "Select project"}+ </span>+ {isSwitching ? (+ <Spinner />+ ) : (+ <CaretDown+ size={14}+ className="shrink-0 text-muted"+ />+ )}+ </button>+ }+ />+ <ComboboxContent+ anchor={projectAnchorRef}+ side="bottom"+ align="start"+ sideOffset={4}+ className={FIELD_CONTENT_CLASS}+ >+ <ComboboxInput+ placeholder="Search projects..."+ showTrigger={false}+ />+ <ComboboxEmpty>No projects found.</ComboboxEmpty>+ <ComboboxList>+ {(project: ProjectOption) => (+ <ComboboxItem key={project.id} value={project}>+ {project.name}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </Field>+ </div>++ {switchError && (+ <p role="alert" className="text-destructive text-sm">+ {switchError}+ </p>+ )}++ {!isLegacyAccessRequired && (+ <Button+ variant="primary"+ loading={isRetrying}+ disabled={isRetrying || isSwitching}+ onClick={onRetry}+ data-attr="desktop-access-retry"+ >+ <ArrowClockwise />+ {isTechnicalError ? "Try again" : "Check again"}+ </Button>+ )}+ </EmptyContent>+ </Empty>+ </div>+ </div>+ </FullScreenLayout>+ );+}diff --git a/products/desktop/packages/ui/src/features/auth/components/InviteCodeScreen.tsx b/products/desktop/packages/ui/src/features/auth/components/InviteCodeScreen.tsxdeleted file mode 100644index 46d38f913aef..000000000000--- a/products/desktop/packages/ui/src/features/auth/components/InviteCodeScreen.tsx+++ /dev/null@@ -1,129 +0,0 @@-import { SignOut } from "@phosphor-icons/react";-import { happyHog } from "@posthog/ui/assets/hedgehogs";-import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";-import { OnboardingHogTip } from "@posthog/ui/primitives/OnboardingHogTip";-import { Button, Callout, Flex, Spinner, Text } from "@radix-ui/themes";-import { motion } from "framer-motion";-import { useAuthUiStateStore } from "../authUiStateStore";-import {- useLogoutMutation,- useRedeemInviteCodeMutation,-} from "../useAuthMutations";--export function InviteCodeScreen() {- const code = useAuthUiStateStore((state) => state.inviteCode);- const setInviteCode = useAuthUiStateStore((state) => state.setInviteCode);- const resetInviteCode = useAuthUiStateStore((state) => state.resetInviteCode);- const redeemMutation = useRedeemInviteCodeMutation();- const logoutMutation = useLogoutMutation();- const errorMessage = redeemMutation.error?.message ?? null;-- const handleSubmit = (e: React.FormEvent) => {- e.preventDefault();- if (!code.trim()) return;- redeemMutation.mutate(code.trim(), {- onSuccess: () => {- resetInviteCode();- },- });- };-- const footerRight = (- <Button- size="1"- variant="ghost"- color="gray"- onClick={() => logoutMutation.mutate()}- className="opacity-50"- >- <SignOut size={14} />- Log out- </Button>- );-- return (- <FullScreenLayout footerRight={footerRight}>- <Flex align="center" justify="center" height="100%" px="8">- <Flex- direction="column"- align="center"- className="h-full w-full max-w-[480px] pt-[24px] pb-[40px]"- >- <Flex- direction="column"- justify="center"- align="center"- className="min-h-0 w-full flex-1"- >- <Flex direction="column" align="start" gap="6" className="w-full">- <Flex direction="column" gap="5" className="w-full">- <motion.div- initial={{ opacity: 0, y: 8 }}- animate={{ opacity: 1, y: 0 }}- transition={{ duration: 0.3 }}- >- <Flex direction="column" gap="2">- <Text className="font-bold text-(--gray-12) text-2xl">- Enter your invite code- </Text>- <Text className="text-(--gray-11) text-sm">- You need an invite code to access PostHog.- </Text>- </Flex>- </motion.div>-- <motion.div- initial={{ opacity: 0, y: 8 }}- animate={{ opacity: 1, y: 0 }}- transition={{ duration: 0.3, delay: 0.05 }}- >- <form onSubmit={handleSubmit}>- <Flex direction="column" gap="3">- {errorMessage && (- <Callout.Root color="red" size="1">- <Callout.Text>{errorMessage}</Callout.Text>- </Callout.Root>- )}- <input- type="text"- value={code}- onChange={(e) => setInviteCode(e.target.value)}- placeholder="Invite code"- disabled={redeemMutation.isPending}- className="box-border h-[44px] w-full rounded-[10px] border border-(--gray-a3) bg-(--color-panel-solid) px-[14px] py-0 text-(--gray-12) text-[15px]"- style={{- outline: "none",- boxShadow:- "0 1px 3px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.02)",- fontFamily: "inherit",- }}- />- <Button- type="submit"- size="3"- disabled={redeemMutation.isPending || !code.trim()}- className="w-full"- >- {redeemMutation.isPending ? (- <Spinner size="1" />- ) : (- "Redeem"- )}- </Button>- </Flex>- </form>- </motion.div>- </Flex>-- <OnboardingHogTip- hogSrc={happyHog}- message="Got a code from a friend or the PostHog team? Pop it in above."- delay={0.1}- />- </Flex>- </Flex>- </Flex>- </Flex>- </FullScreenLayout>- );-}diff --git a/products/desktop/packages/ui/src/features/auth/components/ScopeReauthPrompt.test.tsx b/products/desktop/packages/ui/src/features/auth/components/ScopeReauthPrompt.test.tsxindex 8b9160a81de2..3dec297b16d9 100644--- a/products/desktop/packages/ui/src/features/auth/components/ScopeReauthPrompt.test.tsx+++ b/products/desktop/packages/ui/src/features/auth/components/ScopeReauthPrompt.test.tsx@@ -15,7 +15,11 @@ const authState = {>,currentOrgId: null as string | null,currentProjectId: null as number | null,- hasCodeAccess: null,+ desktopAccess: {+ projectId: null as number | null,+ status: "unchecked" as const,+ reason: null as "startup_plan" | "prepaid_credits" | null,+ },needsScopeReauth: false,};@@ -61,7 +65,11 @@ describe("ScopeReauthPrompt", () => {authState.status = "anonymous";authState.cloudRegion = null;authState.currentProjectId = null;- authState.hasCodeAccess = null;+ authState.desktopAccess = {+ projectId: null,+ status: "unchecked",+ reason: null,+ };authState.needsScopeReauth = false;});diff --git a/products/desktop/packages/ui/src/features/auth/store.ts b/products/desktop/packages/ui/src/features/auth/store.tsindex 6193902b8e89..3c634826b1bd 100644--- a/products/desktop/packages/ui/src/features/auth/store.ts+++ b/products/desktop/packages/ui/src/features/auth/store.ts@@ -11,7 +11,7 @@ export const ANONYMOUS_AUTH_STATE: AuthState = {orgProjectsMap: {},currentOrgId: null,currentProjectId: null,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,sessionType: null,sessionExpiresAt: null,diff --git a/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts b/products/desktop/packages/ui/src/features/auth/useAuthMutations.tsindex 111fae572225..340831fa1cb3 100644--- a/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts+++ b/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts@@ -59,6 +59,13 @@ export function useRedeemInviteCodeMutation() {});}+export function useRetryDesktopAccessMutation() {+ const hostClient = useHostTRPCClient();+ return useMutation({+ mutationFn: () => hostClient.auth.retryDesktopAccess.mutate(),+ });+}+export function useLogoutMutation() {const hostClient = useHostTRPCClient();const fx = useService<IAuthSideEffects>(AUTH_SIDE_EFFECTS);diff --git a/products/desktop/packages/ui/src/features/onboarding/components/InviteCodeStep.tsx b/products/desktop/packages/ui/src/features/onboarding/components/InviteCodeStep.tsxdeleted file mode 100644index f06143fa82b4..000000000000--- a/products/desktop/packages/ui/src/features/onboarding/components/InviteCodeStep.tsx+++ /dev/null@@ -1,142 +0,0 @@-import { ArrowLeft, ArrowRight } from "@phosphor-icons/react";-import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";-import { Button, Callout, Flex, Spinner, Text } from "@radix-ui/themes";-import { motion } from "framer-motion";-import { happyHog } from "../../../assets/hedgehogs";-import { OnboardingHogTip } from "../../../primitives/OnboardingHogTip";-import { track } from "../../../shell/analytics";-import { useAuthUiStateStore } from "../../auth/authUiStateStore";-import { useRedeemInviteCodeMutation } from "../../auth/useAuthMutations";-import { StepActions } from "./StepActions";--interface InviteCodeStepProps {- onNext: () => void;- onBack: () => void;-}--export function InviteCodeStep({ onNext, onBack }: InviteCodeStepProps) {- const code = useAuthUiStateStore((state) => state.inviteCode);- const setInviteCode = useAuthUiStateStore((state) => state.setInviteCode);- const resetInviteCode = useAuthUiStateStore((state) => state.resetInviteCode);- const redeemMutation = useRedeemInviteCodeMutation();- const errorMessage = redeemMutation.error?.message ?? null;-- const handleSubmit = (e: React.FormEvent) => {- e.preventDefault();- if (!code.trim()) return;- redeemMutation.mutate(code.trim(), {- onSuccess: () => {- track(ANALYTICS_EVENTS.ONBOARDING_INVITE_CODE_SUBMITTED, {- success: true,- });- resetInviteCode();- onNext();- },- onError: (err) => {- track(ANALYTICS_EVENTS.ONBOARDING_INVITE_CODE_SUBMITTED, {- success: false,- error_type: err instanceof Error ? err.message : "unknown",- });- },- });- };-- return (- <Flex align="center" justify="center" height="100%" px="8">- <Flex- direction="column"- align="center"- className="h-full w-full max-w-[480px] pt-[24px] pb-[40px]"- >- <Flex- direction="column"- align="center"- className="min-h-0 w-full flex-1 overflow-y-auto"- >- <Flex- direction="column"- align="start"- gap="5"- style={{ margin: "auto 0" }}- className="w-full"- >- <Flex direction="column" gap="5" className="w-full">- <motion.div- initial={{ opacity: 0, y: 8 }}- animate={{ opacity: 1, y: 0 }}- transition={{ duration: 0.3 }}- >- <Flex direction="column" gap="2">- <Text className="font-bold text-(--gray-12) text-2xl">- Enter your invite code- </Text>- <Text className="text-(--gray-11) text-sm">- You need an invite code to access PostHog.- </Text>- </Flex>- </motion.div>-- <motion.div- initial={{ opacity: 0, y: 8 }}- animate={{ opacity: 1, y: 0 }}- transition={{ duration: 0.3, delay: 0.05 }}- >- <form onSubmit={handleSubmit}>- <Flex direction="column" gap="3">- {errorMessage && (- <Callout.Root color="red" size="1">- <Callout.Text>{errorMessage}</Callout.Text>- </Callout.Root>- )}- <input- type="text"- value={code}- onChange={(e) => setInviteCode(e.target.value)}- placeholder="Invite code"- disabled={redeemMutation.isPending}- className="box-border h-[44px] w-full rounded-[10px] border border-(--gray-a3) bg-(--color-panel-solid) px-[14px] py-0 text-(--gray-12) text-[15px]"- style={{- outline: "none",- boxShadow:- "0 1px 3px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.02)",- fontFamily: "inherit",- }}- />- <Button- type="submit"- size="3"- disabled={redeemMutation.isPending || !code.trim()}- className="w-full"- >- {redeemMutation.isPending ? (- <Spinner size="1" />- ) : (- <>- Redeem- <ArrowRight size={16} weight="bold" />- </>- )}- </Button>- </Flex>- </form>- </motion.div>- </Flex>-- <OnboardingHogTip- hogSrc={happyHog}- message="Got a code from a friend or the PostHog team? Pop it in above."- delay={0.1}- />- </Flex>- </Flex>-- <StepActions>- <Button size="3" variant="outline" color="gray" onClick={onBack}>- <ArrowLeft size={16} weight="bold" />- Back- </Button>- </StepActions>- </Flex>- </Flex>- );-}diff --git a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsxindex a7f61b9de09b..3991d4a442d7 100644--- a/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx+++ b/products/desktop/packages/ui/src/features/onboarding/components/OnboardingFlow.tsx@@ -44,7 +44,6 @@ import { useQueryClient } from "@tanstack/react-query";import { AnimatePresence, LayoutGroup, motion } from "framer-motion";import { useEffect, useRef, useState } from "react";import { useHotkeys } from "react-hotkeys-hook";-import { InviteCodeStep } from "./InviteCodeStep";import { ProjectSelectStep } from "./ProjectSelectStep";import { SelectRepoStep } from "./SelectRepoStep";@@ -360,21 +359,6 @@ export function OnboardingFlow({ onOpenSupport }: OnboardingFlowProps) {</motion.div>)}- {currentStep === "invite-code" && (- <motion.div- key="invite-code"- custom={direction}- initial="enter"- animate="center"- exit="exit"- variants={stepVariants}- transition={{ duration: 0.3 }}- className="min-h-0 w-full flex-1"- >- <InviteCodeStep onNext={handleNext} onBack={handleBack} />- </motion.div>- )}-{currentStep === "consent" && (<motion.divkey="consent"diff --git a/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts b/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.tsindex 4cf38fa64004..6b2433b8a153 100644--- a/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts+++ b/products/desktop/packages/ui/src/features/onboarding/hooks/useOnboardingFlow.ts@@ -134,7 +134,6 @@ export function useOnboardingFlow() {],);- const hasCodeAccess = useAuthStateValue((state) => state.hasCodeAccess);const hasImportableConfig = useHasImportableConfig();const { data: githubUserIntegrations } = useUserGithubIntegrations();const hasGithubIntegration = githubUserIntegrations@@ -143,6 +142,11 @@ export function useOnboardingFlow() {// Counted off the store rather than through useProjects, whose auto-select// effect would then run in a second place and re-clear the query cache.const orgProjectsMap = useAuthStateValue((state) => state.orgProjectsMap);+ const hasDesktopAccess = useAuthStateValue(+ (state) =>+ state.desktopAccess.projectId === state.currentProjectId &&+ state.desktopAccess.status === "allowed",+ );const authFetched = useAuthStateFetched();const projectCount = useMemo(() =>@@ -154,7 +158,7 @@ export function useOnboardingFlow() {: undefined,[authFetched, orgProjectsMap],);- const consent = useOrgConsent(hasCodeAccess === true);+ const consent = useOrgConsent(hasDesktopAccess);const consentSatisfied =consent.status === "resolved" ? consent.satisfied : undefined;const [consentRequirement, setConsentRequirement] =@@ -184,19 +188,12 @@ export function useOnboardingFlow() {const activeSteps = useMemo(() =>computeActiveSteps({- hasCodeAccess,hasImportableConfig,hasGithubIntegration,projectCount,consentRequired,}),- [- hasCodeAccess,- hasImportableConfig,- hasGithubIntegration,- projectCount,- consentRequired,- ],+ [hasImportableConfig, hasGithubIntegration, projectCount, consentRequired],);useEffect(() => {diff --git a/products/desktop/packages/ui/src/features/onboarding/onboardingStore.test.ts b/products/desktop/packages/ui/src/features/onboarding/onboardingStore.test.tsnew file mode 100644index 000000000000..4464bdbbec12--- /dev/null+++ b/products/desktop/packages/ui/src/features/onboarding/onboardingStore.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";+import { migrateOnboardingState } from "./onboardingStore";++describe("migrateOnboardingState", () => {+ it("moves a persisted invite-code step forward", () => {+ const migrated = migrateOnboardingState({+ currentStep: "invite-code",+ hasCompletedOnboarding: false,+ hasShippedFirstPr: false,+ selectedProjectId: 1,+ });++ expect(migrated.currentStep).toBe("consent");+ });+});diff --git a/products/desktop/packages/ui/src/features/onboarding/onboardingStore.ts b/products/desktop/packages/ui/src/features/onboarding/onboardingStore.tsindex 66f6c5a43efd..c5bdcc35d906 100644--- a/products/desktop/packages/ui/src/features/onboarding/onboardingStore.ts+++ b/products/desktop/packages/ui/src/features/onboarding/onboardingStore.ts@@ -30,6 +30,16 @@ const initialState: OnboardingStoreState = {selectedProjectId: null,};+export function migrateOnboardingState(+ persistedState: unknown,+): OnboardingStore {+ const state = persistedState as OnboardingStore;+ if ((state.currentStep as string) === "invite-code") {+ return { ...state, currentStep: "consent" };+ }+ return state;+}+export const useOnboardingStore = create<OnboardingStore>()(persist((set) => ({@@ -51,6 +61,8 @@ export const useOnboardingStore = create<OnboardingStore>()(}),{name: "onboarding-store",+ version: 1,+ migrate: migrateOnboardingState,partialize: (state) => ({currentStep: state.currentStep,hasCompletedOnboarding: state.hasCompletedOnboarding,diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.tsindex 4d762672bbc9..e4f2ee819039 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts@@ -91,7 +91,7 @@ const mockAuth = vi.hoisted(() => ({},currentOrgId: "org-1",currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,})),getAuthenticatedClient: vi.fn<() => Promise<Record<string, unknown> | null>>(@@ -374,7 +374,7 @@ describe("SessionService cloud queue recovery (real store, e2e)", () => {},currentOrgId: "org-1",currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,});mockTrpcAgent.onSessionEvent.subscribe.mockReturnValue({diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex 30c0fc7597a7..a44c350da84e 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -160,7 +160,7 @@ const mockAuth = vi.hoisted(() => ({},currentOrgId: "org-1",currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,})),getAuthenticatedClient: vi.fn<() => Promise<Record<string, unknown> | null>>(@@ -525,7 +525,7 @@ describe("SessionService", () => {},currentOrgId: "org-1",currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,});mockTrpcAgent.onSessionEvent.subscribe.mockReturnValue({@@ -694,7 +694,7 @@ describe("SessionService", () => {orgProjectsMap: {},currentOrgId: "org-2",currentProjectId: 456,- hasCodeAccess: true,+ desktopAccess: { projectId: 456, status: "allowed", reason: null },needsScopeReauth: false,});const second = service.getCloudAttachmentPreviewUrl(@@ -905,7 +905,7 @@ describe("SessionService", () => {},currentOrgId: "org-1",currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,});mockBuildAuthenticatedClient.mockReturnValue({@@ -965,7 +965,7 @@ describe("SessionService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: null,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,});mockBuildAuthenticatedClient.mockReturnValue(null);@@ -1001,7 +1001,7 @@ describe("SessionService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: 123,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,});@@ -1034,7 +1034,7 @@ describe("SessionService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,});@@ -6921,7 +6921,7 @@ describe("SessionService", () => {},currentOrgId: "org-1",currentProjectId: 123,- hasCodeAccess: true,+ desktopAccess: { projectId: 123, status: "allowed", reason: null },needsScopeReauth: false,});mockBuildAuthenticatedClient.mockReturnValue({@@ -7196,7 +7196,7 @@ describe("SessionService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: 123,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,});@@ -7295,7 +7295,7 @@ describe("SessionService", () => {orgProjectsMap: {},currentOrgId: null,currentProjectId: 123,- hasCodeAccess: null,+ desktopAccess: { projectId: null, status: "unchecked", reason: null },needsScopeReauth: false,});diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsxindex 4fd6bc6a1656..cf1dfafb6dbc 100644--- a/products/desktop/packages/ui/src/shell/App.tsx+++ b/products/desktop/packages/ui/src/shell/App.tsx@@ -4,8 +4,15 @@ import { EXTERNAL_LINKS, isNotAuthenticatedError } from "@posthog/shared";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { useAuthStateValue } from "@posthog/ui/features/auth/authQueries";import { AuthScreen } from "@posthog/ui/features/auth/components/AuthScreen";-import { InviteCodeScreen } from "@posthog/ui/features/auth/components/InviteCodeScreen";+import { DesktopAccessScreen } from "@posthog/ui/features/auth/components/DesktopAccessScreen";import { ScopeReauthPrompt } from "@posthog/ui/features/auth/components/ScopeReauthPrompt";+import {+ useLogoutMutation,+ useRedeemInviteCodeMutation,+ useRetryDesktopAccessMutation,+ useSelectProjectMutation,+ useSwitchOrgMutation,+} from "@posthog/ui/features/auth/useAuthMutations";import { useAuthSession } from "@posthog/ui/features/auth/useAuthSession";import { useIsOrgAdmin } from "@posthog/ui/features/auth/useOrgRole";import { CanvasGenerationToaster } from "@posthog/ui/features/canvas/freeform/useCanvasGenerationToasts";@@ -51,7 +58,20 @@ function App({ devToolbar }: AppProps) {(state) => state.hasCompletedOnboarding,);const isAuthenticated = authState.status === "authenticated";- const hasCodeAccess = authState.hasCodeAccess;+ const desktopAccess = authState.desktopAccess;+ const selectProjectMutation = useSelectProjectMutation();+ const switchOrgMutation = useSwitchOrgMutation();+ const retryDesktopAccessMutation = useRetryDesktopAccessMutation();+ const redeemInviteCodeMutation = useRedeemInviteCodeMutation();+ const logoutMutation = useLogoutMutation();+ const desktopAccessIsCurrent =+ desktopAccess.projectId === authState.currentProjectId;+ const hasDesktopAccess =+ desktopAccessIsCurrent && desktopAccess.status === "allowed";+ const switchError =+ selectProjectMutation.isError || switchOrgMutation.isError+ ? "Couldn't switch your selection. Try again."+ : null;// Analytics init + dev inbox console moved to host CONTRIBUTIONs// (AnalyticsBootContribution / InboxDemoDevContribution), started by// boot at boot.@@ -60,21 +80,24 @@ function App({ devToolbar }: AppProps) {// CONTRIBUTIONs (WorkspaceEventsContribution / FocusEventsContribution// / AgentEventsContribution), started by boot at boot.- const needsInviteCode =- isAuthenticated && hasCodeAccess === false && hasCompletedOnboarding;+ const isBlockedByAccessPolicy =+ isAuthenticated &&+ desktopAccessIsCurrent &&+ ["blocked", "error"].includes(desktopAccess.status);const authenticatedClient = useOptionalAuthenticatedClient();- const consent = useOrgConsent(isAuthenticated && hasCodeAccess === true);+ const consent = useOrgConsent(isAuthenticated && hasDesktopAccess);const needsConsent =isAuthenticated &&hasCompletedOnboarding &&- hasCodeAccess === true &&+ hasDesktopAccess &&consent.status === "resolved" &&!consent.satisfied;const isCheckingAccess =isAuthenticated &&hasCompletedOnboarding &&- (hasCodeAccess === null ||- (hasCodeAccess === true && consent.status === "loading"));+ (!desktopAccessIsCurrent ||+ ["unchecked", "checking"].includes(desktopAccess.status) ||+ (hasDesktopAccess && consent.status === "loading"));const { isAdmin: isOrgAdmin } = useIsOrgAdmin();const isAdmin = isOrgAdmin === true;useConsentAnalytics(@@ -93,8 +116,7 @@ function App({ devToolbar }: AppProps) {isBootstrapped &&isAuthenticated &&hasCompletedOnboarding &&- !isCheckingAccess &&- !needsInviteCode &&+ hasDesktopAccess &&consent.status === "resolved" &&consent.satisfied;const startupIdentity = getAuthIdentity(authState);@@ -170,9 +192,8 @@ function App({ devToolbar }: AppProps) {return <AppLoadingScreen />;}- // Rendering: onboarding (includes auth + invite code gate) → main appconst renderContent = () => {- if (!hasCompletedOnboarding) {+ if (!hasCompletedOnboarding && !isBlockedByAccessPolicy) {return (<motion.divkey="onboarding"@@ -194,14 +215,39 @@ function App({ devToolbar }: AppProps) {);}- if (needsInviteCode) {+ if (isBlockedByAccessPolicy) {return (<motion.div- key="invite-code"+ key="desktop-access"initial={{ opacity: 1 }}className="h-full">- <InviteCodeScreen />+ <DesktopAccessScreen+ access={desktopAccess}+ orgProjectsMap={authState.orgProjectsMap}+ currentOrgId={authState.currentOrgId}+ currentProjectId={authState.currentProjectId}+ isSwitching={+ selectProjectMutation.isPending || switchOrgMutation.isPending+ }+ isRetrying={retryDesktopAccessMutation.isPending}+ isRedeemingInviteCode={redeemInviteCodeMutation.isPending}+ isLoggingOut={logoutMutation.isPending}+ switchError={switchError}+ redemptionError={redeemInviteCodeMutation.error?.message ?? null}+ onSelectOrganization={(organizationId) =>+ switchOrgMutation.mutate(organizationId)+ }+ onSelectProject={(projectId) =>+ selectProjectMutation.mutate(projectId)+ }+ onRedeemInviteCode={(inviteCode) =>+ redeemInviteCodeMutation.mutate(inviteCode)+ }+ onRetry={() => retryDesktopAccessMutation.mutate()}+ onLogout={() => logoutMutation.mutate()}+ onOpenSupport={() => openExternalUrl(EXTERNAL_LINKS.talkToHuman)}+ /></motion.div>);}