diff --git a/frontend/src/components/navigation/DesktopSessionTree.test.tsx b/frontend/src/components/navigation/DesktopSessionTree.test.tsx index 186e4eba..864c4a8a 100644 --- a/frontend/src/components/navigation/DesktopSessionTree.test.tsx +++ b/frontend/src/components/navigation/DesktopSessionTree.test.tsx @@ -89,6 +89,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => { }) vi.mock('@/hooks/useSessionPins', () => ({ + SESSION_PINS_QUERY_KEY: ['session-pins'], useSessionPins: () => ({ data: sessionPinsData.current }), })) diff --git a/frontend/src/components/session/SessionList.test.tsx b/frontend/src/components/session/SessionList.test.tsx index 15b0fd18..e3b75e42 100644 --- a/frontend/src/components/session/SessionList.test.tsx +++ b/frontend/src/components/session/SessionList.test.tsx @@ -56,6 +56,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => { }) vi.mock('@/hooks/useSessionPins', () => ({ + SESSION_PINS_QUERY_KEY: ['session-pins'], useSessionPins: () => ({ data: sessionPinsData }), useToggleSessionPin: () => ({ mutate: togglePinMock }), })) diff --git a/frontend/src/components/session/SessionPickerDialog.test.tsx b/frontend/src/components/session/SessionPickerDialog.test.tsx index eedba48f..02f76dc4 100644 --- a/frontend/src/components/session/SessionPickerDialog.test.tsx +++ b/frontend/src/components/session/SessionPickerDialog.test.tsx @@ -108,6 +108,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => { }) vi.mock('@/hooks/useSessionPins', () => ({ + SESSION_PINS_QUERY_KEY: ['session-pins'], useSessionPins: () => ({ data: mocks.sessionPins }), useToggleSessionPin: () => ({ mutate: mocks.togglePinMock }), })) diff --git a/frontend/src/components/session/SessionPickerSheet.test.tsx b/frontend/src/components/session/SessionPickerSheet.test.tsx index 33ec181d..87357acb 100644 --- a/frontend/src/components/session/SessionPickerSheet.test.tsx +++ b/frontend/src/components/session/SessionPickerSheet.test.tsx @@ -88,6 +88,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => { }) vi.mock('@/hooks/useSessionPins', () => ({ + SESSION_PINS_QUERY_KEY: ['session-pins'], useSessionPins: () => ({ data: [] }), useToggleSessionPin: () => ({ mutate: vi.fn() }), })) diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 15a1e1d3..e774e866 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -31,6 +31,7 @@ import { useSendErrorStore } from "../stores/sendErrorStore"; import { useSessionStatus, useChildLifecycleForSession } from "../stores/sessionStatusStore"; import { isRunningLifecycle } from "../lib/backgroundWork"; import { childSessionReconciliationQueryKey, invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation"; +import { PERSISTED_CACHE_MAX_AGE_MS } from "../lib/queryPersistence"; import { buildPinnedSessionKeys, buildSessionKey } from "../lib/sessionKey"; import { toggleSessionPin } from "../api/sessionPins"; import { SESSION_PINS_QUERY_KEY } from "./useSessionPins"; @@ -82,6 +83,11 @@ export const useSessionsAcrossDirectories = ( const projectScoped = !allDirectories && projectId !== undefined; const singleCursor = allDirectories || projectScoped; const includeChildren = options?.includeChildren ?? false; + /** + * Only the unfiltered list is restored from disk, so only it keeps the longer `gcTime`; a search + * result stays at the default and is collected as soon as it goes unused. + */ + const persistedGcTime = normalizedSearch === undefined ? PERSISTED_CACHE_MAX_AGE_MS : undefined; const directoryKey = uniqueDirectories.join('|'); const childSessionsParam = includeChildren ? { includeChildren: true } : {}; @@ -179,6 +185,7 @@ export const useSessionsAcrossDirectories = ( getNextPageParam: (lastPage) => lastPage.nextParam, enabled: uniqueDirectories.length > 0 || allDirectories, staleTime: 10000, + gcTime: persistedGcTime, refetchOnWindowFocus: true, refetchOnReconnect: true, }); diff --git a/frontend/src/hooks/useVcsInfo.ts b/frontend/src/hooks/useVcsInfo.ts index b1d27ce7..e1446b63 100644 --- a/frontend/src/hooks/useVcsInfo.ts +++ b/frontend/src/hooks/useVcsInfo.ts @@ -1,6 +1,7 @@ import { useQuery } from '@tanstack/react-query' import { getVcsInfo } from '@/api/opencode' import { vcsInfoQueryKey } from '@/lib/queryInvalidation' +import { PERSISTED_CACHE_MAX_AGE_MS } from '@/lib/queryPersistence' export interface UseVcsInfoOptions { enabled?: boolean @@ -18,6 +19,8 @@ export function useVcsInfo( queryFn: () => getVcsInfo(directory ?? '', serverId), enabled: enabled && Boolean(directory), staleTime: 30_000, + /** The key is only persisted when it ends in `info`, which a prefix default cannot express. */ + gcTime: PERSISTED_CACHE_MAX_AGE_MS, retry: false, }) } diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index 764bb323..dbdc5146 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -214,14 +214,16 @@ export function invalidateSessionCaches(queryClient: QueryClient) { }) } -const SESSION_LIST_QUERY_GROUPS = new Set(['sessions', 'active-work-sessions']) +export const ACTIVE_WORK_SESSIONS_QUERY_ROOT = 'active-work-sessions' + +const SESSION_LIST_QUERY_GROUPS = new Set(['sessions', ACTIVE_WORK_SESSIONS_QUERY_ROOT]) /** * Query key of one server's active-work session list: flat, newest-first, across all directories. * It is distinct from the paged session-list keys so the two data shapes never share a cache entry. */ export function activeWorkSessionsQueryKey(serverId: string): readonly unknown[] { - return ['opencode', 'active-work-sessions', serverId] + return ['opencode', ACTIVE_WORK_SESSIONS_QUERY_ROOT, serverId] } export function invalidateSessionListCaches(queryClient: QueryClient) { @@ -236,7 +238,7 @@ export function invalidateSessionListCaches(queryClient: QueryClient) { * session-list key appends it after its options, and an unscoped key is a local-server key. */ function sessionListQueryServerId(queryKey: readonly unknown[]): string { - if (queryKey[1] === 'active-work-sessions') return String(queryKey[2]) + if (queryKey[1] === ACTIVE_WORK_SESSIONS_QUERY_ROOT) return String(queryKey[2]) return typeof queryKey[4] === 'string' ? queryKey[4] : LOCAL_OPENCODE_SERVER_ID } @@ -256,7 +258,7 @@ function sessionListQueryMatchesDirectories( if (queryKey[0] !== 'opencode') return false if (!SESSION_LIST_QUERY_GROUPS.has(String(queryKey[1]))) return false if (sessionListQueryServerId(queryKey) !== serverId) return false - if (queryKey[1] === 'active-work-sessions') return true + if (queryKey[1] === ACTIVE_WORK_SESSIONS_QUERY_ROOT) return true const directoryKey = queryKey[2] if (typeof directoryKey !== 'string') return false return directoryKey.split('|').some((directory) => directories.has(directory)) diff --git a/frontend/src/lib/queryPersistence.test.ts b/frontend/src/lib/queryPersistence.test.ts index f2e46430..8a4574e2 100644 --- a/frontend/src/lib/queryPersistence.test.ts +++ b/frontend/src/lib/queryPersistence.test.ts @@ -1,17 +1,24 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { QueryClient, type Query } from '@tanstack/react-query' +import { QueryClient, dehydrate, hydrate, type Query } 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, QUERY_CACHE_STORAGE_KEY, applyPersistedQueryDefaults, + capInfiniteQueryPages, clearPersistedQueryCache, + createDropOldestHalfRetryer, createQueryCachePersister, isPersistedQueryKey, queryCacheBuster, + serializePersistedClient, shouldPersistQuery, } from './queryPersistence' +type DehydratedQuery = PersistedClient['clientState']['queries'][number] + function buildQuery( queryClient: QueryClient, queryKey: readonly unknown[], @@ -49,6 +56,21 @@ function createStorage() { } } +function buildPersistedClient(clientState: PersistedClient['clientState']): PersistedClient { + return { buster: 'http://localhost|user-1', timestamp: Date.now(), clientState } +} + +function buildDehydratedQuery( + queryKey: readonly unknown[], + dataUpdatedAt: number, +): DehydratedQuery { + return { + queryHash: JSON.stringify(queryKey), + queryKey, + state: { status: 'success', data: { id: queryKey[0] }, dataUpdatedAt } as DehydratedQuery['state'], + } +} + const clients: QueryClient[] = [] function createClient(): QueryClient { @@ -57,6 +79,19 @@ function createClient(): QueryClient { return client } +async function persistAndRestore(client: QueryClient, storage: ReturnType['storage']) { + vi.useFakeTimers() + const persister = createQueryCachePersister(storage) + void persister.persistClient(buildPersistedClient(dehydrate(client))) + await vi.advanceTimersByTimeAsync(1000) + vi.useRealTimers() + + const restoredClient = createClient() + const persisted = await persister.restoreClient() + if (persisted) hydrate(restoredClient, persisted.clientState) + return restoredClient +} + afterEach(() => { vi.useRealTimers() for (const client of clients.splice(0)) client.clear() @@ -65,10 +100,10 @@ afterEach(() => { 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: '' }]], + ['session search', ['opencode', 'sessions', '/work/repo', { search: 'fix login' }]], ['single session', ['opencode', 'session', 'ses_1', '/work/repo']], ['active work', ['opencode', 'active-work-sessions', 'srv_remote']], ['remote projects', ['opencode', 'projects', 'srv_remote']], @@ -78,6 +113,7 @@ describe('isPersistedQueryKey', () => { }) it.each([ + ['repo git status', ['reposGitStatus', [1, 2]]], ['settings', ['settings', 'user-1']], ['provider credentials', ['provider-credentials']], ['provider auth methods', ['provider-auth-methods']], @@ -129,13 +165,25 @@ describe('shouldPersistQuery', () => { expect(shouldPersistQuery(buildQuery(queryClient, ['provider-credentials']))).toBe(false) expect(shouldPersistQuery(buildQuery(queryClient, ['passkeys']))).toBe(false) }) + + it('persists only the unfiltered session list', () => { + const queryClient = createClient() + const listKey = ['opencode', 'sessions', '/work/repo', { search: '', limit: 25 }] + + expect(shouldPersistQuery(buildQuery(queryClient, listKey))).toBe(true) + expect( + shouldPersistQuery(buildQuery(queryClient, ['opencode', 'sessions', '/work/repo', { search: 'login' }])), + ).toBe(false) + expect( + shouldPersistQuery(buildQuery(queryClient, ['opencode', 'sessions', '/work/repo', { search: ' ' }])), + ).toBe(true) + }) }) 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'], @@ -155,6 +203,7 @@ describe('PERSISTED_QUERY_RULES', () => { 'passkeys', 'schedules', 'all-schedules', + 'reposGitStatus', 'opencode.transcript', 'opencode.providers', 'opencode.config', @@ -162,6 +211,25 @@ describe('PERSISTED_QUERY_RULES', () => { for (const root of excluded) expect(roots).not.toContain(root) }) + + it('builds the session-pin and active-work rules from the shared keys', () => { + expect(PERSISTED_QUERY_RULES.map((rule) => rule.prefix)).toContainEqual([...SESSION_PINS_QUERY_KEY]) + expect(PERSISTED_QUERY_RULES.map((rule) => rule.prefix)).toContainEqual([ + 'opencode', + 'active-work-sessions', + ]) + }) + + it('marks the rules that cannot use a prefix gcTime default', () => { + const rulesWithoutPrefixDefault = PERSISTED_QUERY_RULES.filter( + (rule) => rule.lastSegment !== undefined || rule.gcTimeInQueryOptions, + ) + + expect(rulesWithoutPrefixDefault.map((rule) => rule.prefix)).toEqual([ + ['opencode', 'sessions'], + ['opencode', 'vcs'], + ]) + }) }) describe('queryCacheBuster', () => { @@ -171,6 +239,250 @@ describe('queryCacheBuster', () => { }) }) +const allowlistedFixtures = [ + { + label: 'repo list', + queryKey: ['repos'], + data: [ + { + id: 1, + name: 'app', + localPath: '/work/app', + fullPath: '/work/app', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: 1_700_000_000_000, + lastAccessedAt: 1_700_000_100_000, + isLocal: true, + }, + ], + }, + { + label: 'session pins', + queryKey: [...SESSION_PINS_QUERY_KEY], + data: [{ sessionId: 'ses_1', directory: '/work/repo', pinnedAt: 1_700_000_000_000 }], + }, + { + label: 'linked servers', + queryKey: ['opencode-servers'], + data: [ + { + id: 'srv_kitchen', + name: 'Kitchen', + baseUrl: 'https://kitchen.example.com', + username: 'opencode', + enabled: true, + hasPassword: true, + createdAt: 1, + updatedAt: 2, + }, + ], + }, + { + label: 'session list', + queryKey: ['opencode', 'sessions', '/work/repo', { search: '', limit: 25 }], + data: { + pages: [ + { + items: [ + { + id: 'ses_1', + projectID: 'prj_1', + title: 'Fix login', + time: { created: 1_700_000_000_000, updated: 1_700_000_100_000 }, + location: { directory: '/work/repo' }, + cost: 0.02, + tokens: { input: 10, output: 20, reasoning: 0, cache: { read: 0, write: 0 } }, + }, + ], + nextParam: { mode: 'all', cursor: 'cursor-1' }, + }, + ], + pageParams: [null], + }, + }, + { + label: 'single session', + queryKey: ['opencode', 'session', 'ses_1', '/work/repo'], + data: { + id: 'ses_1', + projectID: 'prj_1', + title: 'Fix login', + time: { created: 1_700_000_000_000, updated: 1_700_000_100_000, archived: 1_700_000_200_000 }, + location: { directory: '/work/repo' }, + cost: 0.02, + tokens: { input: 10, output: 20, reasoning: 0, cache: { read: 0, write: 0 } }, + }, + }, + { + label: 'active work', + queryKey: ['opencode', 'active-work-sessions', 'srv_kitchen'], + data: [ + { + id: 'ses_2', + projectID: 'prj_1', + title: 'Review diff', + time: { created: 1_700_000_000_000, updated: 1_700_000_100_000 }, + location: { directory: '/work/repo' }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + }, + ], + }, + { + label: 'remote projects', + queryKey: ['opencode', 'projects', 'srv_kitchen'], + data: [ + { + id: 'prj_1', + name: 'app', + canonical: '/work/app', + vcs: 'git', + time: { created: 1_700_000_000_000, updated: 1_700_000_100_000, active: 1_700_000_200_000 }, + sandboxes: [{ id: 'sbx_1', directory: '/work/app', created: 1_700_000_000_000 }], + }, + ], + }, + { + label: 'vcs info', + queryKey: ['opencode', 'vcs', '/work/app', 'srv_kitchen', 'info'], + data: { branch: 'main', default_branch: 'main', root: '/work/app' }, + }, +] as const + +describe('persisted query round trip', () => { + it.each(allowlistedFixtures)('restores the $label data unchanged', async ({ queryKey, data }) => { + const sourceClient = createClient() + sourceClient.setQueryData(queryKey, data) + const { storage } = createStorage() + + const restoredClient = await persistAndRestore(sourceClient, storage) + + expect(restoredClient.getQueryData(queryKey)).toEqual(data) + }) + + it('loses repository git status data, which is why it is not allowlisted', async () => { + const sourceClient = createClient() + sourceClient.setQueryData(['reposGitStatus', [1]], new Map([[1, { hasChanges: true }]])) + const { storage } = createStorage() + + const restoredClient = await persistAndRestore(sourceClient, storage) + + expect(restoredClient.getQueryData(['reposGitStatus', [1]])).toEqual({}) + }) +}) + +describe('capInfiniteQueryPages', () => { + it('keeps only the first page and its page param of every infinite query', () => { + const clientState = { + mutations: [], + queries: [ + buildDehydratedQuery(['repos'], 1), + { + ...buildDehydratedQuery(['opencode', 'sessions', '/work/repo'], 2), + state: { + status: 'success', + dataUpdatedAt: 2, + data: { pages: [{ items: ['a'] }, { items: ['b'] }, { items: ['c'] }], pageParams: [undefined, 'c2', 'c3'] }, + } as DehydratedQuery['state'], + }, + ], + } + + const capped = capInfiniteQueryPages(clientState) + + expect(capped.queries[0].state.data).toEqual({ id: 'repos' }) + expect(capped.queries[1].state.data).toEqual({ + pages: [{ items: ['a'] }], + pageParams: [undefined], + }) + expect(clientState.queries[1].state.data).toMatchObject({ + pages: [{ items: ['a'] }, { items: ['b'] }, { items: ['c'] }], + }) + }) + + it('caps the infinite query before the persister writes it', async () => { + const sourceClient = createClient() + sourceClient.setQueryData(['opencode', 'sessions', '/work/repo', { search: '' }], { + pages: [{ items: ['a'] }, { items: ['b'] }], + pageParams: [undefined, 'c2'], + }) + const { storage, store } = createStorage() + + const restoredClient = await persistAndRestore(sourceClient, storage) + + const stored = JSON.parse(store.get(QUERY_CACHE_STORAGE_KEY) ?? '{}') + expect(stored.clientState.queries[0].state.data).toEqual({ + pages: [{ items: ['a'] }], + pageParams: [null], + }) + expect(restoredClient.getQueryData(['opencode', 'sessions', '/work/repo', { search: '' }])).toEqual({ + pages: [{ items: ['a'] }], + pageParams: [null], + }) + }) + + it('leaves plain list data alone', () => { + const clientState = { mutations: [], queries: [buildDehydratedQuery(['repos'], 1)] } + + expect(serializePersistedClient(buildPersistedClient(clientState))).toBe( + JSON.stringify(buildPersistedClient(clientState)), + ) + }) +}) + +describe('createDropOldestHalfRetryer', () => { + it('drops the oldest half of the queries on the first pass', () => { + const retryer = createDropOldestHalfRetryer() + const queries = [4, 1, 3, 2].map((age) => buildDehydratedQuery([`query-${age}`], age)) + + const retried = retryer({ + persistedClient: buildPersistedClient({ mutations: [], queries }), + error: new Error('QuotaExceededError'), + errorCount: 1, + }) + + expect(retried?.clientState.queries.map((query) => query.state.dataUpdatedAt)).toEqual([4, 3]) + }) + + it('keeps halving the remaining queries on later passes of the same save', () => { + const retryer = createDropOldestHalfRetryer() + const queries = [1, 2, 3, 4].map((age) => buildDehydratedQuery([`query-${age}`], age)) + const props = { + persistedClient: buildPersistedClient({ mutations: [], queries }), + error: new Error('QuotaExceededError'), + errorCount: 1, + } + + const first = retryer(props) + const second = retryer({ ...props, persistedClient: first!, errorCount: 2 }) + const third = retryer({ ...props, persistedClient: second!, errorCount: 3 }) + + 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([]) + }) + + it('sorts once per save and starts over for the next save', () => { + const retryer = createDropOldestHalfRetryer() + retryer({ + persistedClient: buildPersistedClient({ mutations: [], queries: [buildDehydratedQuery(['a'], 5)] }), + error: new Error('QuotaExceededError'), + errorCount: 1, + }) + + const nextSave = [buildDehydratedQuery(['b'], 9), buildDehydratedQuery(['c'], 1)] + + const retried = retryer({ + persistedClient: buildPersistedClient({ mutations: [], queries: nextSave }), + error: new Error('QuotaExceededError'), + errorCount: 1, + }) + + expect(retried?.clientState.queries.map((query) => query.queryKey)).toEqual([['b']]) + }) +}) + describe('createQueryCachePersister', () => { it('writes the dehydrated cache under the fixed storage key after the throttle', async () => { vi.useFakeTimers() @@ -191,7 +503,7 @@ describe('createQueryCachePersister', () => { }) }) - it('still writes after dropping the oldest query when the quota rejects a save', async () => { + it('still writes after dropping the oldest half when the quota rejects a save', async () => { vi.useFakeTimers() const { store, storage } = createStorage() let rejections = 1 @@ -221,12 +533,14 @@ describe('createQueryCachePersister', () => { }) describe('applyPersistedQueryDefaults', () => { - it('raises gcTime for every allowlisted rule only', () => { + it('raises gcTime only for the allowlisted rules that use a prefix default', () => { const queryClient = createClient() applyPersistedQueryDefaults(queryClient) for (const rule of PERSISTED_QUERY_RULES) { - expect(queryClient.getQueryDefaults(rule.prefix).gcTime).toBe(PERSISTED_CACHE_MAX_AGE_MS) + const gcTime = queryClient.getQueryDefaults(rule.prefix).gcTime + const usesPrefixDefault = rule.lastSegment === undefined && !rule.gcTimeInQueryOptions + expect(gcTime).toBe(usesPrefixDefault ? PERSISTED_CACHE_MAX_AGE_MS : undefined) } expect(queryClient.getQueryDefaults(['settings', 'user-1']).gcTime).toBeUndefined() @@ -234,6 +548,16 @@ describe('applyPersistedQueryDefaults', () => { expect(queryClient.getDefaultOptions().queries?.gcTime).toBeUndefined() expect(PERSISTED_CACHE_MAX_AGE_MS).toBe(24 * 60 * 60 * 1000) }) + + it('leaves the paged session list and vcs info to their own query options', () => { + const queryClient = createClient() + applyPersistedQueryDefaults(queryClient) + + expect(queryClient.getQueryDefaults(['opencode', 'sessions']).gcTime).toBeUndefined() + expect(queryClient.getQueryDefaults(['opencode', 'vcs']).gcTime).toBeUndefined() + expect(queryClient.defaultQueryOptions({ queryKey: ['opencode', 'sessions', '/work/repo'] }).gcTime) + .toBeUndefined() + }) }) describe('clearPersistedQueryCache', () => { diff --git a/frontend/src/lib/queryPersistence.ts b/frontend/src/lib/queryPersistence.ts index 3308f4bc..82f93c4a 100644 --- a/frontend/src/lib/queryPersistence.ts +++ b/frontend/src/lib/queryPersistence.ts @@ -1,10 +1,20 @@ -import type { Query, QueryClient } from '@tanstack/react-query' +import type { DehydratedState, Query, QueryClient } from '@tanstack/react-query' import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' -import { removeOldestQuery, type Persister } from '@tanstack/react-query-persist-client' +import type { + PersistedClient, + Persister, + PersistRetryer, +} from '@tanstack/react-query-persist-client' +import { SESSION_PINS_QUERY_KEY } from '@/hooks/useSessionPins' +import { ACTIVE_WORK_SESSIONS_QUERY_ROOT } from '@/lib/queryInvalidation' + +type DehydratedQuery = DehydratedState['queries'][number] export interface PersistedQueryRule { readonly prefix: readonly string[] readonly lastSegment?: string + /** Set `gcTime` in the query options instead of a prefix default, because keys under one prefix need different retention. */ + readonly gcTimeInQueryOptions?: boolean } export interface QueryCacheStorage { @@ -21,19 +31,19 @@ export interface QueryCacheStorage { * 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. + * MCP config can carry `client_secret`), `reposGitStatus` (a `Map` that JSON turns into `{}`), 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: SESSION_PINS_QUERY_KEY }, { prefix: ['opencode-servers'] }, - { prefix: ['opencode', 'sessions'] }, + { prefix: ['opencode', 'sessions'], gcTimeInQueryOptions: true }, { prefix: ['opencode', 'session'] }, - { prefix: ['opencode', 'active-work-sessions'] }, + { prefix: ['opencode', ACTIVE_WORK_SESSIONS_QUERY_ROOT] }, { prefix: ['opencode', 'projects'] }, { prefix: ['opencode', 'vcs'], lastSegment: 'info' }, ] @@ -42,6 +52,8 @@ export const PERSISTED_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000 export const QUERY_CACHE_STORAGE_KEY = 'ocm.query-cache.v1' +const SESSION_LIST_OPTIONS_INDEX = 3 + 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 @@ -56,12 +68,29 @@ export function isPersistedQueryKey(queryKey: readonly unknown[]): boolean { return PERSISTED_QUERY_RULES.some((rule) => matchesRule(rule, queryKey)) } +function isSessionListQueryKey(queryKey: readonly unknown[]): boolean { + return queryKey[0] === 'opencode' && queryKey[1] === 'sessions' +} + +function sessionListHasSearch(queryKey: readonly unknown[]): boolean { + const options = queryKey[SESSION_LIST_OPTIONS_INDEX] + if (typeof options !== 'object' || options === null) return false + const search = (options as { search?: unknown }).search + return typeof search === 'string' && search.trim() !== '' +} + /** - * 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. + * Decides whether one query is allowed on disk: its key must match an allowlisted rule, it must + * hold successfully fetched data, and a paged session list must be the unfiltered one. + * + * A search result depends on the query the user typed, so persisting it would spend the storage + * budget on keys that are rarely read again while evicting the lists that are. */ export function shouldPersistQuery(query: Query): boolean { - return query.state.status === 'success' && isPersistedQueryKey(query.queryKey) + if (query.state.status !== 'success') return false + if (!isPersistedQueryKey(query.queryKey)) return false + if (isSessionListQueryKey(query.queryKey) && sessionListHasSearch(query.queryKey)) return false + return true } /** @@ -72,10 +101,84 @@ export function queryCacheBuster(userId: string): string { return `${window.location.origin}|${userId}` } +interface InfiniteQueryData { + pages: unknown[] + pageParams: unknown[] +} + +function isInfiniteQueryData(data: unknown): data is InfiniteQueryData { + if (typeof data !== 'object' || data === null) return false + const candidate = data as Partial + return Array.isArray(candidate.pages) && Array.isArray(candidate.pageParams) +} + +function capInfinitePages(data: unknown): unknown { + if (!isInfiniteQueryData(data) || data.pages.length <= 1) return data + return { pages: data.pages.slice(0, 1), pageParams: data.pageParams.slice(0, 1) } +} + +function capQueryPages(query: DehydratedQuery): DehydratedQuery { + if (query.state.data === undefined) return query + return { + ...query, + state: { ...query.state, data: capInfinitePages(query.state.data) }, + } +} + +/** + * Keeps only the first page of every infinite query in a dehydrated state. + * + * A restored list is refetched page by page anyway, so the extra pages only cost storage, and the + * first page keeps `hasNextPage` derivable from its own next-page parameter. + */ +export function capInfiniteQueryPages(clientState: DehydratedState): DehydratedState { + return { ...clientState, queries: clientState.queries.map(capQueryPages) } +} + +/** Serializes the persisted client with {@link capInfiniteQueryPages} applied before the write. */ +export function serializePersistedClient(client: PersistedClient): string { + return JSON.stringify({ ...client, clientState: capInfiniteQueryPages(client.clientState) }) +} + +/** + * Drops the oldest half of the persisted queries on every failed save. + * + * 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. + */ +export function createDropOldestHalfRetryer(): PersistRetryer { + let ageOrderedQueries: readonly DehydratedQuery[] = [] + + return ({ persistedClient }) => { + const queries = persistedClient.clientState.queries + const isRetryOfSameSave = queries.length < ageOrderedQueries.length + && queries.every((query) => ageOrderedQueries.includes(query)) + if (!isRetryOfSameSave) { + ageOrderedQueries = [...queries].sort( + (left, right) => left.state.dataUpdatedAt - right.state.dataUpdatedAt, + ) + } + + const remaining = new Set(queries) + const oldestFirst = ageOrderedQueries.filter((query) => remaining.has(query)) + const keptQueries = new Set(oldestFirst.slice(Math.ceil(oldestFirst.length / 2))) + + return { + ...persistedClient, + clientState: { + ...persistedClient.clientState, + queries: queries.filter((query) => keptQueries.has(query)), + }, + } + } +} + /** * 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. + * {@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. */ export function createQueryCachePersister( storage: QueryCacheStorage | null = typeof window === 'undefined' ? null : window.localStorage, @@ -84,7 +187,8 @@ export function createQueryCachePersister( storage, key: QUERY_CACHE_STORAGE_KEY, throttleTime: 1000, - retry: removeOldestQuery, + serialize: serializePersistedClient, + retry: createDropOldestHalfRetryer(), }) } @@ -92,9 +196,13 @@ export function createQueryCachePersister( * 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. + * + * `setQueryDefaults` matches by key prefix, so a rule whose keys need different retention, or + * whose key only ends in a specific segment, sets `gcTime` in its own query options instead. */ export function applyPersistedQueryDefaults(queryClient: QueryClient): void { for (const rule of PERSISTED_QUERY_RULES) { + if (rule.lastSegment !== undefined || rule.gcTimeInQueryOptions) continue queryClient.setQueryDefaults(rule.prefix, { gcTime: PERSISTED_CACHE_MAX_AGE_MS }) } }