From a1f1212082b4ce801086df48c0dc06efa9b8fbdc Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:37:51 -0400 Subject: [PATCH] fix(frontend): stop empty persist retries, survive disabled storage and show remote project loading The drop-oldest retryer returns undefined once no query is left, ending the sync persister's retry loop. A throwing localStorage getter yields no persister instead of a crash. useSessionsAcrossDirectories reports isPending under the same condition it enables the query. RemoteProject renders a loader while the server list restores instead of a blank body. --- frontend/src/hooks/useOpenCode.test.tsx | 3 +++ frontend/src/hooks/useOpenCode.ts | 5 ++-- frontend/src/lib/queryPersistence.test.ts | 23 +++++++++++++++++++ frontend/src/lib/queryPersistence.ts | 16 ++++++++++++- frontend/src/pages/RemoteProject.tsx | 10 +++++++- .../pages/__tests__/RemoteProject.test.tsx | 7 ++++-- 6 files changed, 58 insertions(+), 6 deletions(-) diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx index f187e399..27cb6a40 100644 --- a/frontend/src/hooks/useOpenCode.test.tsx +++ b/frontend/src/hooks/useOpenCode.test.tsx @@ -183,10 +183,13 @@ describe('useSessionsAcrossDirectories', () => { { wrapper: createWrapper(queryClient) }, ) + expect(result.current.isPending).toBe(true) + await waitFor(() => { expect(result.current.isLoading).toBe(false) }) + expect(result.current.isPending).toBe(false) expect(mocks.listSessionPage).toHaveBeenCalledWith({ limit: 25, order: 'desc', diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index e774e866..6d53ed7f 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -90,6 +90,7 @@ export const useSessionsAcrossDirectories = ( const persistedGcTime = normalizedSearch === undefined ? PERSISTED_CACHE_MAX_AGE_MS : undefined; const directoryKey = uniqueDirectories.join('|'); const childSessionsParam = includeChildren ? { includeChildren: true } : {}; + const isQueryEnabled = uniqueDirectories.length > 0 || allDirectories; const query = useInfiniteQuery< SessionListPage, @@ -183,7 +184,7 @@ export const useSessionsAcrossDirectories = ( } : undefined, getNextPageParam: (lastPage) => lastPage.nextParam, - enabled: uniqueDirectories.length > 0 || allDirectories, + enabled: isQueryEnabled, staleTime: 10000, gcTime: persistedGcTime, refetchOnWindowFocus: true, @@ -198,7 +199,7 @@ export const useSessionsAcrossDirectories = ( return { data, isLoading: query.isLoading, - isPending: query.isPending && uniqueDirectories.length > 0, + isPending: query.isPending && isQueryEnabled, isPlaceholderData: query.isPlaceholderData, isError: query.isError, fetchNextPage: query.fetchNextPage, diff --git a/frontend/src/lib/queryPersistence.test.ts b/frontend/src/lib/queryPersistence.test.ts index 9bed4dec..9d1e5d72 100644 --- a/frontend/src/lib/queryPersistence.test.ts +++ b/frontend/src/lib/queryPersistence.test.ts @@ -460,10 +460,12 @@ describe('createDropOldestHalfRetryer', () => { const first = retryer(props) const second = retryer({ ...props, persistedClient: first!, errorCount: 2 }) const third = retryer({ ...props, persistedClient: second!, errorCount: 3 }) + const fourth = retryer({ ...props, persistedClient: third!, errorCount: 4 }) expect(first?.clientState.queries.map((query) => query.state.dataUpdatedAt)).toEqual([3, 4]) expect(second?.clientState.queries.map((query) => query.state.dataUpdatedAt)).toEqual([4]) expect(third?.clientState.queries).toEqual([]) + expect(fourth).toBeUndefined() }) it('sorts once per save and starts over for the next save', () => { @@ -527,6 +529,27 @@ describe('createQueryCachePersister', () => { expect(persister.hasPersistedClient()).toBe(false) }) + it('falls back to no storage when reading localStorage throws', () => { + const originalDescriptor = Object.getOwnPropertyDescriptor(window, 'localStorage') + Object.defineProperty(window, 'localStorage', { + configurable: true, + get: () => { + throw new DOMException('denied', 'SecurityError') + }, + }) + + try { + const persister = createQueryCachePersister(undefined) + + expect(() => + persister.persistClient(buildPersistedClient({ mutations: [], queries: [] })), + ).not.toThrow() + expect(persister.hasPersistedClient()).toBe(false) + } finally { + if (originalDescriptor) Object.defineProperty(window, 'localStorage', originalDescriptor) + } + }) + it('still writes after dropping the oldest half when the quota rejects a save', async () => { vi.useFakeTimers() const { store, storage } = createStorage() diff --git a/frontend/src/lib/queryPersistence.ts b/frontend/src/lib/queryPersistence.ts index 6bea51ad..ffefd43a 100644 --- a/frontend/src/lib/queryPersistence.ts +++ b/frontend/src/lib/queryPersistence.ts @@ -187,12 +187,16 @@ export function serializePersistedClient(client: PersistedClient): string { * The sync persister re-serializes after each retry, so removing one query at a time burns a whole * write per query on a large cache. Halving the remaining set converges in a few passes, and the * age order is sorted once per save so the retries only filter it. + * + * Returning `undefined` once no query is left ends the retry loop instead of rewriting an empty + * client that a full quota still rejects. */ export function createDropOldestHalfRetryer(): PersistRetryer { let ageOrderedQueries: readonly DehydratedQuery[] = [] return ({ persistedClient }) => { const queries = persistedClient.clientState.queries + if (queries.length === 0) return undefined const isRetryOfSameSave = queries.length < ageOrderedQueries.length && queries.every((query) => ageOrderedQueries.includes(query)) if (!isRetryOfSameSave) { @@ -215,6 +219,16 @@ export function createDropOldestHalfRetryer(): PersistRetryer { } } +/** Reads `localStorage`, which throws instead of returning `null` when the browser has storage disabled. */ +function readBrowserStorage(): QueryCacheStorage | null { + if (typeof window === 'undefined') return null + try { + return window.localStorage + } catch { + return null + } +} + /** * Creates the localStorage persister that stores the dehydrated cache under * {@link QUERY_CACHE_STORAGE_KEY}. Infinite queries are capped to their first page before the write, @@ -224,7 +238,7 @@ export function createDropOldestHalfRetryer(): PersistRetryer { * 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, + storage: QueryCacheStorage | null = readBrowserStorage(), throttleTime: number = PERSIST_THROTTLE_MS, ): QueryCachePersister { const persister = createSyncStoragePersister({ diff --git a/frontend/src/pages/RemoteProject.tsx b/frontend/src/pages/RemoteProject.tsx index 964488bb..4dc7f1e2 100644 --- a/frontend/src/pages/RemoteProject.tsx +++ b/frontend/src/pages/RemoteProject.tsx @@ -120,7 +120,15 @@ function RemoteProjectContent({ serverId, directory }: { serverId: string; direc
- {!serversLoading && !server ? ( + {serversLoading && directory ? ( +
+ +
+ ) : !serversLoading && !server ? (
{ expect(await screen.findByText('Server not found')).toBeInTheDocument() }) - it('keeps the loading state instead of reporting a missing server while the server list restores', () => { + it('shows a loading state instead of a blank body while the server list restores', () => { mocks.useOpenCodeServers.mockReturnValue({ servers: [], showsInitialLoading: true }) - renderProject() + const { container } = renderProject() + expect(screen.getByRole('status', { name: 'Loading project' })).toBeInTheDocument() + expect(container.querySelectorAll('.animate-spin').length).toBeGreaterThan(0) expect(screen.queryByText('Server not found')).not.toBeInTheDocument() + expect(screen.queryByTestId('session-list')).not.toBeInTheDocument() expect(mocks.listProjects).not.toHaveBeenCalled() })