mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(activity): page active work to the window, resolve backfilled ancestors, and tick the window clock
This commit is contained in:
1 parent
84cdffa261
commit
cd4b8a7e07
2 files changed
+301
-9
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')
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useQueries } from '@tanstack/react-query'
|
||||
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'
|
||||
@@ -7,6 +8,7 @@ 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,
|
||||
@@ -85,6 +87,38 @@ export function useRepoActivityState(repo: Repo): 'needs-input' | 'running' | nu
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
@@ -94,6 +128,8 @@ export function useActiveWork(windowMs: number): {
|
||||
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])
|
||||
|
||||
@@ -101,12 +137,37 @@ export function useActiveWork(windowMs: number): {
|
||||
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)
|
||||
@@ -137,7 +198,7 @@ export function useActiveWork(windowMs: number): {
|
||||
|
||||
const missingRootIDs = useMemo(() => {
|
||||
const ids = new Set<string>()
|
||||
const windowStart = Date.now() - windowMs
|
||||
const windowStart = now - windowMs
|
||||
for (const session of sessions) {
|
||||
if (session.time.updated < windowStart) continue
|
||||
const rootID = rootSessionID(session.id, parents)
|
||||
@@ -150,10 +211,41 @@ export function useActiveWork(windowMs: number): {
|
||||
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
|
||||
}
|
||||
return [...ids]
|
||||
}, [sessions, parents, listedSessionIDs, roots, windowMs])
|
||||
}, [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: missingRootIDs.map((sessionID) =>
|
||||
queries: backfillRootIDs.map((sessionID) =>
|
||||
sessionQueryOptions(sessionID, sessionDirectories.get(sessionID)),
|
||||
),
|
||||
combine: combineQuerySessions,
|
||||
@@ -167,15 +259,15 @@ export function useActiveWork(windowMs: number): {
|
||||
const groups = useMemo(
|
||||
() =>
|
||||
buildActiveWork({
|
||||
now: Date.now(),
|
||||
now,
|
||||
windowMs,
|
||||
repos,
|
||||
sessions: mergedSessions,
|
||||
parents,
|
||||
roots,
|
||||
parents: resolvedParents,
|
||||
roots: resolvedRoots,
|
||||
outcomes,
|
||||
}),
|
||||
[windowMs, repos, mergedSessions, parents, roots, outcomes],
|
||||
[now, windowMs, repos, mergedSessions, resolvedParents, resolvedRoots, outcomes],
|
||||
)
|
||||
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user