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

+184 -2
View File
@@ -1,8 +1,8 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useDeleteSession } from './useOpenCode'
import { useDeleteSession, useSessionsAcrossDirectories } from './useOpenCode'
vi.mock('../lib/toast', () => ({
showToast: {
@@ -82,3 +82,185 @@ describe('useDeleteSession', () => {
)
})
})
describe('useSessionsAcrossDirectories', () => {
const fetchMock = vi.fn()
beforeEach(() => {
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('fetches first page of sessions with v2 pagination and adapted items', async () => {
fetchMock.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-1', projectID: 'proj-1', title: 'Test Session', time: { created: 1000, updated: 1000 } },
],
cursor: { next: 'cursor_abc' },
}), { headers: { 'Content-Type': 'application/json' } }),
)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(() => useSessionsAcrossDirectories('/api/opencode', ['/repo']), { wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(result.current.data).toHaveLength(1)
expect(result.current.data[0].id).toBe('session-1')
expect(result.current.data[0].title).toBe('Test Session')
expect(result.current.hasNextPage).toBe(true)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(fetchMock).toHaveBeenCalledWith(
'http://localhost/api/opencode/api/session?limit=25&order=desc&directory=%2Frepo',
expect.objectContaining({ credentials: 'include' }),
)
})
it('fetches next page via cursor when fetchNextPage is called and flattens items', async () => {
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-1', projectID: 'proj-1', title: 'Page 1', time: { created: 1000, updated: 1000 } },
],
cursor: { next: 'cursor_next' },
}), { headers: { 'Content-Type': 'application/json' } }),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-2', projectID: 'proj-1', title: 'Page 2', time: { created: 2000, updated: 2000 } },
],
}), { headers: { 'Content-Type': 'application/json' } }),
)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(() => useSessionsAcrossDirectories('/api/opencode', ['/repo']), { wrapper })
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(result.current.data).toHaveLength(1)
expect(result.current.data[0].id).toBe('session-1')
await act(async () => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.data).toHaveLength(2)
})
expect(result.current.data[0].id).toBe('session-1')
expect(result.current.data[1].id).toBe('session-2')
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(fetchMock).toHaveBeenNthCalledWith(
2,
'http://localhost/api/opencode/api/session?cursor=cursor_next',
expect.objectContaining({ credentials: 'include' }),
)
})
it('handles multi-directory cursors and only fetches directories with nextCursor', async () => {
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-a1', projectID: 'proj-1', title: 'Session A1', time: { created: 1000, updated: 1000 } },
],
cursor: { next: 'cursor_a' },
}), { headers: { 'Content-Type': 'application/json' } }),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-b1', projectID: 'proj-1', title: 'Session B1', time: { created: 1000, updated: 1000 } },
],
}), { headers: { 'Content-Type': 'application/json' } }),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-a2', projectID: 'proj-1', title: 'Session A2', time: { created: 2000, updated: 2000 } },
],
}), { headers: { 'Content-Type': 'application/json' } }),
)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(
() => useSessionsAcrossDirectories('/api/opencode', ['/w/a', '/w/b']),
{ wrapper },
)
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(result.current.data).toHaveLength(2)
expect(result.current.hasNextPage).toBe(true)
await act(async () => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.data).toHaveLength(3)
})
expect(fetchMock).toHaveBeenCalledTimes(3)
expect(fetchMock).toHaveBeenNthCalledWith(
3,
'http://localhost/api/opencode/api/session?cursor=cursor_a',
expect.objectContaining({ credentials: 'include' }),
)
})
it('sends search parameter when search option is provided', async () => {
fetchMock.mockResolvedValueOnce(
new Response(JSON.stringify({
items: [
{ id: 'session-1', projectID: 'proj-1', title: 'Deploy Session', time: { created: 1000, updated: 1000 } },
],
}), { headers: { 'Content-Type': 'application/json' } }),
)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result } = renderHook(
() => useSessionsAcrossDirectories('/api/opencode', ['/repo'], { search: 'deploy' }),
{ wrapper },
)
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(fetchMock).toHaveBeenCalledWith(
'http://localhost/api/opencode/api/session?limit=25&order=desc&search=deploy&directory=%2Frepo',
expect.objectContaining({ credentials: 'include' }),
)
})
})
+79 -36
View File
@@ -1,4 +1,4 @@
import { useQueries, useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
import { useMemo, useRef, useEffect, useCallback } from "react";
import { OpenCodeClient } from "../api/opencode";
import { FetchError } from "../api/fetchWrapper";
@@ -13,6 +13,7 @@ import { parseNetworkError } from "../lib/opencode-errors";
import { showToast } from "../lib/toast";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { useSendErrorStore } from "../stores/sendErrorStore";
import { invalidateSessionListCaches } from "../lib/queryInvalidation";
type AssistantMessage = components["schemas"]["AssistantMessage"];
@@ -36,33 +37,90 @@ export const useOpenCodeClient = (opcodeUrl: string | null | undefined, director
);
};
const SESSION_LIST_PAGE_SIZE = 25
interface UseSessionsAcrossDirectoriesOptions {
search?: string
limit?: number
}
type SessionPageParam = Record<string, string>
export const useSessionsAcrossDirectories = (
opcodeUrl: string | null | undefined,
directories: string[],
options?: UseSessionsAcrossDirectoriesOptions,
) => {
const uniqueDirectories = useMemo(
() => Array.from(new Set(directories.filter(Boolean))),
[directories],
);
const normalizedSearch = options?.search?.trim() || undefined;
const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE;
const directoryKey = uniqueDirectories.join('|');
const queries = useQueries({
queries: uniqueDirectories.map((directory) => ({
queryKey: ["opencode", "sessions", opcodeUrl, directory],
queryFn: () => new OpenCodeClient(opcodeUrl!, directory).listSessions(),
enabled: !!opcodeUrl && !!directory,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
staleTime: 10000,
})),
const query = useInfiniteQuery({
queryKey: ['opencode', 'sessions', opcodeUrl, directoryKey, { search: normalizedSearch, limit }],
queryFn: async ({ pageParam }) => {
if (!pageParam) {
const pages = await Promise.all(
uniqueDirectories.map((directory) =>
new OpenCodeClient(opcodeUrl!, directory).listSessionsPage({
limit,
order: 'desc',
search: normalizedSearch,
}),
),
);
const cursors: SessionPageParam = {};
const items: Array<components['schemas']['Session']> = [];
for (let i = 0; i < pages.length; i++) {
items.push(...pages[i].items);
if (pages[i].nextCursor) {
cursors[uniqueDirectories[i]] = pages[i].nextCursor!;
}
}
return { items, cursors };
}
const entries = Object.entries(pageParam);
const pages = await Promise.all(
entries.map(([directory, cursor]) =>
new OpenCodeClient(opcodeUrl!, directory).listSessionsPage({ cursor }),
),
);
const cursors: SessionPageParam = {};
const items: Array<components['schemas']['Session']> = [];
for (let i = 0; i < pages.length; i++) {
items.push(...pages[i].items);
if (pages[i].nextCursor) {
cursors[entries[i][0]] = pages[i].nextCursor!;
}
}
return { items, cursors };
},
initialPageParam: undefined as SessionPageParam | undefined,
getNextPageParam: (lastPage) => {
if (Object.keys(lastPage.cursors).length > 0) {
return lastPage.cursors;
}
return undefined;
},
enabled: !!opcodeUrl && uniqueDirectories.length > 0,
staleTime: 10000,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
});
return useMemo(() => {
const data = queries.flatMap((q) => q.data ?? []);
const isLoading = queries.some((q) => q.isLoading);
const isError = queries.some((q) => q.isError);
return { data, isLoading, isError };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [directoryKey, queries.map((q) => q.dataUpdatedAt).join('|'), queries.map((q) => q.isLoading).join('|')]);
return {
data: query.data?.pages.flatMap((page) => page.items) ?? [],
isLoading: query.isLoading,
isError: query.isError,
fetchNextPage: query.fetchNextPage,
hasNextPage: query.hasNextPage,
isFetchingNextPage: query.isFetchingNextPage,
error: query.error,
};
};
export const useSession = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => {
@@ -115,7 +173,7 @@ export const useCreateSession = (
return client.createSession(data);
},
onSuccess: (session) => {
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, directory] });
invalidateSessionListCaches(queryClient, opcodeUrl);
onSuccess?.(session);
},
onError: (error) => {
@@ -219,23 +277,8 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory
onError: () => {
showToast.error('Failed to delete sessions');
},
onSettled: (_data, _error, variables) => {
const targets = variables ? (Array.isArray(variables) ? variables : [variables]) : [];
const affectedDirectories = new Set([
...directories,
...targets
.map((target) => getDeleteSessionTargetDirectory(target))
.filter((value): value is string => !!value),
]);
if (affectedDirectories.size === 0) {
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl] });
return;
}
for (const affectedDirectory of affectedDirectories) {
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, affectedDirectory] });
}
onSettled: () => {
invalidateSessionListCaches(queryClient, opcodeUrl);
},
});
};
@@ -252,7 +295,7 @@ export const useUpdateSession = (opcodeUrl: string | null | undefined, directory
onSuccess: (_, variables) => {
const { sessionID } = variables;
queryClient.invalidateQueries({ queryKey: ["opencode", "session", opcodeUrl, sessionID, directory] });
queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, directory] });
invalidateSessionListCaches(queryClient, opcodeUrl);
},
});
};
+63
View File
@@ -54,6 +54,9 @@ class MockEventSource {
emit(type: string, data: unknown) {
const event = { data: JSON.stringify(data) } as MessageEvent
this.listeners.get(type)?.forEach((listener) => listener(event))
if (type === 'message' && this.onmessage) {
this.onmessage(event)
}
}
}
@@ -211,4 +214,64 @@ describe('useSSE', () => {
unmount()
})
it('sets single-session cache and invalidates session list on session.updated', async () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries')
const setQueryDataSpy = vi.spyOn(queryClient, 'setQueryData')
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const { result, unmount } = renderHook(
() => useSSE('http://localhost:5551', '/repo', 'session-1'),
{ wrapper }
)
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
act(() => {
MockEventSource.instances[0].emit('connected', { clientId: 'client-1' })
})
await waitFor(() => expect(result.current.isConnected).toBe(true))
// Clear initial connection-related calls
invalidateQueriesSpy.mockClear()
setQueryDataSpy.mockClear()
const sessionData = {
id: 'session-2',
projectID: 'proj-1',
title: 'Updated Session',
time: { created: 1000, updated: 2000 },
}
act(() => {
MockEventSource.instances[0].emit('message', {
type: 'session.updated',
properties: { info: sessionData },
})
})
await waitFor(() => {
expect(setQueryDataSpy).toHaveBeenCalledWith(
['opencode', 'session', 'http://localhost:5551', 'session-2', '/repo'],
sessionData,
)
})
await waitFor(() => {
expect(invalidateQueriesSpy).toHaveBeenCalledWith(
expect.objectContaining({ predicate: expect.any(Function) }),
)
})
unmount()
})
})
+5 -16
View File
@@ -1,7 +1,8 @@
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useOpenCodeClient } from './useOpenCode'
import type { SSEEvent, MessageWithParts, Session } from '@/api/types'
import { invalidateSessionListCaches, invalidateSessionListCachesDebounced } from '@/lib/queryInvalidation'
import type { SSEEvent, MessageWithParts } from '@/api/types'
import { showToast } from '@/lib/toast'
import { settingsApi } from '@/api/settings'
import { useSessionStatus } from '@/stores/sessionStatusStore'
@@ -105,28 +106,16 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
if ('info' in event.properties) {
const session = event.properties.info
const sessionQueryKey = ['opencode', 'session', opcodeUrl, session.id, cacheDirectory]
const sessionsQueryKey = ['opencode', 'sessions', opcodeUrl, cacheDirectory]
queryClient.setQueryData(sessionQueryKey, session)
const sessions = queryClient.getQueryData<Session[]>(sessionsQueryKey)
if (sessions) {
const exists = sessions.some((item) => item.id === session.id)
const updated = exists
? sessions.map((item) => (item.id === session.id ? session : item))
: [session, ...sessions]
queryClient.setQueryData(sessionsQueryKey, updated)
break
}
queryClient.invalidateQueries({ queryKey: sessionsQueryKey })
invalidateSessionListCachesDebounced(queryClient)
break
}
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, cacheDirectory] })
invalidateSessionListCachesDebounced(queryClient)
break
case 'session.deleted':
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, cacheDirectory] })
invalidateSessionListCaches(queryClient, opcodeUrl)
if ('sessionID' in event.properties) {
queryClient.invalidateQueries({
queryKey: ['opencode', 'session', opcodeUrl, event.properties.sessionID, cacheDirectory]