feat(session): paginated session list with infinite scroll and assistant mode improvements (#243)

* feat(session): paginated session list with infinite scroll and search

Replace per-directory useQueries session listing with a combined
cursor-based useInfiniteQuery (25 per page, loads more on scroll) and
move search into the API query instead of client-side filtering.

Add OpenCodeClient.listSessionsPage backed by the v2 /api/session
endpoint plus a toLegacySession adapter. Add invalidateSessionListCaches
to centralize session-list cache invalidation for infinite queries, and
update EventContext and useSSE to handle the new infinite-query cache
shape.

* fix(session): centralize and debounce session-list cache invalidation

Migrate ResetPermissionsDialog off the stale per-directory cache key
(which no longer matches the infinite-query key shape and hardcoded the
opencode URL) to the shared invalidateSessionListCaches helper, and drop
the now-unused repoDirectory prop and its call sites.

Debounce session-list invalidation on SSE session.updated events in
EventContext and useSSE so a burst of updates coalesces into a single
refetch instead of one per event. Fix the directory fallback in
EventContext getClient so it never returns the joined directory key.

* fix(permissions): scope instance dispose to the repo directory

Drop the session-list cache invalidation from ResetPermissionsDialog:
disposing the OpenCode instance does not change the persisted session
list, so the refetch was unnecessary, and the prior cache key no longer
matched the paginated shape.

Guard the reset-permissions route against an empty repo directory so it
never forwards /instance/dispose without a directory, which would
dispose the entire server instead of only the repo's instance.
This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-31 10:32:14 -04:00
1 parent 78d934772e
commit eedbbfb94e
17 files changed
+931 -116

No files matched your search

+95 -1
View File
@@ -5,7 +5,7 @@ import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { PermissionRequest, QuestionRequest } from '@/api/types'
import { EventProvider, usePermissions, useQuestions, useSSEHealth } from './EventContext'
import { EventProvider, useEventContext, usePermissions, useQuestions, useSSEHealth } from './EventContext'
const mocks = vi.hoisted(() => ({
listRepos: vi.fn(),
@@ -346,6 +346,100 @@ describe('EventProvider questions', () => {
it('handles session.updated event without throwing when cache has infinite-query data', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
// Seed infinite-query shaped data into session-list cache
queryClient.setQueryData(
['opencode', 'sessions', 'http://localhost:5551', '/repo', { search: undefined, limit: 25 }],
{
pages: [{
items: [
{ id: 'existing-session', projectID: 'proj-1', title: 'Existing', directory: '/repo', time: { created: 1000, updated: 1000 } },
],
cursors: {},
}],
pageParams: [undefined],
},
)
const wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
</MemoryRouter>
)
render(<Harness />, { wrapper })
await waitFor(() => {
expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled()
})
// Trigger session.updated event - should not throw with infinite-query cache data
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
expect(() => {
act(() => {
onEvent({
type: 'session.updated',
properties: {
info: { id: 'new-session', projectID: 'proj-1', title: 'New', directory: '/repo', time: { created: 2000, updated: 2000 } },
},
})
})
}).not.toThrow()
})
it('getClient resolves directory from infinite-query session list cache', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
// Seed infinite-query data with a session that has directory field
queryClient.setQueryData(
['opencode', 'sessions', 'http://localhost:5551', '/repo', { search: undefined, limit: 25 }],
{
pages: [{
items: [
{ id: 'ses-infinite', projectID: 'proj-1', title: 'From Infinite Query', directory: '/repo', time: { created: 1000, updated: 1000 } },
],
cursors: {},
}],
pageParams: [undefined],
},
)
// Ensure no single-session cache exists for this session (forces fallback to session-list lookup)
const wrapper = ({ children }: { children: ReactNode }) => (
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<EventProvider>{children}</EventProvider>
</QueryClientProvider>
</MemoryRouter>
)
function ClientHarness() {
const { getClient } = useEventContext()
const client = getClient('ses-infinite')
return <div data-testid="client-result">{client ? 'found' : 'not-found'}</div>
}
render(<ClientHarness />, { wrapper })
await waitFor(() => {
expect(screen.getByTestId('client-result')).toHaveTextContent('found')
})
})
it('exposes sseHealth through context', async () => {
mocks.getHealth.mockReturnValue({ isConnected: true, isHealthy: true, lastEventAt: Date.now(), isStalled: false })
mocks.subscribeGlobalMonitor.mockImplementation(({ onHealthChange }) => {
+27 -12
View File
@@ -8,6 +8,7 @@ import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent,
import { showToast } from '@/lib/toast'
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { invalidateSessionListCachesDebounced } from '@/lib/queryInvalidation'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
type PermissionsBySession = Record<string, PermissionRequest[]>
@@ -229,12 +230,25 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
for (const query of queries) {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'sessions' && key.length >= 4) {
const sessionsList = query.state.data as Array<{ id: string }> | undefined
if (!sessionsList) continue
const found = sessionsList.find(s => s.id === sessionID)
if (found) {
const directory = key[3] as string
if (directory) return directory
const sessionsData = query.state.data
if (!sessionsData) continue
if (Array.isArray(sessionsData)) {
const found = sessionsData.find((s: { id: string }) => s.id === sessionID)
if (found) {
const directory = (found as { directory?: string }).directory || (key[3] as string)
if (directory) return directory
}
continue
}
if (typeof sessionsData === 'object' && 'pages' in sessionsData) {
const infiniteData = sessionsData as { pages: Array<{ items: Array<{ id: string; directory?: string }> }> }
for (const page of infiniteData.pages) {
if (!page.items) continue
const found = page.items.find(s => s.id === sessionID)
if (found && found.directory) return found.directory
}
}
}
}
@@ -488,18 +502,19 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
case 'session.updated':
if ('info' in event.properties) {
const sessionInfo = event.properties.info as { id: string }
// Update single-session cache entries
const cache = queryClient.getQueryCache()
for (const query of cache.getAll()) {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'sessions' && key.length >= 4) {
const currentList = query.state.data as Array<{ id: string }> | undefined
if (!currentList) continue
const exists = currentList.some(s => s.id === sessionInfo.id)
if (!exists) {
queryClient.setQueryData(key, [...currentList, sessionInfo])
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
const sessionData = query.state.data as { id: string } | undefined
if (sessionData?.id === sessionInfo.id) {
queryClient.setQueryData(key, sessionInfo)
}
}
}
// Invalidate session list caches instead of mutating infinite-query data
invalidateSessionListCachesDebounced(queryClient)
}
break
case 'lsp.updated':