Skip to content

Commit 405cbd5

Browse files
authored
fix(session): load more pages when filtered list underfills viewport (chriswritescode-dev#351)
Load additional session pages when child filtering leaves the viewport underfilled. Preserve directory and workspace identity, stop automatic pagination after next-page errors, and provide explicit retry with regression coverage. Fixes chriswritescode-dev#350
1 parent dd1b102 commit 405cbd5

3 files changed

Lines changed: 289 additions & 26 deletions

File tree

‎frontend/src/components/session/SessionList.test.tsx‎

Lines changed: 248 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,51 @@
11
import { beforeEach, describe, expect, it, vi } from 'vitest'
22
import { render, screen, waitFor, within, fireEvent } from '@testing-library/react'
33
import userEvent from '@testing-library/user-event'
4+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5+
import type { ReactNode } from 'react'
46
import { SessionList } from './SessionList'
57

6-
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
8+
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
79
createSessionMock: vi.fn(),
810
deleteSessionMock: vi.fn(),
911
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; parentID?: string; time: { updated: number } }>,
1012
createSessionState: { directory: undefined as string | undefined },
1113
fetchNextPageMock: vi.fn(),
1214
hasNextPageRef: { current: false },
1315
isFetchingNextPageRef: { current: false },
16+
isFetchNextPageErrorRef: { current: false },
17+
useRealSessionsHookRef: { current: false },
1418
lastSessionsHookArgs: { current: undefined as { opcodeUrl: string; directories: string[]; options?: { search?: string; limit?: number } } | undefined },
1519
sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
1620
togglePinMock: vi.fn(),
1721
}))
1822

19-
vi.mock('@/hooks/useOpenCode', () => ({
20-
useSessionsAcrossDirectories: (opcodeUrl: string, directories: string[], options?: { search?: string; limit?: number }) => {
21-
lastSessionsHookArgs.current = { opcodeUrl, directories, options }
22-
// Simulate server-side search: return empty data when a search query is active
23-
const data = options?.search ? [] : sessionsData
24-
return {
25-
data,
26-
isLoading: false,
27-
fetchNextPage: fetchNextPageMock,
28-
hasNextPage: hasNextPageRef.current,
29-
isFetchingNextPage: isFetchingNextPageRef.current,
30-
}
31-
},
32-
useCreateSession: (_opcodeUrl: string, directory?: string) => {
33-
createSessionState.directory = directory
34-
return { mutate: createSessionMock }
35-
},
36-
useDeleteSession: () => ({ mutateAsync: deleteSessionMock, isPending: false }),
37-
}))
23+
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
24+
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
25+
return {
26+
...actual,
27+
useSessionsAcrossDirectories: (opcodeUrl: string, directories: string[], options?: { search?: string; limit?: number }) => {
28+
if (useRealSessionsHookRef.current) {
29+
return actual.useSessionsAcrossDirectories(opcodeUrl, directories, options)
30+
}
31+
lastSessionsHookArgs.current = { opcodeUrl, directories, options }
32+
const data = options?.search ? [] : sessionsData
33+
return {
34+
data,
35+
isLoading: false,
36+
fetchNextPage: fetchNextPageMock,
37+
hasNextPage: hasNextPageRef.current,
38+
isFetchingNextPage: isFetchingNextPageRef.current,
39+
isFetchNextPageError: isFetchNextPageErrorRef.current,
40+
}
41+
},
42+
useCreateSession: (_opcodeUrl: string, directory?: string) => {
43+
createSessionState.directory = directory
44+
return { mutate: createSessionMock }
45+
},
46+
useDeleteSession: () => ({ mutateAsync: deleteSessionMock, isPending: false }),
47+
}
48+
})
3849

