mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
fix(sessions): address PR #403 review findings
- fetch picker sessions only while the dialog is open - list all-projects sessions with one request per page - block infinite-scroll paging while a search is pending - memoize picker rows with stable callbacks - remove deleted sessions from list caches instead of refetching - keep the repo tab when the open session is deleted - reuse useSessionSearch in the sidebar session tree - drop dead activeSessionID/isActive and share delete, session-key and repo-map helpers - move usePersistentBoolean to its own hook
This commit is contained in:
1 parent
85288d6393
commit
2d14972fad
24 files changed
+814
-412
No files matched your search
@@ -134,12 +134,58 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('deletes each session through the facade and invalidates the session list cache', async () => {
|
||||
it('issues one call per page across all directories and paginates by cursor', async () => {
|
||||
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
|
||||
if (cursor === 'cursor_all') {
|
||||
return { items: [sessionInfo('ses_all2', '/w/b', 2000)] }
|
||||
}
|
||||
return { items: [sessionInfo('ses_all1', '/w/a')], nextCursor: 'cursor_all' }
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(
|
||||
() => useSessionsAcrossDirectories(['/w/a', '/w/b'], { allDirectories: true }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
})
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1'])
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.fetchNextPage()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data).toHaveLength(2)
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
|
||||
expect(mocks.listSessionPage).toHaveBeenLastCalledWith({ cursor: 'cursor_all' })
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
|
||||
})
|
||||
|
||||
it('deletes each session through the facade and removes it from cached lists without invalidating', async () => {
|
||||
mocks.deleteSession.mockResolvedValue(undefined)
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25 }]
|
||||
queryClient.setQueryData(listKey, { pages: [{ items: [], cursors: {} }], pageParams: [undefined] })
|
||||
const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25, allDirectories: false }]
|
||||
queryClient.setQueryData(listKey, {
|
||||
pages: [{
|
||||
items: [sessionInfo('ses_a1', '/w/a'), sessionInfo('ses_a2', '/w/a')],
|
||||
nextParam: undefined,
|
||||
}],
|
||||
pageParams: [undefined],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useDeleteSession(['/w/a']), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
@@ -150,6 +196,31 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
})
|
||||
|
||||
expect(mocks.deleteSession).toHaveBeenCalledWith('ses_a1')
|
||||
const cached = queryClient.getQueryData<{ pages: Array<{ items: SessionInfo[] }> }>(listKey)
|
||||
expect(cached?.pages[0].items.map((session) => session.id)).toEqual(['ses_a2'])
|
||||
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(false)
|
||||
})
|
||||
|
||||
it('invalidates the session list cache when a delete fails', async () => {
|
||||
mocks.deleteSession.mockRejectedValue(new Error('nope'))
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const listKey = ['opencode', 'sessions', '/w/a', { search: undefined, limit: 25, allDirectories: false }]
|
||||
queryClient.setQueryData(listKey, {
|
||||
pages: [{ items: [sessionInfo('ses_a1', '/w/a')], nextParam: undefined }],
|
||||
pageParams: [undefined],
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useDeleteSession(['/w/a']), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await expect(
|
||||
result.current.mutateAsync({ id: 'ses_a1', directory: '/w/a' }),
|
||||
).rejects.toThrow('Failed to delete 1 session(s)')
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true)
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation, useQueryClient, useInfiniteQuery, type InfiniteData } from "@tanstack/react-query";
|
||||
import { useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import {
|
||||
createSession,
|
||||
@@ -42,9 +42,19 @@ interface UseSessionsAcrossDirectoriesOptions {
|
||||
search?: string
|
||||
limit?: number
|
||||
keepPreviousResults?: boolean
|
||||
allDirectories?: boolean
|
||||
}
|
||||
|
||||
type SessionPageParam = Record<string, string>
|
||||
type SessionDirectoryCursors = Record<string, string>
|
||||
|
||||
type SessionListPageParam =
|
||||
| { mode: 'directories'; cursors: SessionDirectoryCursors }
|
||||
| { mode: 'all'; cursor: string }
|
||||
|
||||
interface SessionListPage {
|
||||
items: SessionInfo[]
|
||||
nextParam?: SessionListPageParam
|
||||
}
|
||||
|
||||
export const useSessionsAcrossDirectories = (
|
||||
directories: string[],
|
||||
@@ -57,12 +67,32 @@ export const useSessionsAcrossDirectories = (
|
||||
const normalizedSearch = options?.search?.trim() || undefined;
|
||||
const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE;
|
||||
const keepPreviousResults = options?.keepPreviousResults ?? false;
|
||||
const allDirectories = options?.allDirectories ?? false;
|
||||
const directoryKey = uniqueDirectories.join('|');
|
||||
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit }],
|
||||
const query = useInfiniteQuery<
|
||||
SessionListPage,
|
||||
Error,
|
||||
InfiniteData<SessionListPage, SessionListPageParam | undefined>,
|
||||
readonly unknown[],
|
||||
SessionListPageParam | undefined
|
||||
>({
|
||||
queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit, allDirectories }],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (!pageParam) {
|
||||
if (allDirectories) {
|
||||
const cursor = pageParam?.mode === 'all' ? pageParam.cursor : undefined;
|
||||
const page = await listSessionPage(
|
||||
cursor === undefined
|
||||
? { limit, order: 'desc', search: normalizedSearch }
|
||||
: { cursor },
|
||||
);
|
||||
return {
|
||||
items: page.items,
|
||||
nextParam: page.nextCursor ? { mode: 'all', cursor: page.nextCursor } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (!pageParam || pageParam.mode !== 'directories') {
|
||||
const pages = await Promise.all(
|
||||
uniqueDirectories.map((directory) =>
|
||||
listSessionPage({
|
||||
@@ -73,7 +103,7 @@ export const useSessionsAcrossDirectories = (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const cursors: SessionPageParam = {};
|
||||
const cursors: SessionDirectoryCursors = {};
|
||||
const items: SessionInfo[] = [];
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
items.push(...pages[i].items);
|
||||
@@ -81,14 +111,17 @@ export const useSessionsAcrossDirectories = (
|
||||
cursors[uniqueDirectories[i]] = pages[i].nextCursor!;
|
||||
}
|
||||
}
|
||||
return { items, cursors };
|
||||
return {
|
||||
items,
|
||||
nextParam: Object.keys(cursors).length > 0 ? { mode: 'directories', cursors } : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const entries = Object.entries(pageParam);
|
||||
const entries = Object.entries(pageParam.cursors);
|
||||
const pages = await Promise.all(
|
||||
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
|
||||
);
|
||||
const cursors: SessionPageParam = {};
|
||||
const cursors: SessionDirectoryCursors = {};
|
||||
const items: SessionInfo[] = [];
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
items.push(...pages[i].items);
|
||||
@@ -96,19 +129,17 @@ export const useSessionsAcrossDirectories = (
|
||||
cursors[entries[i][0]] = pages[i].nextCursor!;
|
||||
}
|
||||
}
|
||||
return { items, cursors };
|
||||
return {
|
||||
items,
|
||||
nextParam: Object.keys(cursors).length > 0 ? { mode: 'directories', cursors } : undefined,
|
||||
};
|
||||
},
|
||||
initialPageParam: undefined as SessionPageParam | undefined,
|
||||
initialPageParam: undefined as SessionListPageParam | undefined,
|
||||
placeholderData: keepPreviousResults
|
||||
? (previousData, previousQuery) =>
|
||||
previousQuery?.queryKey[2] === directoryKey ? previousData : undefined
|
||||
: undefined,
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (Object.keys(lastPage.cursors).length > 0) {
|
||||
return lastPage.cursors;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
getNextPageParam: (lastPage) => lastPage.nextParam,
|
||||
enabled: uniqueDirectories.length > 0,
|
||||
staleTime: 10000,
|
||||
refetchOnWindowFocus: true,
|
||||
@@ -252,19 +283,43 @@ export const useDeleteSession = (directory?: string | string[]) => {
|
||||
|
||||
return { deleted: targets.length, results }
|
||||
},
|
||||
onSuccess: ({ deleted }) => {
|
||||
onSuccess: ({ deleted }, variables) => {
|
||||
removeDeletedSessionsFromListCaches(queryClient, variables);
|
||||
cleanupSessionPins(queryClient, variables, primaryDirectory);
|
||||
showToast.success(deleted === 1 ? 'Session deleted' : `${deleted} sessions deleted`);
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to delete sessions');
|
||||
},
|
||||
onSettled: (_data, _error, variables) => {
|
||||
onError: (_error, variables) => {
|
||||
invalidateSessionListCaches(queryClient);
|
||||
cleanupSessionPins(queryClient, variables, primaryDirectory);
|
||||
showToast.error('Failed to delete sessions');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const removeDeletedSessionsFromListCaches = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
) => {
|
||||
const deletedIDs = new Set(
|
||||
(Array.isArray(variables) ? variables : [variables]).map(getDeleteSessionTargetId),
|
||||
);
|
||||
if (deletedIDs.size === 0) return;
|
||||
queryClient.setQueriesData<InfiniteData<SessionListPage, SessionListPageParam | undefined>>(
|
||||
{ queryKey: ['opencode', 'sessions'] },
|
||||
(current) => {
|
||||
if (!current) return current;
|
||||
let changed = false;
|
||||
const pages = current.pages.map((page) => {
|
||||
const items = page.items.filter((item) => !deletedIDs.has(item.id));
|
||||
if (items.length === page.items.length) return page;
|
||||
changed = true;
|
||||
return { ...page, items };
|
||||
});
|
||||
return changed ? { ...current, pages } : current;
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const cleanupSessionPins = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
variables: DeleteSessionTarget | DeleteSessionTarget[],
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { usePersistentBoolean } from './usePersistentBoolean'
|
||||
|
||||
const STORAGE_KEY = 'oc:test:flag'
|
||||
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}
|
||||
|
||||
describe('usePersistentBoolean', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
writable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: window.localStorage,
|
||||
writable: true,
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('returns the fallback when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(localStorageMock.getItem).toHaveBeenCalledWith(STORAGE_KEY)
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns a stored true value', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('toggles the value and persists it to localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith(STORAGE_KEY, 'true')
|
||||
})
|
||||
|
||||
it('returns the fallback when the stored value is malformed JSON', () => {
|
||||
localStorageMock.getItem.mockReturnValue('not-json{{')
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns the fallback when the stored value is JSON but not a boolean', () => {
|
||||
localStorageMock.getItem.mockReturnValue('"some string"')
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, false))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('honours a true fallback when no value is stored', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => usePersistentBoolean(STORAGE_KEY, true))
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
|
||||
function readStorage(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorage(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function readStoredBoolean(key: string, fallback: boolean): boolean {
|
||||
const stored = readStorage(key)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored)
|
||||
return typeof parsed === 'boolean' ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists a boolean preference under `key` in localStorage and returns it with a toggler.
|
||||
* Falls back to `fallback` when the stored value is missing or malformed.
|
||||
*/
|
||||
export function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
|
||||
const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setValue((prev: boolean) => {
|
||||
const newValue = !prev
|
||||
writeStorage(key, newValue)
|
||||
return newValue
|
||||
})
|
||||
}, [key])
|
||||
|
||||
return [value, toggle]
|
||||
}
|
||||
@@ -4,15 +4,15 @@ import { useSessionSearch } from './useSessionSearch'
|
||||
|
||||
const { sessionsData, lastArgsRef, flagsRef } = vi.hoisted(() => ({
|
||||
sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
|
||||
lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined },
|
||||
flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false } },
|
||||
lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean } } | undefined },
|
||||
flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false } },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => {
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean }) => {
|
||||
lastArgsRef.current = { directories, options }
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const data = search
|
||||
@@ -21,6 +21,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
return {
|
||||
data,
|
||||
isLoading: false,
|
||||
isError: flagsRef.current.isError,
|
||||
isPlaceholderData: flagsRef.current.isPlaceholderData,
|
||||
fetchNextPage: vi.fn(),
|
||||
hasNextPage: flagsRef.current.hasNextPage,
|
||||
@@ -38,7 +39,7 @@ describe('useSessionSearch', () => {
|
||||
{ id: 'ses_beta', title: 'beta task', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
)
|
||||
lastArgsRef.current = undefined
|
||||
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false }
|
||||
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -89,23 +90,59 @@ describe('useSessionSearch', () => {
|
||||
expect(result.current.isSearchPending).toBe(false)
|
||||
})
|
||||
|
||||
it('passes allDirectories through to useSessionsAcrossDirectories', () => {
|
||||
renderHook(() => useSessionSearch(['/w/a'], { allDirectories: true }))
|
||||
|
||||
expect(lastArgsRef.current?.options?.allDirectories).toBe(true)
|
||||
})
|
||||
|
||||
it('passes isError through from useSessionsAcrossDirectories', () => {
|
||||
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: true }
|
||||
|
||||
const { result } = renderHook(() => useSessionSearch(['/w/a']))
|
||||
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
it('blocks pagination while a search is pending', () => {
|
||||
vi.useFakeTimers()
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
const { result } = renderHook(() => useSessionSearch(['/w/a']))
|
||||
|
||||
expect(result.current.canFetchNextPage).toBe(true)
|
||||
|
||||
act(() => {
|
||||
result.current.setQuery('deploy')
|
||||
})
|
||||
|
||||
expect(result.current.isSearchPending).toBe(true)
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(150)
|
||||
})
|
||||
|
||||
expect(result.current.isSearchPending).toBe(false)
|
||||
expect(result.current.canFetchNextPage).toBe(true)
|
||||
})
|
||||
|
||||
it('exposes canFetchNextPage only when paging is safe', () => {
|
||||
const { result, rerender } = renderHook(() => useSessionSearch(['/w/a']))
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(true)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: true, isFetchNextPageError: false, isPlaceholderData: false, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: true, isPlaceholderData: false, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true }
|
||||
flagsRef.current = { hasNextPage: true, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: true, isError: false }
|
||||
rerender()
|
||||
expect(result.current.canFetchNextPage).toBe(false)
|
||||
})
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
||||
import { selectRootSessions } from '@/components/session/session-partition'
|
||||
import { buildSessionKey } from '@/lib/sessionKey'
|
||||
import type { Session } from '@/api/types'
|
||||
import { getSessionKey } from '@/lib/sessionKey'
|
||||
|
||||
const DEFAULT_LIMIT = 25
|
||||
|
||||
export interface UseSessionSearchOptions {
|
||||
limit?: number
|
||||
allDirectories?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,6 +17,7 @@ export interface UseSessionSearchOptions {
|
||||
*/
|
||||
export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
|
||||
const limit = options.limit ?? DEFAULT_LIMIT
|
||||
const allDirectories = options.allDirectories ?? false
|
||||
const [query, setQuery] = useState('')
|
||||
const trimmedQuery = query.trim()
|
||||
const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
|
||||
@@ -24,22 +25,19 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
const {
|
||||
data: sessions,
|
||||
isLoading,
|
||||
isError,
|
||||
isPlaceholderData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
} = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true })
|
||||
} = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true, allDirectories })
|
||||
|
||||
const directorySet = useMemo(() => new Set(directories), [directories])
|
||||
const getSessionSelectionKey = useCallback(
|
||||
(session: Session) => buildSessionKey(session.location.directory, session.id),
|
||||
[],
|
||||
)
|
||||
|
||||
const rootSessions = useMemo(
|
||||
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
|
||||
[sessions, directorySet, getSessionSelectionKey],
|
||||
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionKey }),
|
||||
[sessions, directorySet],
|
||||
)
|
||||
|
||||
const filteredSessions = useMemo(() => {
|
||||
@@ -50,7 +48,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
|
||||
const isSearchPending = trimmedQuery !== search || isPlaceholderData
|
||||
const canFetchNextPage = Boolean(
|
||||
hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData,
|
||||
hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isSearchPending,
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -61,6 +59,7 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
filteredSessions,
|
||||
isSearchPending,
|
||||
isLoading,
|
||||
isError,
|
||||
isPlaceholderData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
|
||||
@@ -9,7 +9,7 @@ const localStorageMock = {
|
||||
clear: vi.fn(),
|
||||
}
|
||||
|
||||
describe('sidebar collapse hooks', () => {
|
||||
describe('useSidebarCollapsed', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
@@ -26,52 +26,27 @@ describe('sidebar collapse hooks', () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('useSidebarCollapsed', () => {
|
||||
it('returns false by default when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
it('reads and persists under the sidebar storage key with a false default', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:collapsed')
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
it('returns stored value from localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
it('returns the stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
it('toggles collapsed state and persists to localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
|
||||
})
|
||||
|
||||
it('returns false when stored value is malformed JSON', () => {
|
||||
localStorageMock.getItem.mockReturnValue('not-json{{')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when stored value is JSON but not a boolean', () => {
|
||||
localStorageMock.getItem.mockReturnValue('"some string"')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,54 +1,7 @@
|
||||
import { useState, useCallback } from 'react'
|
||||
import { usePersistentBoolean } from './usePersistentBoolean'
|
||||
|
||||
const STORAGE_KEY = 'oc:sidebar:collapsed'
|
||||
|
||||
function readStorage(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorage(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function readStoredBoolean(key: string, fallback: boolean): boolean {
|
||||
const stored = readStorage(key)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored)
|
||||
return typeof parsed === 'boolean' ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists a boolean preference under `key` in localStorage and returns it with a toggler.
|
||||
* Falls back to `fallback` when the stored value is missing or malformed.
|
||||
*/
|
||||
export function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
|
||||
const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setValue((prev: boolean) => {
|
||||
const newValue = !prev
|
||||
writeStorage(key, newValue)
|
||||
return newValue
|
||||
})
|
||||
}, [key])
|
||||
|
||||
return [value, toggle]
|
||||
}
|
||||
|
||||
export function useSidebarCollapsed(): [boolean, () => void] {
|
||||
return usePersistentBoolean(STORAGE_KEY, false)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useQueries, useQuery } from '@tanstack/react-query'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useSessionPins } from '@/hooks/useSessionPins'
|
||||
import { buildPinnedSessionKeys, buildSessionKey } from '@/lib/sessionKey'
|
||||
import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import {
|
||||
SIDEBAR_SESSIONS_PER_REPO,
|
||||
@@ -46,9 +46,7 @@ export function useSidebarRepoGroups(input: {
|
||||
const missingPins = useMemo(() => {
|
||||
if (search) return []
|
||||
const repoDirectories = new Set(directories)
|
||||
const fetchedKeys = new Set(
|
||||
sessions.map((session) => buildSessionKey(session.location.directory, session.id)),
|
||||
)
|
||||
const fetchedKeys = new Set(sessions.map(getSessionKey))
|
||||
return (sessionPins ?? []).filter(
|
||||
(pin) =>
|
||||
repoDirectories.has(pin.directory) &&
|
||||
|
||||
Reference in new issue
Block a user