mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Merge pull request #436 from chriswritescode-dev/feat/activity-switcher
feat(activity): surface active work across the session picker, tool rail and mobile
This commit is contained in:
60 files changed
+3992
-491
No files matched your search
@@ -0,0 +1,200 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { MS_PER_MINUTE } from '@/lib/activeWork'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useActiveWork } from './useActiveWork'
|
||||
|
||||
const REPO_PATH = '/repo'
|
||||
const WINDOW_MS = 60 * MS_PER_MINUTE
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listSessionPage: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
useNavigableRepos: vi.fn(),
|
||||
pendingSessionIDs: [] as string[],
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return {
|
||||
...actual,
|
||||
listSessionPage: mocks.listSessionPage,
|
||||
getSession: mocks.getSession,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useSidebarRepoGroups', () => ({
|
||||
useNavigableRepos: mocks.useNavigableRepos,
|
||||
}))
|
||||
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePermissions: () => ({ pendingSessionIDs: mocks.pendingSessionIDs }),
|
||||
useForms: () => ({ pendingSessionIDs: mocks.pendingSessionIDs }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
loading: vi.fn(),
|
||||
promise: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const session = (id: string, updated: number, parentID?: string | null): SessionInfo => ({
|
||||
id,
|
||||
projectID: 'proj_1',
|
||||
title: `Session ${id}`,
|
||||
time: { created: updated, updated },
|
||||
location: { directory: REPO_PATH },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
...(parentID === undefined ? {} : { parentID }),
|
||||
})
|
||||
|
||||
const repo: Repo = {
|
||||
id: 1,
|
||||
fullPath: REPO_PATH,
|
||||
localPath: REPO_PATH,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
}
|
||||
|
||||
const createQueryClient = () =>
|
||||
new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
|
||||
const createWrapper = (queryClient: QueryClient) =>
|
||||
({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
const recentIDs = (groups: { recent: Array<{ session: SessionInfo }> }): string[] =>
|
||||
groups.recent.map((item) => item.session.id)
|
||||
|
||||
describe('useActiveWork', () => {
|
||||
beforeEach(() => {
|
||||
mocks.listSessionPage.mockReset()
|
||||
mocks.getSession.mockReset()
|
||||
mocks.useNavigableRepos.mockReset()
|
||||
mocks.useNavigableRepos.mockReturnValue({ repos: [repo], isLoading: false, refetch: vi.fn() })
|
||||
useSessionStatus.setState({
|
||||
statuses: new Map(),
|
||||
statusCache: new Map(),
|
||||
statusRevisions: new Map(),
|
||||
knownSessions: new Set(),
|
||||
outcomes: new Map(),
|
||||
parents: new Map(),
|
||||
directories: new Map(),
|
||||
runningShells: new Map(),
|
||||
shellRevisions: new Map(),
|
||||
shellRevision: 0,
|
||||
revision: 0,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('requests the next page while the oldest loaded session is inside the window', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
|
||||
if (cursor === 'page2') {
|
||||
return { items: [session('root2', now - 1500)] }
|
||||
}
|
||||
return {
|
||||
items: [session('a', now - 500), session('b', now - 1000)],
|
||||
nextCursor: 'page2',
|
||||
}
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root2'))
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({ cursor: 'page2', includeChildren: true })
|
||||
})
|
||||
|
||||
it('does not request another page when the oldest loaded session is outside the window', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listSessionPage.mockResolvedValue({
|
||||
items: [session('recent', now - 500), session('old', now - 2 * WINDOW_MS)],
|
||||
nextCursor: 'page2',
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('recent'))
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('resolves an unlisted grandchild to its ancestor root', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listSessionPage.mockResolvedValue({ items: [session('G', now - 500, 'C')] })
|
||||
mocks.getSession.mockImplementation(async (id: string) => {
|
||||
if (id === 'C') return session('C', now - 1000, 'R')
|
||||
if (id === 'R') return session('R', now - 1500, null)
|
||||
throw new Error(`unexpected session ${id}`)
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('R'))
|
||||
|
||||
expect(recentIDs(result.current.groups)).not.toContain('C')
|
||||
})
|
||||
|
||||
it('keeps groups referentially stable across a rerender', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listSessionPage.mockResolvedValue({ items: [session('root', now - 500)] })
|
||||
|
||||
const { result, rerender } = renderHook(() => useActiveWork(WINDOW_MS), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root'))
|
||||
|
||||
const before = result.current.groups
|
||||
rerender()
|
||||
|
||||
expect(result.current.groups).toBe(before)
|
||||
})
|
||||
|
||||
it('drops a recent root once the clock advances past the window', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const now = Date.now()
|
||||
mocks.listSessionPage.mockResolvedValue({ items: [session('root', now - 1000)] })
|
||||
|
||||
const { result } = renderHook(() => useActiveWork(MS_PER_MINUTE), {
|
||||
wrapper: createWrapper(createQueryClient()),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('root'))
|
||||
|
||||
await act(async () => {
|
||||
vi.setSystemTime(now + 5 * MS_PER_MINUTE)
|
||||
vi.advanceTimersByTime(MS_PER_MINUTE)
|
||||
})
|
||||
|
||||
expect(recentIDs(result.current.groups)).not.toContain('root')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,278 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useQueries, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
|
||||
import { useForms, usePermissions } from '@/contexts/EventContext'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
|
||||
import {
|
||||
MS_PER_MINUTE,
|
||||
buildActiveWork,
|
||||
buildRepoActivityIndex,
|
||||
collectActiveRoots,
|
||||
repoActivityFromIndex,
|
||||
rootSessionID,
|
||||
type ActiveWorkGroups,
|
||||
} from '@/lib/activeWork'
|
||||
import {
|
||||
combineQuerySessions,
|
||||
mergeExtraSessions,
|
||||
} from '@/components/navigation/sidebar-session-tree'
|
||||
import type { Repo } from '@/api/types'
|
||||
|
||||
const ACTIVE_WORK_SESSION_LIMIT = 50
|
||||
|
||||
/**
|
||||
* The active-work time window in minutes, derived from the user's configured
|
||||
* `activityWindowMinutes` with the shared default as a fallback.
|
||||
*/
|
||||
export function useActivityWindowMinutes(): number {
|
||||
const { preferences } = useSettings()
|
||||
return preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
|
||||
}
|
||||
|
||||
/** Pending permission and form session ids, merged once per snapshot into a referentially stable list. */
|
||||
function usePendingInputSessionIDs(): string[] {
|
||||
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
|
||||
const pendingFormSessionIDs = useForms().pendingSessionIDs
|
||||
|
||||
return useMemo(
|
||||
() => [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
|
||||
[pendingPermissionSessionIDs, pendingFormSessionIDs],
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Distinct active roots for a badge: needs-input roots and running roots that are not also
|
||||
* pending input. Reads only the session-status store and the pending queues, with no network.
|
||||
*/
|
||||
export function useActiveWorkCounts(): { needsInput: number; running: number } {
|
||||
const statuses = useSessionStatus((state) => state.statuses)
|
||||
const parents = useSessionStatus((state) => state.parents)
|
||||
const runningShells = useSessionStatus((state) => state.runningShells)
|
||||
const pendingInputSessionIDs = usePendingInputSessionIDs()
|
||||
|
||||
return useMemo(() => {
|
||||
const roots = collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs })
|
||||
|
||||
let running = 0
|
||||
for (const rootID of roots.running) {
|
||||
if (!roots.needsInput.has(rootID)) running += 1
|
||||
}
|
||||
|
||||
return { needsInput: roots.needsInput.size, running }
|
||||
}, [statuses, parents, runningShells, pendingInputSessionIDs])
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a repo has any active session, returned as a primitive so rows only re-render when it
|
||||
* changes. Reads only the session-status store and the pending queues, with no network.
|
||||
*/
|
||||
export function useRepoActivityState(repo: Repo): 'needs-input' | 'running' | null {
|
||||
const pendingInputSessionIDs = usePendingInputSessionIDs()
|
||||
|
||||
return useSessionStatus((state) =>
|
||||
repoActivityFromIndex(
|
||||
repo,
|
||||
buildRepoActivityIndex({
|
||||
statuses: state.statuses,
|
||||
parents: state.parents,
|
||||
runningShells: state.runningShells,
|
||||
directories: state.directories,
|
||||
pendingInputSessionIDs,
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks a session's ancestor chain through the shared session cache, returning each link as
|
||||
* `[sessionID, parentID]` from the session down to its root. Stops at a root, a missing session,
|
||||
* or a cycle. Reusing `sessionQueryOptions` keeps these reads on the shared session cache.
|
||||
*/
|
||||
async function fetchAncestorLinks(
|
||||
queryClient: QueryClient,
|
||||
sessionID: string,
|
||||
directories: ReadonlyMap<string, string>,
|
||||
): Promise<Array<[string, string | null]>> {
|
||||
const links: Array<[string, string | null]> = []
|
||||
const visited = new Set<string>()
|
||||
let currentID: string | null | undefined = sessionID
|
||||
|
||||
while (currentID && !visited.has(currentID)) {
|
||||
visited.add(currentID)
|
||||
const session: SessionInfo = await queryClient.fetchQuery(
|
||||
sessionQueryOptions(currentID, directories.get(currentID)),
|
||||
)
|
||||
const parentID: string | null = session.parentID ?? null
|
||||
links.push([session.id, parentID])
|
||||
currentID = parentID
|
||||
}
|
||||
|
||||
return links
|
||||
}
|
||||
|
||||
/** Flattens the resolved ancestor links from each query result, dropping unresolved queries. */
|
||||
const combineAncestorLinks = (
|
||||
results: Array<{ data?: Array<[string, string | null]> }>,
|
||||
): Array<[string, string | null]> => results.flatMap((result) => result.data ?? [])
|
||||
|
||||
/**
|
||||
* The full active-work list. Performs network reads, so it must only be used by components that
|
||||
* are mounted while visible (the session picker fetches only while open).
|
||||
*/
|
||||
export function useActiveWork(windowMs: number): {
|
||||
groups: ActiveWorkGroups
|
||||
isLoading: boolean
|
||||
isError: boolean
|
||||
} {
|
||||
const queryClient = useQueryClient()
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
const { repos, isLoading: isReposLoading } = useNavigableRepos()
|
||||
const repoDirectories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
|
||||
|
||||
const {
|
||||
data: sessions,
|
||||
isLoading: isSessionsLoading,
|
||||
isError: isSessionsError,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
} = useSessionsAcrossDirectories(repoDirectories, {
|
||||
allDirectories: true,
|
||||
limit: ACTIVE_WORK_SESSION_LIMIT,
|
||||
includeChildren: true,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => setNow(Date.now()), MS_PER_MINUTE)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
const oldestLoadedUpdatedAt = sessions.at(-1)?.time.updated
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasNextPage || isFetchingNextPage || isFetchNextPageError) return
|
||||
if (oldestLoadedUpdatedAt === undefined || oldestLoadedUpdatedAt < now - windowMs) return
|
||||
void fetchNextPage()
|
||||
}, [
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
oldestLoadedUpdatedAt,
|
||||
now,
|
||||
windowMs,
|
||||
fetchNextPage,
|
||||
])
|
||||
|
||||
const statuses = useSessionStatus((state) => state.statuses)
|
||||
const storeParents = useSessionStatus((state) => state.parents)
|
||||
const runningShells = useSessionStatus((state) => state.runningShells)
|
||||
const outcomes = useSessionStatus((state) => state.outcomes)
|
||||
const sessionDirectories = useSessionStatus((state) => state.directories)
|
||||
const pendingInputSessionIDs = usePendingInputSessionIDs()
|
||||
|
||||
const parents = useMemo(() => {
|
||||
const merged = new Map<string, string | null>()
|
||||
for (const session of sessions) {
|
||||
merged.set(session.id, session.parentID ?? null)
|
||||
}
|
||||
for (const [sessionID, parentID] of storeParents) {
|
||||
if (!merged.has(sessionID)) merged.set(sessionID, parentID)
|
||||
}
|
||||
return merged
|
||||
}, [sessions, storeParents])
|
||||
|
||||
const roots = useMemo(
|
||||
() => collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs }),
|
||||
[statuses, parents, runningShells, pendingInputSessionIDs],
|
||||
)
|
||||
|
||||
const listedSessionIDs = useMemo(
|
||||
() => new Set(sessions.map((session) => session.id)),
|
||||
[sessions],
|
||||
)
|
||||
|
||||
const missingRootIDs = useMemo(() => {
|
||||
const ids = new Set<string>()
|
||||
const windowStart = now - windowMs
|
||||
for (const session of sessions) {
|
||||
if (session.time.updated < windowStart) continue
|
||||
const rootID = rootSessionID(session.id, parents)
|
||||
if (!listedSessionIDs.has(rootID)) ids.add(rootID)
|
||||
}
|
||||
for (const sessionID of roots.needsInput) {
|
||||
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
|
||||
}
|
||||
for (const sessionID of roots.running) {
|
||||
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
|
||||
}
|
||||
return [...ids]
|
||||
}, [sessions, parents, listedSessionIDs, roots, windowMs, now])
|
||||
|
||||
const ancestorLinks = useQueries({
|
||||
queries: missingRootIDs.map((sessionID) => ({
|
||||
queryKey: ['opencode', 'session-ancestry', sessionID] as const,
|
||||
queryFn: () => fetchAncestorLinks(queryClient, sessionID, sessionDirectories),
|
||||
staleTime: Infinity,
|
||||
})),
|
||||
combine: combineAncestorLinks,
|
||||
})
|
||||
|
||||
const resolvedParents = useMemo(() => {
|
||||
const merged = new Map(parents)
|
||||
for (const [sessionID, parentID] of ancestorLinks) {
|
||||
merged.set(sessionID, parentID)
|
||||
}
|
||||
return merged
|
||||
}, [parents, ancestorLinks])
|
||||
|
||||
const resolvedRoots = useMemo(
|
||||
() => collectActiveRoots({ statuses, parents: resolvedParents, runningShells, pendingInputSessionIDs }),
|
||||
[statuses, resolvedParents, runningShells, pendingInputSessionIDs],
|
||||
)
|
||||
|
||||
const backfillRootIDs = useMemo(() => {
|
||||
const ids = new Set<string>()
|
||||
for (const sessionID of missingRootIDs) {
|
||||
const rootID = rootSessionID(sessionID, resolvedParents)
|
||||
if (!listedSessionIDs.has(rootID)) ids.add(rootID)
|
||||
}
|
||||
return [...ids]
|
||||
}, [missingRootIDs, resolvedParents, listedSessionIDs])
|
||||
|
||||
const fetchedSessions = useQueries({
|
||||
queries: backfillRootIDs.map((sessionID) =>
|
||||
sessionQueryOptions(sessionID, sessionDirectories.get(sessionID)),
|
||||
),
|
||||
combine: combineQuerySessions,
|
||||
})
|
||||
|
||||
const mergedSessions = useMemo(
|
||||
() => mergeExtraSessions(sessions, fetchedSessions),
|
||||
[sessions, fetchedSessions],
|
||||
)
|
||||
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
buildActiveWork({
|
||||
now,
|
||||
windowMs,
|
||||
repos,
|
||||
sessions: mergedSessions,
|
||||
parents: resolvedParents,
|
||||
roots: resolvedRoots,
|
||||
outcomes,
|
||||
}),
|
||||
[now, windowMs, repos, mergedSessions, resolvedParents, resolvedRoots, outcomes],
|
||||
)
|
||||
|
||||
return {
|
||||
groups,
|
||||
isLoading: isReposLoading || isSessionsLoading,
|
||||
isError: isSessionsError,
|
||||
}
|
||||
}
|
||||
@@ -174,6 +174,61 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
|
||||
})
|
||||
|
||||
it('requests child sessions and records includeChildren in the query key', async () => {
|
||||
mocks.listSessionPage.mockResolvedValue({ items: [sessionInfo('ses_child', '/w/a')] })
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result } = renderHook(
|
||||
() => useSessionsAcrossDirectories(['/w/a'], { includeChildren: true }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
})
|
||||
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledWith({
|
||||
directory: '/w/a',
|
||||
limit: 25,
|
||||
order: 'desc',
|
||||
search: undefined,
|
||||
includeChildren: true,
|
||||
})
|
||||
expect(queryClient.getQueryCache().getAll()[0]?.queryKey).toEqual([
|
||||
'opencode',
|
||||
'sessions',
|
||||
'/w/a',
|
||||
{
|
||||
search: undefined,
|
||||
limit: 25,
|
||||
allDirectories: false,
|
||||
project: undefined,
|
||||
subpath: undefined,
|
||||
includeChildren: true,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps root-only and include-children lists in distinct cache entries', async () => {
|
||||
mocks.listSessionPage.mockResolvedValue({ items: [] })
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const wrapper = createWrapper(queryClient)
|
||||
renderHook(() => useSessionsAcrossDirectories(['/w/a']), { wrapper })
|
||||
renderHook(() => useSessionsAcrossDirectories(['/w/a'], { includeChildren: true }), { wrapper })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
const optionObjects = queryClient
|
||||
.getQueryCache()
|
||||
.getAll()
|
||||
.map((query) => query.queryKey[3] as { includeChildren?: boolean })
|
||||
expect(optionObjects.some((options) => options.includeChildren === true)).toBe(true)
|
||||
expect(optionObjects.some((options) => options.includeChildren === false)).toBe(true)
|
||||
})
|
||||
|
||||
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') {
|
||||
|
||||
@@ -44,6 +44,7 @@ interface UseSessionsAcrossDirectoriesOptions {
|
||||
keepPreviousResults?: boolean
|
||||
allDirectories?: boolean
|
||||
project?: { id: string; subpath: string }
|
||||
includeChildren?: boolean
|
||||
}
|
||||
|
||||
type SessionDirectoryCursors = Record<string, string>
|
||||
@@ -73,7 +74,9 @@ export const useSessionsAcrossDirectories = (
|
||||
const projectSubpath = options?.project?.subpath;
|
||||
const projectScoped = !allDirectories && projectId !== undefined;
|
||||
const singleCursor = allDirectories || projectScoped;
|
||||
const includeChildren = options?.includeChildren ?? false;
|
||||
const directoryKey = uniqueDirectories.join('|');
|
||||
const childSessionsParam = includeChildren ? { includeChildren: true } : {};
|
||||
|
||||
const query = useInfiniteQuery<
|
||||
SessionListPage,
|
||||
@@ -86,7 +89,7 @@ export const useSessionsAcrossDirectories = (
|
||||
'opencode',
|
||||
'sessions',
|
||||
directoryKey,
|
||||
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath },
|
||||
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath, includeChildren },
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (singleCursor) {
|
||||
@@ -98,8 +101,9 @@ export const useSessionsAcrossDirectories = (
|
||||
order: 'desc',
|
||||
search: normalizedSearch,
|
||||
...(projectScoped ? { project: projectId, subpath: projectSubpath } : {}),
|
||||
...childSessionsParam,
|
||||
}
|
||||
: { cursor },
|
||||
: { cursor, ...childSessionsParam },
|
||||
);
|
||||
return {
|
||||
items: page.items,
|
||||
@@ -115,6 +119,7 @@ export const useSessionsAcrossDirectories = (
|
||||
limit,
|
||||
order: 'desc',
|
||||
search: normalizedSearch,
|
||||
...childSessionsParam,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -134,7 +139,9 @@ export const useSessionsAcrossDirectories = (
|
||||
|
||||
const entries = Object.entries(pageParam.cursors);
|
||||
const pages = await Promise.all(
|
||||
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
|
||||
entries.map(([directory, cursor]) =>
|
||||
listSessionPage({ directory, cursor, ...childSessionsParam }),
|
||||
),
|
||||
);
|
||||
const cursors: SessionDirectoryCursors = {};
|
||||
const items: SessionInfo[] = [];
|
||||
|
||||
@@ -67,14 +67,14 @@ describe('useSSE', () => {
|
||||
MockEventSource.instances = []
|
||||
shellApi.listShells.mockResolvedValue([])
|
||||
shellApi.removeShell.mockResolvedValue(undefined)
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), directories: new Map(), revision: 0 })
|
||||
useSendErrorStore.setState({ errors: {} })
|
||||
globalThis.EventSource = MockEventSource as unknown as typeof EventSource
|
||||
globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true } as Response))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), revision: 0 })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), knownSessions: new Set(), outcomes: new Map(), directories: new Map(), revision: 0 })
|
||||
useSendErrorStore.setState({ errors: {} })
|
||||
globalThis.EventSource = originalEventSource
|
||||
globalThis.fetch = originalFetch
|
||||
|
||||
@@ -4,29 +4,16 @@ import { listRepos } from '@/api/repos'
|
||||
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useSessionPins } from '@/hooks/useSessionPins'
|
||||
import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import type { Repo } from '@/api/types'
|
||||
import {
|
||||
SIDEBAR_SESSIONS_PER_REPO,
|
||||
buildSidebarRepoGroups,
|
||||
combineQuerySessions,
|
||||
mergeExtraSessions,
|
||||
selectNavigableRepos,
|
||||
type SidebarRepoGroup,
|
||||
} from '@/components/navigation/sidebar-session-tree'
|
||||
|
||||
const combinePinnedSessions = (results: Array<{ data?: Session }>): Session[] =>
|
||||
results.flatMap((result) => (result.data ? [result.data] : []))
|
||||
|
||||
const mergeSessions = (sessions: Session[], pinnedSessions: Session[]): Session[] => {
|
||||
if (pinnedSessions.length === 0) return sessions
|
||||
const seen = new Set(sessions.map((session) => session.id))
|
||||
const extras: Session[] = []
|
||||
for (const session of pinnedSessions) {
|
||||
if (seen.has(session.id)) continue
|
||||
seen.add(session.id)
|
||||
extras.push(session)
|
||||
}
|
||||
return extras.length === 0 ? sessions : [...sessions, ...extras]
|
||||
}
|
||||
|
||||
export function useSidebarRepoGroups(input: {
|
||||
repos: Repo[]
|
||||
search?: string
|
||||
@@ -56,11 +43,11 @@ export function useSidebarRepoGroups(input: {
|
||||
|
||||
const pinnedSessions = useQueries({
|
||||
queries: missingPins.map((pin) => sessionQueryOptions(pin.sessionId, pin.directory)),
|
||||
combine: combinePinnedSessions,
|
||||
combine: combineQuerySessions,
|
||||
})
|
||||
|
||||
const mergedSessions = useMemo(
|
||||
() => mergeSessions(sessions, pinnedSessions),
|
||||
() => mergeExtraSessions(sessions, pinnedSessions),
|
||||
[sessions, pinnedSessions],
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { toggleToolDialogParams, toggleToolPanelParams } from './useToolPanel'
|
||||
import { createElement } from 'react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { isPanelTool, toggleToolDialogParams, toggleToolPanelParams, useToolPanel } from './useToolPanel'
|
||||
|
||||
describe('activity tool', () => {
|
||||
it('is a panel tool', () => {
|
||||
expect(isPanelTool('activity')).toBe(true)
|
||||
})
|
||||
|
||||
it('clears without opening a dialog when the panel is not docked', async () => {
|
||||
function Probe() {
|
||||
useToolPanel(false)
|
||||
const location = useLocation()
|
||||
return createElement('div', { 'data-testid': 'search' }, location.search)
|
||||
}
|
||||
|
||||
render(
|
||||
createElement(
|
||||
MemoryRouter,
|
||||
{ initialEntries: ['/repos/1/sessions/abc?panel=activity'] },
|
||||
createElement(Probe),
|
||||
),
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('search').textContent).not.toContain('panel=activity'))
|
||||
expect(screen.getByTestId('search').textContent).not.toContain('dialog=activity')
|
||||
})
|
||||
})
|
||||
|
||||
describe('toggleToolPanelParams', () => {
|
||||
it('opens a tool, clears other tools owned params, and preserves unrelated params', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useUrlParams } from './useUrlParams'
|
||||
|
||||
const PANEL_PARAM = 'panel'
|
||||
|
||||
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules'] as const
|
||||
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules', 'activity'] as const
|
||||
|
||||
export type PanelTool = (typeof PANEL_TOOLS)[number]
|
||||
|
||||
@@ -14,7 +14,7 @@ const TOOL_OWNED_PARAMS: Partial<Record<PanelTool, readonly string[]>> = {
|
||||
schedules: ['scheduleTab', 'scheduleDialog', 'jobId', 'runId'],
|
||||
}
|
||||
|
||||
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules'])
|
||||
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules', 'activity'])
|
||||
|
||||
export function isPanelTool(value: string | null): value is PanelTool {
|
||||
return value !== null && (PANEL_TOOLS as readonly string[]).includes(value)
|
||||
|
||||
Reference in new issue
Block a user