diff --git a/frontend/src/contexts/AuthContext.test.tsx b/frontend/src/contexts/AuthContext.test.tsx index da9151af..d25fc276 100644 --- a/frontend/src/contexts/AuthContext.test.tsx +++ b/frontend/src/contexts/AuthContext.test.tsx @@ -1,11 +1,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { render, waitFor } from '@testing-library/react' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, render, waitFor } from '@testing-library/react' +import { QueryClient, QueryClientProvider, dehydrate } from '@tanstack/react-query' import { MemoryRouter, Route, Routes } from 'react-router-dom' import { LocationCatcher } from '@/test/test-utils' import { AuthProvider } from './AuthContext' +import { QueryCachePersistenceProvider } from './QueryCachePersistenceContext' import { useAuth } from '@/hooks/useAuth' -import { QUERY_CACHE_STORAGE_KEY } from '@/lib/queryPersistence' +import { QUERY_CACHE_STORAGE_KEY, queryCacheBuster } from '@/lib/queryPersistence' import { STORED_AUTH_USER_KEY } from '@/lib/authSession' const mocks = vi.hoisted(() => ({ @@ -30,7 +31,7 @@ type AuthValue = ReturnType const STORED_USER = { id: 'user-1', email: 'user@example.com', name: 'Ada' } -function renderAuth(initialEntry: string) { +function renderAuth(initialEntry: string, options: { persistence?: boolean } = {}) { const capturedPathname: { current: string } = { current: '' } const capturedSearch: { current: string } = { current: '' } const captured: { current: AuthValue | null } = { current: null } @@ -45,7 +46,13 @@ function renderAuth(initialEntry: string) { path="/login" element={( - + {options.persistence ? ( + + + + ) : ( + + )} )} /> @@ -205,21 +212,76 @@ describe('AuthProvider session restore', () => { expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull() }) - it('clears the stored user, the persisted cache and the query cache on logout', async () => { + it('clears the stored user on logout and leaves the cache teardown to its owner', async () => { localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER)) - localStorage.setItem(QUERY_CACHE_STORAGE_KEY, '{}') - const { captured, queryClient } = renderAuth('/login') - const clearSpy = vi.spyOn(queryClient, 'clear') - queryClient.setQueryData(['repos'], [{ id: 1 }]) + const { captured } = renderAuth('/login') mocks.signOut.mockImplementation(async (options: { fetchOptions?: { onSuccess?: () => void } }) => { options.fetchOptions?.onSuccess?.() return { data: null } }) - await captured.current?.logout() + await act(async () => { + await captured.current?.logout() + }) expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull() - expect(localStorage.getItem(QUERY_CACHE_STORAGE_KEY)).toBeNull() - expect(clearSpy).toHaveBeenCalled() + expect(captured.current?.isAuthenticated).toBe(false) + expect(mocks.signOut).toHaveBeenCalled() + }) + + it('signs out and clears the persisted cache when sign-out fails offline', async () => { + localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER)) + mocks.useSession.mockReturnValue({ + data: { user: STORED_USER }, + error: null, + isPending: false, + refetch: mocks.refetch, + }) + const seededClient = new QueryClient() + seededClient.setQueryData(['repos'], [{ id: 1 }]) + localStorage.setItem(QUERY_CACHE_STORAGE_KEY, JSON.stringify({ + buster: queryCacheBuster(STORED_USER.id), + timestamp: Date.now(), + clientState: dehydrate(seededClient), + })) + mocks.signOut.mockRejectedValue(new TypeError('Failed to fetch')) + + const { captured } = renderAuth('/login', { persistence: true }) + await waitFor(() => expect(localStorage.getItem(QUERY_CACHE_STORAGE_KEY)).not.toBeNull()) + + await act(async () => { + await captured.current?.logout() + }) + + expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull() + await waitFor(() => expect(captured.current?.isAuthenticated).toBe(false)) + await waitFor(() => expect(localStorage.getItem(QUERY_CACHE_STORAGE_KEY)).toBeNull()) + }) + + it.each([ + ['removes the stored user', () => localStorage.removeItem(STORED_AUTH_USER_KEY)], + ['switches the stored user', () => localStorage.setItem( + STORED_AUTH_USER_KEY, + JSON.stringify({ id: 'user-2', email: 'two@example.com', name: 'Grace' }), + )], + ])('signs out when another tab %s', async (_label, changeStoredUser) => { + localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER)) + mocks.useSession.mockReturnValue({ + data: { user: STORED_USER }, + error: null, + isPending: false, + refetch: mocks.refetch, + }) + + const { captured } = renderAuth('/login') + await waitFor(() => expect(captured.current?.isAuthenticated).toBe(true)) + + act(() => { + changeStoredUser() + window.dispatchEvent(new StorageEvent('storage', { key: STORED_AUTH_USER_KEY })) + }) + + await waitFor(() => expect(captured.current?.isAuthenticated).toBe(false)) + expect(mocks.signOut).toHaveBeenCalled() }) }) diff --git a/frontend/src/contexts/AuthContext.tsx b/frontend/src/contexts/AuthContext.tsx index 90d151af..0d9df3c6 100644 --- a/frontend/src/contexts/AuthContext.tsx +++ b/frontend/src/contexts/AuthContext.tsx @@ -1,18 +1,15 @@ /* eslint-disable react-refresh/only-export-components */ import { createContext, useEffect, useMemo, useState, useCallback, type ReactNode } from 'react' -import { useQueryClient } from '@tanstack/react-query' -import { useSession, signIn, signUp, signOut, authClient, type AuthUser } from '@/lib/auth-client' +import { useSession, signIn, signUp, signOut, authClient } from '@/lib/auth-client' import { useNavigate, useLocation } from 'react-router-dom' import { getLoginRedirectTarget } from '@/lib/auth-loaders' import { + STORED_AUTH_USER_KEY, clearStoredAuthUser, - isTransientSessionError, readStoredAuthUser, - toStoredAuthUser, - writeStoredAuthUser, + reconcileStoredAuthUser, type StoredAuthUser, } from '@/lib/authSession' -import { clearPersistedQueryCache } from '@/lib/queryPersistence' interface AuthConfig { enabledProviders: string[] @@ -21,10 +18,8 @@ interface AuthConfig { adminConfigured: boolean } -export type AuthContextUser = Pick - interface AuthContextValue { - user: AuthContextUser | null + user: StoredAuthUser | null isAuthenticated: boolean isLoading: boolean config: AuthConfig | null @@ -48,7 +43,7 @@ interface AuthProviderProps { export function AuthProvider({ children }: AuthProviderProps) { const { data: session, error: sessionError, isPending, refetch } = useSession() const [storedUser, setStoredUser] = useState(() => readStoredAuthUser()) - const queryClient = useQueryClient() + const [signedOut, setSignedOut] = useState(false) const [config, setConfig] = useState(null) const navigate = useNavigate() const location = useLocation() @@ -58,16 +53,10 @@ export function AuthProvider({ children }: AuthProviderProps) { ) useEffect(() => { - if (session?.user) { - const validatedUser = toStoredAuthUser(session.user) - writeStoredAuthUser(validatedUser) - setStoredUser(validatedUser) - return - } if (isPending) return - if (isTransientSessionError(sessionError)) return - clearStoredAuthUser() - setStoredUser(null) + const reconciledUser = reconcileStoredAuthUser(session?.user ?? null, sessionError) + setStoredUser(reconciledUser) + if (reconciledUser !== null) setSignedOut(false) }, [session, sessionError, isPending]) useEffect(() => { @@ -142,24 +131,41 @@ export function AuthProvider({ children }: AuthProviderProps) { }, []) const logout = useCallback(async () => { - clearStoredAuthUser() + setSignedOut(true) setStoredUser(null) - clearPersistedQueryCache() - queryClient.clear() - await signOut({ - fetchOptions: { - onSuccess: () => { - window.location.href = '/login' + clearStoredAuthUser() + try { + await signOut({ + fetchOptions: { + onSuccess: () => { + window.location.href = '/login' + }, }, - }, - }) - }, [queryClient]) + }) + } catch { + return + } + }, []) const refreshSession = useCallback(async () => { await refetch() }, [refetch]) - const user = session?.user ?? storedUser + const user = signedOut ? null : session?.user ?? storedUser + + useEffect(() => { + if (user === null) return + + const handleStorageChange = (event: StorageEvent) => { + if (event.key !== null && event.key !== STORED_AUTH_USER_KEY) return + const nextUser = readStoredAuthUser() + if (nextUser !== null && nextUser.id === user.id) return + void logout() + } + + window.addEventListener('storage', handleStorageChange) + return () => window.removeEventListener('storage', handleStorageChange) + }, [user, logout]) const value = useMemo(() => ({ user, diff --git a/frontend/src/contexts/QueryCachePersistenceContext.test.tsx b/frontend/src/contexts/QueryCachePersistenceContext.test.tsx index 4e378233..4dfce90b 100644 --- a/frontend/src/contexts/QueryCachePersistenceContext.test.tsx +++ b/frontend/src/contexts/QueryCachePersistenceContext.test.tsx @@ -2,9 +2,12 @@ import { act, render, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, QueryClientProvider, dehydrate, useIsRestoring } from '@tanstack/react-query' import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' -import type { Persister } from '@tanstack/react-query-persist-client' import { QueryCachePersistenceProvider } from './QueryCachePersistenceContext' -import { QUERY_CACHE_STORAGE_KEY, queryCacheBuster } from '@/lib/queryPersistence' +import { + QUERY_CACHE_STORAGE_KEY, + queryCacheBuster, + type QueryCachePersister, +} from '@/lib/queryPersistence' const mocks = vi.hoisted(() => ({ useAuth: vi.fn(), @@ -52,8 +55,16 @@ function createStorage() { type TestStorage = ReturnType['storage'] -function createTestPersister(storage: TestStorage): Persister { - return createSyncStoragePersister({ storage, key: QUERY_CACHE_STORAGE_KEY, throttleTime: 0 }) +function createTestPersister(storage: TestStorage, throttleTime = 0): QueryCachePersister { + const persister = createSyncStoragePersister({ + storage, + key: QUERY_CACHE_STORAGE_KEY, + throttleTime, + }) + return { + ...persister, + hasPersistedClient: () => storage.getItem(QUERY_CACHE_STORAGE_KEY) !== null, + } } function seed( @@ -72,9 +83,12 @@ function seed( } let restoringValue: boolean | undefined +let restoringHistory: boolean[] = [] function RestoringProbe() { - restoringValue = useIsRestoring() + const isRestoring = useIsRestoring() + restoringValue = isRestoring + restoringHistory.push(isRestoring) return null } @@ -86,11 +100,16 @@ function createClient(): QueryClient { return client } -function tree(auth: AuthStub, persister: Persister, client: QueryClient) { +function tree( + auth: AuthStub, + persister: QueryCachePersister, + client: QueryClient, + persistThrottleMs = 0, +) { mocks.useAuth.mockReturnValue(auth) return ( - + @@ -105,6 +124,7 @@ async function settle(): Promise { beforeEach(() => { restoringValue = undefined + restoringHistory = [] mocks.useAuth.mockReset() localStorage.clear() }) @@ -178,7 +198,7 @@ describe('QueryCachePersistenceProvider', () => { it('is restoring until the restore resolves', async () => { let resolveRestore: () => void = () => {} - const persister: Persister = { + const persister: QueryCachePersister = { persistClient: vi.fn(), restoreClient: vi.fn( () => new Promise((resolve) => { @@ -186,6 +206,7 @@ describe('QueryCachePersistenceProvider', () => { }), ), removeClient: vi.fn(), + hasPersistedClient: () => true, } render(tree(signedIn(), persister, createClient())) @@ -225,4 +246,72 @@ describe('QueryCachePersistenceProvider', () => { await waitFor(() => expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false)) await waitFor(() => expect(restoringValue).toBe(false)) }) + + it('subscribes without a restoring pass when nothing is persisted yet', async () => { + const { store, storage } = createStorage() + const client = createClient() + const persister = createTestPersister(storage) + + render(tree(signedIn(), persister, client)) + + expect(restoringHistory).not.toContain(true) + + act(() => { + client.setQueryData(['repos'], [{ id: 1 }]) + }) + await settle() + + expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(true) + expect(restoringHistory).not.toContain(true) + }) + + it('saves an allowlisted update but not a transcript update', async () => { + const client = createClient() + const persistClient = vi.fn() + const persister: QueryCachePersister = { + persistClient, + restoreClient: () => undefined, + removeClient: vi.fn(), + hasPersistedClient: () => false, + } + + render(tree(signedIn(), persister, client)) + + act(() => { + client.setQueryData(['opencode', 'transcript', 'ses_1'], [{ text: 'streamed' }]) + }) + await settle() + expect(persistClient).not.toHaveBeenCalled() + + act(() => { + client.setQueryData(['repos'], [{ id: 1 }]) + }) + await settle() + + expect(persistClient).toHaveBeenCalledTimes(1) + const persisted = persistClient.mock.calls[0][0] + expect(persisted.buster).toBe(queryCacheBuster('user-1')) + expect(persisted.clientState.queries.map((query: { queryKey: unknown[] }) => query.queryKey)).toEqual([ + ['repos'], + ]) + }) + + it('drops a save scheduled before sign-out instead of rewriting the cache', async () => { + const { store, storage } = createStorage() + const client = createClient() + const persister = createTestPersister(storage) + + const view = render(tree(signedIn(), persister, client, 20)) + act(() => { + client.setQueryData(['repos'], [{ id: 1 }]) + }) + + view.rerender(tree(signedOut(), persister, client, 20)) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 60)) + }) + + expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false) + expect(client.getQueryData(['repos'])).toBeUndefined() + }) }) diff --git a/frontend/src/contexts/QueryCachePersistenceContext.tsx b/frontend/src/contexts/QueryCachePersistenceContext.tsx index 5e126c57..b9bbb3ab 100644 --- a/frontend/src/contexts/QueryCachePersistenceContext.tsx +++ b/frontend/src/contexts/QueryCachePersistenceContext.tsx @@ -1,56 +1,76 @@ -import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { IsRestoringProvider, useQueryClient } from '@tanstack/react-query' import { persistQueryClientRestore, - persistQueryClientSubscribe, - type Persister, + persistQueryClientSave, } from '@tanstack/react-query-persist-client' import { useAuth } from '@/hooks/useAuth' import { PERSISTED_CACHE_MAX_AGE_MS, + PERSIST_THROTTLE_MS, + createBusterGuardedPersister, createQueryCachePersister, queryCacheBuster, + shouldPersistCacheEvent, shouldPersistQuery, + type QueryCachePersister, } from '@/lib/queryPersistence' export interface QueryCachePersistenceProviderProps { children?: ReactNode - persister?: Persister + persister?: QueryCachePersister + /** Spacing between persisted saves; tests lower it instead of waiting a second per write. */ + persistThrottleMs?: number } /** * Restores the allowlisted part of the React Query cache for the signed-in account and keeps it * persisted while that account stays signed in. * - * The restore starts only once the session resolves to a signed-in user and uses - * `"|"` as the persister buster, so a cache written for another origin or account - * is discarded instead of hydrating this one. While the restore is in flight the subtree runs under - * `IsRestoringProvider`, which keeps queries from fetching before the persisted data is available. + * This provider owns the cache teardown. Signing out or switching accounts clears both the in-memory + * client and the persisted cache here, and the persister drops any save still queued for the account + * that just left, so a trailing write cannot recreate the previous account's cache. * - * A cache stored for a different user id is dropped from memory as well, and leaving the signed-in - * state clears both the in-memory client and the persisted cache. + * The restore starts only once the session resolves to a signed-in user and uses + * `"|"` as the persister buster, so a cache written for another origin or account is + * discarded instead of hydrating this one. While the restore is in flight the subtree runs under + * `IsRestoringProvider`, which keeps queries from fetching before the persisted data is available. + * A first sign-in with nothing on disk subscribes straight away, because there is nothing to wait for. + * + * Saves are driven by query cache events whose key is allowlisted and, for an update, whose action + * changes data or status, so a streaming transcript update costs no dehydrate. */ export function QueryCachePersistenceProvider({ children, persister, + persistThrottleMs = PERSIST_THROTTLE_MS, }: QueryCachePersistenceProviderProps) { const queryClient = useQueryClient() const { user, isAuthenticated, isLoading } = useAuth() - const defaultPersister = useMemo(() => createQueryCachePersister(), []) - const activePersister = persister ?? defaultPersister + const defaultPersister = useMemo(() => createQueryCachePersister(undefined, 0), []) + const basePersister = persister ?? defaultPersister const userId = isAuthenticated ? user?.id ?? null : null const buster = userId === null ? null : queryCacheBuster(userId) + const activeBusterRef = useRef(null) const [restoredBuster, setRestoredBuster] = useState(null) const previousUserIdRef = useRef(null) - const restoring = buster !== null && restoredBuster !== buster + const hasPersistedCache = useMemo( + () => buster !== null && basePersister.hasPersistedClient(), + [buster, basePersister], + ) + const restoring = buster !== null && restoredBuster !== buster && hasPersistedCache + const activePersister = useMemo( + () => createBusterGuardedPersister({ + persister: basePersister, + readBuster: () => activeBusterRef.current, + throttleTime: persistThrottleMs, + }), + [basePersister, persistThrottleMs], + ) - useEffect(() => { - const previousUserId = previousUserIdRef.current - previousUserIdRef.current = userId - if (previousUserId !== null && userId !== null && previousUserId !== userId) { - queryClient.clear() - } - }, [userId, queryClient]) + useLayoutEffect(() => { + activeBusterRef.current = buster + }, [buster]) useEffect(() => { if (isLoading) return @@ -59,35 +79,53 @@ export function QueryCachePersistenceProvider({ setRestoredBuster(null) void Promise.resolve(activePersister.removeClient()).catch(() => {}) queryClient.clear() + previousUserIdRef.current = null return } + if (previousUserIdRef.current !== null && previousUserIdRef.current !== userId) { + queryClient.clear() + } + previousUserIdRef.current = userId + let cancelled = false let unsubscribe: (() => void) | undefined - void (async () => { - await persistQueryClientRestore({ - queryClient, - persister: activePersister, - maxAge: PERSISTED_CACHE_MAX_AGE_MS, - buster, - }).catch(() => {}) - if (cancelled) return - - setRestoredBuster(buster) - unsubscribe = persistQueryClientSubscribe({ - queryClient, - persister: activePersister, - buster, - dehydrateOptions: { shouldDehydrateQuery: shouldPersistQuery }, + const subscribe = () => { + unsubscribe = queryClient.getQueryCache().subscribe((event) => { + if (!shouldPersistCacheEvent(event)) return + void persistQueryClientSave({ + queryClient, + persister: activePersister, + buster, + dehydrateOptions: { shouldDehydrateQuery: shouldPersistQuery }, + }).catch(() => {}) }) - })() + } + + if (!hasPersistedCache) { + setRestoredBuster(buster) + subscribe() + } else { + void (async () => { + await persistQueryClientRestore({ + queryClient, + persister: activePersister, + maxAge: PERSISTED_CACHE_MAX_AGE_MS, + buster, + }).catch(() => {}) + if (cancelled) return + + setRestoredBuster(buster) + subscribe() + })() + } return () => { cancelled = true unsubscribe?.() } - }, [buster, isLoading, activePersister, queryClient]) + }, [buster, userId, isLoading, hasPersistedCache, activePersister, queryClient]) return {children} } diff --git a/frontend/src/lib/auth-loaders.ts b/frontend/src/lib/auth-loaders.ts index 91bed82e..1a7beeda 100644 --- a/frontend/src/lib/auth-loaders.ts +++ b/frontend/src/lib/auth-loaders.ts @@ -1,12 +1,6 @@ import { redirect, type LoaderFunctionArgs } from 'react-router-dom' import { getSession } from './auth-client' -import { - clearStoredAuthUser, - isTransientSessionError, - readStoredAuthUser, - toStoredAuthUser, - writeStoredAuthUser, -} from './authSession' +import { reconcileStoredAuthUser } from './authSession' export interface AuthConfig { enabledProviders: string[] @@ -118,30 +112,26 @@ export async function registerLoader() { } /** - * Guards a signed-in route. A validated user is remembered so the next cold start can open the app - * before the network answers; when the session read fails transiently (network, 5xx, timeout) the - * remembered user stands in for it. A successful read with no user, or a 401, is authoritative and - * deletes the remembered profile. + * Guards a signed-in route through {@link reconcileStoredAuthUser}: a validated user is let through + * and remembered for the next cold start, a transient session failure is let through while a + * remembered user stands in for it, and an authoritative empty or rejected session is redirected to + * login with the requested location. */ export async function protectedLoader({ request }: LoaderFunctionArgs) { const url = new URL(request.url) let session: Awaited> | null = null + let failure: unknown = null try { session = await getSession() - } catch { - session = null + } catch (error) { + failure = error } - if (session?.data?.user) { - writeStoredAuthUser(toStoredAuthUser(session.data.user)) - return null - } - - if (session === null || isTransientSessionError(session.error)) { - if (readStoredAuthUser() !== null) return null - } else { - clearStoredAuthUser() - } + const storedUser = reconcileStoredAuthUser( + session?.data?.user ?? null, + failure ?? session?.error ?? null, + ) + if (storedUser !== null) return null return redirect(loginRedirectPath(`${url.pathname}${url.search}${url.hash}`)) } diff --git a/frontend/src/lib/authSession.test.ts b/frontend/src/lib/authSession.test.ts new file mode 100644 index 00000000..0d408cad --- /dev/null +++ b/frontend/src/lib/authSession.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { + STORED_AUTH_USER_KEY, + clearStoredAuthUser, + readStoredAuthUser, + reconcileStoredAuthUser, + writeStoredAuthUser, +} from './authSession' + +const STORED_USER = { id: 'user-1', email: 'user@example.com', name: 'Ada' } + +function storedValue(): unknown { + return JSON.parse(localStorage.getItem(STORED_AUTH_USER_KEY) ?? 'null') +} + +describe('reconcileStoredAuthUser', () => { + beforeEach(() => { + localStorage.clear() + }) + + it('saves a validated user and returns the profile without its extra fields', () => { + const user = { ...STORED_USER, emailVerified: true, sessionToken: 'secret' } + + expect(reconcileStoredAuthUser(user, null)).toEqual(STORED_USER) + expect(storedValue()).toEqual(STORED_USER) + }) + + it('replaces a previously stored profile with the validated user', () => { + writeStoredAuthUser(STORED_USER) + + reconcileStoredAuthUser({ id: 'user-2', email: 'two@example.com', name: 'Grace' }, null) + + expect(storedValue()).toEqual({ id: 'user-2', email: 'two@example.com', name: 'Grace' }) + }) + + it.each([ + ['a network failure', new TypeError('Failed to fetch')], + ['a 5xx response', { status: 503, statusText: 'Service Unavailable' }], + ])('keeps the stored profile on %s', (_label, error) => { + writeStoredAuthUser(STORED_USER) + + expect(reconcileStoredAuthUser(null, error)).toEqual(STORED_USER) + expect(storedValue()).toEqual(STORED_USER) + }) + + it('keeps nothing on a transient failure without a stored profile', () => { + expect(reconcileStoredAuthUser(null, new TypeError('Failed to fetch'))).toBeNull() + expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull() + }) + + it.each([ + ['a 401 response', { status: 401, statusText: 'Unauthorized' }], + ['a response without a user', null], + ])('clears the stored profile on %s', (_label, error) => { + writeStoredAuthUser(STORED_USER) + + expect(reconcileStoredAuthUser(null, error)).toBeNull() + expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull() + }) + + it('keeps an unreadable stored profile out of the result', () => { + localStorage.setItem(STORED_AUTH_USER_KEY, '{not json') + + expect(readStoredAuthUser()).toBeNull() + expect(reconcileStoredAuthUser(null, new TypeError('Failed to fetch'))).toBeNull() + }) + + it('clears the stored profile through clearStoredAuthUser', () => { + writeStoredAuthUser(STORED_USER) + + clearStoredAuthUser() + + expect(readStoredAuthUser()).toBeNull() + }) +}) diff --git a/frontend/src/lib/authSession.ts b/frontend/src/lib/authSession.ts index f04a84c2..0389d48c 100644 --- a/frontend/src/lib/authSession.ts +++ b/frontend/src/lib/authSession.ts @@ -59,3 +59,29 @@ export function isTransientSessionError(error: unknown): boolean { } return true } + +/** + * Applies the stored-profile rule to one session read and keeps storage in step with it. + * + * A validated user replaces the saved profile; a transient failure keeps whatever was saved, so an + * offline cold start still opens the app; anything else is authoritative and deletes the profile. + * + * @param user The user of a validated session, or `null` when the read returned none. + * @param error The session read error, if the read failed. + * @returns The profile that now stands for the session, or `null` when the app is signed out. + */ +export function reconcileStoredAuthUser( + user: StoredAuthUser | null, + error: unknown, +): StoredAuthUser | null { + if (user !== null) { + const storedUser = toStoredAuthUser(user) + writeStoredAuthUser(storedUser) + return storedUser + } + + if (isTransientSessionError(error)) return readStoredAuthUser() + + clearStoredAuthUser() + return null +} diff --git a/frontend/src/lib/queryPersistence.test.ts b/frontend/src/lib/queryPersistence.test.ts index 8a4574e2..9bed4dec 100644 --- a/frontend/src/lib/queryPersistence.test.ts +++ b/frontend/src/lib/queryPersistence.test.ts @@ -1,20 +1,23 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { QueryClient, dehydrate, hydrate, type Query } from '@tanstack/react-query' +import { QueryClient, dehydrate, hydrate, type Query, type QueryCacheNotifyEvent } from '@tanstack/react-query' import type { PersistedClient } from '@tanstack/react-query-persist-client' import { SESSION_PINS_QUERY_KEY } from '@/hooks/useSessionPins' import { PERSISTED_CACHE_MAX_AGE_MS, PERSISTED_QUERY_RULES, + PERSIST_THROTTLE_MS, QUERY_CACHE_STORAGE_KEY, applyPersistedQueryDefaults, capInfiniteQueryPages, - clearPersistedQueryCache, + createBusterGuardedPersister, createDropOldestHalfRetryer, createQueryCachePersister, isPersistedQueryKey, queryCacheBuster, serializePersistedClient, + shouldPersistCacheEvent, shouldPersistQuery, + type QueryCachePersister, } from './queryPersistence' type DehydratedQuery = PersistedClient['clientState']['queries'][number] @@ -503,6 +506,27 @@ describe('createQueryCachePersister', () => { }) }) + it('reports whether a cache is already stored', () => { + const { store, storage } = createStorage() + const persister = createQueryCachePersister(storage) + + expect(persister.hasPersistedClient()).toBe(false) + store.set(QUERY_CACHE_STORAGE_KEY, '{}') + expect(persister.hasPersistedClient()).toBe(true) + }) + + it('reports no stored cache when the storage read throws', () => { + const persister = createQueryCachePersister({ + getItem: () => { + throw new Error('denied') + }, + setItem: () => {}, + removeItem: () => {}, + }) + + expect(persister.hasPersistedClient()).toBe(false) + }) + it('still writes after dropping the oldest half when the quota rejects a save', async () => { vi.useFakeTimers() const { store, storage } = createStorage() @@ -560,15 +584,184 @@ describe('applyPersistedQueryDefaults', () => { }) }) -describe('clearPersistedQueryCache', () => { +describe('persister teardown', () => { it('removes only the persisted cache key', () => { const { store, storage } = createStorage() store.set(QUERY_CACHE_STORAGE_KEY, '{}') store.set('ocm.auth.user', '{}') - clearPersistedQueryCache(storage) + createQueryCachePersister(storage).removeClient() expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false) expect(store.has('ocm.auth.user')).toBe(true) }) }) + +describe('shouldPersistCacheEvent', () => { + const queryClient = createClient() + + function updateEvent( + queryKey: readonly unknown[], + action: { type: string } & Record, + ): QueryCacheNotifyEvent { + return { + type: 'updated', + query: buildQuery(queryClient, queryKey), + action, + } as QueryCacheNotifyEvent + } + + it.each([ + ['added', { type: 'added' }], + ['removed', { type: 'removed' }], + ])('reports an allowlisted query that was %s', (_label, event) => { + expect( + shouldPersistCacheEvent({ + ...event, + query: buildQuery(queryClient, ['repos']), + } as QueryCacheNotifyEvent), + ).toBe(true) + expect( + shouldPersistCacheEvent({ + ...event, + query: buildQuery(queryClient, ['opencode', 'transcript', 'ses_1']), + } as QueryCacheNotifyEvent), + ).toBe(false) + }) + + it.each([ + ['success', { type: 'success', data: null }], + ['error', { type: 'error', error: new Error('boom') }], + ['failed', { type: 'failed', failureCount: 1, error: new Error('boom') }], + ['invalidate', { type: 'invalidate' }], + ])('reports an allowlisted query updated on %s', (_label, action) => { + expect(shouldPersistCacheEvent(updateEvent(['repos'], action))).toBe(true) + }) + + it.each([ + ['fetch', { type: 'fetch' }], + ['pause', { type: 'pause' }], + ['continue', { type: 'continue' }], + ])('ignores a %s action, which only moves the fetch status', (_label, action) => { + expect(shouldPersistCacheEvent(updateEvent(['repos'], action))).toBe(false) + }) + + it('ignores a transcript update, which streams once per frame', () => { + expect( + shouldPersistCacheEvent(updateEvent(['opencode', 'transcript', 'ses_1'], { type: 'success', data: null })), + ).toBe(false) + }) + + it('ignores observer-only events', () => { + expect( + shouldPersistCacheEvent({ + type: 'observerResultsUpdated', + query: buildQuery(queryClient, ['repos']), + } as QueryCacheNotifyEvent), + ).toBe(false) + }) +}) + +describe('createBusterGuardedPersister', () => { + function createBasePersister( + storage: ReturnType['storage'], + ): QueryCachePersister { + return createQueryCachePersister(storage, 0) + } + + it('writes the pending client once the throttle elapses', async () => { + vi.useFakeTimers() + const { store, storage } = createStorage() + const persister = createBusterGuardedPersister({ + persister: createBasePersister(storage), + readBuster: () => 'http://localhost|user-1', + }) + + void persister.persistClient(buildPersistedClient({ mutations: [], queries: [] })) + await vi.advanceTimersByTimeAsync(PERSIST_THROTTLE_MS) + await vi.advanceTimersByTimeAsync(1) + + expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(true) + }) + + it('coalesces the saves inside one throttle window into the last one', async () => { + vi.useFakeTimers() + const { store, storage } = createStorage() + const persister = createBusterGuardedPersister({ + persister: createBasePersister(storage), + readBuster: () => 'http://localhost|user-1', + }) + + void persister.persistClient(buildPersistedClient({ mutations: [], queries: [] })) + void persister.persistClient( + buildPersistedClient({ mutations: [], queries: [buildDehydratedQuery(['repos'], 1)] }), + ) + await vi.advanceTimersByTimeAsync(PERSIST_THROTTLE_MS) + await vi.advanceTimersByTimeAsync(1) + + const persisted = JSON.parse(store.get(QUERY_CACHE_STORAGE_KEY) ?? '{}') + expect(persisted.clientState.queries).toHaveLength(1) + }) + + it('drops a save whose buster is no longer active when the throttle elapses', async () => { + vi.useFakeTimers() + const { store, storage } = createStorage() + let buster: string | null = 'http://localhost|user-1' + const persister = createBusterGuardedPersister({ + persister: createBasePersister(storage), + readBuster: () => buster, + }) + + void persister.persistClient(buildPersistedClient({ mutations: [], queries: [] })) + buster = null + await vi.advanceTimersByTimeAsync(PERSIST_THROTTLE_MS) + await vi.advanceTimersByTimeAsync(1) + + expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false) + }) + + it('drops a save queued for the previous account after the user changes', async () => { + vi.useFakeTimers() + const { store, storage } = createStorage() + let buster: string | null = 'http://localhost|user-1' + const persister = createBusterGuardedPersister({ + persister: createBasePersister(storage), + readBuster: () => buster, + }) + + void persister.persistClient(buildPersistedClient({ mutations: [], queries: [] })) + buster = 'http://localhost|user-2' + await vi.advanceTimersByTimeAsync(PERSIST_THROTTLE_MS) + await vi.advanceTimersByTimeAsync(1) + + expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false) + }) + + it('forgets the pending save on removeClient', async () => { + vi.useFakeTimers() + const { store, storage } = createStorage() + const persister = createBusterGuardedPersister({ + persister: createBasePersister(storage), + readBuster: () => 'http://localhost|user-1', + }) + + void persister.persistClient(buildPersistedClient({ mutations: [], queries: [] })) + persister.removeClient() + await vi.advanceTimersByTimeAsync(PERSIST_THROTTLE_MS) + await vi.advanceTimersByTimeAsync(1) + + expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false) + }) + + it('reports whether a cache is stored through the wrapped persister', () => { + const { store, storage } = createStorage() + const persister = createBusterGuardedPersister({ + persister: createBasePersister(storage), + readBuster: () => 'http://localhost|user-1', + }) + + expect(persister.hasPersistedClient()).toBe(false) + store.set(QUERY_CACHE_STORAGE_KEY, '{}') + expect(persister.hasPersistedClient()).toBe(true) + }) +}) diff --git a/frontend/src/lib/queryPersistence.ts b/frontend/src/lib/queryPersistence.ts index 82f93c4a..6bea51ad 100644 --- a/frontend/src/lib/queryPersistence.ts +++ b/frontend/src/lib/queryPersistence.ts @@ -1,4 +1,9 @@ -import type { DehydratedState, Query, QueryClient } from '@tanstack/react-query' +import type { + DehydratedState, + Query, + QueryCacheNotifyEvent, + QueryClient, +} from '@tanstack/react-query' import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' import type { PersistedClient, @@ -23,6 +28,11 @@ export interface QueryCacheStorage { removeItem: (key: string) => void } +export interface QueryCachePersister extends Persister { + /** Whether a cache for any buster is currently stored, so a first save needs no restore pass. */ + hasPersistedClient: () => boolean +} + /** * Query-key prefixes whose cached data is written to disk so a previously loaded list can paint * before the network answers. @@ -50,10 +60,41 @@ export const PERSISTED_QUERY_RULES: readonly PersistedQueryRule[] = [ export const PERSISTED_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000 +/** Minimum spacing between persisted saves, so a burst of cache changes costs one write. */ +export const PERSIST_THROTTLE_MS = 1000 + export const QUERY_CACHE_STORAGE_KEY = 'ocm.query-cache.v1' const SESSION_LIST_OPTIONS_INDEX = 3 +/** + * Cache actions that change stored data or a query status. `fetch`, `pause` and `continue` only move + * `fetchStatus`, which is not persisted, so they never justify a save. + */ +const PERSISTED_UPDATE_ACTIONS: ReadonlySet = new Set([ + 'success', + 'error', + 'failed', + 'invalidate', + 'setState', +]) + +/** + * Whether a query cache event can change the persisted cache: the query key must be allowlisted and, + * for an update, the action must change data or status. + * + * Streaming a transcript rewrites its key once per frame, so filtering here keeps the expensive + * dehydrate away from every non-allowlisted update. + */ +export function shouldPersistCacheEvent(event: QueryCacheNotifyEvent): boolean { + if (event.type === 'added' || event.type === 'removed') { + return isPersistedQueryKey(event.query.queryKey) + } + if (event.type !== 'updated') return false + if (!PERSISTED_UPDATE_ACTIONS.has(event.action.type)) return false + return isPersistedQueryKey(event.query.queryKey) +} + function matchesRule(rule: PersistedQueryRule, queryKey: readonly unknown[]): boolean { if (queryKey.length < rule.prefix.length) return false if (!rule.prefix.every((segment, index) => queryKey[index] === segment)) return false @@ -176,20 +217,78 @@ export function createDropOldestHalfRetryer(): PersistRetryer { /** * Creates the localStorage persister that stores the dehydrated cache under - * {@link QUERY_CACHE_STORAGE_KEY}, saving at most once per second. Infinite queries are capped to - * their first page before the write, and {@link createDropOldestHalfRetryer} keeps a full quota - * from silencing persistence. + * {@link QUERY_CACHE_STORAGE_KEY}. Infinite queries are capped to their first page before the write, + * and {@link createDropOldestHalfRetryer} keeps a full quota from silencing persistence. + * + * Writes are spaced by `throttleTime`; {@link createBusterGuardedPersister} throttles at the buster + * level instead, so the persister it wraps is created with a zero throttle. */ export function createQueryCachePersister( storage: QueryCacheStorage | null = typeof window === 'undefined' ? null : window.localStorage, -): Persister { - return createSyncStoragePersister({ + throttleTime: number = PERSIST_THROTTLE_MS, +): QueryCachePersister { + const persister = createSyncStoragePersister({ storage, key: QUERY_CACHE_STORAGE_KEY, - throttleTime: 1000, + throttleTime, serialize: serializePersistedClient, retry: createDropOldestHalfRetryer(), }) + + return { + ...persister, + hasPersistedClient: () => { + if (storage === null) return false + try { + return storage.getItem(QUERY_CACHE_STORAGE_KEY) !== null + } catch { + return false + } + }, + } +} + +export interface BusterGuardedPersisterOptions { + persister: QueryCachePersister + /** The buster that may still be written, or `null` once the account is signed out. */ + readBuster: () => string | null + throttleTime?: number +} + +/** + * Wraps a persister so a save runs only when the buster that owns it is still active at write time. + * + * The throttle lives here, after the guard, because a save scheduled before sign-out would otherwise + * land after `removeClient` and rewrite the previous account's cache. + */ +export function createBusterGuardedPersister({ + persister, + readBuster, + throttleTime = PERSIST_THROTTLE_MS, +}: BusterGuardedPersisterOptions): QueryCachePersister { + let timer: ReturnType | null = null + let pendingClient: PersistedClient | null = null + + const flush = () => { + timer = null + const client = pendingClient + pendingClient = null + if (client === null || client.buster !== readBuster()) return + void Promise.resolve(persister.persistClient(client)).catch(() => {}) + } + + return { + persistClient: (client) => { + pendingClient = client + if (timer === null) timer = setTimeout(flush, throttleTime) + }, + restoreClient: () => persister.restoreClient(), + removeClient: () => { + pendingClient = null + return persister.removeClient() + }, + hasPersistedClient: () => persister.hasPersistedClient(), + } } /** @@ -206,14 +305,3 @@ export function applyPersistedQueryDefaults(queryClient: QueryClient): void { queryClient.setQueryDefaults(rule.prefix, { gcTime: PERSISTED_CACHE_MAX_AGE_MS }) } } - -/** Removes the persisted cache from storage, e.g. on logout. */ -export function clearPersistedQueryCache( - storage: QueryCacheStorage | null = typeof window === 'undefined' ? null : window.localStorage, -): void { - try { - storage?.removeItem(QUERY_CACHE_STORAGE_KEY) - } catch { - return - } -} diff --git a/frontend/src/pages/RemoteProject.tsx b/frontend/src/pages/RemoteProject.tsx index c172d1e3..964488bb 100644 --- a/frontend/src/pages/RemoteProject.tsx +++ b/frontend/src/pages/RemoteProject.tsx @@ -28,7 +28,7 @@ import { ToolSidePanel } from '@/components/navigation/ToolSidePanel' function RemoteProjectContent({ serverId, directory }: { serverId: string; directory?: string }) { const navigate = useNavigate() - const { servers, isLoading: serversLoading } = useOpenCodeServers() + const { servers, showsInitialLoading: serversLoading } = useOpenCodeServers() const { openTab } = useSettingsDialog() const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp') const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills') diff --git a/frontend/src/pages/__tests__/RemoteProject.test.tsx b/frontend/src/pages/__tests__/RemoteProject.test.tsx index 324677ca..63701397 100644 --- a/frontend/src/pages/__tests__/RemoteProject.test.tsx +++ b/frontend/src/pages/__tests__/RemoteProject.test.tsx @@ -98,7 +98,7 @@ describe('RemoteProject', () => { mocks.listProjects.mockResolvedValue([project]) mocks.getVcsInfo.mockResolvedValue({ branch: { current: 'main', default: 'main' } }) mocks.useCreateSession.mockReturnValue({ mutate: mocks.createSession, isPending: false }) - mocks.useOpenCodeServers.mockReturnValue({ servers: [server], isLoading: false }) + mocks.useOpenCodeServers.mockReturnValue({ servers: [server], showsInitialLoading: false }) mocks.useSettingsDialog.mockReturnValue({ openTab: mocks.openTab }) mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false }) }) @@ -175,7 +175,7 @@ describe('RemoteProject', () => { it('shows the disabled state without loading projects', async () => { mocks.useOpenCodeServers.mockReturnValue({ servers: [{ ...server, enabled: false }], - isLoading: false, + showsInitialLoading: false, }) renderProject() @@ -186,17 +186,26 @@ describe('RemoteProject', () => { }) it('shows the missing-server state', async () => { - mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false }) + mocks.useOpenCodeServers.mockReturnValue({ servers: [], showsInitialLoading: false }) renderProject() expect(await screen.findByText('Server not found')).toBeInTheDocument() }) + it('keeps the loading state instead of reporting a missing server while the server list restores', () => { + mocks.useOpenCodeServers.mockReturnValue({ servers: [], showsInitialLoading: true }) + + renderProject() + + expect(screen.queryByText('Server not found')).not.toBeInTheDocument() + expect(mocks.listProjects).not.toHaveBeenCalled() + }) + it('opens server settings from the disabled state', async () => { mocks.useOpenCodeServers.mockReturnValue({ servers: [{ ...server, enabled: false }], - isLoading: false, + showsInitialLoading: false, }) renderProject()