mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(frontend): persist the query cache and restore the signed-in session offline
Allowlisted query data is persisted to localStorage for 24h, scoped to the origin and user and cleared on sign-out. The last validated user is remembered so a cold start opens with cached lists when the session check fails on the network, while a 401 or signed-out response still signs out. Lists keep cached data when a refetch fails.
This commit is contained in:
1 parent
881529728d
commit
b6c21de0bb
28 files changed
+1325
-102
No files matched your search
@@ -28,7 +28,9 @@
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@tailwindcss/vite": "^4.1.14",
|
||||
"@tanstack/react-query": "^5.90.5",
|
||||
"@tanstack/query-sync-storage-persister": "5.101.2",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"@tanstack/react-query-persist-client": "5.101.2",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
|
||||
+12
-6
@@ -28,6 +28,7 @@ import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { ThemeProvider, useThemeMode } from './contexts/ThemeContext'
|
||||
import { AuthProvider } from './contexts/AuthContext'
|
||||
import { QueryCachePersistenceProvider } from './contexts/QueryCachePersistenceContext'
|
||||
import { KeyboardShortcutsProvider } from './contexts/KeyboardShortcutsContext'
|
||||
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
|
||||
import { OpenCodeServerProvider, isLocalOpenCodeServer } from '@/contexts/OpenCodeServerContext'
|
||||
@@ -38,6 +39,7 @@ import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog'
|
||||
import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders'
|
||||
import { getSwipeBackTarget, isSessionDetailRoute } from '@/lib/navigation'
|
||||
import { onNotificationClick } from '@/lib/serviceWorker'
|
||||
import { applyPersistedQueryDefaults } from '@/lib/queryPersistence'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
@@ -55,6 +57,8 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
})
|
||||
|
||||
applyPersistedQueryDefaults(queryClient)
|
||||
|
||||
function SSHHostKeyDialogWrapper() {
|
||||
const { sshHostKey } = useEventContext()
|
||||
return (
|
||||
@@ -168,12 +172,14 @@ function ServerScope({ children }: { children: ReactNode }) {
|
||||
function RootLayout() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<ThemeProvider>
|
||||
<TTSProvider>
|
||||
<ThemedToaster />
|
||||
<Outlet />
|
||||
</TTSProvider>
|
||||
</ThemeProvider>
|
||||
<QueryCachePersistenceProvider>
|
||||
<ThemeProvider>
|
||||
<TTSProvider>
|
||||
<ThemedToaster />
|
||||
<Outlet />
|
||||
</TTSProvider>
|
||||
</ThemeProvider>
|
||||
</QueryCachePersistenceProvider>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { IsRestoringProvider, QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { OpenCodeProject } from '@/api/opencode'
|
||||
import { RemoteProjectNavList } from './RemoteProjectNav'
|
||||
|
||||
@@ -132,22 +132,25 @@ function createWrapper(
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
}),
|
||||
isRestoring = false,
|
||||
) {
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
{children}
|
||||
<LocationSpy />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
<IsRestoringProvider value={isRestoring}>
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
{children}
|
||||
<LocationSpy />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</IsRestoringProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
@@ -174,7 +177,11 @@ describe('RemoteProjectNavList', () => {
|
||||
mocks.sessions = [createSession('a1', '/projects/alpha', Date.now())]
|
||||
mocks.hasNextPage.current = false
|
||||
mocks.listProjects.mockResolvedValue([alpha, beta])
|
||||
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [kitchen],
|
||||
isLoading: false,
|
||||
showsInitialLoading: false,
|
||||
})
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
statuses: [],
|
||||
statusById: { srv_kitchen: { serverId: 'srv_kitchen', connected: true, version: null, error: null } },
|
||||
@@ -289,6 +296,7 @@ describe('RemoteProjectNavList', () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [{ ...kitchen, enabled: false }],
|
||||
isLoading: false,
|
||||
showsInitialLoading: false,
|
||||
})
|
||||
|
||||
render(
|
||||
@@ -343,6 +351,39 @@ describe('RemoteProjectNavList', () => {
|
||||
expect(screen.queryByText('Could not load projects')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the project list loading while the cache restore holds the query', () => {
|
||||
mocks.listProjects.mockReturnValue(new Promise(() => {}))
|
||||
|
||||
render(<RemoteListHarness serverId="srv_kitchen" />, {
|
||||
wrapper: createWrapper('/', undefined, true),
|
||||
})
|
||||
|
||||
expect(screen.getByText('Loading projects...')).toBeInTheDocument()
|
||||
expect(screen.queryByText('No projects')).not.toBeInTheDocument()
|
||||
expect(mocks.listProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the sidebar loading while the server list is restoring', () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [],
|
||||
isLoading: false,
|
||||
showsInitialLoading: true,
|
||||
})
|
||||
|
||||
render(
|
||||
<RemoteProjectNavList
|
||||
serverId="srv_kitchen"
|
||||
isVisible
|
||||
onOpenProject={vi.fn()}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
{ wrapper: createWrapper('/') },
|
||||
)
|
||||
|
||||
expect(screen.getByText('Loading projects...')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Server not found')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports an unreachable server on a failed project load', async () => {
|
||||
mocks.listProjects.mockRejectedValue(new Error('offline'))
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
|
||||
@@ -360,20 +360,19 @@ export function RemoteProjectNavList({
|
||||
onOpenProject,
|
||||
onSelectSession,
|
||||
}: RemoteProjectNavListProps) {
|
||||
const { servers, isLoading: isServersLoading } = useOpenCodeServers()
|
||||
const { servers, showsInitialLoading: isServersLoading } = useOpenCodeServers()
|
||||
const { statusById } = useOpenCodeServerStatuses()
|
||||
const server = servers.find((candidate) => candidate.id === serverId)
|
||||
const { directory: activeDirectory } = useActiveRemoteDirectory(serverId)
|
||||
|
||||
const { projects, isLoading: projectsLoading, isError: projectsError, hasData: hasProjects } =
|
||||
useRemoteProjectsByActivity(serverId)
|
||||
const { projects, showsInitialLoading, showsError } = useRemoteProjectsByActivity(serverId)
|
||||
const trimmedSearch = search.trim()
|
||||
|
||||
if (isServersLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (!server) return <SessionNavStatus>Server not found</SessionNavStatus>
|
||||
if (!server.enabled) return <SessionNavStatus>Server is disabled</SessionNavStatus>
|
||||
if (projectsLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (projectsError && !hasProjects) {
|
||||
if (showsInitialLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (showsError) {
|
||||
return (
|
||||
<SessionNavStatus>
|
||||
{statusById[serverId]?.connected === false ? 'Server unreachable' : 'Could not load projects'}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
@@ -64,8 +64,12 @@ function createRepo(overrides: Partial<Repo> = {}): Repo {
|
||||
}
|
||||
}
|
||||
|
||||
function renderRepoList(onAddRepo: () => void = vi.fn()) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
function renderRepoList(
|
||||
onAddRepo: () => void = vi.fn(),
|
||||
options: { queryClient?: QueryClient } = {},
|
||||
) {
|
||||
const queryClient = options.queryClient
|
||||
?? new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
@@ -121,6 +125,26 @@ describe('RepoList', () => {
|
||||
expect(await screen.findByText('No recently accessed repositories')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the error state when the first load fails', async () => {
|
||||
mocks.listRepos.mockRejectedValue(new Error('offline'))
|
||||
|
||||
renderRepoList()
|
||||
|
||||
expect(await screen.findByText(/Failed to load repositories/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps cached repositories when the refetch fails', async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
queryClient.setQueryData(['repos'], [createRepo()])
|
||||
mocks.listRepos.mockRejectedValue(new Error('offline'))
|
||||
|
||||
renderRepoList(vi.fn(), { queryClient })
|
||||
|
||||
expect(await screen.findByText('demo-app')).toBeInTheDocument()
|
||||
await waitFor(() => expect(queryClient.getQueryState(['repos'])?.status).toBe('error'))
|
||||
expect(screen.queryByText(/Failed to load repositories/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels the confirm button "Unlink" for a local repository', async () => {
|
||||
mocks.listRepos.mockResolvedValue([createRepo()])
|
||||
const user = userEvent.setup()
|
||||
|
||||
@@ -162,7 +162,7 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
|
||||
|
||||
const {
|
||||
data: repos,
|
||||
isLoading,
|
||||
isPending,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ["repos"],
|
||||
@@ -312,7 +312,7 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
|
||||
|
||||
const renderContent = () => {
|
||||
switch (true) {
|
||||
case isLoading && !repos:
|
||||
case isPending && !repos:
|
||||
return (
|
||||
<div className="px-0 md:px-4 md:pt-4 h-full flex flex-col">
|
||||
<div className="px-2 md:px-0">
|
||||
@@ -332,7 +332,7 @@ export function RepoList({ onAddRepo }: { onAddRepo: () => void }) {
|
||||
</div>
|
||||
)
|
||||
|
||||
case !!error:
|
||||
case !!error && !repos:
|
||||
return (
|
||||
<div className="text-center p-8 text-destructive">
|
||||
Failed to load repositories:{" "}
|
||||
|
||||
@@ -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 ? <RemoteProjectListLoading /> : null}
|
||||
|
||||
{isDisabled ? (
|
||||
<LinkedServerStateCard
|
||||
icon={Server}
|
||||
@@ -131,15 +133,13 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && showsProjectError ? (
|
||||
{server && !isDisabled && showsError ? (
|
||||
<Card className="flex flex-col items-center gap-3 p-6 text-center">
|
||||
<Server className="h-8 w-8 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium">Could not load projects</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{error instanceof Error
|
||||
? error.message
|
||||
: 'The server did not respond.'}
|
||||
{error instanceof Error ? error.message : 'The server did not respond.'}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => refetch()}>
|
||||
@@ -148,8 +148,8 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && !showsProjectError ? (
|
||||
isLoading ? (
|
||||
{server && !isDisabled && !showsError ? (
|
||||
showsInitialLoading ? (
|
||||
<RemoteProjectListLoading />
|
||||
) : projects.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center p-12 text-center">
|
||||
|
||||
@@ -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([])
|
||||
|
||||
|
||||
@@ -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(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<SessionList
|
||||
|
||||
@@ -52,6 +52,7 @@ export const SessionList = ({
|
||||
filteredSessions,
|
||||
isSearchPending,
|
||||
isLoading,
|
||||
isPending,
|
||||
isPlaceholderData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
@@ -186,7 +187,9 @@ export const SessionList = ({
|
||||
);
|
||||
};
|
||||
|
||||
if (!isLoading && !isPlaceholderData && (!sessions || sessions.length === 0)) {
|
||||
const isInitialLoading = isPending && (!sessions || sessions.length === 0);
|
||||
|
||||
if (!isInitialLoading && !isPlaceholderData && (!sessions || sessions.length === 0)) {
|
||||
if (isFetchNextPageError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-4 text-sm text-muted-foreground">
|
||||
@@ -286,7 +289,7 @@ export const SessionList = ({
|
||||
onScroll={handleSessionsScroll}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{isLoading && !renderSessions ? (
|
||||
{isPending && !renderSessions ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">Loading sessions...</div>
|
||||
) : renderSessions ? (
|
||||
renderSessions({
|
||||
|
||||
@@ -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<typeof useAuth>
|
||||
|
||||
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(
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
|
||||
<Routes>
|
||||
<Route
|
||||
path="/login"
|
||||
element={(
|
||||
<AuthProvider>
|
||||
<AuthProbe captured={captured} />
|
||||
</AuthProvider>
|
||||
)}
|
||||
/>
|
||||
<Route path="/" element={null} />
|
||||
<Route path="/repos/:id" element={null} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} capturedPathname={capturedPathname} />
|
||||
<Routes>
|
||||
<Route
|
||||
path="/login"
|
||||
element={(
|
||||
<AuthProvider>
|
||||
<AuthProbe captured={captured} />
|
||||
</AuthProvider>
|
||||
)}
|
||||
/>
|
||||
<Route path="/" element={null} />
|
||||
<Route path="/repos/:id" element={null} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<AuthUser, 'id' | 'email' | 'name'>
|
||||
|
||||
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<StoredAuthUser | null>(() => readStoredAuthUser())
|
||||
const queryClient = useQueryClient()
|
||||
const [config, setConfig] = useState<AuthConfig | null>(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<AuthContextValue>(() => ({
|
||||
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,
|
||||
|
||||
@@ -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<string, string>()
|
||||
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<typeof createStorage>['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 (
|
||||
<QueryClientProvider client={client}>
|
||||
<QueryCachePersistenceProvider persister={persister}>
|
||||
<RestoringProbe />
|
||||
</QueryCachePersistenceProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
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<undefined>((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))
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
* `"<origin>|<userId>"` 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<string | null>(null)
|
||||
const previousUserIdRef = useRef<string | null>(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 <IsRestoringProvider value={restoring}>{children}</IsRestoringProvider>
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<ReturnType<typeof getSession>> | 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}`))
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { readStoredValue, removeStoredValue, writeStoredValue } from './persistentStorage'
|
||||
import type { AuthUser } from './auth-client'
|
||||
|
||||
export type StoredAuthUser = Pick<AuthUser, 'id' | 'email' | 'name'>
|
||||
|
||||
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<string, unknown>
|
||||
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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<unknown, Error, unknown, readonly unknown[]>(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<string, string>()
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<T>(
|
||||
data: T | undefined,
|
||||
isError: boolean,
|
||||
enabled = true,
|
||||
): CachedListStates {
|
||||
return {
|
||||
showsInitialLoading: enabled && data === undefined && !isError,
|
||||
showsError: isError && data === undefined,
|
||||
}
|
||||
}
|
||||
Generated
+42
-9
@@ -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':
|
||||
|
||||
Reference in new issue
Block a user