Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(ios): stop repeated re-auth on iOS — only latch definitive refresh rejections (#5553)
Peter Chinmanf888e59de8c8
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex 910b42f223..9c8639882e 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -95,7 +95,6 @@ const AUTH_URLS = [`${ROUTER_BASE_CONCAT}setup`,`${ROUTER_BASE_CONCAT}signup`,`${ROUTER_BASE_CONCAT}email-signup-callback`,- `${ROUTER_BASE_CONCAT}offline`,`${ROUTER_BASE_CONCAT}welcome`,`${ROUTER_BASE_CONCAT}mobile-email-signup`,`${ROUTER_BASE_CONCAT}team-invite`,diff --git a/apps/web/src/features/auth/Login.tsx b/apps/web/src/features/auth/Login.tsxindex 8638b3a570..f14bc36430 100644--- a/apps/web/src/features/auth/Login.tsx+++ b/apps/web/src/features/auth/Login.tsx@@ -493,9 +493,12 @@ export function Login(props: { signupMode?: boolean }) {? rawToken[rawToken.length - 1]: rawToken;if (session_code && typeof session_code === 'string') {- unsetTokenPromise();authServiceClient.sessionLogin({ session_code }).then(async (res) => {if (res.isOk()) {+ // Reset token state only after the session cookies have actually+ // changed — resetting before sessionLogin opens a window where a+ // visibility-triggered refresh re-latches under the new generation.+ unsetTokenPromise();await invalidateAllAfterLogin();await initEmailLink().match(() => {},diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.tsindex ebb34d8189..e36d1f76b9 100644--- a/apps/web/src/features/auth/useSsoLogin.ts+++ b/apps/web/src/features/auth/useSsoLogin.ts@@ -65,13 +65,15 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {return;}- unsetTokenPromise();-const res = await authServiceClient.sessionLogin({session_code: result.token,});if (res.isOk()) {+ // Reset token state only after the session cookies have actually+ // changed — resetting before sessionLogin opens a window where a+ // visibility-triggered refresh re-latches under the new generation.+ unsetTokenPromise();await invalidateAllAfterLogin();await initEmailLink().match(() => {},diff --git a/apps/web/src/lib/core/context/user.test.ts b/apps/web/src/lib/core/context/user.test.tsnew file mode 100644index 0000000000..58ddb5e8d2--- /dev/null+++ b/apps/web/src/lib/core/context/user.test.ts@@ -0,0 +1,92 @@+/**+ * @vitest-environment jsdom+ */++import { ThrownResultError } from '@core/util/result';+import type { UserInfoData } from '@queries/auth/user-info';+import { describe, expect, test, vi } from 'vitest';+import { deriveIsAuthenticated } from './user';++vi.mock('@queries/auth/user-info', () => ({+ useUserInfoQuery: vi.fn(),+}));++type QueryState = Parameters<typeof deriveIsAuthenticated>[0];++function queryState(overrides: Partial<QueryState>): QueryState {+ return {+ isLoading: false,+ isError: false,+ error: null,+ data: undefined,+ ...overrides,+ } as QueryState;+}++function thrownError(code: string) {+ return new ThrownResultError([{ code, message: '' }]);+}++const authenticated = { authenticated: true } as UserInfoData;++describe('deriveIsAuthenticated', () => {+ test('loading with no data is unknown', () => {+ expect(deriveIsAuthenticated(queryState({ isLoading: true }))).toBe(+ undefined+ );+ });++ test('a 401 with no data is signed out', () => {+ expect(+ deriveIsAuthenticated(+ queryState({ isError: true, error: thrownError('UNAUTHORIZED') })+ )+ ).toBe(false);+ });++ test('a 401 wins over retained data', () => {+ expect(+ deriveIsAuthenticated(+ queryState({+ isError: true,+ error: thrownError('UNAUTHORIZED'),+ data: authenticated,+ })+ )+ ).toBe(false);+ });++ test('a transient failure with no data is unknown', () => {+ expect(+ deriveIsAuthenticated(+ queryState({ isError: true, error: thrownError('NETWORK_ERROR') })+ )+ ).toBe(undefined);+ });++ test('retained data survives a failed background refetch', () => {+ // An offline cold start restores user-info from cache, then the mount+ // refetch fails; last-known auth state must win over the transient error.+ expect(+ deriveIsAuthenticated(+ queryState({+ isError: true,+ error: thrownError('NETWORK_ERROR'),+ data: authenticated,+ })+ )+ ).toBe(true);+ });++ test('a successful unauthenticated response is signed out', () => {+ expect(+ deriveIsAuthenticated(+ queryState({ data: { authenticated: false } as UserInfoData })+ )+ ).toBe(false);+ });++ test('settled with no data and no error is signed out', () => {+ expect(deriveIsAuthenticated(queryState({}))).toBe(false);+ });+});diff --git a/apps/web/src/lib/core/context/user.ts b/apps/web/src/lib/core/context/user.tsindex b697143341..f3d7f954c6 100644--- a/apps/web/src/lib/core/context/user.ts+++ b/apps/web/src/lib/core/context/user.ts@@ -23,6 +23,28 @@ type UserContextValue = {referralCode: Accessor<string | undefined>;};+/**+ * Derives the auth state from the user-info query. Data-first: a failed+ * background refetch keeps the previous data alongside the error, and the+ * last-known auth state must survive it — otherwise an offline cold start+ * that restored user-info from cache drops all auth-gated chrome.+ */+export function deriveIsAuthenticated(+ query: Pick<+ ReturnType<typeof useUserInfoQuery>,+ 'isLoading' | 'isError' | 'error' | 'data'+ >+): boolean | undefined {+ // Only a 401 proves the user is signed out; it wins even over retained data.+ if (thrownResultErrorHasCode(query.error, 'UNAUTHORIZED')) return false;+ if (query.data) return query.data.authenticated ?? false;+ // No data and no definitive signal: a transient failure (network blip, 5xx)+ // leaves the auth state unknown so consumers don't bounce an authenticated+ // user to login.+ if (query.isLoading || query.isError) return undefined;+ return false;+}+export const [UserContextProvider, useUserContext] =createAssertedContextProvider('UserContext', (): UserContextValue => {const query = useUserInfoQuery({ enabled: shouldQueryUserInfo });@@ -33,19 +55,7 @@ export const [UserContextProvider, useUserContext] =const isLoading = () => query.isLoading;- const isAuthenticated = createMemo((): boolean | undefined => {- if (query.isLoading) return undefined;- if (query.isError) {- // Only a 401 proves the user is signed out; a transient failure- // (network blip, 5xx) leaves the auth state unknown so consumers- // don't bounce an authenticated user to login.- return thrownResultErrorHasCode(query.error, 'UNAUTHORIZED')- ? false- : undefined;- }- if (!query.data) return false;- return query.data.authenticated ?? false;- });+ const isAuthenticated = createMemo(() => deriveIsAuthenticated(query));const userId = createMemo(() => userInfo()?.id);const email = createMemo(() => userInfo()?.email);diff --git a/apps/web/src/lib/core/util/fetchWithToken.spec.ts b/apps/web/src/lib/core/util/fetchWithToken.spec.tsindex 822cb08960..8d3b7c0ce0 100644--- a/apps/web/src/lib/core/util/fetchWithToken.spec.ts+++ b/apps/web/src/lib/core/util/fetchWithToken.spec.ts@@ -5,6 +5,7 @@import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import {+ confirmSessionExpired,fetchToken,fetchWithToken,unsetTokenPromise,@@ -12,15 +13,29 @@ import {const RESOURCE_URL = 'https://localhost/resource';+// One of the auth service's definitive "session cannot be refreshed" bodies.+const REFRESH_REJECTED_BODY = 'no refresh token to refresh';+function jsonResponse(status: number, body: unknown = {}): Response {return {ok: status >= 200 && status < 300,status,json: () => Promise.resolve(body),+ text: () => Promise.resolve(JSON.stringify(body)),headers: new Headers({ 'Content-Type': 'application/json' }),} as Response;}+function textResponse(status: number, body: string): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: () => Promise.reject(new SyntaxError('not json')),+ text: () => Promise.resolve(body),+ headers: new Headers({ 'Content-Type': 'text/plain' }),+ } as Response;+}+function deferred<T>() {let resolve!: (value: T) => void;const promise = new Promise<T>((r) => {@@ -46,6 +61,7 @@ describe('fetchWithToken refresh latch', () => {afterEach(() => {global.fetch = originalFetch;mockFetch.mockReset();+ vi.useRealTimers();});const refreshCalls = () =>@@ -53,7 +69,11 @@ describe('fetchWithToken refresh latch', () => {test('fires at most one doomed refresh across sequential 401s', async () => {mockFetch.mockImplementation((input) =>- Promise.resolve(isRefresh(input) ? jsonResponse(400) : jsonResponse(401))+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, REFRESH_REJECTED_BODY)+ : jsonResponse(401)+ ));for (let i = 0; i < 3; i++) {@@ -67,6 +87,17 @@ describe('fetchWithToken refresh latch', () => {expect(refreshCalls()).toBe(1);});+ test('a 401 from the refresh endpoint latches', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(isRefresh(input) ? jsonResponse(401) : jsonResponse(401))+ );++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ await fetchWithToken<{ data: string }>(RESOURCE_URL);++ expect(refreshCalls()).toBe(1);+ });+test('authenticated expired-token request still refreshes and retries', async () => {let refreshed = false;mockFetch.mockImplementation((input) => {@@ -114,9 +145,107 @@ describe('fetchWithToken refresh latch', () => {expect(refreshCalls()).toBe(2);});+ test('a proxy 400 without a known rejection body does not latch', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, '<html>Bad Request</html>')+ : jsonResponse(401)+ )+ );++ const result = await fetchWithToken<{ data: string }>(RESOURCE_URL);+ await fetchWithToken<{ data: string }>(RESOURCE_URL);++ expect(refreshCalls()).toBe(2);+ // The transient failure surfaces as-is instead of masquerading as a dead+ // session.+ expect(result.isErr()).toBe(true);+ if (result.isErr()) {+ expect(result.error.some((e) => e.code === 'HTTP_ERROR')).toBe(true);+ expect(result.error.some((e) => e.code === 'UNAUTHORIZED')).toBe(false);+ }+ });++ test('a gateway error (502) surfaces as HTTP_ERROR and does not latch', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(isRefresh(input) ? jsonResponse(502) : jsonResponse(401))+ );++ const result = await fetchWithToken<{ data: string }>(RESOURCE_URL);+ await fetchWithToken<{ data: string }>(RESOURCE_URL);++ expect(refreshCalls()).toBe(2);+ expect(result.isErr()).toBe(true);+ if (result.isErr()) {+ expect(result.error.some((e) => e.code === 'UNAUTHORIZED')).toBe(false);+ }+ });++ test('a latched failure expires after the TTL', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ mockFetch.mockImplementation((input) =>+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, REFRESH_REJECTED_BODY)+ : jsonResponse(401)+ )+ );++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(1);++ vi.setSystemTime(Date.now() + 61_000);++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(2);+ });++ test('regaining visibility clears the latch', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, REFRESH_REJECTED_BODY)+ : jsonResponse(401)+ )+ );++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(1);++ // jsdom's visibilityState is 'visible', so this models a foregrounding.+ document.dispatchEvent(new Event('visibilitychange'));++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(2);+ });++ test('regaining connectivity clears the latch', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, REFRESH_REJECTED_BODY)+ : jsonResponse(401)+ )+ );++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(1);++ window.dispatchEvent(new Event('online'));++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(2);+ });+test('unsetTokenPromise clears the latch so refresh is attempted again', async () => {mockFetch.mockImplementation((input) =>- Promise.resolve(isRefresh(input) ? jsonResponse(400) : jsonResponse(401))+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, REFRESH_REJECTED_BODY)+ : jsonResponse(401)+ ));await fetchWithToken<{ data: string }>(RESOURCE_URL);@@ -148,8 +277,8 @@ describe('fetchWithToken refresh latch', () => {await tick();expect(refreshCalls()).toBe(2);- // R1 fails under the stale generation.- pending[0].resolve(jsonResponse(400));+ // R1 fails definitively under the stale generation.+ pending[0].resolve(textResponse(400, REFRESH_REJECTED_BODY));expect((await p1).isErr()).toBe(true);// R1's finally must not have cleared R2's tokenPromise: a call now dedupes@@ -166,4 +295,37 @@ describe('fetchWithToken refresh latch', () => {expect((await fetchToken()).isOk()).toBe(true);expect(refreshCalls()).toBe(3);});++ test('confirmSessionExpired bypasses the latch and confirms a definitive rejection', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(+ isRefresh(input)+ ? textResponse(400, REFRESH_REJECTED_BODY)+ : jsonResponse(401)+ )+ );++ await fetchWithToken<{ data: string }>(RESOURCE_URL);+ expect(refreshCalls()).toBe(1);++ // Despite the latch, confirmation must consult the server again.+ await expect(confirmSessionExpired()).resolves.toBe(true);+ expect(refreshCalls()).toBe(2);+ });++ test('confirmSessionExpired reports a transient failure as not expired', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(isRefresh(input) ? jsonResponse(503) : jsonResponse(401))+ );++ await expect(confirmSessionExpired()).resolves.toBe(false);+ });++ test('confirmSessionExpired reports an alive session as not expired', async () => {+ mockFetch.mockImplementation((input) =>+ Promise.resolve(isRefresh(input) ? jsonResponse(200) : jsonResponse(401))+ );++ await expect(confirmSessionExpired()).resolves.toBe(false);+ });});diff --git a/apps/web/src/lib/core/util/fetchWithToken.ts b/apps/web/src/lib/core/util/fetchWithToken.tsindex cf177a9f01..68e4c86733 100644--- a/apps/web/src/lib/core/util/fetchWithToken.ts+++ b/apps/web/src/lib/core/util/fetchWithToken.ts@@ -54,21 +54,67 @@ type TokenResult = Result<void, ResultError<FetchWithTokenErrorCode>[]>;let tokenPromise: Promise<TokenResult> | null = null;-// Once /jwt/refresh fails because the session is not authenticated (400/401),-// cache that failure so subsequent 401s short-circuit instead of each firing-// another doomed refresh. An anonymous visitor on a public link otherwise-// triggers one refresh per authenticated app-chrome query. Cleared by-// unsetTokenPromise, which the login flows call on a session change.+// Once /jwt/refresh definitively rejects the session, cache that failure so+// subsequent 401s short-circuit instead of each firing another doomed refresh.+// An anonymous visitor on a public link otherwise triggers one refresh per+// authenticated app-chrome query. Only a definitive rejection latches:+// transient failures (proxy errors, outages) must never be remembered as+// "logged out". Cleared by unsetTokenPromise on login, by TTL expiry, and when+// the app regains visibility/connectivity — on native the webview lives for+// days without a reload, so a permanent latch turns one bad response into a+// forced re-login.let refreshUnavailable: TokenResult | null = null;+let refreshUnavailableAt = 0;+const REFRESH_UNAVAILABLE_TTL_MS = 60_000;// Bumped on every reset. A refresh started before a reset carries the older// generation, so once the session has moved on (e.g. a login) it can neither// re-latch refreshUnavailable nor clear a newer tokenPromise on completion.let refreshGeneration = 0;+function clearRefreshLatch() {+ refreshUnavailable = null;+}++if (typeof window !== 'undefined' && typeof document !== 'undefined') {+ window.addEventListener('online', clearRefreshLatch);+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') clearRefreshLatch();+ });+}++// The auth service's definitive "this session cannot be refreshed" bodies+// (RefreshError and the token-extraction middleware in authentication_service+// return these as text/plain 400s). Any other non-2xx on /jwt/refresh — proxy+// 400s, 408/429, 5xx — is transient and must not latch.+const REFRESH_REJECTED_BODIES = new Set([+ 'invalid refresh token',+ 'no access token to refresh',+ 'no refresh token to refresh',+]);++const classifyRefreshError: ErrorResponseHandler<never> = async (response) => {+ if (response.status === 400) {+ let body = '';+ try {+ body = (await response.text()).trim();+ } catch {}+ if (REFRESH_REJECTED_BODIES.has(body)) {+ return { code: 'UNAUTHORIZED', message: body };+ }+ }+ return {+ code: 'HTTP_ERROR',+ message: `HTTP error! status: ${response.status}`,+ };+};+export async function fetchToken(): Promise<TokenResult> {if (refreshUnavailable != null) {- return refreshUnavailable;+ if (Date.now() - refreshUnavailableAt < REFRESH_UNAVAILABLE_TTL_MS) {+ return refreshUnavailable;+ }+ refreshUnavailable = null;}if (tokenPromise == null) {const generation = refreshGeneration;@@ -83,6 +129,7 @@ export async function fetchToken(): Promise<TokenResult> {Accept: 'application/json',},cache: 'no-store',+ errorResponseHandler: classifyRefreshError,});@@ -90,11 +137,10 @@ export async function fetchToken(): Promise<TokenResult> {const failure = err(result.error);if (generation === refreshGeneration &&- result.error.some(- (e) => e.code === 'HTTP_ERROR' || e.code === 'UNAUTHORIZED'- )+ result.error.some((e) => e.code === 'UNAUTHORIZED')) {refreshUnavailable = failure;+ refreshUnavailableAt = Date.now();}return failure;}@@ -110,6 +156,18 @@ export async function fetchToken(): Promise<TokenResult> {return tokenPromise;}+/**+ * Bypasses any latched refresh failure and asks the auth service directly+ * whether the session can still be refreshed. Returns true only on a+ * definitive rejection. Callers about to destroy local session state must use+ * this instead of trusting a possibly-stale latched UNAUTHORIZED.+ */+export async function confirmSessionExpired(): Promise<boolean> {+ refreshUnavailable = null;+ const result = await fetchToken();+ return result.isErr() && result.error.some((e) => e.code === 'UNAUTHORIZED');+}+/*** Performs a fetch request with automatic token refresh on unauthorized errors.*@@ -161,14 +219,10 @@ export async function fetchWithToken<result.error.some((error) => error.code === 'UNAUTHORIZED')) {const tokenResult = await fetchToken();- if (- tokenResult.isErr() &&- tokenResult.error.some((error) => error.code === 'HTTP_ERROR')- ) {- // converting this most likely a bad request to unauthorized error- return err([{ code: 'UNAUTHORIZED', message: '' }]);- }if (tokenResult.isErr()) {+ // A definitive rejection already carries UNAUTHORIZED; transient refresh+ // failures surface as-is so callers don't treat an outage as a dead+ // session.return err(tokenResult.error);}diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.tsindex 4b8cb1f7b7..3ace7462a6 100644--- a/apps/web/src/lib/queries/auth/user-info.ts+++ b/apps/web/src/lib/queries/auth/user-info.ts@@ -35,6 +35,10 @@ export function useUserInfoQuery(options?: UseUserInfoQueryOptions) {),throwOnError: false,staleTime: USER_INFO_STALE_TIME,+ // Never pause on navigator.onLine — it reports false during native cold+ // launches (e.g. woken by a notification tap) while the network is fine,+ // and a paused auth check renders as "unauthenticated" at the base path.+ networkMode: 'always',enabled,};});@@ -74,6 +78,7 @@ export async function prefetchUserInfo() {await throwOnErr(async () => await authServiceClient.getLegacyUserPermissions()),+ networkMode: 'always',}));}@@ -86,6 +91,7 @@ async function _fetchUserInfo() {await throwOnErr(async () => await authServiceClient.getLegacyUserPermissions()),+ networkMode: 'always',});}diff --git a/apps/web/src/lib/queries/persistence-scopes.ts b/apps/web/src/lib/queries/persistence-scopes.tsindex fcc35d14bc..0edcb431f8 100644--- a/apps/web/src/lib/queries/persistence-scopes.ts+++ b/apps/web/src/lib/queries/persistence-scopes.ts@@ -56,7 +56,6 @@ export function createQueryPersistenceScopes(store: createPerQueryIDBStore({dbName: createPersistenceKey('user-info', 1),}),- maxAge: { value: 7, unit: 'd' },buster,shouldPersist: (queryKey: QueryKey) =>partialMatchKey(queryKey, authKeys.userInfo.queryKey),diff --git a/apps/web/src/lib/queries/persistence.test.ts b/apps/web/src/lib/queries/persistence.test.tsindex 0b161ee2af..cda7d47711 100644--- a/apps/web/src/lib/queries/persistence.test.ts+++ b/apps/web/src/lib/queries/persistence.test.ts@@ -1,13 +1,21 @@import { partialMatchKey } from '@tanstack/query-core';import { QueryClient } from '@tanstack/solid-query';import { describe, expect, it, vi } from 'vitest';+import { authKeys } from './auth/keys';import { channelKeys } from './channel/keys';import { type PersistScope, setupQueryPersistence } from './persistence';import type {PerQueryPersistence,PersistedQueryEntry,} from './persistence/per-query-idb';-import { shouldPersistChannelQuery } from './persistence-scopes';+import {+ createQueryPersistenceScopes,+ shouldPersistChannelQuery,+} from './persistence-scopes';++vi.mock('@core/mobile/isNativeMobilePlatform', () => ({+ isNativeMobilePlatform: () => true,+}));function createMockStore(): PerQueryPersistence & {entries: Map<string, PersistedQueryEntry>;@@ -272,6 +280,52 @@ describe('setupQueryPersistence', () => {expect(store.remove).toHaveBeenCalledWith('["channel","old"]');});+ it('restores entries regardless of age when the scope has no max age', async () => {+ const queryClient = new QueryClient();+ const store = createMockStore();+ const tenYearsAgo = Date.now() - 10 * 365 * 24 * 60 * 60 * 1000;++ store.entries.set('["identity","user"]', {+ queryHash: '["identity","user"]',+ queryKey: ['identity', 'user'],+ data: { authenticated: true },+ dataUpdatedAt: tenYearsAgo,+ persistedAt: tenYearsAgo,+ buster: 'test',+ });++ const scope = createScope(['identity'], store, { maxAge: undefined });+ setupQueryPersistence({ queryClient, scopes: [scope] });++ void queryClient.prefetchQuery({+ queryKey: ['identity', 'user'],+ queryFn: () => new Promise(() => {}),+ });++ await Promise.resolve();+ await Promise.resolve();++ expect(queryClient.getQueryData(['identity', 'user'])).toEqual({+ authenticated: true,+ });+ expect(store.remove).not.toHaveBeenCalled();+ });++ it('configures only native user-info persistence without an expiry', () => {+ const scopes = createQueryPersistenceScopes('test');+ const userInfoScope = scopes.find((scope) =>+ scope.shouldPersist(authKeys.userInfo.queryKey)+ );++ expect(userInfoScope).toBeDefined();+ expect(userInfoScope?.maxAge).toBeUndefined();+ expect(+ scopes+ .filter((scope) => scope !== userInfoScope)+ .every((scope) => scope.maxAge !== undefined)+ ).toBe(true);+ });+it('removes buster-mismatched entries instead of restoring', async () => {const queryClient = new QueryClient();const store = createMockStore();diff --git a/apps/web/src/lib/queries/persistence.ts b/apps/web/src/lib/queries/persistence.tsindex 5c0cd76644..114439bdef 100644--- a/apps/web/src/lib/queries/persistence.ts+++ b/apps/web/src/lib/queries/persistence.ts@@ -24,7 +24,8 @@ export function createPersistenceKey(export type PersistScope = Readonly<{store: PerQueryPersistence;- maxAge: ParsedDuration;+ /** Omit to retain same-buster entries regardless of their age. */+ maxAge?: ParsedDuration;buster: string;shouldPersist: (queryKey: QueryKey) => boolean;shouldRestore?: (queryKey: QueryKey) => boolean;@@ -45,17 +46,20 @@ type QueryClientLike = {};/**- * Validates a persisted entry against the current cache-buster and max age.+ * Validates a persisted entry against the current cache-buster and optional+ * max age.* Returns 'valid' if the entry can be restored, or a reason string* explaining why it should be discarded.*/function validatePersistedEntry(entry: PersistedQueryEntry,buster: string,- maxAgeMs: number+ maxAgeMs?: number): 'valid' | 'buster_mismatch' | 'expired' {if (entry.buster !== buster) return 'buster_mismatch';- if (Date.now() - entry.dataUpdatedAt > maxAgeMs) return 'expired';+ if (maxAgeMs !== undefined && Date.now() - entry.dataUpdatedAt > maxAgeMs) {+ return 'expired';+ }return 'valid';}@@ -84,7 +88,9 @@ async function handleRestore(if (!entry) return;- const maxAgeMs = parsedDurationToMilliseconds(scope.maxAge);+ const maxAgeMs = scope.maxAge+ ? parsedDurationToMilliseconds(scope.maxAge)+ : undefined;if (validatePersistedEntry(entry, scope.buster, maxAgeMs) !== 'valid') {scope.store.remove(query.queryHash);return;diff --git a/apps/web/src/routes/BasePath.test.tsx b/apps/web/src/routes/BasePath.test.tsxnew file mode 100644index 0000000000..d8bee069e8--- /dev/null+++ b/apps/web/src/routes/BasePath.test.tsx@@ -0,0 +1,259 @@+/**+ * @vitest-environment jsdom+ */++import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';+import { ThrownResultError } from '@core/util/result';+import { QueryClientProvider } from '@tanstack/solid-query';+import type { JSX } from 'solid-js';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ clearLocalAuthSession: vi.fn(),+ confirmSessionExpired: vi.fn(),+ fetchUserInfo: vi.fn(),+ hasLoginCookie: true,+ nativeMobile: false,+ navigate: vi.fn(),+}));++vi.mock('@app/features/paywall/use-checkout-completion-listener', () => ({+ useCheckoutCompletionListener: () => () => false,+}));++vi.mock('@core/auth/logout', () => ({+ clearLocalAuthSession: mocks.clearLocalAuthSession,+}));++vi.mock('@core/mobile/isNativeMobilePlatform', () => ({+ isNativeMobilePlatform: () => mocks.nativeMobile,+}));++vi.mock('@core/util/cookies', () => ({+ hasLoginCookie: () => mocks.hasLoginCookie,+}));++vi.mock('@core/util/fetchWithToken', () => ({+ confirmSessionExpired: mocks.confirmSessionExpired,+}));++// A single client instance shared with the component under test: the+// SessionExpiredRedirect confirm path reads the refetched query error straight+// off this client, so the mock must hand both sides the same cache.+vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return {+ queryClient: new QueryClient({+ defaultOptions: { queries: { retry: false } },+ }),+ };+});++// Thin re-implementation of the user-info query over the mocked client, so the+// test controls fetch outcomes while keeping real query semantics (error+// state, invalidation-triggered refetches).+vi.mock('@queries/auth/user-info', async () => {+ const { useQuery } = await import('@tanstack/solid-query');+ const { queryClient } = await import('@queries/client');+ const authKeys = { userInfo: { queryKey: ['auth', 'userInfo'] } };+ return {+ authKeys,+ invalidateUserInfo: () =>+ queryClient.invalidateQueries({ queryKey: authKeys.userInfo.queryKey }),+ useUserInfoQuery: () =>+ useQuery(() => ({+ queryKey: authKeys.userInfo.queryKey,+ queryFn: mocks.fetchUserInfo,+ networkMode: 'always',+ })),+ };+});++vi.mock('@solidjs/router', () => ({+ // Mirrors the real Navigate component: a replace navigation on render.+ Navigate: (props: { href: string }) => {+ mocks.navigate(props.href, { replace: true });+ return null;+ },+ useSearchParams: () => [{}, () => {}],+}));++vi.mock('@ui', () => ({+ Button: (props: { children: JSX.Element; onClick?: () => void }) => (+ <button onClick={props.onClick}>{props.children}</button>+ ),+}));++import { queryClient } from '@queries/client';+import { BasePathComponent } from './BasePath';++const UNAUTHORIZED_ERROR = () =>+ new ThrownResultError([+ { code: 'UNAUTHORIZED', message: 'Unauthorized access' },+ ]);++const SERVER_ERROR = () =>+ new ThrownResultError([+ { code: 'SERVER_ERROR', message: 'Internal server error' },+ ]);++let dispose: (() => void) | undefined;++function renderRoute(): HTMLElement {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const disposeRender = render(+ () => (+ <QueryClientProvider client={queryClient}>+ <BasePathComponent />+ </QueryClientProvider>+ ),+ container+ );+ dispose = () => {+ disposeRender();+ container.remove();+ };+ return container;+}++/** Lets in-flight query/resource promises settle before negative assertions. */+function flush() {+ return new Promise((resolve) => setTimeout(resolve, 25));+}++beforeEach(() => {+ mocks.hasLoginCookie = true;+ mocks.nativeMobile = false;+ mocks.navigate.mockReset();+ mocks.fetchUserInfo.mockReset();+ mocks.confirmSessionExpired.mockReset();+ mocks.clearLocalAuthSession.mockReset();+ mocks.clearLocalAuthSession.mockResolvedValue(undefined);+ sessionStorage.clear();+ queryClient.clear();+ window.history.replaceState({}, '', '/app/');+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+});++describe('BasePathComponent', () => {+ it('redirects an authenticated session to the default route', async () => {+ mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });++ renderRoute();++ await vi.waitFor(() => {+ expect(mocks.navigate).toHaveBeenCalledWith(DEFAULT_ROUTE, {+ replace: true,+ });+ });+ });++ it('redirects a session without a login cookie to welcome', async () => {+ mocks.hasLoginCookie = false;+ mocks.fetchUserInfo.mockResolvedValue({ authenticated: false });++ renderRoute();++ await vi.waitFor(() => {+ expect(mocks.navigate).toHaveBeenCalledWith('/welcome', {+ replace: true,+ });+ });+ expect(mocks.confirmSessionExpired).not.toHaveBeenCalled();+ });++ it('clears the session and redirects on a confirmed expiry', async () => {+ mocks.fetchUserInfo.mockRejectedValue(UNAUTHORIZED_ERROR());+ mocks.confirmSessionExpired.mockResolvedValue(true);++ renderRoute();++ await vi.waitFor(() => {+ expect(mocks.clearLocalAuthSession).toHaveBeenCalled();+ expect(mocks.navigate).toHaveBeenCalledWith('/welcome', {+ replace: true,+ });+ });+ });++ it('keeps a cookie-backed session off welcome when the confirm refresh fails transiently', async () => {+ // A latched refresh failure surfaced UNAUTHORIZED, but the confirming+ // refresh says the session is alive — and the user-info refetch then hits+ // a transient server failure. The query settles into a non-UNAUTHORIZED+ // error: "unknown", not "unauthenticated".+ mocks.fetchUserInfo+ .mockRejectedValueOnce(UNAUTHORIZED_ERROR())+ .mockRejectedValue(SERVER_ERROR());+ mocks.confirmSessionExpired.mockResolvedValue(false);++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(mocks.confirmSessionExpired).toHaveBeenCalled();+ expect(mocks.fetchUserInfo).toHaveBeenCalledTimes(2);+ });+ await flush();++ // The local session survives and the unknown state renders nothing+ // instead of bouncing a possibly-valid session to login.+ expect(mocks.clearLocalAuthSession).not.toHaveBeenCalled();+ expect(mocks.navigate).not.toHaveBeenCalled();+ expect(container.textContent).toBe('');+ });++ it('asks native users to verify their session when no local identity is available', async () => {+ mocks.nativeMobile = true;+ mocks.fetchUserInfo.mockRejectedValue(SERVER_ERROR());++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Unable to connect.');+ });+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ it('enters the native app with a cached identity when its refresh fails', async () => {+ mocks.nativeMobile = true;+ mocks.fetchUserInfo.mockRejectedValue(SERVER_ERROR());+ queryClient.setQueryData(['auth', 'userInfo'], { authenticated: true });++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(mocks.navigate).toHaveBeenCalledWith(DEFAULT_ROUTE, {+ replace: true,+ });+ });+ await flush();++ expect(container.textContent).not.toContain('Unable to connect.');+ });++ it('enters the app after session verification succeeds', async () => {+ mocks.nativeMobile = true;+ mocks.fetchUserInfo+ .mockRejectedValueOnce(SERVER_ERROR())+ .mockResolvedValue({ authenticated: true });++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Unable to connect.');+ });++ container.querySelector('button')?.click();++ await vi.waitFor(() => {+ expect(mocks.navigate).toHaveBeenCalledWith(DEFAULT_ROUTE, {+ replace: true,+ });+ });+ });+});diff --git a/apps/web/src/routes/BasePath.tsx b/apps/web/src/routes/BasePath.tsxnew file mode 100644index 0000000000..b3d5761f99--- /dev/null+++ b/apps/web/src/routes/BasePath.tsx@@ -0,0 +1,163 @@+import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';+import { useCheckoutCompletionListener } from '@app/features/paywall/use-checkout-completion-listener';+import { clearLocalAuthSession } from '@core/auth/logout';+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';+import { hasLoginCookie } from '@core/util/cookies';+import { confirmSessionExpired } from '@core/util/fetchWithToken';+import { consumePostLoginRedirect } from '@core/util/postLoginRedirect';+import { thrownResultErrorHasCode } from '@core/util/result';+import {+ authKeys,+ invalidateUserInfo,+ useUserInfoQuery,+} from '@queries/auth/user-info';+import { queryClient } from '@queries/client';+import { Navigate, useSearchParams } from '@solidjs/router';+import { Button } from '@ui';+import {+ createResource,+ createSignal,+ Match,+ onMount,+ Show,+ Switch,+} from 'solid-js';++function getCurrentQueryString() {+ const params = new URLSearchParams(window.location.search);+ return params.toString().length > 0 ? `?${params.toString()}` : '';+}++function shouldShowNativeSessionVerificationFallback(+ userInfoQuery: ReturnType<typeof useUserInfoQuery>+) {+ return (+ userInfoQuery.isError &&+ !userInfoQuery.data?.authenticated &&+ hasLoginCookie() &&+ isNativeMobilePlatform() &&+ !thrownResultErrorHasCode(userInfoQuery.error, 'UNAUTHORIZED')+ );+}++function SessionVerificationFallback(props: {+ onRetry: () => Promise<unknown>;+}) {+ const [retrying, setRetrying] = createSignal(false);++ const handleRetry = async () => {+ setRetrying(true);+ try {+ await props.onRetry();+ } finally {+ setRetrying(false);+ }+ };++ return (+ <div class="flex flex-col items-center justify-center gap-4 size-full text-ink-muted">+ <p class="text-sm">Unable to connect. Please check your network.</p>+ <Button+ class="mt-2"+ disabled={retrying()}+ onClick={handleRetry}+ variant="base"+ >+ {retrying() ? 'Retrying…' : 'Retry'}+ </Button>+ </div>+ );+}++function SessionExpiredRedirect() {+ // The UNAUTHORIZED that got us here can come from a latched refresh failure+ // without the server ever being consulted, so confirm with a fresh refresh+ // before destroying local session state. If the session turns out to be+ // alive, refetch user-info instead and only treat a repeat 401 as real.+ const [expired] = createResource(async () => {+ if (!(await confirmSessionExpired())) {+ await invalidateUserInfo();+ const stillUnauthorized = thrownResultErrorHasCode(+ queryClient.getQueryState(authKeys.userInfo.queryKey)?.error,+ 'UNAUTHORIZED'+ );+ if (!stillUnauthorized) return false;+ }+ await clearLocalAuthSession().catch((error) => {+ console.error('Failed to clear local auth session', error);+ });+ return true;+ });++ return (+ <Show when={expired()}>+ <Navigate href={`/welcome${getCurrentQueryString()}`} />+ </Show>+ );+}++export function BasePathComponent() {+ const [searchParams] = useSearchParams();+ const userInfoQuery = useUserInfoQuery();+ const checkoutRefreshPending = useCheckoutCompletionListener();++ onMount(() => {+ if (searchParams.upgrade === 'true') {+ sessionStorage.setItem('showUpgradeModal', 'true');+ }+ });++ // check session storage for redirect url+ const redirectUrl = consumePostLoginRedirect();+ if (redirectUrl) {+ const relativeUrl = redirectUrl.replace(window.location.origin, '');+ window.location.href = relativeUrl;+ return;+ }++ // Preserve existing query parameters when redirecting+ const queryString = getCurrentQueryString();+ const redirectPath = `${DEFAULT_ROUTE}${queryString}`;++ return (+ <Switch>+ <Match when={userInfoQuery.isLoading || checkoutRefreshPending()}>+ {null}+ </Match>+ <Match+ when={+ hasLoginCookie() &&+ thrownResultErrorHasCode(userInfoQuery.error, 'UNAUTHORIZED')+ }+ >+ <SessionExpiredRedirect />+ </Match>+ <Match when={userInfoQuery.data?.authenticated}>+ <Navigate href={redirectPath} />+ </Match>+ {/* A failed remote check does not make an authenticated cached session+ unusable: the data branch above enters the local app first. Block only+ when native has a login marker but no locally verifiable identity. */}+ <Match when={shouldShowNativeSessionVerificationFallback(userInfoQuery)}>+ <SessionVerificationFallback onRetry={() => userInfoQuery.refetch()} />+ </Match>+ {/* Backstop: the user-info query sets networkMode 'always', so it never+ pauses on navigator.onLine (which misreports offline during native+ cold launches) and this state is currently unreachable. If that ever+ regresses, a paused query (isLoading false, no data) means "unknown",+ not "unauthenticated": wait for the fetch to resume rather than show+ login to a possibly-valid session. */}+ <Match when={userInfoQuery.fetchStatus === 'paused'}>{null}</Match>+ {/* An errored query on a cookie-backed session is also "unknown": a+ transient refresh or server failure is not proof the session is gone+ (a definitive UNAUTHORIZED is handled above). Keep the local session+ and wait for a retry instead of bouncing to login. */}+ <Match when={hasLoginCookie() && userInfoQuery.isError}>{null}</Match>+ <Match+ when={!userInfoQuery.isLoading && !userInfoQuery.data?.authenticated}+ >+ <Navigate href={`/welcome${queryString}`} />+ </Match>+ </Switch>+ );+}diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex 339abbd624..be3d6258d0 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -11,7 +11,6 @@ import { SearchProvider } from '@app/features/next-soup/search-context';import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';import { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';import MobileWebSignup from '@app/features/onboarding/MobileWebSignup';-import { useCheckoutCompletionListener } from '@app/features/paywall/use-checkout-completion-listener';import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';import { TeamInviteAcceptance } from '@app/features/team-invitations/TeamInviteAcceptance';@@ -33,7 +32,6 @@ import { GlobalAppStateProvider } from '@components/app/GlobalAppState';import { Layout } from '@components/app/Layout';import { ReactiveFavicon } from '@components/app/ReactiveFavicon';import { LAYOUT_ROUTE } from '@components/app/split-layout/SplitLayoutRoute';-import { clearLocalAuthSession } from '@core/auth/logout';import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';import { LoadingBlock } from '@core/component/LoadingBlock';import { ToastRegion } from '@core/component/Toast/ToastRegion';@@ -55,14 +53,11 @@ import { createBlockOrchestrator } from '@core/orchestrator';import { formatTabTitle, tabTitleSignal } from '@core/signal/tabTitle';import {getLoginCookieOptions,- hasLoginCookie,syncLoginStorage,updateCookie,} from '@core/util/cookies';import { licenseChannel } from '@core/util/licenseUpdateBroadcastChannel';import { isTauri } from '@core/util/platform';-import { consumePostLoginRedirect } from '@core/util/postLoginRedirect';-import { thrownResultErrorHasCode } from '@core/util/result';import { transformShortIdInUrlPathname } from '@core/util/url';import { EntityProvider } from '@entity';import { MaybeTauriProvider } from '@macro/tauri';@@ -95,7 +90,6 @@ import {Router,type RouterProps,useLocation,- useSearchParams,} from '@solidjs/router';import {applyTheme,@@ -109,15 +103,14 @@ import {createEffect,createSignal,type JSX,- Match,on,onCleanup,onMount,type ParentProps,Show,Suspense,- Switch,} from 'solid-js';+import { BasePathComponent } from './BasePath';import { TaskRoute } from './TaskRoute';/** Syncs login cookie with auth state. Only updates on successful query (not errors/loading). */@@ -174,121 +167,6 @@ const rootPreload: RoutePreloadFunc = async (args) => {}};-function OfflineFallback(props: { onRetry: () => Promise<unknown> }) {- const [retrying, setRetrying] = createSignal(false);-- const handleRetry = async () => {- setRetrying(true);- await props.onRetry();- setRetrying(false);- };-- return (- <div class="flex flex-col items-center justify-center gap-4 size-full text-ink-muted">- <p class="text-sm">Unable to connect. Please check your network.</p>- <Button- class="mt-2"- disabled={retrying()}- onClick={handleRetry}- variant="base"- >- {retrying() ? 'Retrying…' : 'Retry'}- </Button>- </div>- );-}--const OFFLINE_ROUTE = '/offline';--function getCurrentQueryString() {- const params = new URLSearchParams(window.location.search);- return params.toString().length > 0 ? `?${params.toString()}` : '';-}--function shouldShowNativeOfflineFallback(- userInfoQuery: ReturnType<typeof useUserInfoQuery>-) {- return (- userInfoQuery.isError &&- hasLoginCookie() &&- isNativeMobilePlatform() &&- !thrownResultErrorHasCode(userInfoQuery.error, 'UNAUTHORIZED')- );-}--function SessionExpiredRedirect() {- void clearLocalAuthSession().catch((error) => {- console.error('Failed to clear local auth session', error);- });- return <Navigate href={`/welcome${getCurrentQueryString()}`} />;-}--function OfflineFallbackRoute() {- const userInfoQuery = useUserInfoQuery();-- // Once the query settles into anything other than a genuine connectivity- // failure, bounce to the base path.- return (- <Switch fallback={<Navigate href={`/${getCurrentQueryString()}`} />}>- <Match when={userInfoQuery.isLoading}>{null}</Match>- <Match when={shouldShowNativeOfflineFallback(userInfoQuery)}>- <OfflineFallback onRetry={() => userInfoQuery.refetch()} />- </Match>- </Switch>- );-}--function BasePathComponent() {- const [searchParams] = useSearchParams();- const userInfoQuery = useUserInfoQuery();- const checkoutRefreshPending = useCheckoutCompletionListener();-- onMount(() => {- if (searchParams.upgrade === 'true') {- sessionStorage.setItem('showUpgradeModal', 'true');- }- });-- // check session storage for redirect url- const redirectUrl = consumePostLoginRedirect();- if (redirectUrl) {- const relativeUrl = redirectUrl.replace(window.location.origin, '');- window.location.href = relativeUrl;- return;- }-- // Preserve existing query parameters when redirecting- const queryString = getCurrentQueryString();- const redirectPath = `${DEFAULT_ROUTE}${queryString}`;-- return (- <Switch>- <Match when={userInfoQuery.isLoading || checkoutRefreshPending()}>- {null}- </Match>- <Match- when={- hasLoginCookie() &&- thrownResultErrorHasCode(userInfoQuery.error, 'UNAUTHORIZED')- }- >- <SessionExpiredRedirect />- </Match>- <Match when={userInfoQuery.data?.authenticated}>- <Navigate href={redirectPath} />- </Match>- <Match when={shouldShowNativeOfflineFallback(userInfoQuery)}>- <Navigate href={`${OFFLINE_ROUTE}${queryString}`} />- </Match>- <Match- when={!userInfoQuery.isLoading && !userInfoQuery.data?.authenticated}- >- <Navigate href={`/welcome${queryString}`} />- </Match>- </Switch>- );-}-function NotFound() {if (isNativeMobilePlatform()) return <Navigate href={DEFAULT_ROUTE} />;window.location.href = window.location.origin;@@ -453,10 +331,6 @@ const ROUTES: RouteDefinition[] = [path: '/login',component: () => <Login />,},- {- path: OFFLINE_ROUTE,- component: OfflineFallbackRoute,- },{path: '/welcome',component: () =>