3950
vi.mock('@/hooks/useSessionPins', () => ({
4051
useSessionPins: () => ({ data: sessionPinsData }),
@@ -55,6 +66,8 @@ describe('SessionList', () => {
5566
fetchNextPageMock.mockReset()
5667
hasNextPageRef.current = false
5768
isFetchingNextPageRef.current = false
69+
isFetchNextPageErrorRef.current = false
70+
useRealSessionsHookRef.current = false
5871
lastSessionsHookArgs.current = undefined
5972
sessionPinsData.splice(0, sessionPinsData.length)
6073
togglePinMock.mockReset()
@@ -277,6 +290,52 @@ describe('SessionList', () => {
277290
})
278291
})
279292

293+
it('auto-fetches next page when filtered sessions underfill the scroll viewport', async () => {
294+
sessionsData.splice(0, sessionsData.length,
295+
{ id: 'root1', title: 'root session 1', directory: '/w/a', time: { updated: 4 } },
296+
{ id: 'root2', title: 'root session 2', directory: '/w/a', time: { updated: 3 } },
297+
{ id: 'root3', title: 'root session 3', directory: '/w/a', time: { updated: 2 } },
298+
{ id: 'root4', title: 'root session 4', directory: '/w/a', time: { updated: 1 } },
299+
...Array.from({ length: 21 }, (_, index) => ({
300+
id: `child${index}`,
301+
title: `child session ${index}`,
302+
directory: '/w/a',
303+
parentID: `root${index}`,
304+
time: { updated: index },
305+
})),
306+
)
307+
hasNextPageRef.current = true
308+
const scrollHeightDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight')
309+
const clientHeightDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight')
310+
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', { configurable: true, value: 300 })
311+
Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, value: 500 })
312+
313+
try {
314+
render(
315+
<SessionList
316+
opcodeUrl="/api/opencode"
317+
directories={['/w/a']}
318+
onSelectSession={vi.fn()}
319+
/>,
320+
)
321+
322+
await waitFor(() => {
323+
expect(fetchNextPageMock).toHaveBeenCalled()
324+
})
325+
} finally {
326+
if (scrollHeightDescriptor) {
327+
Object.defineProperty(HTMLElement.prototype, 'scrollHeight', scrollHeightDescriptor)
328+
} else {
329+
Reflect.deleteProperty(HTMLElement.prototype, 'scrollHeight')
330+
}
331+
if (clientHeightDescriptor) {
332+
Object.defineProperty(HTMLElement.prototype, 'clientHeight', clientHeightDescriptor)
333+
} else {
334+
Reflect.deleteProperty(HTMLElement.prototype, 'clientHeight')
335+
}
336+
}
337+
})
338+
280339
it('renders pinned session under a Pinned heading and excludes it from Today', () => {
281340
const pinnedTime = Date.now()
282341
sessionPinsData.push({ sessionId: 'ses_a', directory: '/w/a', pinnedAt: pinnedTime })
@@ -320,4 +379,173 @@ describe('SessionList', () => {
320379

321380
expect(togglePinMock).toHaveBeenCalledWith({ sessionId: 'ses_x', directory: '/w/a', pinned: true })
322381
})
382+
383+
it('shows a retry action and stops automatic pagination while a next-page error is active', async () => {
384+
hasNextPageRef.current = true
385+
isFetchNextPageErrorRef.current = true
386+
387+
render(
388+
<SessionList
389+
opcodeUrl="/api/opencode"
390+
directories={['/w/a']}
391+
onSelectSession={vi.fn()}
392+
/>,
393+
)
394+
395+
expect(screen.getByText('Failed to load more sessions.')).toBeTruthy()
396+
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
397+
398+
const scrollContainer = screen.getByRole('region', { name: 'Sessions' })
399+
Object.defineProperty(scrollContainer, 'scrollHeight', { value: 1000, configurable: true })
400+
Object.defineProperty(scrollContainer, 'clientHeight', { value: 500, configurable: true })
401+
Object.defineProperty(scrollContainer, 'scrollTop', { value: 300, configurable: true })
402+
fireEvent.scroll(scrollContainer)
403+
404+
await waitFor(() => {
405+
expect(fetchNextPageMock).not.toHaveBeenCalled()
406+
})
407+
})
408+
409+
it('retries the next page when the retry action is clicked after an error', async () => {
410+
hasNextPageRef.current = true
411+
isFetchNextPageErrorRef.current = true
412+
const user = userEvent.setup()
413+
414+
render(
415+
<SessionList
416+
opcodeUrl="/api/opencode"
417+
directories={['/w/a']}
418+
onSelectSession={vi.fn()}
419+
/>,
420+
)
421+
422+
await user.click(screen.getByRole('button', { name: 'Retry' }))
423+
424+
expect(fetchNextPageMock).toHaveBeenCalledTimes(1)
425+
})
426+
427+
it('shows the retry action instead of the loading state when the first page is empty and the next page failed', () => {
428+
sessionsData.splice(0, sessionsData.length)
429+
hasNextPageRef.current = true
430+
isFetchNextPageErrorRef.current = true
431+
432+
render(
433+
<SessionList
434+
opcodeUrl="/api/opencode"
435+
directories={['/w/a']}
436+
onSelectSession={vi.fn()}
437+
/>,
438+
)
439+
440+
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()
441+
expect(screen.queryByText('Loading sessions...')).toBeNull()
442+
})
443+
444+
it('stops automatic pagination after a persistent next-page error and appends older roots on explicit retry with real React Query', async () => {
445+
const fetchMock = vi.fn()
446+
vi.stubGlobal('fetch', fetchMock)
447+
448+
const pageOneItems = [
449+
...Array.from({ length: 4 }, (_, index) => ({
450+
id: `root${index}`,
451+
projectID: 'proj_1',
452+
title: `root session ${index}`,
453+
time: { created: 100 + index, updated: 100 + index },
454+
})),
455+
...Array.from({ length: 21 }, (_, index) => ({
456+
id: `child${index}`,
457+
projectID: 'proj_1',
458+
parentID: `root${index}`,
459+
title: `child session ${index}`,
460+
time: { created: index, updated: index },
461+
})),
462+
]
463+
464+
let cursorAttempts = 0
465+
let recovered = false
466+
let resolveRecovery: ((response: Response) => void) | undefined
467+
fetchMock.mockImplementation((input: RequestInfo | URL) => {
468+
const url = String(input)
469+
if (url.includes('cursor=cursor_next')) {
470+
cursorAttempts += 1
471+
if (!recovered) {
472+
return Promise.resolve(new Response(JSON.stringify({ error: 'persistent failure' }), {
473+
status: 500,
474+
headers: { 'Content-Type': 'application/json' },
475+
}))
476+
}
477+
return new Promise<Response>((resolve) => {
478+
resolveRecovery = resolve
479+
})
480+
}
481+
return Promise.resolve(new Response(JSON.stringify({
482+
items: pageOneItems,
483+
cursor: { next: 'cursor_next' },
484+
}), { status: 200, headers: { 'Content-Type': 'application/json' } }))
485+
})
486+
487+
useRealSessionsHookRef.current = true
488+
const queryClient = new QueryClient({
489+
defaultOptions: { queries: { retry: 1, retryDelay: 0 }, mutations: { retry: false } },
490+
})
491+
const wrapper = ({ children }: { children: ReactNode }) => (
492+
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
493+
)
494+
495+
let unmount: (() => void) | undefined
496+
try {
497+
const rendered = render(
498+
<SessionList
499+
opcodeUrl="/api/opencode"
500+
directories={['/w/a']}
501+
onSelectSession={vi.fn()}
502+
/>,
503+
{ wrapper },
504+
)
505+
unmount = rendered.unmount
506+
507+
await waitFor(() => {
508+
expect(screen.getByText('root session 0')).toBeTruthy()
509+
})
510+
511+
await waitFor(() => {
512+
expect(screen.getByText('Failed to load more sessions.')).toBeTruthy()
513+
})
514+
expect(cursorAttempts).toBe(2)
515+
516+
const scrollContainer = screen.getByRole('region', { name: 'Sessions' })
517+
fireEvent.scroll(scrollContainer)
518+
fireEvent.scroll(scrollContainer)
519+
520+
await new Promise((resolve) => setTimeout(resolve, 20))
521+
expect(cursorAttempts).toBe(2)
522+
523+
recovered = true
524+
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
525+
526+
await waitFor(() => {
527+
expect(resolveRecovery).toBeDefined()
528+
})
529+
expect(screen.getByRole('button', { name: 'Retry' })).toBeDisabled()
530+
expect(screen.getByText('Loading more sessions...')).toBeTruthy()
531+
expect(screen.getByText('root session 0')).toBeTruthy()
532+
expect(screen.queryByText('child session 0')).toBeNull()
533+
534+
resolveRecovery?.(new Response(JSON.stringify({
535+
items: [{ id: 'older_root', projectID: 'proj_1', title: 'older root session', time: { created: 1, updated: 1 } }],
536+
}), { status: 200, headers: { 'Content-Type': 'application/json' } }))
537+
538+
await waitFor(() => {
539+
expect(screen.getByText('older root session')).toBeTruthy()
540+
})
541+
expect(cursorAttempts).toBe(3)
542+
expect(screen.getByText('root session 0')).toBeTruthy()
543+
expect(screen.queryByText('child session 0')).toBeNull()
544+
expect(screen.queryByText('Failed to load more sessions.')).toBeNull()
545+
} finally {
546+
unmount?.()
547+
queryClient.clear()
548+
vi.unstubAllGlobals()
549+
}
550+
})
323551
})

0 commit comments

Comments
 (0)