mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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:
1 parent
78d934772e
commit
eedbbfb94e
17 files changed
+931
-116
No files matched your search
@@ -470,7 +470,11 @@ app.get('/', async (c) => {
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
|
||||
if (!repo.fullPath) {
|
||||
return c.json({ error: 'Repo has no directory to reset' }, 400)
|
||||
}
|
||||
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: '/instance/dispose',
|
||||
|
||||
@@ -248,4 +248,63 @@ describe('Repo Routes', () => {
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/reset-permissions', () => {
|
||||
it('should return 404 when repo not found', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(null)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/reset-permissions', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('should return 400 without disposing when repo has no directory', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: undefined,
|
||||
localPath: 'assistant',
|
||||
fullPath: '',
|
||||
sourcePath: undefined,
|
||||
branch: undefined,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
}
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
|
||||
const forward = vi.fn(async () => new Response(JSON.stringify(true), { status: 200 }))
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
|
||||
const res = await app.request('/1/reset-permissions', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(forward).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should dispose only the repo directory and return success', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
}
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
|
||||
const forward = vi.fn(async () => new Response(JSON.stringify(true), { status: 200 }))
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ forward }))
|
||||
const res = await app.request('/1/reset-permissions', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(forward).toHaveBeenCalledWith({
|
||||
method: 'POST',
|
||||
path: '/instance/dispose',
|
||||
directory: '/tmp/test-repo',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -42,4 +42,130 @@ describe('OpenCodeClient', () => {
|
||||
'Workspace not found: wrk_stale',
|
||||
)
|
||||
})
|
||||
|
||||
describe('listSessionsPage', () => {
|
||||
it('sends first-page params to /api/session with directory and returns adapted sessions', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: 'ses_1',
|
||||
projectID: 'proj_1',
|
||||
workspaceID: 'ws_1',
|
||||
parentID: 'parent_1',
|
||||
title: 'My Session',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
},
|
||||
],
|
||||
cursor: { next: 'cursor_next' },
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: 'deploy',
|
||||
})
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/api/session?limit=25&order=desc&search=deploy&directory=%2Frepo',
|
||||
expect.any(Object),
|
||||
)
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.items[0]).toMatchObject({
|
||||
id: 'ses_1',
|
||||
projectID: 'proj_1',
|
||||
directory: '/repo',
|
||||
parentID: 'parent_1',
|
||||
title: 'My Session',
|
||||
version: 'v2',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
})
|
||||
})
|
||||
|
||||
it('sends cursor-only params without directory for cursor-based requests', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
|
||||
await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({ cursor: 'cursor_123' })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/api/session?cursor=cursor_123',
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
it('exposes response cursor as nextCursor', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [],
|
||||
cursor: { next: 'next_1' },
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage({ limit: 10 })
|
||||
|
||||
expect(result.nextCursor).toBe('next_1')
|
||||
})
|
||||
|
||||
it('uses Untitled Session for empty title', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: 'ses_2',
|
||||
projectID: 'proj_2',
|
||||
title: '',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode', '/repo').listSessionsPage()
|
||||
|
||||
expect(result.items[0].title).toBe('Untitled Session')
|
||||
})
|
||||
|
||||
it('works without directory set', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
items: [
|
||||
{
|
||||
id: 'ses_3',
|
||||
projectID: 'proj_3',
|
||||
title: 'No Dir',
|
||||
time: { created: 1000, updated: 2000 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
|
||||
const result = await new OpenCodeClient('/api/opencode').listSessionsPage({ limit: 5 })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://localhost/api/opencode/api/session?limit=5',
|
||||
expect.any(Object),
|
||||
)
|
||||
expect(result.items[0].directory).toBe('')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,34 @@ type SendPromptResponse = paths['/session/{sessionID}/message']['post']['respons
|
||||
type LspStatusResponse = paths['/lsp']['get']['responses']['200']['content']['application/json']
|
||||
type LspStatus = LspStatusResponse[number]
|
||||
|
||||
type LegacySession = SessionListResponse[number]
|
||||
type SessionV2Info = {
|
||||
id: string
|
||||
parentID?: string
|
||||
projectID: string
|
||||
workspaceID?: string
|
||||
title: string
|
||||
time: LegacySession['time']
|
||||
path?: unknown
|
||||
}
|
||||
type SessionPageCursor = { previous?: string; next?: string }
|
||||
type SessionPageResponse = { items: SessionV2Info[]; cursor?: SessionPageCursor }
|
||||
type SessionPageParams = { limit?: number; order?: 'asc' | 'desc'; search?: string; cursor?: string }
|
||||
type SessionPage = { items: LegacySession[]; nextCursor?: string }
|
||||
|
||||
function toLegacySession(session: SessionV2Info, directory?: string): LegacySession {
|
||||
return {
|
||||
id: session.id,
|
||||
projectID: session.projectID,
|
||||
workspaceID: session.workspaceID,
|
||||
directory: directory ?? '',
|
||||
parentID: session.parentID,
|
||||
title: session.title || 'Untitled Session',
|
||||
version: 'v2',
|
||||
time: session.time,
|
||||
} as LegacySession
|
||||
}
|
||||
|
||||
export type { SendPromptResponse, SendCommandResponse, LspStatus }
|
||||
|
||||
export class OpenCodeClient {
|
||||
@@ -34,7 +62,7 @@ export class OpenCodeClient {
|
||||
this.directory = directory
|
||||
}
|
||||
|
||||
private getParams(params?: Record<string, string>) {
|
||||
private getParams(params?: Record<string, string | number | boolean | undefined>) {
|
||||
if (!this.directory) return params
|
||||
return { ...params, directory: this.directory }
|
||||
}
|
||||
@@ -45,6 +73,24 @@ export class OpenCodeClient {
|
||||
})
|
||||
}
|
||||
|
||||
async listSessionsPage(params?: SessionPageParams): Promise<SessionPage> {
|
||||
const isCursorRequest = params?.cursor !== undefined
|
||||
const queryParams = isCursorRequest
|
||||
? { cursor: params.cursor }
|
||||
: this.getParams({
|
||||
...(params?.limit !== undefined && { limit: params.limit }),
|
||||
...(params?.order !== undefined && { order: params.order }),
|
||||
...(params?.search !== undefined && { search: params.search }),
|
||||
})
|
||||
const response = await fetchWrapper<SessionPageResponse>(`${this.baseURL}/api/session`, {
|
||||
params: queryParams,
|
||||
})
|
||||
return {
|
||||
items: response.items.map((item) => toLegacySession(item, this.directory)),
|
||||
nextCursor: response.cursor?.next,
|
||||
}
|
||||
}
|
||||
|
||||
async getSession(sessionID: string) {
|
||||
return fetchWrapper<SessionResponse>(`${this.baseURL}/session/${sessionID}`, {
|
||||
params: this.getParams(),
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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]
|
||||
|
||||
@@ -34,3 +34,28 @@ export function invalidateSessionCaches(queryClient: QueryClient) {
|
||||
query.queryKey[1] === 'messages'),
|
||||
})
|
||||
}
|
||||
|
||||
export function invalidateSessionListCaches(queryClient: QueryClient, opcodeUrl?: string | null) {
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) => {
|
||||
if (query.queryKey[0] !== 'opencode') return false
|
||||
if (query.queryKey[1] !== 'sessions') return false
|
||||
if (opcodeUrl && query.queryKey[2] !== opcodeUrl) return false
|
||||
return true
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const sessionListInvalidationTimers = new WeakMap<QueryClient, ReturnType<typeof setTimeout>>()
|
||||
|
||||
export function invalidateSessionListCachesDebounced(queryClient: QueryClient, delayMs = 200) {
|
||||
const existing = sessionListInvalidationTimers.get(queryClient)
|
||||
if (existing) clearTimeout(existing)
|
||||
sessionListInvalidationTimers.set(
|
||||
queryClient,
|
||||
setTimeout(() => {
|
||||
sessionListInvalidationTimers.delete(queryClient)
|
||||
invalidateSessionListCaches(queryClient)
|
||||
}, delayMs),
|
||||
)
|
||||
}
|
||||
@@ -162,7 +162,7 @@ export function AssistantRedirect() {
|
||||
/>
|
||||
)}
|
||||
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
|
||||
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} repoDirectory={assistantDirectory} />
|
||||
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} />
|
||||
</>
|
||||
)}
|
||||
{repo && (
|
||||
|
||||
@@ -313,7 +313,6 @@ export function RepoDetail() {
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
repoId={repoId}
|
||||
repoDirectory={composerDirectory}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -652,7 +652,6 @@ export function SessionDetail() {
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
repoId={repoId}
|
||||
repoDirectory={repoDirectory}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user