mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
fix(sessions): scope the session picker to the OpenCode project across worktrees
This commit is contained in:
1 parent
04cb3f8291
commit
e40eca2838
7 files changed
+288
-59
No files matched your search
@@ -31,6 +31,8 @@ export type ShellInfo = Awaited<ReturnType<OpenCodeApi['shell']['list']>>['data'
|
||||
|
||||
export type ShellOutputChunk = Awaited<ReturnType<OpenCodeApi['shell']['output']>>['data']
|
||||
|
||||
export type OpenCodeLocationInfo = Awaited<ReturnType<OpenCodeApi['location']['get']>>
|
||||
|
||||
export interface SessionPage {
|
||||
items: SessionInfo[]
|
||||
nextCursor?: string
|
||||
@@ -38,6 +40,8 @@ export interface SessionPage {
|
||||
|
||||
export interface SessionPageInput {
|
||||
directory?: string
|
||||
project?: string
|
||||
subpath?: string
|
||||
limit?: number
|
||||
order?: 'asc' | 'desc'
|
||||
search?: string
|
||||
@@ -94,6 +98,8 @@ export async function listSessionPage(input: SessionPageInput): Promise<SessionP
|
||||
const { data, cursor } = await callOpenCode((api) =>
|
||||
api.session.list({
|
||||
...(input.directory === undefined ? {} : { directory: input.directory }),
|
||||
...(input.project === undefined ? {} : { project: input.project }),
|
||||
...(input.subpath === undefined ? {} : { subpath: input.subpath }),
|
||||
parentID: 'null',
|
||||
limit: input.limit,
|
||||
order: input.order,
|
||||
@@ -104,6 +110,10 @@ export async function listSessionPage(input: SessionPageInput): Promise<SessionP
|
||||
return { items: data, nextCursor: cursor.next ?? undefined }
|
||||
}
|
||||
|
||||
export async function getOpenCodeLocation(directory: string): Promise<OpenCodeLocationInfo> {
|
||||
return callOpenCode((api) => api.location.get(openCodeLocation(directory)))
|
||||
}
|
||||
|
||||
export async function getSession(sessionID: string): Promise<SessionInfo> {
|
||||
return callOpenCode((api) => api.session.get({ sessionID }))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useState } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
@@ -10,30 +11,41 @@ const mocks = vi.hoisted(() => ({
|
||||
sessionsData: [] as Session[],
|
||||
lastDirectories: [] as string[],
|
||||
lastAllDirectories: false,
|
||||
lastProject: undefined as { id: string; subpath: string } | undefined,
|
||||
locationData: undefined as
|
||||
| { directory: string; project: { id: string; directory: string; canonical: string } }
|
||||
| undefined,
|
||||
sessionsHook: vi.fn(),
|
||||
fetchNextPage: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
togglePinMock: vi.fn(),
|
||||
siblings: [] as Array<Repo & { worktreeSource?: 'opencode' | 'schedule' | 'git' }>,
|
||||
getOpenCodeLocation: vi.fn(),
|
||||
sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
|
||||
repos: [] as Repo[],
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return { ...actual, getOpenCodeLocation: mocks.getOpenCodeLocation }
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (
|
||||
directories: string[],
|
||||
options?: { search?: string; allDirectories?: boolean },
|
||||
options?: { search?: string; allDirectories?: boolean; project?: { id: string; subpath: string } },
|
||||
) => {
|
||||
mocks.sessionsHook()
|
||||
mocks.lastDirectories = directories
|
||||
mocks.lastAllDirectories = options?.allDirectories ?? false
|
||||
mocks.lastProject = options?.project
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const base = directories.length === 0 ? [] : mocks.sessionsData
|
||||
const data = search
|
||||
? mocks.sessionsData.filter((session) => (session.title ?? '').toLowerCase().includes(search))
|
||||
: mocks.sessionsData
|
||||
? base.filter((session) => (session.title ?? '').toLowerCase().includes(search))
|
||||
: base
|
||||
return {
|
||||
data,
|
||||
isLoading: false,
|
||||
@@ -48,10 +60,6 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useRepoSiblings', () => ({
|
||||
useRepoSiblings: () => ({ data: mocks.siblings }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSessionPins', () => ({
|
||||
useSessionPins: () => ({ data: mocks.sessionPins }),
|
||||
useToggleSessionPin: () => ({ mutate: mocks.togglePinMock }),
|
||||
@@ -90,15 +98,20 @@ function repo(id: number, name: string, fullPath: string): Repo {
|
||||
}
|
||||
}
|
||||
|
||||
function worktreeSibling(id: number, name: string, fullPath: string): Repo & { worktreeSource: 'opencode' } {
|
||||
return { ...repo(id, name, fullPath), isWorktree: true, worktreeSource: 'opencode' }
|
||||
function renderWithClient(ui: React.ReactElement) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const directory = mocks.repos[0]?.fullPath
|
||||
if (mocks.locationData && directory) {
|
||||
queryClient.setQueryData(['opencode', 'location', directory], mocks.locationData)
|
||||
}
|
||||
return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)
|
||||
}
|
||||
|
||||
function renderPicker(overrides: Partial<React.ComponentProps<typeof SessionPickerDialog>> = {}) {
|
||||
const onOpenChange = vi.fn()
|
||||
const onSelectSession = vi.fn()
|
||||
const onDeleteActiveSession = vi.fn()
|
||||
render(
|
||||
renderWithClient(
|
||||
<SessionPickerDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
@@ -119,7 +132,12 @@ describe('SessionPickerDialog', () => {
|
||||
stubMatchMedia(true)
|
||||
localStorage.clear()
|
||||
mocks.deleteSessionMock.mockResolvedValue(undefined)
|
||||
mocks.siblings = []
|
||||
mocks.locationData = {
|
||||
directory: '/w/a',
|
||||
project: { id: 'global', directory: '/w/a', canonical: '/w/a' },
|
||||
}
|
||||
mocks.getOpenCodeLocation.mockResolvedValue(mocks.locationData)
|
||||
mocks.lastProject = undefined
|
||||
mocks.sessionPins = []
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.sessionsData = []
|
||||
@@ -222,24 +240,86 @@ describe('SessionPickerDialog', () => {
|
||||
expect(localStorage.getItem('oc:session-picker:all-projects')).toBe('false')
|
||||
})
|
||||
|
||||
it('includes the repo worktrees and labels worktree sessions with the folder name', () => {
|
||||
it('lists project sessions across worktrees and labels them with the folder name', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a')]
|
||||
mocks.siblings = [
|
||||
repo(1, 'alpha', '/w/a'),
|
||||
worktreeSibling(2, 'alpha', '/w/worktrees/alpha-feature'),
|
||||
]
|
||||
mocks.locationData = {
|
||||
directory: '/w/a',
|
||||
project: { id: 'proj_x', directory: '/w/a', canonical: '/w/a' },
|
||||
}
|
||||
mocks.sessionsData = [
|
||||
session('ses_root', 'Root session', '/w/a', 2000),
|
||||
session('ses_wt', 'Worktree session', '/w/worktrees/alpha-feature', 1000),
|
||||
session('ses_root', 'Root session', '/w/a', 3000),
|
||||
session('ses_wt', 'Worktree session', '/w/.opencode/state/opencode/worktree/proj_x/test', 2000),
|
||||
session('ses_schedule', 'Schedule session', '/w/schedule-worktrees/job-11-run-361', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
|
||||
expect(mocks.lastDirectories).toEqual(['/w/a', '/w/worktrees/alpha-feature'])
|
||||
expect(screen.getByText('Worktree session')).toBeInTheDocument()
|
||||
expect(await screen.findByText('Worktree session')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedule session')).toBeInTheDocument()
|
||||
expect(screen.getByText('Root session')).toBeInTheDocument()
|
||||
expect(screen.getByText('alpha-feature')).toBeInTheDocument()
|
||||
expect(screen.getByRole('option', { name: /Root session/ }).textContent).not.toContain('alpha-feature')
|
||||
const rootRow = screen.getByRole('option', { name: /Root session/ })
|
||||
const worktreeRow = screen.getByRole('option', { name: /Worktree session/ })
|
||||
const scheduleRow = screen.getByRole('option', { name: /Schedule session/ })
|
||||
expect(worktreeRow.textContent).toContain('test')
|
||||
expect(scheduleRow.textContent).toContain('job-11-run-361')
|
||||
expect(rootRow.textContent).not.toContain('test')
|
||||
expect(rootRow.textContent).not.toContain('job-11-run-361')
|
||||
expect(mocks.lastProject).toEqual({ id: 'proj_x', subpath: '' })
|
||||
})
|
||||
|
||||
it('falls back to the repo directory listing when the location project is global', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.sessionsData = [
|
||||
session('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
session('ses_b', 'Beta session', '/w/b', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
|
||||
expect(await screen.findByText('Alpha session')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Beta session')).not.toBeInTheDocument()
|
||||
expect(mocks.lastDirectories).toEqual(['/w/a'])
|
||||
expect(mocks.lastProject).toBeUndefined()
|
||||
})
|
||||
|
||||
it('falls back to the repo directory listing when the location lookup fails', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.locationData = undefined
|
||||
mocks.getOpenCodeLocation.mockRejectedValue(new Error('location unavailable'))
|
||||
mocks.sessionsData = [
|
||||
session('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
session('ses_b', 'Beta session', '/w/b', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
|
||||
expect(await screen.findByText('Alpha session')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Beta session')).not.toBeInTheDocument()
|
||||
expect(mocks.lastProject).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not issue a directory listing while the location is pending', async () => {
|
||||
let resolveLocation:
|
||||
| ((value: { directory: string; project: { id: string; directory: string; canonical: string } }) => void)
|
||||
| undefined
|
||||
mocks.locationData = undefined
|
||||
mocks.getOpenCodeLocation.mockReturnValue(new Promise((resolve) => { resolveLocation = resolve }))
|
||||
mocks.sessionsData = [session('ses_a', 'Alpha session', '/w/a', 2000)]
|
||||
|
||||
renderPicker()
|
||||
|
||||
expect(screen.getByText('Loading sessions...')).toBeInTheDocument()
|
||||
expect(mocks.lastDirectories).toEqual([])
|
||||
expect(screen.queryByText('Alpha session')).not.toBeInTheDocument()
|
||||
|
||||
await act(async () => {
|
||||
resolveLocation?.({
|
||||
directory: '/w/a',
|
||||
project: { id: 'global', directory: '/w/a', canonical: '/w/a' },
|
||||
})
|
||||
})
|
||||
|
||||
expect(await screen.findByText('Alpha session')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not query sessions while closed and queries after opening', async () => {
|
||||
@@ -261,7 +341,7 @@ describe('SessionPickerDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(<Host />)
|
||||
renderWithClient(<Host />)
|
||||
|
||||
expect(mocks.sessionsHook).not.toHaveBeenCalled()
|
||||
|
||||
@@ -379,7 +459,7 @@ describe('SessionPickerDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(<Host />)
|
||||
renderWithClient(<Host />)
|
||||
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'Other' } })
|
||||
expect(screen.queryByText('Active session')).not.toBeInTheDocument()
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { format, startOfDay } from 'date-fns'
|
||||
import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
|
||||
import { isWorktreeSibling } from '@opencode-manager/shared/utils'
|
||||
import { getOpenCodeLocation } from '@/api/opencode'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
@@ -20,7 +21,6 @@ import { useDeleteSession } from '@/hooks/useOpenCode'
|
||||
import { useSessionSearch } from '@/hooks/useSessionSearch'
|
||||
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
|
||||
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
|
||||
import { useRepoSiblings } from '@/hooks/useRepoSiblings'
|
||||
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
|
||||
@@ -93,10 +93,51 @@ function optionId(baseId: string, index: number): string {
|
||||
return `${baseId}-option-${index}`
|
||||
}
|
||||
|
||||
function worktreeDirectoryLabel(session: Session, repoPath: string | undefined): string | undefined {
|
||||
const directory = session.location.directory
|
||||
if (!repoPath || directory === repoPath) return undefined
|
||||
const segments = directory.replace(/\/+$/, '').split('/').filter(Boolean)
|
||||
function stripTrailingSlashes(value: string): string {
|
||||
return value.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
function relativeSubpath(base: string, target: string): string {
|
||||
const baseSegments = stripTrailingSlashes(base).split('/').filter(Boolean)
|
||||
const targetSegments = stripTrailingSlashes(target).split('/').filter(Boolean)
|
||||
let common = 0
|
||||
while (
|
||||
common < baseSegments.length &&
|
||||
common < targetSegments.length &&
|
||||
baseSegments[common] === targetSegments[common]
|
||||
) {
|
||||
common += 1
|
||||
}
|
||||
const upward = baseSegments.length - common
|
||||
const downward = targetSegments.slice(common)
|
||||
return [...Array.from({ length: upward }, () => '..'), ...downward].join('/')
|
||||
}
|
||||
|
||||
function sessionRootDirectory(session: Session): string {
|
||||
const directory = stripTrailingSlashes(session.location.directory)
|
||||
const subpath = session.subpath
|
||||
if (!subpath) return directory
|
||||
const depth = subpath.split('/').filter(Boolean).length
|
||||
let root = directory
|
||||
for (let index = 0; index < depth; index += 1) {
|
||||
const separator = root.lastIndexOf('/')
|
||||
if (separator <= 0) break
|
||||
root = root.slice(0, separator)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
function isPathInside(base: string, target: string): boolean {
|
||||
const normalizedBase = stripTrailingSlashes(base)
|
||||
if (target === normalizedBase) return true
|
||||
return target.startsWith(`${normalizedBase}/`)
|
||||
}
|
||||
|
||||
function sessionWorktreeLabel(session: Session, canonical: string | undefined): string | undefined {
|
||||
if (!canonical) return undefined
|
||||
const root = sessionRootDirectory(session)
|
||||
if (isPathInside(canonical, root)) return undefined
|
||||
const segments = root.split('/').filter(Boolean)
|
||||
return segments[segments.length - 1]
|
||||
}
|
||||
|
||||
@@ -266,25 +307,32 @@ function SessionPickerContent({
|
||||
return map
|
||||
}, [repos, currentRepo])
|
||||
|
||||
const { data: siblings } = useRepoSiblings(currentRepo?.id)
|
||||
const locationQuery = useQuery({
|
||||
queryKey: ['opencode', 'location', currentRepo?.fullPath],
|
||||
queryFn: () => getOpenCodeLocation(currentRepo!.fullPath),
|
||||
enabled: !allProjects && Boolean(currentRepo?.fullPath),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})
|
||||
|
||||
const worktreeDirectories = useMemo(
|
||||
() =>
|
||||
(siblings ?? [])
|
||||
.filter((sibling) => isWorktreeSibling(sibling) && !!sibling.fullPath)
|
||||
.map((sibling) => sibling.fullPath),
|
||||
[siblings],
|
||||
)
|
||||
const location = locationQuery.data
|
||||
const locationPending = !allProjects && Boolean(currentRepo?.fullPath) && locationQuery.isPending
|
||||
const projectOption = useMemo(() => {
|
||||
if (allProjects || !location || location.project.id === 'global') return undefined
|
||||
return {
|
||||
id: location.project.id,
|
||||
subpath: relativeSubpath(location.project.directory, location.directory),
|
||||
}
|
||||
}, [allProjects, location])
|
||||
|
||||
const directories = useMemo(() => {
|
||||
if (!allProjects) {
|
||||
if (!currentRepo) return []
|
||||
return Array.from(new Set([currentRepo.fullPath, ...worktreeDirectories]))
|
||||
if (allProjects) {
|
||||
const paths = repos.map((repo) => repo.fullPath)
|
||||
if (currentRepo) paths.push(currentRepo.fullPath)
|
||||
return Array.from(new Set(paths))
|
||||
}
|
||||
const paths = repos.map((repo) => repo.fullPath)
|
||||
if (currentRepo) paths.push(currentRepo.fullPath)
|
||||
return Array.from(new Set(paths))
|
||||
}, [allProjects, repos, currentRepo, worktreeDirectories])
|
||||
if (locationPending) return []
|
||||
return currentRepo ? [currentRepo.fullPath] : []
|
||||
}, [allProjects, repos, currentRepo, locationPending])
|
||||
|
||||
const {
|
||||
query,
|
||||
@@ -297,7 +345,9 @@ function SessionPickerContent({
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
canFetchNextPage,
|
||||
} = useSessionSearch(directories, { allDirectories: allProjects })
|
||||
} = useSessionSearch(directories, { allDirectories: allProjects, project: projectOption })
|
||||
|
||||
const isPickerLoading = isLoading || locationPending
|
||||
|
||||
const resolveRepo = useCallback(
|
||||
(session: Session) => repoByDirectory.get(session.location.directory) ?? currentRepo,
|
||||
@@ -552,7 +602,7 @@ function SessionPickerContent({
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">
|
||||
{isLoading
|
||||
{isPickerLoading
|
||||
? 'Loading sessions...'
|
||||
: isSearchPending
|
||||
? 'Searching sessions...'
|
||||
@@ -587,7 +637,7 @@ function SessionPickerContent({
|
||||
isPinned={pinnedKeys.has(row.key)}
|
||||
isPendingDelete={pendingDeleteKey === row.key}
|
||||
showRepo={allProjects}
|
||||
label={allProjects ? undefined : worktreeDirectoryLabel(row.session, currentRepo?.fullPath)}
|
||||
label={allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical)}
|
||||
onOpen={openRow}
|
||||
onHover={moveCursor}
|
||||
onTogglePin={handleTogglePin}
|
||||
|
||||
@@ -174,6 +174,48 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
|
||||
})
|
||||
|
||||
it('pages a project scope through one cursor query with project and subpath', async () => {
|
||||
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
|
||||
if (cursor === 'cursor_project') {
|
||||
return { items: [sessionInfo('ses_wt', '/w/worktrees/alpha-feature', 2000)] }
|
||||
}
|
||||
return { items: [sessionInfo('ses_root', '/w/a')], nextCursor: 'cursor_project' }
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(
|
||||
() => useSessionsAcrossDirectories(['/w/a'], { project: { id: 'proj_x', subpath: '' } }),
|
||||
{ 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,
|
||||
project: 'proj_x',
|
||||
subpath: '',
|
||||
})
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_root'])
|
||||
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_project' })
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_root', 'ses_wt'])
|
||||
})
|
||||
|
||||
it('deletes each session through the facade and removes it from cached lists without invalidating', async () => {
|
||||
mocks.deleteSession.mockResolvedValue(undefined)
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ interface UseSessionsAcrossDirectoriesOptions {
|
||||
limit?: number
|
||||
keepPreviousResults?: boolean
|
||||
allDirectories?: boolean
|
||||
project?: { id: string; subpath: string }
|
||||
}
|
||||
|
||||
type SessionDirectoryCursors = Record<string, string>
|
||||
@@ -68,6 +69,10 @@ export const useSessionsAcrossDirectories = (
|
||||
const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE;
|
||||
const keepPreviousResults = options?.keepPreviousResults ?? false;
|
||||
const allDirectories = options?.allDirectories ?? false;
|
||||
const projectId = options?.project?.id;
|
||||
const projectSubpath = options?.project?.subpath;
|
||||
const projectScoped = !allDirectories && projectId !== undefined;
|
||||
const singleCursor = allDirectories || projectScoped;
|
||||
const directoryKey = uniqueDirectories.join('|');
|
||||
|
||||
const query = useInfiniteQuery<
|
||||
@@ -77,13 +82,23 @@ export const useSessionsAcrossDirectories = (
|
||||
readonly unknown[],
|
||||
SessionListPageParam | undefined
|
||||
>({
|
||||
queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit, allDirectories }],
|
||||
queryKey: [
|
||||
'opencode',
|
||||
'sessions',
|
||||
directoryKey,
|
||||
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath },
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (allDirectories) {
|
||||
if (singleCursor) {
|
||||
const cursor = pageParam?.mode === 'all' ? pageParam.cursor : undefined;
|
||||
const page = await listSessionPage(
|
||||
cursor === undefined
|
||||
? { limit, order: 'desc', search: normalizedSearch }
|
||||
? {
|
||||
limit,
|
||||
order: 'desc',
|
||||
search: normalizedSearch,
|
||||
...(projectScoped ? { project: projectId, subpath: projectSubpath } : {}),
|
||||
}
|
||||
: { cursor },
|
||||
);
|
||||
return {
|
||||
@@ -136,8 +151,12 @@ export const useSessionsAcrossDirectories = (
|
||||
},
|
||||
initialPageParam: undefined as SessionListPageParam | undefined,
|
||||
placeholderData: keepPreviousResults
|
||||
? (previousData, previousQuery) =>
|
||||
previousQuery?.queryKey[2] === directoryKey ? previousData : undefined
|
||||
? (previousData, previousQuery) => {
|
||||
if (!previousQuery) return undefined
|
||||
const sameDirectory = previousQuery.queryKey[2] === directoryKey
|
||||
const previousProject = (previousQuery.queryKey[3] as { project?: string } | undefined)?.project
|
||||
return sameDirectory && previousProject === projectId ? previousData : undefined
|
||||
}
|
||||
: undefined,
|
||||
getNextPageParam: (lastPage) => lastPage.nextParam,
|
||||
enabled: uniqueDirectories.length > 0,
|
||||
|
||||
@@ -4,7 +4,7 @@ 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; allDirectories?: boolean } } | undefined },
|
||||
lastArgsRef: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean; project?: { id: string; subpath: string } } } | undefined },
|
||||
flagsRef: { current: { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: false } },
|
||||
}))
|
||||
|
||||
@@ -12,7 +12,7 @@ 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; allDirectories?: boolean }) => {
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean; allDirectories?: boolean; project?: { id: string; subpath: string } }) => {
|
||||
lastArgsRef.current = { directories, options }
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const data = search
|
||||
@@ -96,6 +96,22 @@ describe('useSessionSearch', () => {
|
||||
expect(lastArgsRef.current?.options?.allDirectories).toBe(true)
|
||||
})
|
||||
|
||||
it('forwards a project scope and skips directory filtering', () => {
|
||||
sessionsData.splice(
|
||||
0,
|
||||
sessionsData.length,
|
||||
{ id: 'ses_root', title: 'root', location: { directory: '/w/a' }, time: { updated: 2 } },
|
||||
{ id: 'ses_wt', title: 'worktree', location: { directory: '/w/other' }, time: { updated: 1 } },
|
||||
)
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSessionSearch(['/w/a'], { project: { id: 'proj_x', subpath: '' } }),
|
||||
)
|
||||
|
||||
expect(lastArgsRef.current?.options?.project).toEqual({ id: 'proj_x', subpath: '' })
|
||||
expect(result.current.filteredSessions.map((session) => session.id)).toEqual(['ses_root', 'ses_wt'])
|
||||
})
|
||||
|
||||
it('passes isError through from useSessionsAcrossDirectories', () => {
|
||||
flagsRef.current = { hasNextPage: false, isFetchingNextPage: false, isFetchNextPageError: false, isPlaceholderData: false, isError: true }
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ const DEFAULT_LIMIT = 25
|
||||
export interface UseSessionSearchOptions {
|
||||
limit?: number
|
||||
allDirectories?: boolean
|
||||
project?: { id: string; subpath: string }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -18,6 +19,7 @@ export interface UseSessionSearchOptions {
|
||||
export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
|
||||
const limit = options.limit ?? DEFAULT_LIMIT
|
||||
const allDirectories = options.allDirectories ?? false
|
||||
const project = options.project
|
||||
const [query, setQuery] = useState('')
|
||||
const trimmedQuery = query.trim()
|
||||
const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
|
||||
@@ -31,13 +33,23 @@ export function useSessionSearch(directories: string[], options: UseSessionSearc
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
} = useSessionsAcrossDirectories(directories, { search, limit, keepPreviousResults: true, allDirectories })
|
||||
} = useSessionsAcrossDirectories(directories, {
|
||||
search,
|
||||
limit,
|
||||
keepPreviousResults: true,
|
||||
allDirectories,
|
||||
project,
|
||||
})
|
||||
|
||||
const directorySet = useMemo(() => new Set(directories), [directories])
|
||||
|
||||
const rootSessions = useMemo(
|
||||
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionKey }),
|
||||
[sessions, directorySet],
|
||||
() =>
|
||||
selectRootSessions(sessions ?? [], {
|
||||
directories: project ? undefined : directorySet,
|
||||
keyFn: getSessionKey,
|
||||
}),
|
||||
[sessions, directorySet, project],
|
||||
)
|
||||
|
||||
const filteredSessions = useMemo(() => {
|
||||
|
||||
Reference in new issue
Block a user