Failed to load repositories:{" "}
diff --git a/frontend/src/components/servers/RemoteProjectList.tsx b/frontend/src/components/servers/RemoteProjectList.tsx
index c0f8f14b..89cdd9db 100644
--- a/frontend/src/components/servers/RemoteProjectList.tsx
+++ b/frontend/src/components/servers/RemoteProjectList.tsx
@@ -86,7 +86,7 @@ function RemoteProjectListLoading() {
}
function RemoteProjectListContent({ serverId }: { serverId: string }) {
- const { servers, isLoading: serversLoading } = useOpenCodeServers()
+ const { servers, showsInitialLoading: serversLoading } = useOpenCodeServers()
const { openTab } = useSettingsDialog()
const [openDirectoryOpen, setOpenDirectoryOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
@@ -94,8 +94,8 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
const server = servers.find((candidate) => candidate.id === serverId)
const isDisabled = server !== undefined && !server.enabled
- const { projects, activityById, isLoading, isError, hasData, error, refetch } = useRemoteProjectsByActivity(serverId)
- const showsProjectError = isError && !hasData
+ const { projects, activityById, showsInitialLoading, showsError, error, refetch } =
+ useRemoteProjectsByActivity(serverId)
const filteredProjects = useMemo(() => {
const query = searchQuery.trim().toLowerCase()
@@ -121,6 +121,8 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
/>
) : null}
+ {serversLoading ?
) : null}
- {server && !isDisabled && showsProjectError ? (
+ {server && !isDisabled && showsError ? (
) : null}
- {server && !isDisabled && !showsProjectError ? (
- isLoading ? (
+ {server && !isDisabled && !showsError ? (
+ showsInitialLoading ? (
diff --git a/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx b/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx
index 9492e0aa..fd709c3f 100644
--- a/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx
+++ b/frontend/src/components/servers/__tests__/RemoteProjectList.test.tsx
@@ -148,7 +148,11 @@ describe('RemoteProjectList', () => {
mocks.listProjects.mockResolvedValue([project])
mocks.listSessionPage.mockResolvedValue({ items: [] })
mocks.useCreateSession.mockReturnValue({ mutateAsync: mocks.createSession, isPending: false })
- mocks.useOpenCodeServers.mockReturnValue({ servers: [server], isLoading: false })
+ mocks.useOpenCodeServers.mockReturnValue({
+ servers: [server],
+ isLoading: false,
+ showsInitialLoading: false,
+ })
mocks.useSettingsDialog.mockReturnValue({ openTab: mocks.openTab })
})
@@ -396,6 +400,7 @@ describe('RemoteProjectList', () => {
mocks.useOpenCodeServers.mockReturnValue({
servers: [{ ...server, enabled: false }],
isLoading: false,
+ showsInitialLoading: false,
})
renderProjectList()
@@ -405,7 +410,11 @@ describe('RemoteProjectList', () => {
})
it('shows a missing server state when the server is no longer configured', async () => {
- mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false })
+ mocks.useOpenCodeServers.mockReturnValue({
+ servers: [],
+ isLoading: false,
+ showsInitialLoading: false,
+ })
renderProjectList('srv_gone')
@@ -413,6 +422,19 @@ describe('RemoteProjectList', () => {
expect(mocks.listProjects).not.toHaveBeenCalled()
})
+ it('loads instead of reporting a missing server while the server list is restoring', () => {
+ mocks.useOpenCodeServers.mockReturnValue({
+ servers: [],
+ isLoading: false,
+ showsInitialLoading: true,
+ })
+
+ const { container } = renderProjectList('srv_gone')
+
+ expect(screen.queryByText('Server not found')).not.toBeInTheDocument()
+ expect(container.querySelectorAll('.animate-pulse').length).toBeGreaterThan(0)
+ })
+
it('shows an empty state when the server has no projects', async () => {
mocks.listProjects.mockResolvedValue([])
diff --git a/frontend/src/components/session/SessionList.test.tsx b/frontend/src/components/session/SessionList.test.tsx
index 34be5ca7..15b0fd18 100644
--- a/frontend/src/components/session/SessionList.test.tsx
+++ b/frontend/src/components/session/SessionList.test.tsx
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { SessionList } from './SessionList'
-const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, isLoadingRef, isPlaceholderDataRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
+const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, isLoadingRef, isPendingRef, isPlaceholderDataRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
createSessionMock: vi.fn(),
deleteSessionMock: vi.fn(),
sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
@@ -15,6 +15,7 @@ const { createSessionMock, deleteSessionMock, sessionsData, createSessionState,
isFetchingNextPageRef: { current: false },
isFetchNextPageErrorRef: { current: false },
isLoadingRef: { current: false },
+ isPendingRef: { current: false },
isPlaceholderDataRef: { current: false },
useRealSessionsHookRef: { current: false },
lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined },
@@ -38,6 +39,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
return {
data,
isLoading: isLoadingRef.current,
+ isPending: isPendingRef.current || isLoadingRef.current,
isPlaceholderData: isPlaceholderDataRef.current,
fetchNextPage: fetchNextPageMock,
hasNextPage: hasNextPageRef.current,
@@ -78,6 +80,7 @@ describe('SessionList', () => {
isFetchingNextPageRef.current = false
isFetchNextPageErrorRef.current = false
isLoadingRef.current = false
+ isPendingRef.current = false
isPlaceholderDataRef.current = false
useRealSessionsHookRef.current = false
lastSessionsHookArgs.current = undefined
@@ -589,6 +592,21 @@ describe('SessionList', () => {
it('keeps the search input rendered while the first page is loading', () => {
isLoadingRef.current = true
+ isPendingRef.current = true
+
+ render(
+
,
+ )
+
+ expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy()
+ expect(screen.getByText('Loading sessions...')).toBeTruthy()
+ })
+
+ it('keeps the search input rendered while the cache is restoring', () => {
+ isPendingRef.current = true
render(
@@ -286,7 +289,7 @@ export const SessionList = ({
onScroll={handleSessionsScroll}
>
- {isLoading && !renderSessions ? (
+ {isPending && !renderSessions ? (
Loading sessions...
) : renderSessions ? (
renderSessions({
diff --git a/frontend/src/contexts/AuthContext.test.tsx b/frontend/src/contexts/AuthContext.test.tsx
index a61f5672..da9151af 100644
--- a/frontend/src/contexts/AuthContext.test.tsx
+++ b/frontend/src/contexts/AuthContext.test.tsx
@@ -1,9 +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 { MemoryRouter, Route, Routes } from 'react-router-dom'
import { LocationCatcher } from '@/test/test-utils'
import { AuthProvider } from './AuthContext'
import { useAuth } from '@/hooks/useAuth'
+import { QUERY_CACHE_STORAGE_KEY } from '@/lib/queryPersistence'
+import { STORED_AUTH_USER_KEY } from '@/lib/authSession'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
@@ -25,41 +28,47 @@ vi.mock('@/lib/auth-client', () => ({
type AuthValue = ReturnType
-function AuthProbe({ captured }: { captured: { current: AuthValue | null } }) {
- captured.current = useAuth()
- return null
-}
+const STORED_USER = { id: 'user-1', email: 'user@example.com', name: 'Ada' }
function renderAuth(initialEntry: string) {
const capturedPathname: { current: string } = { current: '' }
const capturedSearch: { current: string } = { current: '' }
const captured: { current: AuthValue | null } = { current: null }
+ const queryClient = new QueryClient()
render(
-
-
-
-
-
-
- )}
- />
-
-
-
- ,
+
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ ,
)
- return { capturedPathname, capturedSearch, captured }
+ return { capturedPathname, capturedSearch, captured, queryClient }
+}
+
+function AuthProbe({ captured }: { captured: { current: AuthValue | null } }) {
+ captured.current = useAuth()
+ return null
}
describe('AuthProvider post-login navigation', () => {
beforeEach(() => {
vi.clearAllMocks()
- mocks.useSession.mockReturnValue({ data: null, isPending: false, refetch: mocks.refetch })
+ localStorage.clear()
+ mocks.useSession.mockReturnValue({ data: null, error: null, isPending: false, refetch: mocks.refetch })
mocks.refetch.mockResolvedValue(undefined)
mocks.signInEmail.mockResolvedValue({ data: { user: { id: 'user-1' } } })
mocks.signInPasskey.mockResolvedValue({ data: { user: { id: 'user-1' } } })
@@ -124,3 +133,93 @@ describe('AuthProvider post-login navigation', () => {
})
})
})
+
+describe('AuthProvider session restore', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ mocks.useSession.mockReturnValue({ data: null, error: null, isPending: false, refetch: mocks.refetch })
+ mocks.refetch.mockResolvedValue(undefined)
+ mocks.signOut.mockResolvedValue({ data: null })
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ enabledProviders: ['credentials'], registrationEnabled: true, isFirstUser: false, adminConfigured: true }),
+ }))
+ })
+
+ it('stores the validated user for the next cold start', async () => {
+ 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))
+ expect(JSON.parse(localStorage.getItem(STORED_AUTH_USER_KEY) ?? '')).toEqual(STORED_USER)
+ })
+
+ it('treats a transient session failure as signed in with the stored user', async () => {
+ localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER))
+ mocks.useSession.mockReturnValue({
+ data: null,
+ error: new TypeError('Failed to fetch'),
+ isPending: false,
+ refetch: mocks.refetch,
+ })
+
+ const { captured } = renderAuth('/login')
+
+ await waitFor(() => expect(captured.current?.isAuthenticated).toBe(true))
+ expect(captured.current?.user).toEqual(STORED_USER)
+ expect(localStorage.getItem(STORED_AUTH_USER_KEY)).not.toBeNull()
+ })
+
+ it('keeps the stored user while the session is still loading', async () => {
+ localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER))
+ mocks.useSession.mockReturnValue({ data: null, error: null, isPending: true, refetch: mocks.refetch })
+
+ const { captured } = renderAuth('/login')
+
+ await waitFor(() => expect(captured.current?.isAuthenticated).toBe(true))
+ expect(captured.current?.isLoading).toBe(false)
+ })
+
+ it.each([
+ ['a 401 response', { status: 401, statusText: 'Unauthorized' }],
+ ['a successful response without a user', null],
+ ])('clears the stored user on %s', async (_label, error) => {
+ localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER))
+ mocks.useSession.mockReturnValue({
+ data: null,
+ error,
+ isPending: false,
+ refetch: mocks.refetch,
+ })
+
+ const { captured } = renderAuth('/login')
+
+ await waitFor(() => expect(captured.current?.isAuthenticated).toBe(false))
+ expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull()
+ })
+
+ it('clears the stored user, the persisted cache and the query cache on logout', 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 }])
+ mocks.signOut.mockImplementation(async (options: { fetchOptions?: { onSuccess?: () => void } }) => {
+ options.fetchOptions?.onSuccess?.()
+ return { data: null }
+ })
+
+ await captured.current?.logout()
+
+ expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull()
+ expect(localStorage.getItem(QUERY_CACHE_STORAGE_KEY)).toBeNull()
+ expect(clearSpy).toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/contexts/AuthContext.tsx b/frontend/src/contexts/AuthContext.tsx
index cfc8e696..90d151af 100644
--- a/frontend/src/contexts/AuthContext.tsx
+++ b/frontend/src/contexts/AuthContext.tsx
@@ -1,8 +1,18 @@
/* 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 { useNavigate, useLocation } from 'react-router-dom'
import { getLoginRedirectTarget } from '@/lib/auth-loaders'
+import {
+ clearStoredAuthUser,
+ isTransientSessionError,
+ readStoredAuthUser,
+ toStoredAuthUser,
+ writeStoredAuthUser,
+ type StoredAuthUser,
+} from '@/lib/authSession'
+import { clearPersistedQueryCache } from '@/lib/queryPersistence'
interface AuthConfig {
enabledProviders: string[]
@@ -11,8 +21,10 @@ interface AuthConfig {
adminConfigured: boolean
}
+export type AuthContextUser = Pick
+
interface AuthContextValue {
- user: AuthUser | null
+ user: AuthContextUser | null
isAuthenticated: boolean
isLoading: boolean
config: AuthConfig | null
@@ -34,7 +46,9 @@ interface AuthProviderProps {
}
export function AuthProvider({ children }: AuthProviderProps) {
- const { data: session, isPending, refetch } = useSession()
+ const { data: session, error: sessionError, isPending, refetch } = useSession()
+ const [storedUser, setStoredUser] = useState(() => readStoredAuthUser())
+ const queryClient = useQueryClient()
const [config, setConfig] = useState(null)
const navigate = useNavigate()
const location = useLocation()
@@ -43,6 +57,19 @@ export function AuthProvider({ children }: AuthProviderProps) {
[location.search],
)
+ useEffect(() => {
+ if (session?.user) {
+ const validatedUser = toStoredAuthUser(session.user)
+ writeStoredAuthUser(validatedUser)
+ setStoredUser(validatedUser)
+ return
+ }
+ if (isPending) return
+ if (isTransientSessionError(sessionError)) return
+ clearStoredAuthUser()
+ setStoredUser(null)
+ }, [session, sessionError, isPending])
+
useEffect(() => {
const fetchConfig = async () => {
try {
@@ -115,6 +142,10 @@ export function AuthProvider({ children }: AuthProviderProps) {
}, [])
const logout = useCallback(async () => {
+ clearStoredAuthUser()
+ setStoredUser(null)
+ clearPersistedQueryCache()
+ queryClient.clear()
await signOut({
fetchOptions: {
onSuccess: () => {
@@ -122,16 +153,18 @@ export function AuthProvider({ children }: AuthProviderProps) {
},
},
})
- }, [])
+ }, [queryClient])
const refreshSession = useCallback(async () => {
await refetch()
}, [refetch])
+ const user = session?.user ?? storedUser
+
const value = useMemo(() => ({
- user: session?.user ?? null,
- isAuthenticated: !!session?.user,
- isLoading: isPending,
+ user,
+ isAuthenticated: !!user,
+ isLoading: isPending && !user,
config,
signInWithEmail,
signInWithProvider,
@@ -141,7 +174,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
logout,
refreshSession,
}), [
- session,
+ user,
isPending,
config,
signInWithEmail,
diff --git a/frontend/src/contexts/QueryCachePersistenceContext.test.tsx b/frontend/src/contexts/QueryCachePersistenceContext.test.tsx
new file mode 100644
index 00000000..4e378233
--- /dev/null
+++ b/frontend/src/contexts/QueryCachePersistenceContext.test.tsx
@@ -0,0 +1,228 @@
+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'
+
+const mocks = vi.hoisted(() => ({
+ useAuth: vi.fn(),
+}))
+
+vi.mock('@/hooks/useAuth', () => ({ useAuth: mocks.useAuth }))
+
+interface AuthStub {
+ user: { id: string; email: string; name: string } | null
+ isAuthenticated: boolean
+ isLoading: boolean
+}
+
+function signedIn(userId = 'user-1'): AuthStub {
+ return {
+ user: { id: userId, email: `${userId}@example.com`, name: userId },
+ isAuthenticated: true,
+ isLoading: false,
+ }
+}
+
+function signedOut(): AuthStub {
+ return { user: null, isAuthenticated: false, isLoading: false }
+}
+
+function loading(): AuthStub {
+ return { user: null, isAuthenticated: false, isLoading: true }
+}
+
+function createStorage() {
+ const store = new Map()
+ return {
+ store,
+ storage: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ store.set(key, value)
+ },
+ removeItem: (key: string) => {
+ store.delete(key)
+ },
+ },
+ }
+}
+
+type TestStorage = ReturnType['storage']
+
+function createTestPersister(storage: TestStorage): Persister {
+ return createSyncStoragePersister({ storage, key: QUERY_CACHE_STORAGE_KEY, throttleTime: 0 })
+}
+
+function seed(
+ storage: TestStorage,
+ buster: string,
+ queryKey: readonly unknown[] = ['repos'],
+ data: unknown = [{ id: 1 }],
+): void {
+ const seedClient = new QueryClient()
+ seedClient.setQueryData(queryKey, data)
+ storage.setItem(
+ QUERY_CACHE_STORAGE_KEY,
+ JSON.stringify({ buster, timestamp: Date.now(), clientState: dehydrate(seedClient) }),
+ )
+ seedClient.clear()
+}
+
+let restoringValue: boolean | undefined
+
+function RestoringProbe() {
+ restoringValue = useIsRestoring()
+ return null
+}
+
+const clients: QueryClient[] = []
+
+function createClient(): QueryClient {
+ const client = new QueryClient()
+ clients.push(client)
+ return client
+}
+
+function tree(auth: AuthStub, persister: Persister, client: QueryClient) {
+ mocks.useAuth.mockReturnValue(auth)
+ return (
+
+
+
+
+
+ )
+}
+
+async function settle(): Promise {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ })
+}
+
+beforeEach(() => {
+ restoringValue = undefined
+ mocks.useAuth.mockReset()
+ localStorage.clear()
+})
+
+afterEach(() => {
+ for (const client of clients.splice(0)) client.clear()
+})
+
+describe('QueryCachePersistenceProvider', () => {
+ it('restores the cache written for the current user', async () => {
+ const { store, storage } = createStorage()
+ seed(storage, queryCacheBuster('user-1'))
+ const client = createClient()
+
+ render(tree(signedIn(), createTestPersister(storage), client))
+
+ await waitFor(() => expect(client.getQueryData(['repos'])).toEqual([{ id: 1 }]))
+ await waitFor(() => expect(restoringValue).toBe(false))
+ expect(store.size).toBe(1)
+ })
+
+ it('discards a cache written for another user', async () => {
+ const { store, storage } = createStorage()
+ seed(storage, queryCacheBuster('user-2'))
+ const client = createClient()
+
+ render(tree(signedIn('user-1'), createTestPersister(storage), client))
+
+ await waitFor(() => expect(restoringValue).toBe(false))
+ expect(client.getQueryData(['repos'])).toBeUndefined()
+ expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false)
+ })
+
+ it('keeps the stored cache while the session is still loading', async () => {
+ const { store, storage } = createStorage()
+ seed(storage, queryCacheBuster('user-1'))
+ const client = createClient()
+
+ render(tree(loading(), createTestPersister(storage), client))
+ await settle()
+
+ expect(client.getQueryData(['repos'])).toBeUndefined()
+ expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(true)
+ expect(restoringValue).toBe(false)
+ })
+
+ it('persists allowlisted successful queries only', async () => {
+ const { store, storage } = createStorage()
+ const client = createClient()
+
+ render(tree(signedIn(), createTestPersister(storage), client))
+ await waitFor(() => expect(restoringValue).toBe(false))
+
+ act(() => {
+ client.setQueryData(['repos'], [{ id: 1 }])
+ client.setQueryData(['opencode', 'sessions', '/work/repo'], [{ id: 'ses_1' }])
+ client.setQueryData(['settings', 'user-1'], { opencodeServerAuth: 'secret' })
+ client.setQueryData(['opencode', 'transcript', 'ses_1'], [{ text: 'streamed' }])
+ client.setQueryData(['provider-credentials'], [{ apiKey: 'secret' }])
+ })
+ await settle()
+
+ const persisted = JSON.parse(store.get(QUERY_CACHE_STORAGE_KEY) ?? '{}')
+ const roots = persisted.clientState.queries.map((query: { queryKey: unknown[] }) => query.queryKey[0])
+
+ expect(persisted.buster).toBe(queryCacheBuster('user-1'))
+ expect(roots.sort()).toEqual(['opencode', 'repos'])
+ expect(store.get(QUERY_CACHE_STORAGE_KEY)).not.toContain('secret')
+ expect(store.get(QUERY_CACHE_STORAGE_KEY)).not.toContain('streamed')
+ })
+
+ it('is restoring until the restore resolves', async () => {
+ let resolveRestore: () => void = () => {}
+ const persister: Persister = {
+ persistClient: vi.fn(),
+ restoreClient: vi.fn(
+ () => new Promise((resolve) => {
+ resolveRestore = () => resolve(undefined)
+ }),
+ ),
+ removeClient: vi.fn(),
+ }
+
+ render(tree(signedIn(), persister, createClient()))
+ expect(restoringValue).toBe(true)
+
+ act(() => resolveRestore())
+ await waitFor(() => expect(restoringValue).toBe(false))
+ })
+
+ it('clears the persisted cache and the in-memory cache on sign-out', async () => {
+ const { store, storage } = createStorage()
+ seed(storage, queryCacheBuster('user-1'))
+ const persister = createTestPersister(storage)
+ const client = createClient()
+
+ const view = render(tree(signedIn(), persister, client))
+ await waitFor(() => expect(client.getQueryData(['repos'])).toEqual([{ id: 1 }]))
+
+ view.rerender(tree(signedOut(), persister, client))
+
+ await waitFor(() => expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false))
+ expect(client.getQueryData(['repos'])).toBeUndefined()
+ })
+
+ it('clears the in-memory cache when the validated user changes', async () => {
+ const { store, storage } = createStorage()
+ seed(storage, queryCacheBuster('user-1'))
+ const persister = createTestPersister(storage)
+ const client = createClient()
+
+ const view = render(tree(signedIn('user-1'), persister, client))
+ await waitFor(() => expect(client.getQueryData(['repos'])).toEqual([{ id: 1 }]))
+
+ view.rerender(tree(signedIn('user-2'), persister, client))
+
+ await waitFor(() => expect(client.getQueryData(['repos'])).toBeUndefined())
+ await waitFor(() => expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false))
+ await waitFor(() => expect(restoringValue).toBe(false))
+ })
+})
diff --git a/frontend/src/contexts/QueryCachePersistenceContext.tsx b/frontend/src/contexts/QueryCachePersistenceContext.tsx
new file mode 100644
index 00000000..5e126c57
--- /dev/null
+++ b/frontend/src/contexts/QueryCachePersistenceContext.tsx
@@ -0,0 +1,93 @@
+import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import { IsRestoringProvider, useQueryClient } from '@tanstack/react-query'
+import {
+ persistQueryClientRestore,
+ persistQueryClientSubscribe,
+ type Persister,
+} from '@tanstack/react-query-persist-client'
+import { useAuth } from '@/hooks/useAuth'
+import {
+ PERSISTED_CACHE_MAX_AGE_MS,
+ createQueryCachePersister,
+ queryCacheBuster,
+ shouldPersistQuery,
+} from '@/lib/queryPersistence'
+
+export interface QueryCachePersistenceProviderProps {
+ children?: ReactNode
+ persister?: Persister
+}
+
+/**
+ * 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.
+ *
+ * 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.
+ */
+export function QueryCachePersistenceProvider({
+ children,
+ persister,
+}: QueryCachePersistenceProviderProps) {
+ const queryClient = useQueryClient()
+ const { user, isAuthenticated, isLoading } = useAuth()
+ const defaultPersister = useMemo(() => createQueryCachePersister(), [])
+ const activePersister = persister ?? defaultPersister
+ const userId = isAuthenticated ? user?.id ?? null : null
+ const buster = userId === null ? null : queryCacheBuster(userId)
+ const [restoredBuster, setRestoredBuster] = useState(null)
+ const previousUserIdRef = useRef(null)
+ const restoring = buster !== null && restoredBuster !== buster
+
+ useEffect(() => {
+ const previousUserId = previousUserIdRef.current
+ previousUserIdRef.current = userId
+ if (previousUserId !== null && userId !== null && previousUserId !== userId) {
+ queryClient.clear()
+ }
+ }, [userId, queryClient])
+
+ useEffect(() => {
+ if (isLoading) return
+
+ if (buster === null) {
+ setRestoredBuster(null)
+ void Promise.resolve(activePersister.removeClient()).catch(() => {})
+ queryClient.clear()
+ return
+ }
+
+ 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 },
+ })
+ })()
+
+ return () => {
+ cancelled = true
+ unsubscribe?.()
+ }
+ }, [buster, isLoading, activePersister, queryClient])
+
+ return {children}
+}
diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts
index dc2db00a..15a1e1d3 100644
--- a/frontend/src/hooks/useOpenCode.ts
+++ b/frontend/src/hooks/useOpenCode.ts
@@ -191,6 +191,7 @@ export const useSessionsAcrossDirectories = (
return {
data,
isLoading: query.isLoading,
+ isPending: query.isPending && uniqueDirectories.length > 0,
isPlaceholderData: query.isPlaceholderData,
isError: query.isError,
fetchNextPage: query.fetchNextPage,
diff --git a/frontend/src/hooks/useOpenCodeServers.ts b/frontend/src/hooks/useOpenCodeServers.ts
index 75010108..2a4904a6 100644
--- a/frontend/src/hooks/useOpenCodeServers.ts
+++ b/frontend/src/hooks/useOpenCodeServers.ts
@@ -14,6 +14,7 @@ import {
testOpenCodeServerById,
updateOpenCodeServer,
} from '@/api/opencodeServers'
+import { cachedListStates } from '@/lib/queryState'
const OPENCODE_SERVERS_QUERY_KEY = ['opencode-servers']
const OPENCODE_SERVER_STATUSES_QUERY_KEY = ['opencode-server-statuses']
@@ -55,9 +56,13 @@ export function useOpenCodeServers(options: { enabled?: boolean } = {}) {
mutationFn: (id: string) => testOpenCodeServerById(id),
})
+ const serversListState = cachedListStates(serversQuery.data, serversQuery.isError)
+
return {
servers: serversQuery.data ?? [],
isLoading: serversQuery.isLoading,
+ /** True only while no server list is cached and no error settled, so a restore is not read as a missing server. */
+ showsInitialLoading: serversListState.showsInitialLoading,
isSuccess: serversQuery.isSuccess,
error: serversQuery.error,
refetch: serversQuery.refetch,
diff --git a/frontend/src/hooks/useRemoteProjects.test.tsx b/frontend/src/hooks/useRemoteProjects.test.tsx
index 741e61a7..28a230df 100644
--- a/frontend/src/hooks/useRemoteProjects.test.tsx
+++ b/frontend/src/hooks/useRemoteProjects.test.tsx
@@ -99,7 +99,7 @@ describe('useRemoteProjects', () => {
wrapper: createWrapper(),
})
- expect(result.current.isLoading).toBe(false)
+ expect(result.current.showsInitialLoading).toBe(false)
expect(result.current.projects).toEqual([])
expect(mocks.listProjects).not.toHaveBeenCalled()
})
@@ -112,6 +112,30 @@ describe('useRemoteProjects', () => {
expect(mocks.listProjects).not.toHaveBeenCalled()
})
+ it('reports the initial loading state while nothing is cached, including a restored pending query', () => {
+ mocks.listProjects.mockReturnValue(new Promise(() => {}))
+
+ const { result } = renderHook(() => useRemoteProjects('srv_kitchen'), {
+ wrapper: createWrapper(),
+ })
+
+ expect(result.current.showsInitialLoading).toBe(true)
+ expect(result.current.showsError).toBe(false)
+ expect(result.current.projects).toEqual([])
+ })
+
+ it('reports the error state only when the load failed with nothing cached', async () => {
+ mocks.listProjects.mockRejectedValue(new Error('offline'))
+
+ const { result } = renderHook(() => useRemoteProjects('srv_kitchen'), {
+ wrapper: createWrapper(),
+ })
+
+ await waitFor(() => expect(result.current.showsError).toBe(true))
+ expect(result.current.showsInitialLoading).toBe(false)
+ expect(result.current.error?.message).toBe('offline')
+ })
+
it('keeps the cached projects and reports the failure when a refetch fails', async () => {
mocks.listProjects
.mockResolvedValueOnce([createProject('app', { created: 1, updated: 2 })])
@@ -125,8 +149,9 @@ describe('useRemoteProjects', () => {
result.current.refetch()
- await waitFor(() => expect(result.current.isError).toBe(true))
- expect(result.current.hasData).toBe(true)
+ await waitFor(() => expect(result.current.error?.message).toBe('offline'))
+ expect(result.current.showsError).toBe(false)
+ expect(result.current.showsInitialLoading).toBe(false)
expect(result.current.projects.map((project) => project.id)).toEqual(['app'])
expect(result.current.error?.message).toBe('offline')
})
diff --git a/frontend/src/hooks/useRemoteProjects.ts b/frontend/src/hooks/useRemoteProjects.ts
index fc81bb54..df1c6099 100644
--- a/frontend/src/hooks/useRemoteProjects.ts
+++ b/frontend/src/hooks/useRemoteProjects.ts
@@ -4,6 +4,7 @@ import { listProjects, rankProjectsBySessionActivity, sortProjectsByUpdatedAt, t
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { serverScopedKey } from '@/lib/serverScope'
+import { cachedListStates } from '@/lib/queryState'
const REMOTE_PROJECT_ACTIVITY_SESSION_LIMIT = 100
@@ -14,9 +15,10 @@ export interface UseRemoteProjectsOptions {
export interface UseRemoteProjectsResult {
projects: OpenCodeProject[]
- isLoading: boolean
- isError: boolean
- hasData: boolean
+ /** True only while no project list is cached and no error settled, so a restore does not flash a skeleton. */
+ showsInitialLoading: boolean
+ /** True only when the query failed and no cached list remains to render. */
+ showsError: boolean
error: Error | null
refetch: () => void
}
@@ -67,12 +69,16 @@ export function useRemoteProjects(
() => sortProjectsByUpdatedAt(projectsQuery.data ?? []),
[projectsQuery.data],
)
+ const { showsInitialLoading, showsError } = cachedListStates(
+ projectsQuery.data,
+ projectsQuery.isError,
+ projectsQuery.isEnabled,
+ )
return {
projects,
- isLoading: projectsQuery.isLoading,
- isError: projectsQuery.isError,
- hasData: projectsQuery.data !== undefined,
+ showsInitialLoading,
+ showsError,
error: projectsQuery.error,
refetch: projectsQuery.refetch,
}
@@ -96,7 +102,7 @@ export function useRemoteProjectsByActivity(
const projectsResult = useRemoteProjects(serverId, options)
const { data: sessions } = useSessionsAcrossDirectories([], {
serverId,
- allDirectories: projectsResult.hasData,
+ allDirectories: projectsResult.projects.length > 0,
limit: REMOTE_PROJECT_ACTIVITY_SESSION_LIMIT,
})
diff --git a/frontend/src/hooks/useSessionSearch.ts b/frontend/src/hooks/useSessionSearch.ts
index 03ba5e46..1298b94b 100644
--- a/frontend/src/hooks/useSessionSearch.ts
+++ b/frontend/src/hooks/useSessionSearch.ts
@@ -33,6 +33,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
const {
data: sessions,
isLoading,
+ isPending,
isError,
isPlaceholderData,
fetchNextPage,
@@ -79,6 +80,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
filteredSessions,
isSearchPending,
isLoading,
+ isPending,
isError,
isPlaceholderData,
fetchNextPage,
diff --git a/frontend/src/lib/auth-loaders.test.ts b/frontend/src/lib/auth-loaders.test.ts
index 0c4268f4..8df337a9 100644
--- a/frontend/src/lib/auth-loaders.test.ts
+++ b/frontend/src/lib/auth-loaders.test.ts
@@ -1,6 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { LoaderFunctionArgs } from 'react-router-dom'
import { getLoginRedirectTarget, loginLoader, loginRedirectPath, protectedLoader, resolveRedirectTarget } from './auth-loaders'
+import { STORED_AUTH_USER_KEY } from './authSession'
+
+const STORED_USER_KEY_VALUE = { id: 'user-1', email: 'user@example.com', name: 'Ada' }
const mocks = vi.hoisted(() => ({
getSession: vi.fn(),
@@ -52,10 +55,11 @@ describe('auth redirect targets', () => {
describe('protectedLoader', () => {
beforeEach(() => {
vi.clearAllMocks()
+ localStorage.clear()
})
it('redirects an anonymous visitor to login carrying the requested location', async () => {
- mocks.getSession.mockResolvedValue({ data: null })
+ mocks.getSession.mockResolvedValue({ data: null, error: null })
const result = await protectedLoader(loaderArgs('http://localhost/repos/2?tab=workspaces#session'))
@@ -63,10 +67,64 @@ describe('protectedLoader', () => {
})
it('lets an authenticated visitor through', async () => {
- mocks.getSession.mockResolvedValue({ data: { user: { id: 'user-1' } } })
+ mocks.getSession.mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null })
await expect(protectedLoader(loaderArgs('http://localhost/repos/2'))).resolves.toBeNull()
})
+
+ it('remembers the validated user for an offline cold start', async () => {
+ mocks.getSession.mockResolvedValue({
+ data: { user: { id: 'user-1', email: 'user@example.com', name: 'Ada' } },
+ error: null,
+ })
+
+ await protectedLoader(loaderArgs('http://localhost/repos/2'))
+
+ expect(JSON.parse(localStorage.getItem(STORED_AUTH_USER_KEY) ?? '')).toEqual({
+ id: 'user-1',
+ email: 'user@example.com',
+ name: 'Ada',
+ })
+ })
+
+ it('lets a stored user through when the session read fails transiently', async () => {
+ localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER_KEY_VALUE))
+ mocks.getSession.mockRejectedValue(new TypeError('Failed to fetch'))
+
+ await expect(protectedLoader(loaderArgs('http://localhost/repos/2'))).resolves.toBeNull()
+ expect(localStorage.getItem(STORED_AUTH_USER_KEY)).not.toBeNull()
+ })
+
+ it('lets a stored user through on a 5xx response', async () => {
+ localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER_KEY_VALUE))
+ mocks.getSession.mockResolvedValue({
+ data: null,
+ error: { status: 503, statusText: 'Service Unavailable' },
+ })
+
+ await expect(protectedLoader(loaderArgs('http://localhost/repos/2'))).resolves.toBeNull()
+ })
+
+ it('redirects when a transient failure has no stored user', async () => {
+ mocks.getSession.mockRejectedValue(new TypeError('Failed to fetch'))
+
+ const result = await protectedLoader(loaderArgs('http://localhost/repos/2'))
+
+ expect(redirectLocation(result)).toBe('/login?redirect=%2Frepos%2F2')
+ })
+
+ it.each([
+ ['a 401 response', { status: 401, statusText: 'Unauthorized' }],
+ ['a successful response without a user', null],
+ ])('forgets the stored user and redirects on %s', async (_label, error) => {
+ localStorage.setItem(STORED_AUTH_USER_KEY, JSON.stringify(STORED_USER_KEY_VALUE))
+ mocks.getSession.mockResolvedValue({ data: null, error })
+
+ const result = await protectedLoader(loaderArgs('http://localhost/repos/2'))
+
+ expect(redirectLocation(result)).toBe('/login?redirect=%2Frepos%2F2')
+ expect(localStorage.getItem(STORED_AUTH_USER_KEY)).toBeNull()
+ })
})
describe('loginLoader', () => {
diff --git a/frontend/src/lib/auth-loaders.ts b/frontend/src/lib/auth-loaders.ts
index 1c16c753..91bed82e 100644
--- a/frontend/src/lib/auth-loaders.ts
+++ b/frontend/src/lib/auth-loaders.ts
@@ -1,5 +1,12 @@
import { redirect, type LoaderFunctionArgs } from 'react-router-dom'
import { getSession } from './auth-client'
+import {
+ clearStoredAuthUser,
+ isTransientSessionError,
+ readStoredAuthUser,
+ toStoredAuthUser,
+ writeStoredAuthUser,
+} from './authSession'
export interface AuthConfig {
enabledProviders: string[]
@@ -110,13 +117,31 @@ export async function registerLoader() {
return { config }
}
+/**
+ * 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.
+ */
export async function protectedLoader({ request }: LoaderFunctionArgs) {
- const session = await getSession()
-
- if (!session.data?.user) {
- const url = new URL(request.url)
- return redirect(loginRedirectPath(`${url.pathname}${url.search}${url.hash}`))
+ const url = new URL(request.url)
+ let session: Awaited> | null = null
+ try {
+ session = await getSession()
+ } catch {
+ session = null
}
- return null
+ if (session?.data?.user) {
+ writeStoredAuthUser(toStoredAuthUser(session.data.user))
+ return null
+ }
+
+ if (session === null || isTransientSessionError(session.error)) {
+ if (readStoredAuthUser() !== null) return null
+ } else {
+ clearStoredAuthUser()
+ }
+
+ return redirect(loginRedirectPath(`${url.pathname}${url.search}${url.hash}`))
}
diff --git a/frontend/src/lib/authSession.ts b/frontend/src/lib/authSession.ts
new file mode 100644
index 00000000..f04a84c2
--- /dev/null
+++ b/frontend/src/lib/authSession.ts
@@ -0,0 +1,61 @@
+import { readStoredValue, removeStoredValue, writeStoredValue } from './persistentStorage'
+import type { AuthUser } from './auth-client'
+
+export type StoredAuthUser = Pick
+
+export const STORED_AUTH_USER_KEY = 'ocm.auth.user'
+
+function isStoredAuthUser(value: unknown): value is StoredAuthUser {
+ if (value === null || typeof value !== 'object') return false
+ const candidate = value as Record
+ return (
+ typeof candidate.id === 'string' &&
+ candidate.id.length > 0 &&
+ typeof candidate.email === 'string' &&
+ typeof candidate.name === 'string'
+ )
+}
+
+/**
+ * Reads the profile saved by the last successful session validation. A missing, corrupt or partial
+ * record is treated as absent so a failed write cannot wedge the offline restore path.
+ */
+export function readStoredAuthUser(): StoredAuthUser | null {
+ const raw = readStoredValue(STORED_AUTH_USER_KEY)
+ if (raw === null) return null
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ return isStoredAuthUser(parsed) ? toStoredAuthUser(parsed) : null
+ } catch {
+ return null
+ }
+}
+
+/** Keeps only the fields the offline restore needs, so no session tokens reach storage. */
+export function toStoredAuthUser(user: StoredAuthUser): StoredAuthUser {
+ return { id: user.id, email: user.email, name: user.name }
+}
+
+/** Saves the validated profile so a later cold start can open the app before the network answers. */
+export function writeStoredAuthUser(user: StoredAuthUser): void {
+ writeStoredValue(STORED_AUTH_USER_KEY, toStoredAuthUser(user))
+}
+
+/** Deletes the saved profile after logout or after the server rejected the session. */
+export function clearStoredAuthUser(): void {
+ removeStoredValue(STORED_AUTH_USER_KEY)
+}
+
+/**
+ * Whether a failed session read is transient (network error, 5xx, timeout, abort) rather than the
+ * server rejecting the session. better-auth reports HTTP failures as an `error` carrying `status`
+ * and a rejected fetch as a thrown error with no status, so only an explicit 401 counts as
+ * authoritative.
+ */
+export function isTransientSessionError(error: unknown): boolean {
+ if (error === null || error === undefined) return false
+ if (typeof error === 'object' && 'status' in error) {
+ return (error as { status?: unknown }).status !== 401
+ }
+ return true
+}
diff --git a/frontend/src/lib/persistentStorage.ts b/frontend/src/lib/persistentStorage.ts
index 65c610f6..6546d057 100644
--- a/frontend/src/lib/persistentStorage.ts
+++ b/frontend/src/lib/persistentStorage.ts
@@ -13,3 +13,11 @@ export function writeStoredValue(key: string, value: unknown): void {
return
}
}
+
+export function removeStoredValue(key: string): void {
+ try {
+ localStorage.removeItem(key)
+ } catch {
+ return
+ }
+}
diff --git a/frontend/src/lib/queryPersistence.test.ts b/frontend/src/lib/queryPersistence.test.ts
new file mode 100644
index 00000000..f2e46430
--- /dev/null
+++ b/frontend/src/lib/queryPersistence.test.ts
@@ -0,0 +1,250 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, type Query } from '@tanstack/react-query'
+import {
+ PERSISTED_CACHE_MAX_AGE_MS,
+ PERSISTED_QUERY_RULES,
+ QUERY_CACHE_STORAGE_KEY,
+ applyPersistedQueryDefaults,
+ clearPersistedQueryCache,
+ createQueryCachePersister,
+ isPersistedQueryKey,
+ queryCacheBuster,
+ shouldPersistQuery,
+} from './queryPersistence'
+
+function buildQuery(
+ queryClient: QueryClient,
+ queryKey: readonly unknown[],
+ status: 'pending' | 'success' | 'error' = 'success',
+): Query {
+ const query = queryClient
+ .getQueryCache()
+ .build(queryClient, {
+ queryKey,
+ queryFn: async () => null,
+ })
+
+ if (status === 'success') {
+ query.setState({ status: 'success', data: { ok: true }, fetchStatus: 'idle' })
+ } else if (status === 'error') {
+ query.setState({ status: 'error', error: new Error('boom'), fetchStatus: 'idle' })
+ }
+
+ return query
+}
+
+function createStorage() {
+ const store = new Map()
+ return {
+ store,
+ storage: {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ store.set(key, value)
+ },
+ removeItem: (key: string) => {
+ store.delete(key)
+ },
+ },
+ }
+}
+
+const clients: QueryClient[] = []
+
+function createClient(): QueryClient {
+ const client = new QueryClient()
+ clients.push(client)
+ return client
+}
+
+afterEach(() => {
+ vi.useRealTimers()
+ for (const client of clients.splice(0)) client.clear()
+})
+
+describe('isPersistedQueryKey', () => {
+ it.each([
+ ['repo list', ['repos']],
+ ['repo git status', ['reposGitStatus', [1, 2]]],
+ ['session pins', ['session-pins']],
+ ['linked servers', ['opencode-servers']],
+ ['session list', ['opencode', 'sessions', '/work/repo', { search: '' }]],
+ ['single session', ['opencode', 'session', 'ses_1', '/work/repo']],
+ ['active work', ['opencode', 'active-work-sessions', 'srv_remote']],
+ ['remote projects', ['opencode', 'projects', 'srv_remote']],
+ ['vcs info', ['opencode', 'vcs', '/work/repo', 'srv_remote', 'info']],
+ ])('allows the %s key', (_label, queryKey) => {
+ expect(isPersistedQueryKey(queryKey)).toBe(true)
+ })
+
+ it.each([
+ ['settings', ['settings', 'user-1']],
+ ['provider credentials', ['provider-credentials']],
+ ['provider auth methods', ['provider-auth-methods']],
+ ['passkeys', ['passkeys']],
+ ['schedules', ['schedules', '/work/repo']],
+ ['all schedules', ['all-schedules']],
+ ['repo schedules', ['repo-schedules', 1]],
+ ['transcript', ['opencode', 'transcript', 'ses_1']],
+ ['providers', ['opencode', 'providers', '/work/repo']],
+ ['commands', ['opencode', 'commands', '/work/repo']],
+ ['agents', ['opencode', 'agents', '/work/repo']],
+ ['config', ['opencode', 'config', 'model', '/work/repo']],
+ ['pending actions', ['opencode', 'pending-actions', 'ses_1', '/work/repo']],
+ ['shells', ['opencode', 'shells', '/work/repo']],
+ ['session reconciliation', ['opencode', 'session-reconcile', 'ses_1']],
+ ['vcs status', ['opencode', 'vcs', '/work/repo', 'status']],
+ ['vcs diff', ['opencode', 'vcs', '/work/repo', 'diff', 'branch']],
+ ['repo detail', ['repo', 1]],
+ ['server health', ['health']],
+ ])('rejects the %s key', (_label, queryKey) => {
+ expect(isPersistedQueryKey(queryKey)).toBe(false)
+ })
+
+ it('rejects an empty or non-string key', () => {
+ expect(isPersistedQueryKey([])).toBe(false)
+ expect(isPersistedQueryKey([42])).toBe(false)
+ })
+})
+
+describe('shouldPersistQuery', () => {
+ it('persists a successful query under an allowlisted rule', () => {
+ const queryClient = createClient()
+
+ expect(shouldPersistQuery(buildQuery(queryClient, ['repos']))).toBe(true)
+ expect(shouldPersistQuery(buildQuery(queryClient, ['opencode', 'sessions', '/work/repo']))).toBe(true)
+ })
+
+ it('rejects a non-success query even under an allowlisted rule', () => {
+ const queryClient = createClient()
+
+ expect(shouldPersistQuery(buildQuery(queryClient, ['repos'], 'pending'))).toBe(false)
+ expect(shouldPersistQuery(buildQuery(queryClient, ['repos'], 'error'))).toBe(false)
+ })
+
+ it('rejects a successful query whose data root carries secrets', () => {
+ const queryClient = createClient()
+
+ expect(shouldPersistQuery(buildQuery(queryClient, ['settings', 'user-1']))).toBe(false)
+ expect(shouldPersistQuery(buildQuery(queryClient, ['provider-credentials']))).toBe(false)
+ expect(shouldPersistQuery(buildQuery(queryClient, ['passkeys']))).toBe(false)
+ })
+})
+
+describe('PERSISTED_QUERY_RULES', () => {
+ it('covers exactly the list and roster roots', () => {
+ expect(PERSISTED_QUERY_RULES.map((rule) => rule.prefix)).toEqual([
+ ['repos'],
+ ['reposGitStatus'],
+ ['session-pins'],
+ ['opencode-servers'],
+ ['opencode', 'sessions'],
+ ['opencode', 'session'],
+ ['opencode', 'active-work-sessions'],
+ ['opencode', 'projects'],
+ ['opencode', 'vcs'],
+ ])
+ })
+
+ it('never names a secret-bearing or transcript root', () => {
+ const roots = PERSISTED_QUERY_RULES.map((rule) => rule.prefix.join('.'))
+ const excluded = [
+ 'settings',
+ 'provider-credentials',
+ 'provider-auth-methods',
+ 'passkeys',
+ 'schedules',
+ 'all-schedules',
+ 'opencode.transcript',
+ 'opencode.providers',
+ 'opencode.config',
+ ]
+
+ for (const root of excluded) expect(roots).not.toContain(root)
+ })
+})
+
+describe('queryCacheBuster', () => {
+ it('scopes the buster to the origin and the user id', () => {
+ expect(queryCacheBuster('user-1')).toBe('http://localhost|user-1')
+ expect(queryCacheBuster('user-2')).not.toBe(queryCacheBuster('user-1'))
+ })
+})
+
+describe('createQueryCachePersister', () => {
+ it('writes the dehydrated cache under the fixed storage key after the throttle', async () => {
+ vi.useFakeTimers()
+ const { store, storage } = createStorage()
+ const persister = createQueryCachePersister(storage)
+
+ void persister.persistClient({
+ buster: 'http://localhost|user-1',
+ timestamp: Date.now(),
+ clientState: { mutations: [], queries: [] },
+ })
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect([...store.keys()]).toEqual([QUERY_CACHE_STORAGE_KEY])
+ expect(JSON.parse(store.get(QUERY_CACHE_STORAGE_KEY) ?? '')).toMatchObject({
+ buster: 'http://localhost|user-1',
+ clientState: { queries: [] },
+ })
+ })
+
+ it('still writes after dropping the oldest query when the quota rejects a save', async () => {
+ vi.useFakeTimers()
+ const { store, storage } = createStorage()
+ let rejections = 1
+ const persister = createQueryCachePersister({
+ ...storage,
+ setItem: (key: string, value: string) => {
+ if (rejections > 0) {
+ rejections -= 1
+ throw new Error('QuotaExceededError')
+ }
+ store.set(key, value)
+ },
+ })
+
+ void persister.persistClient({
+ buster: 'http://localhost|user-1',
+ timestamp: Date.now(),
+ clientState: {
+ mutations: [],
+ queries: [{ queryKey: ['repos'], state: { data: [], dataUpdatedAt: 1 } } as never],
+ },
+ })
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(true)
+ })
+})
+
+describe('applyPersistedQueryDefaults', () => {
+ it('raises gcTime for every allowlisted rule only', () => {
+ const queryClient = createClient()
+ applyPersistedQueryDefaults(queryClient)
+
+ for (const rule of PERSISTED_QUERY_RULES) {
+ expect(queryClient.getQueryDefaults(rule.prefix).gcTime).toBe(PERSISTED_CACHE_MAX_AGE_MS)
+ }
+
+ expect(queryClient.getQueryDefaults(['settings', 'user-1']).gcTime).toBeUndefined()
+ expect(queryClient.getQueryDefaults(['opencode', 'transcript', 'ses_1']).gcTime).toBeUndefined()
+ expect(queryClient.getDefaultOptions().queries?.gcTime).toBeUndefined()
+ expect(PERSISTED_CACHE_MAX_AGE_MS).toBe(24 * 60 * 60 * 1000)
+ })
+})
+
+describe('clearPersistedQueryCache', () => {
+ it('removes only the persisted cache key', () => {
+ const { store, storage } = createStorage()
+ store.set(QUERY_CACHE_STORAGE_KEY, '{}')
+ store.set('ocm.auth.user', '{}')
+
+ clearPersistedQueryCache(storage)
+
+ expect(store.has(QUERY_CACHE_STORAGE_KEY)).toBe(false)
+ expect(store.has('ocm.auth.user')).toBe(true)
+ })
+})
diff --git a/frontend/src/lib/queryPersistence.ts b/frontend/src/lib/queryPersistence.ts
new file mode 100644
index 00000000..3308f4bc
--- /dev/null
+++ b/frontend/src/lib/queryPersistence.ts
@@ -0,0 +1,111 @@
+import type { Query, QueryClient } from '@tanstack/react-query'
+import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
+import { removeOldestQuery, type Persister } from '@tanstack/react-query-persist-client'
+
+export interface PersistedQueryRule {
+ readonly prefix: readonly string[]
+ readonly lastSegment?: string
+}
+
+export interface QueryCacheStorage {
+ getItem: (key: string) => string | null
+ setItem: (key: string, value: string) => void
+ removeItem: (key: string) => void
+}
+
+/**
+ * Query-key prefixes whose cached data is written to disk so a previously loaded list can paint
+ * before the network answers.
+ *
+ * Every rule is a list or roster key whose shape is stable across reloads of the same account.
+ * Excluded on purpose: `settings` (contains the OpenCode server auth token and API keys),
+ * `provider-credentials`, `passkeys`, `provider-auth-methods`, the `opencode` transcript kinds
+ * (large, and rewritten on every streamed token), `schedules` and `all-schedules` (a schedule or
+ * MCP config can carry `client_secret`), and every root not listed here.
+ *
+ * `opencode` shares one root with transcript, provider and config keys, so those rules match the
+ * second segment too and the `vcs` rule additionally requires `info` as the last segment.
+ */
+export const PERSISTED_QUERY_RULES: readonly PersistedQueryRule[] = [
+ { prefix: ['repos'] },
+ { prefix: ['reposGitStatus'] },
+ { prefix: ['session-pins'] },
+ { prefix: ['opencode-servers'] },
+ { prefix: ['opencode', 'sessions'] },
+ { prefix: ['opencode', 'session'] },
+ { prefix: ['opencode', 'active-work-sessions'] },
+ { prefix: ['opencode', 'projects'] },
+ { prefix: ['opencode', 'vcs'], lastSegment: 'info' },
+]
+
+export const PERSISTED_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000
+
+export const QUERY_CACHE_STORAGE_KEY = 'ocm.query-cache.v1'
+
+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
+ return rule.lastSegment === undefined || queryKey[queryKey.length - 1] === rule.lastSegment
+}
+
+/**
+ * Whether a query key belongs to one of the allowlisted roots. Only the segments named by a rule
+ * are inspected, so the directory, server id or search options appended to a list key stay free.
+ */
+export function isPersistedQueryKey(queryKey: readonly unknown[]): boolean {
+ return PERSISTED_QUERY_RULES.some((rule) => matchesRule(rule, queryKey))
+}
+
+/**
+ * Decides whether one query is allowed on disk: its key must match an allowlisted rule and it must
+ * hold successfully fetched data. Pending and error states carry nothing worth restoring.
+ */
+export function shouldPersistQuery(query: Query): boolean {
+ return query.state.status === 'success' && isPersistedQueryKey(query.queryKey)
+}
+
+/**
+ * Cache owner key used as the persister `buster`. A persisted cache written for another origin or
+ * account is discarded on restore instead of hydrating this one.
+ */
+export function queryCacheBuster(userId: string): string {
+ return `${window.location.origin}|${userId}`
+}
+
+/**
+ * Creates the localStorage persister that stores the dehydrated cache under
+ * {@link QUERY_CACHE_STORAGE_KEY}, saving at most once per second. `removeOldestQuery` keeps a full
+ * quota from silencing persistence: the oldest entry is dropped and the write retried.
+ */
+export function createQueryCachePersister(
+ storage: QueryCacheStorage | null = typeof window === 'undefined' ? null : window.localStorage,
+): Persister {
+ return createSyncStoragePersister({
+ storage,
+ key: QUERY_CACHE_STORAGE_KEY,
+ throttleTime: 1000,
+ retry: removeOldestQuery,
+ })
+}
+
+/**
+ * Raises `gcTime` to {@link PERSISTED_CACHE_MAX_AGE_MS} for the allowlisted rules only, so a
+ * restored inactive query survives long enough to be rendered while the global `gcTime` keeps its
+ * normal value.
+ */
+export function applyPersistedQueryDefaults(queryClient: QueryClient): void {
+ for (const rule of PERSISTED_QUERY_RULES) {
+ 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/lib/queryState.test.ts b/frontend/src/lib/queryState.test.ts
new file mode 100644
index 00000000..1ead7b27
--- /dev/null
+++ b/frontend/src/lib/queryState.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest'
+import { cachedListStates } from './queryState'
+
+describe('cachedListStates', () => {
+ it('shows the skeleton only while there is no data and no error', () => {
+ expect(cachedListStates(undefined, false)).toEqual({
+ showsInitialLoading: true,
+ showsError: false,
+ })
+ })
+
+ it('shows the error only when the query failed without cached data', () => {
+ expect(cachedListStates(undefined, true)).toEqual({
+ showsInitialLoading: false,
+ showsError: true,
+ })
+ })
+
+ it('keeps cached data on screen after a failed refetch', () => {
+ expect(cachedListStates([], true)).toEqual({
+ showsInitialLoading: false,
+ showsError: false,
+ })
+ expect(cachedListStates([{ id: 1 }], true)).toEqual({
+ showsInitialLoading: false,
+ showsError: false,
+ })
+ })
+
+ it('keeps loaded data on screen while a refetch runs', () => {
+ expect(cachedListStates([], false)).toEqual({
+ showsInitialLoading: false,
+ showsError: false,
+ })
+ })
+
+ it('does not report a load for a query that is not allowed to run', () => {
+ expect(cachedListStates(undefined, false, false)).toEqual({
+ showsInitialLoading: false,
+ showsError: false,
+ })
+ })
+})
diff --git a/frontend/src/lib/queryState.ts b/frontend/src/lib/queryState.ts
new file mode 100644
index 00000000..4b056d69
--- /dev/null
+++ b/frontend/src/lib/queryState.ts
@@ -0,0 +1,27 @@
+export interface CachedListStates {
+ showsInitialLoading: boolean
+ showsError: boolean
+}
+
+/**
+ * Derives the two states a list screen renders from a query that may already hold cached data.
+ *
+ * A restored or offline query runs pending without fetching, so `isLoading` stays false while no
+ * data is available yet, and a failed refetch keeps the succeeded data. Keying both states on
+ * `data === undefined` keeps cached lists on screen instead of flashing a skeleton or an empty
+ * state during a restore.
+ *
+ * @param data Query data, `undefined` until the first successful load or restore.
+ * @param isError Whether the query settled with an error.
+ * @param enabled Whether the query is allowed to run, so an intentionally idle query is not a load.
+ */
+export function cachedListStates(
+ data: T | undefined,
+ isError: boolean,
+ enabled = true,
+): CachedListStates {
+ return {
+ showsInitialLoading: enabled && data === undefined && !isError,
+ showsError: isError && data === undefined,
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 22ed7a3c..35821067 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -153,9 +153,15 @@ importers:
'@tailwindcss/vite':
specifier: ^4.1.14
version: 4.1.18(vite@7.3.0(@types/node@24.10.4)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0))
+ '@tanstack/query-sync-storage-persister':
+ specifier: 5.101.2
+ version: 5.101.2
'@tanstack/react-query':
- specifier: ^5.90.5
- version: 5.90.16(react@19.2.3)
+ specifier: ^5.101.2
+ version: 5.101.2(react@19.2.3)
+ '@tanstack/react-query-persist-client':
+ specifier: 5.101.2
+ version: 5.101.2(@tanstack/react-query@5.101.2(react@19.2.3))(react@19.2.3)
'@xterm/addon-fit':
specifier: ^0.11.0
version: 0.11.0
@@ -2256,11 +2262,23 @@ packages:
peerDependencies:
vite: ^5.2.0 || ^6 || ^7
- '@tanstack/query-core@5.90.16':
- resolution: {integrity: sha512-MvtWckSVufs/ja463/K4PyJeqT+HMlJWtw6PrCpywznd2NSgO3m4KwO9RqbFqGg6iDE8vVMFWMeQI4Io3eEYww==}
+ '@tanstack/query-core@5.101.2':
+ resolution: {integrity: sha512-hH5MLoJhF7KaIGd7q3xTXGXvslI+GYlM1Z/35aSHHWaCJWB7XvTSHYuV3eM7tw+aE0mT/xMro4M4Q9rCGHT0lw==}
- '@tanstack/react-query@5.90.16':
- resolution: {integrity: sha512-bpMGOmV4OPmif7TNMteU/Ehf/hoC0Kf98PDc0F4BZkFrEapRMEqI/V6YS0lyzwSV6PQpY1y4xxArUIfBW5LVxQ==}
+ '@tanstack/query-persist-client-core@5.101.2':
+ resolution: {integrity: sha512-rgMsbvBVpSPDUsprC9FYxojdG0Q1LH6yq1i3DXz2aps4VEqv2l4Msj3YDqIifU3xkl/DrYe9YWntZAJLrM6xTg==}
+
+ '@tanstack/query-sync-storage-persister@5.101.2':
+ resolution: {integrity: sha512-hRyLEJvkUWtfCUA3Lf5vD1CrXbHHK4pZNM/iNd7JM5GgC4CWzGIHkVkeg8zC2LV11KceKObKgjNuMSg3b6NOjA==}
+
+ '@tanstack/react-query-persist-client@5.101.2':
+ resolution: {integrity: sha512-19UpaRtf0lvB2QAJ2MoixxtGf3osMOd508g99EsttUj4+3eLs+ulnNgYjB7AkQMHrRlcbVXqpVNqWkB4a7g8Zw==}
+ peerDependencies:
+ '@tanstack/react-query': ^5.101.2
+ react: ^18 || ^19
+
+ '@tanstack/react-query@5.101.2':
+ resolution: {integrity: sha512-seDkr6kzGzX1okaaTtZPtgA688CDPlXUz1C6xSg0ESqn04Vuc8tlrYms1s3de+znBqhPVxFRfpAfUf+6XvfPWg==}
peerDependencies:
react: ^18 || ^19
@@ -7618,11 +7636,26 @@ snapshots:
tailwindcss: 4.1.18
vite: 7.3.0(@types/node@24.10.4)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
- '@tanstack/query-core@5.90.16': {}
+ '@tanstack/query-core@5.101.2': {}
- '@tanstack/react-query@5.90.16(react@19.2.3)':
+ '@tanstack/query-persist-client-core@5.101.2':
dependencies:
- '@tanstack/query-core': 5.90.16
+ '@tanstack/query-core': 5.101.2
+
+ '@tanstack/query-sync-storage-persister@5.101.2':
+ dependencies:
+ '@tanstack/query-core': 5.101.2
+ '@tanstack/query-persist-client-core': 5.101.2
+
+ '@tanstack/react-query-persist-client@5.101.2(@tanstack/react-query@5.101.2(react@19.2.3))(react@19.2.3)':
+ dependencies:
+ '@tanstack/query-persist-client-core': 5.101.2
+ '@tanstack/react-query': 5.101.2(react@19.2.3)
+ react: 19.2.3
+
+ '@tanstack/react-query@5.101.2(react@19.2.3)':
+ dependencies:
+ '@tanstack/query-core': 5.101.2
react: 19.2.3
'@testing-library/dom@10.4.1':