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

@@ -1,4 +1,4 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useMutation } from "@tanstack/react-query";
import { resetRepoPermissions } from "@/api/repos";
import {
Dialog,
@@ -16,23 +16,16 @@ interface ResetPermissionsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoId: number;
repoDirectory?: string;
}
export function ResetPermissionsDialog({
open,
onOpenChange,
repoId,
repoDirectory,
}: ResetPermissionsDialogProps) {
const queryClient = useQueryClient();
const resetPermissionsMutation = useMutation({
mutationFn: () => resetRepoPermissions(repoId),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["opencode", "sessions", "http://localhost:5551", repoDirectory],
});
showToast.success("Permissions reset successfully");
onOpenChange(false);
},
@@ -1,20 +1,32 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen, waitFor, within } from '@testing-library/react'
import { render, screen, waitFor, within, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionList } from './SessionList'
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState } = vi.hoisted(() => ({
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, lastSessionsHookArgs } = vi.hoisted(() => ({
createSessionMock: vi.fn(),
deleteSessionMock: vi.fn(),
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; time: { updated: number } }>,
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; parentID?: string; time: { updated: number } }>,
createSessionState: { directory: undefined as string | undefined },
fetchNextPageMock: vi.fn(),
hasNextPageRef: { current: false },
isFetchingNextPageRef: { current: false },
lastSessionsHookArgs: { current: undefined as { opcodeUrl: string; directories: string[]; options?: { search?: string; limit?: number } } | undefined },
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSessionsAcrossDirectories: () => ({
data: sessionsData,
isLoading: false,
}),
useSessionsAcrossDirectories: (opcodeUrl: string, directories: string[], options?: { search?: string; limit?: number }) => {
lastSessionsHookArgs.current = { opcodeUrl, directories, options }
// Simulate server-side search: return empty data when a search query is active
const data = options?.search ? [] : sessionsData
return {
data,
isLoading: false,
fetchNextPage: fetchNextPageMock,
hasNextPage: hasNextPageRef.current,
isFetchingNextPage: isFetchingNextPageRef.current,
}
},
useCreateSession: (_opcodeUrl: string, directory?: string) => {
createSessionState.directory = directory
return { mutate: createSessionMock }
@@ -33,6 +45,10 @@ describe('SessionList', () => {
createSessionState.directory = undefined
deleteSessionMock.mockReset()
deleteSessionMock.mockResolvedValue(undefined)
fetchNextPageMock.mockReset()
hasNextPageRef.current = false
isFetchingNextPageRef.current = false
lastSessionsHookArgs.current = undefined
})
it('selects duplicate session IDs independently by workspace directory', async () => {
@@ -110,4 +126,145 @@ describe('SessionList', () => {
expect(createSessionState.directory).toBe('/w/b')
expect(createSessionMock).toHaveBeenCalledWith({ agent: undefined })
})
it('passes search query and limit option to useSessionsAcrossDirectories', async () => {
const user = userEvent.setup()
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
const searchInput = screen.getByPlaceholderText('Search sessions...')
await user.type(searchInput, 'deploy')
await waitFor(() => {
expect(lastSessionsHookArgs.current?.options?.search).toBe('deploy')
expect(lastSessionsHookArgs.current?.options?.limit).toBe(25)
})
})
it('fetches next page when scrolling near the bottom and hasNextPage is true', async () => {
hasNextPageRef.current = true
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
const scrollContainer = screen.getByRole('region', { name: 'Sessions' })
Object.defineProperty(scrollContainer, 'scrollHeight', { value: 1000, configurable: true })
Object.defineProperty(scrollContainer, 'clientHeight', { value: 500, configurable: true })
Object.defineProperty(scrollContainer, 'scrollTop', { value: 300, configurable: true })
fireEvent.scroll(scrollContainer)
await waitFor(() => {
expect(fetchNextPageMock).toHaveBeenCalled()
})
})
it('does not fetch next page on scroll when isFetchingNextPage is true', async () => {
hasNextPageRef.current = true
isFetchingNextPageRef.current = true
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
const scrollContainer = screen.getByRole('region', { name: 'Sessions' })
Object.defineProperty(scrollContainer, 'scrollHeight', { value: 1000, configurable: true })
Object.defineProperty(scrollContainer, 'clientHeight', { value: 500, configurable: true })
Object.defineProperty(scrollContainer, 'scrollTop', { value: 300, configurable: true })
fireEvent.scroll(scrollContainer)
await waitFor(() => {
expect(fetchNextPageMock).not.toHaveBeenCalled()
})
})
it('shows search-results empty state instead of create-session card when search returns no results', async () => {
const user = userEvent.setup()
// Default beforeEach data has 3 sessions; typing search triggers mock to return empty data
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
await user.type(screen.getByPlaceholderText('Search sessions...'), 'nonexistent')
await waitFor(() => {
expect(screen.getByText('No sessions found')).toBeTruthy()
})
expect(screen.queryByText('No sessions yet')).toBeNull()
expect(screen.queryByText('Click here to start a new session')).toBeNull()
})
it('shows create-session card when there are no sessions and no active search', () => {
sessionsData.splice(0, sessionsData.length)
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
expect(screen.getByText('No sessions yet')).toBeTruthy()
expect(screen.getByText('Click here to start a new session')).toBeTruthy()
})
it('shows loading state instead of create-session card when the first page is empty but more pages are pending', () => {
sessionsData.splice(0, sessionsData.length)
hasNextPageRef.current = true
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
expect(screen.getByText('Loading sessions...')).toBeTruthy()
expect(screen.queryByText('No sessions yet')).toBeNull()
expect(screen.queryByText('Click here to start a new session')).toBeNull()
})
it('auto-fetches next page when all visible sessions are filtered out as child sessions', async () => {
sessionsData.splice(0, sessionsData.length,
{ id: 'child1', title: 'child session', directory: '/w/a', parentID: 'parent1', time: { updated: Date.now() } },
{ id: 'child2', title: 'child session 2', directory: '/w/a', parentID: 'parent2', time: { updated: Date.now() } },
)
hasNextPageRef.current = true
isFetchingNextPageRef.current = false
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
await waitFor(() => {
expect(fetchNextPageMock).toHaveBeenCalled()
})
})
})
+50 -29
View File
@@ -1,4 +1,4 @@
import { useCallback, useState, useMemo } from "react";
import { useCallback, useState, useMemo, useEffect } from "react";
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
import { DeleteSessionDialog } from "./DeleteSessionDialog";
@@ -37,33 +37,26 @@ export const SessionList = ({
const getSessionSelectionKey = useCallback((session: { id: string; directory?: string }) =>
`${session.directory ?? primaryDirectory ?? ''}:${session.id}`,
[primaryDirectory]);
const { data: sessions, isLoading } = useSessionsAcrossDirectories(opcodeUrl, directoriesList);
const [searchQuery, setSearchQuery] = useState("");
const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useSessionsAcrossDirectories(opcodeUrl, directoriesList, { search: searchQuery, limit: 25 });
const deleteSession = useDeleteSession(opcodeUrl, directoriesList);
const createSession = useCreateSession(opcodeUrl, sessionCreateDirectory, (newSession) => {
onSelectSession(newSession.id);
});
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [sessionToDelete, setSessionToDelete] = useState<DeleteSessionTarget | DeleteSessionTarget[] | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set());
const [manageMode, setManageMode] = useState(false);
const filteredSessions = useMemo(() => {
if (!sessions) return [];
let filtered = sessions.filter((session) => {
const filtered = sessions.filter((session) => {
if (session.parentID) return false;
if (directorySet.size > 0 && session.directory && !directorySet.has(session.directory)) return false;
return true;
});
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase();
filtered = filtered.filter((session) =>
(session.title || "Untitled Session").toLowerCase().includes(query),
);
}
const uniqueSessions = new Map<string, (typeof filtered)[number]>();
filtered.forEach((session) => {
const key = getSessionSelectionKey(session);
@@ -73,7 +66,7 @@ export const SessionList = ({
});
return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated);
}, [sessions, searchQuery, directorySet, getSessionSelectionKey]);
}, [sessions, directorySet, getSessionSelectionKey]);
const todaySessions = useMemo(() => {
const today = new Date();
@@ -87,26 +80,44 @@ export const SessionList = ({
return filteredSessions.filter((session) => new Date(session.time.updated) < today);
}, [filteredSessions]);
const handleSessionsScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage) {
void fetchNextPage();
}
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
useEffect(() => {
if (!isLoading && filteredSessions.length === 0 && hasNextPage && !isFetchingNextPage) {
void fetchNextPage();
}
}, [isLoading, filteredSessions.length, hasNextPage, isFetchingNextPage, fetchNextPage]);
if (isLoading) {
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
}
if (!sessions || sessions.length === 0) {
return (
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<Card
className="p-6 cursor-pointer hover:bg-accent hover:border-border transition-all border-dashed"
onClick={() => createSession.mutate({ agent: undefined })}
>
<div className="flex flex-col items-center justify-center gap-2 text-center">
<p className="font-medium">No sessions yet</p>
<p className="text-sm text-muted-foreground">
Click here to start a new session
</p>
</div>
</Card>
</div>
);
if (hasNextPage || isFetchingNextPage) {
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
}
if (!searchQuery.trim()) {
return (
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<Card
className="p-6 cursor-pointer hover:bg-accent hover:border-border transition-all border-dashed"
onClick={() => createSession.mutate({ agent: undefined })}
>
<div className="flex flex-col items-center justify-center gap-2 text-center">
<p className="font-medium">No sessions yet</p>
<p className="text-sm text-muted-foreground">
Click here to start a new session
</p>
</div>
</Card>
</div>
);
}
}
const getDeleteTarget = (session: { id: string; directory?: string; workspaceID?: string }): DeleteSessionTarget => {
@@ -236,9 +247,14 @@ export const SessionList = ({
)}
</div>
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<div
className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]"
role="region"
aria-label="Sessions"
onScroll={handleSessionsScroll}
>
<div className="flex flex-col gap-4">
{filteredSessions.length === 0 ? (
{filteredSessions.length === 0 && !isFetchingNextPage ? (
<div className="text-sm text-muted-foreground text-center py-4">
No sessions found
</div>
@@ -283,6 +299,11 @@ export const SessionList = ({
))}
</>
)}
{isFetchingNextPage && (
<div className="text-sm text-muted-foreground text-center py-4">
Loading more sessions...
</div>
)}
</div>
</div>