mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(sidebar): add repo-grouped session navigation with live status (#361)
* feat(sidebar): add repo-grouped session navigation with live status - Add a searchable, collapsible session tree to the desktop sidebar, grouped by repository with pinned and time-bucketed ordering. - Track per-session busy, retry, and compact status in a shared store fed by the SSE event stream and scoped by directory. - Extract shared navigation components reused by the desktop tree and the mobile repo quick-switch sheet. - Show a Git tab and hide Schedules inside a repo on the mobile tab bar; add Repos and Assistant entries to the session More drawer. - Replace the CommitsTab local relative-time formatter with a shared formatShortRelativeTime util. * refactor(sidebar): unify session status tracking and navigation helpers * feat(sidebar): add collapsible sessions and menu sections * fix(sessions): keep specific live status over snapshot busy
This commit is contained in:
1 parent
1389e8e59c
commit
015a44a5f3
45 files changed
+3347
-763
No files matched your search
@@ -1,6 +1,16 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useUrlParams } from './useUrlParams'
|
||||
|
||||
export function openDialogParam(
|
||||
updateParams: ReturnType<typeof useUrlParams>['updateParams'],
|
||||
name: string,
|
||||
): void {
|
||||
updateParams((p) => {
|
||||
p.set('dialog', name)
|
||||
p.delete('mobileTab')
|
||||
}, 'push')
|
||||
}
|
||||
|
||||
export function useDialogParam(name: string): [boolean, (open: boolean) => void] {
|
||||
const { searchParams, updateParams } = useUrlParams()
|
||||
|
||||
@@ -8,14 +18,15 @@ export function useDialogParam(name: string): [boolean, (open: boolean) => void]
|
||||
|
||||
const setOpen = useCallback(
|
||||
(open: boolean) => {
|
||||
if (open) {
|
||||
openDialogParam(updateParams, name)
|
||||
return
|
||||
}
|
||||
updateParams((p) => {
|
||||
if (open) {
|
||||
p.set('dialog', name)
|
||||
p.delete('mobileTab')
|
||||
} else if (p.get('dialog') === name) {
|
||||
if (p.get('dialog') === name) {
|
||||
p.delete('dialog')
|
||||
}
|
||||
}, open ? 'push' : 'replace')
|
||||
}, 'replace')
|
||||
},
|
||||
[updateParams, name],
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ import { showToast } from "../lib/toast";
|
||||
import { useSendErrorStore } from "../stores/sendErrorStore";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
import { invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation";
|
||||
import { buildSessionKey } from "../lib/sessionKey";
|
||||
import { buildPinnedSessionKeys, buildSessionKey } from "../lib/sessionKey";
|
||||
import { toggleSessionPin } from "../api/sessionPins";
|
||||
import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
|
||||
import { admitInboxItem, type TranscriptCache } from "../lib/session-projection";
|
||||
@@ -39,6 +39,8 @@ const isSameModelRef = (left: ModelRef, right: ModelRef | undefined) =>
|
||||
|
||||
const SESSION_LIST_PAGE_SIZE = 25
|
||||
|
||||
const EMPTY_SESSIONS: SessionInfo[] = []
|
||||
|
||||
interface UseSessionsAcrossDirectoriesOptions {
|
||||
search?: string
|
||||
limit?: number
|
||||
@@ -110,8 +112,13 @@ export const useSessionsAcrossDirectories = (
|
||||
refetchOnReconnect: true,
|
||||
});
|
||||
|
||||
const data = useMemo(
|
||||
() => query.data?.pages.flatMap((page) => page.items) ?? EMPTY_SESSIONS,
|
||||
[query.data],
|
||||
);
|
||||
|
||||
return {
|
||||
data: query.data?.pages.flatMap((page) => page.items) ?? [],
|
||||
data,
|
||||
isLoading: query.isLoading,
|
||||
isError: query.isError,
|
||||
fetchNextPage: query.fetchNextPage,
|
||||
@@ -122,16 +129,22 @@ export const useSessionsAcrossDirectories = (
|
||||
};
|
||||
};
|
||||
|
||||
const sessionQueryKey = (sessionID: string | undefined, directory?: string) =>
|
||||
["opencode", "session", sessionID, directory] as const;
|
||||
|
||||
export const sessionQueryOptions = (sessionID: string | undefined, directory?: string) => ({
|
||||
queryKey: sessionQueryKey(sessionID, directory),
|
||||
queryFn: () => getSession(sessionID!),
|
||||
enabled: !!sessionID,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
staleTime: 15000,
|
||||
retry: (failureCount: number, error: unknown) =>
|
||||
!(error instanceof FetchError && error.statusCode === 404) && failureCount < 3,
|
||||
});
|
||||
|
||||
export const useSession = (sessionID: string | undefined, directory?: string) => {
|
||||
return useQuery({
|
||||
queryKey: ["opencode", "session", sessionID, directory],
|
||||
queryFn: () => getSession(sessionID!),
|
||||
enabled: !!sessionID,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchOnReconnect: true,
|
||||
staleTime: 15000,
|
||||
retry: (failureCount, error) => !(error instanceof FetchError && error.statusCode === 404) && failureCount < 3,
|
||||
});
|
||||
return useQuery(sessionQueryOptions(sessionID, directory));
|
||||
};
|
||||
|
||||
export const useCreateSession = (
|
||||
@@ -232,7 +245,7 @@ const cleanupSessionPins = (
|
||||
) => {
|
||||
const pins = queryClient.getQueryData<SessionPin[]>(SESSION_PINS_QUERY_KEY) ?? [];
|
||||
if (pins.length === 0) return;
|
||||
const pinnedKeys = new Set(pins.map((p) => buildSessionKey(p.directory, p.sessionId)));
|
||||
const pinnedKeys = buildPinnedSessionKeys(pins);
|
||||
const targets = (Array.isArray(variables) ? variables : [variables])
|
||||
.map((target) => ({
|
||||
sessionId: getDeleteSessionTargetId(target),
|
||||
@@ -256,15 +269,12 @@ export const useUpdateSession = (directory?: string) => {
|
||||
},
|
||||
onSuccess: (_, variables) => {
|
||||
const { sessionID } = variables;
|
||||
queryClient.invalidateQueries({ queryKey: ["opencode", "session", sessionID, directory] });
|
||||
queryClient.invalidateQueries({ queryKey: sessionQueryKey(sessionID, directory) });
|
||||
invalidateSessionListCaches(queryClient);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const sessionQueryKey = (sessionID: string, directory?: string) =>
|
||||
["opencode", "session", sessionID, directory] as const;
|
||||
|
||||
const patchCachedSessionSelection = (
|
||||
queryClient: ReturnType<typeof useQueryClient>,
|
||||
sessionID: string,
|
||||
@@ -459,7 +469,7 @@ export const useSendShell = (directory?: string) => {
|
||||
const { sessionID } = variables;
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["opencode", "session", sessionID, directory],
|
||||
queryKey: sessionQueryKey(sessionID, directory),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,16 +4,9 @@ import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useSSE } from './useSSE'
|
||||
import { useSessionStatus } from '../stores/sessionStatusStore'
|
||||
import { useSendErrorStore } from '../stores/sendErrorStore'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
active: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
listActiveSessions: mocks.active,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
dismiss: vi.fn(),
|
||||
@@ -60,14 +53,15 @@ describe('useSSE', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
MockEventSource.instances = []
|
||||
mocks.active.mockResolvedValue({})
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: 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.getState().replaceStatuses({})
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
|
||||
useSendErrorStore.setState({ errors: {} })
|
||||
globalThis.EventSource = originalEventSource
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
@@ -130,92 +124,7 @@ describe('useSSE', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('clears stale active statuses from the initial status snapshot', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
useSessionStatus.getState().setStatus('session-1', { type: 'busy' })
|
||||
|
||||
const { unmount } = renderHook(
|
||||
() => useSSE('/repo', 'session-1'),
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
await connect(0, 'client-1')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('preserves optimistic active status when a poll snapshot omits the session', () => {
|
||||
useSessionStatus.getState().setOptimisticActive('session-1', 10_000)
|
||||
|
||||
useSessionStatus.getState().replaceStatuses({})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
|
||||
|
||||
useSessionStatus.getState().replaceStatuses({
|
||||
'session-1': { type: 'idle' },
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('ignores stale status snapshots after the directory changes', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
let resolveRepoA: (value: Record<string, { type: 'running' }>) => void = () => {}
|
||||
let resolveRepoB: (value: Record<string, { type: 'running' }>) => void = () => {}
|
||||
mocks.active
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveRepoA = resolve }))
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { resolveRepoB = resolve }))
|
||||
|
||||
const { rerender, unmount } = renderHook(
|
||||
({ directory }) => useSSE(directory, 'session-1'),
|
||||
{ wrapper: createWrapper(queryClient), initialProps: { directory: '/repo-a' } }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
|
||||
await connect(0, 'client-1')
|
||||
|
||||
rerender({ directory: '/repo-b' })
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(2))
|
||||
|
||||
await connect(1, 'client-2')
|
||||
|
||||
await act(async () => {
|
||||
resolveRepoB({ 'session-b': { type: 'running' } })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
resolveRepoA({ 'session-a': { type: 'running' } })
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-b')).toEqual({ type: 'busy' })
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the session list and cached session query on session.created', async () => {
|
||||
it('invalidates the cached session query on session.created', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
@@ -244,15 +153,12 @@ describe('useSSE', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-2'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ predicate: expect.any(Function) }),
|
||||
)
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the session list and cached session query on session.renamed', async () => {
|
||||
it('invalidates the cached session query on session.renamed', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
@@ -281,15 +187,12 @@ describe('useSSE', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-2'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ predicate: expect.any(Function) }),
|
||||
)
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the session list and removes the session query on session.deleted', async () => {
|
||||
it('removes the session query on session.deleted', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
@@ -319,44 +222,6 @@ describe('useSSE', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
expect(removeQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-2'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ predicate: expect.any(Function) }),
|
||||
)
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the session list on session.moved', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('/repo', 'session-1'),
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
await connect(0, 'client-1')
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
invalidateQueries.mockClear()
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'session.moved',
|
||||
directory: '/repo',
|
||||
data: { sessionID: 'session-2', projectID: 'proj-1', location: { directory: '/repo-2' } },
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ predicate: expect.any(Function) }),
|
||||
)
|
||||
})
|
||||
|
||||
unmount()
|
||||
@@ -552,7 +417,7 @@ describe('useSSE', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('handles envelopes whose directory is null', async () => {
|
||||
it('does not write session status from stream events', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
@@ -569,24 +434,35 @@ describe('useSSE', () => {
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
directory: null,
|
||||
payload: { type: 'session.execution.started', data: { sessionID: 'session-9' } },
|
||||
})
|
||||
const events = [
|
||||
{ type: 'session.status', directory: '/repo', data: { sessionID: 'session-1', status: { type: 'busy' } } },
|
||||
{ type: 'session.execution.started', directory: '/repo', data: { sessionID: 'session-1' } },
|
||||
{ type: 'session.idle', directory: '/repo', data: { sessionID: 'session-1' } },
|
||||
]
|
||||
for (const event of events) {
|
||||
MockEventSource.instances[0].emit('message', event)
|
||||
}
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('applies session.status and session.idle to the status store', async () => {
|
||||
it('clears the network send error on session.idle', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'session-1',
|
||||
title: 'Failed to send',
|
||||
message: 'Network error',
|
||||
kind: 'network',
|
||||
})
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('/repo', 'session-1'),
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
@@ -596,16 +472,6 @@ describe('useSSE', () => {
|
||||
await connect(0, 'client-1')
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'session.status',
|
||||
directory: '/repo',
|
||||
data: { sessionID: 'session-1', status: { type: 'busy' } },
|
||||
})
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
|
||||
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', {
|
||||
type: 'session.idle',
|
||||
@@ -614,46 +480,7 @@ describe('useSSE', () => {
|
||||
})
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('applies session execution lifecycle events to the status store', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('/repo', 'session-1'),
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
await connect(0, 'client-1')
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
|
||||
const emit = (type: string, data: Record<string, unknown>) => {
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', { type, directory: '/repo', data })
|
||||
})
|
||||
}
|
||||
|
||||
emit('session.execution.started', { sessionID: 'session-1' })
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'busy' })
|
||||
|
||||
emit('session.execution.succeeded', { sessionID: 'session-1' })
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
|
||||
emit('session.execution.started', { sessionID: 'session-1' })
|
||||
emit('session.execution.failed', { sessionID: 'session-1', error: { message: 'failed' } })
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
|
||||
emit('session.execution.started', { sessionID: 'session-1' })
|
||||
emit('session.execution.interrupted', { sessionID: 'session-1', reason: 'user' })
|
||||
expect(useSessionStatus.getState().getStatus('session-1')).toEqual({ type: 'idle' })
|
||||
expect(useSendErrorStore.getState().getError('session-1')).toBeNull()
|
||||
|
||||
unmount()
|
||||
})
|
||||
@@ -697,52 +524,6 @@ describe('useSSE', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the session list on terminal execution, metadata, and usage events', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSSE('/repo', 'session-1'),
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
)
|
||||
|
||||
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
|
||||
await connect(0, 'client-1')
|
||||
await waitFor(() => expect(result.current.isConnected).toBe(true))
|
||||
|
||||
const emit = (type: string, data: Record<string, unknown>) => {
|
||||
act(() => {
|
||||
MockEventSource.instances[0].emit('message', { type, directory: '/repo', data })
|
||||
})
|
||||
}
|
||||
|
||||
for (const type of ['session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted']) {
|
||||
invalidateQueries.mockClear()
|
||||
emit(type, { sessionID: 'session-2' })
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ predicate: expect.any(Function) }),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
for (const type of ['session.metadata.updated', 'session.usage.updated']) {
|
||||
invalidateQueries.mockClear()
|
||||
emit(type, { sessionID: 'session-2', metadata: {}, cost: 0, tokens: {} })
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ predicate: expect.any(Function) }),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('does not invalidate the session list on per-token delta events', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { useEffect, useRef, useState, useCallback, useMemo } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import type { SessionInfo, V2Event } from '@opencode-manager/shared/opencode'
|
||||
import { invalidateSessionListCaches, invalidateSessionListCachesDebounced, shellsQueryKey } from '@/lib/queryInvalidation'
|
||||
import { invalidateSessionListCaches, shellsQueryKey } from '@/lib/queryInvalidation'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSendErrorStore } from '@/stores/sendErrorStore'
|
||||
import { openCodeEventStream } from '@/lib/opencode-event-stream'
|
||||
import type { EventStreamSubscription } from '@/lib/opencode-event-stream'
|
||||
import { listActiveSessions, type ShellInfo } from '@/api/opencode'
|
||||
|
||||
const STATUS_POLL_INTERVAL_MS = 5000
|
||||
import type { ShellInfo } from '@/api/opencode'
|
||||
|
||||
type V2StreamEvent = V2Event & { directory?: string }
|
||||
|
||||
@@ -51,14 +48,11 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
const queryClient = useQueryClient()
|
||||
const mountedRef = useRef(true)
|
||||
const sessionIdRef = useRef(currentSessionId)
|
||||
const statusSyncVersionRef = useRef(0)
|
||||
const eventStreamSubscriptionRef = useRef<EventStreamSubscription | null>(null)
|
||||
sessionIdRef.current = currentSessionId
|
||||
const [isConnected, setIsConnected] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isReconnecting, setIsReconnecting] = useState(false)
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus)
|
||||
const replaceSessionStatuses = useSessionStatus((state) => state.replaceStatuses)
|
||||
|
||||
const resolveCacheDirectory = useCallback(
|
||||
(eventDirectory: string | undefined): string | undefined => {
|
||||
@@ -75,12 +69,10 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
|
||||
switch (event.type) {
|
||||
case 'session.created':
|
||||
invalidateSessionListCachesDebounced(queryClient)
|
||||
invalidateSessionQueryIfCached(queryClient, event.data.sessionID)
|
||||
break
|
||||
|
||||
case 'session.renamed':
|
||||
invalidateSessionListCachesDebounced(queryClient)
|
||||
invalidateSessionQueryIfCached(queryClient, event.data.sessionID)
|
||||
break
|
||||
|
||||
@@ -108,39 +100,13 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
break
|
||||
|
||||
case 'session.deleted':
|
||||
invalidateSessionListCaches(queryClient)
|
||||
queryClient.removeQueries({ queryKey: ['opencode', 'session', event.data.sessionID] })
|
||||
break
|
||||
|
||||
case 'session.moved':
|
||||
invalidateSessionListCachesDebounced(queryClient)
|
||||
break
|
||||
|
||||
case 'session.status':
|
||||
setSessionStatus(event.data.sessionID, event.data.status)
|
||||
break
|
||||
|
||||
case 'session.idle':
|
||||
setSessionStatus(event.data.sessionID, { type: 'idle' })
|
||||
useSendErrorStore.getState().clearNetworkError(event.data.sessionID)
|
||||
break
|
||||
|
||||
case 'session.execution.started':
|
||||
setSessionStatus(event.data.sessionID, { type: 'busy' })
|
||||
break
|
||||
|
||||
case 'session.execution.succeeded':
|
||||
case 'session.execution.failed':
|
||||
case 'session.execution.interrupted':
|
||||
setSessionStatus(event.data.sessionID, { type: 'idle' })
|
||||
invalidateSessionListCachesDebounced(queryClient)
|
||||
break
|
||||
|
||||
case 'session.metadata.updated':
|
||||
case 'session.usage.updated':
|
||||
invalidateSessionListCachesDebounced(queryClient)
|
||||
break
|
||||
|
||||
case 'shell.created': {
|
||||
const info = event.data.info
|
||||
queryClient.setQueryData<ShellInfo[]>(shellsQueryKey(cacheDirectory), (current) =>
|
||||
@@ -168,36 +134,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}, [queryClient, directorySet, resolveCacheDirectory, setSessionStatus])
|
||||
|
||||
const fetchInitialData = useCallback(async () => {
|
||||
if (!primaryDirectory || !mountedRef.current) return
|
||||
const syncVersion = ++statusSyncVersionRef.current
|
||||
|
||||
try {
|
||||
const active = await listActiveSessions()
|
||||
if (mountedRef.current && statusSyncVersionRef.current === syncVersion && active) {
|
||||
const statuses = Object.fromEntries(
|
||||
Object.keys(active).map((sessionID) => [sessionID, { type: 'busy' as const }]),
|
||||
)
|
||||
replaceSessionStatuses(statuses)
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof Error && !err.message.includes('aborted')) {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}, [primaryDirectory, replaceSessionStatuses])
|
||||
|
||||
useEffect(() => {
|
||||
if (!primaryDirectory) return
|
||||
|
||||
const interval = setInterval(() => {
|
||||
void fetchInitialData().catch(() => undefined)
|
||||
}, STATUS_POLL_INTERVAL_MS)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [primaryDirectory, fetchInitialData])
|
||||
}, [queryClient, directorySet, resolveCacheDirectory])
|
||||
|
||||
const refreshCurrentSession = useCallback(() => {
|
||||
const sessionId = sessionIdRef.current
|
||||
@@ -222,7 +159,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
mountedRef.current = true
|
||||
|
||||
if (directoriesList.length === 0) {
|
||||
statusSyncVersionRef.current += 1
|
||||
setIsConnected(false)
|
||||
setIsReconnecting(false)
|
||||
return
|
||||
@@ -241,7 +177,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
|
||||
if (connected) {
|
||||
setError(null)
|
||||
void fetchInitialData().catch(() => undefined)
|
||||
syncCurrentSession()
|
||||
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
|
||||
} else {
|
||||
@@ -278,7 +213,6 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
statusSyncVersionRef.current += 1
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
window.removeEventListener('focus', handleReconnect)
|
||||
window.removeEventListener('online', handleReconnect)
|
||||
@@ -288,7 +222,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
eventStreamSubscriptionRef.current = null
|
||||
}
|
||||
}
|
||||
}, [directoryKey, directoriesList, handleSSEEvent, fetchInitialData, syncCurrentSession, refreshCurrentSession, queryClient])
|
||||
}, [directoryKey, directoriesList, handleSSEEvent, syncCurrentSession, refreshCurrentSession, queryClient])
|
||||
|
||||
useEffect(() => {
|
||||
if (isConnected && document.visibilityState === 'visible') {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useSidebarCollapsed } from './useSidebarCollapsed'
|
||||
import { useSidebarCollapsed, useSidebarSectionCollapsed } from './useSidebarCollapsed'
|
||||
|
||||
describe('useSidebarCollapsed', () => {
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
}
|
||||
|
||||
describe('sidebar collapse hooks', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
@@ -26,50 +26,86 @@ describe('useSidebarCollapsed', () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('returns false by default when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
describe('useSidebarCollapsed', () => {
|
||||
it('returns false by default when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns stored value from localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
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(false)
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed', 'true')
|
||||
it('returns stored value from localStorage', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
it('returns false when stored value is malformed JSON', () => {
|
||||
localStorageMock.getItem.mockReturnValue('not-json{{')
|
||||
describe('useSidebarSectionCollapsed', () => {
|
||||
it('returns false by default when no stored value', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
const { result } = renderHook(() => useSidebarSectionCollapsed('sessions'))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
expect(result.current[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when stored value is JSON but not a boolean', () => {
|
||||
localStorageMock.getItem.mockReturnValue('"some string"')
|
||||
it('returns stored value from the section key', () => {
|
||||
localStorageMock.getItem.mockReturnValue('true')
|
||||
|
||||
const { result } = renderHook(() => useSidebarCollapsed())
|
||||
const { result } = renderHook(() => useSidebarSectionCollapsed('menu'))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:collapsed:menu')
|
||||
expect(result.current[0]).toBe(true)
|
||||
})
|
||||
|
||||
it('toggles collapsed state and persists under the section key', () => {
|
||||
localStorageMock.getItem.mockReturnValue(null)
|
||||
|
||||
const { result } = renderHook(() => useSidebarSectionCollapsed('sessions'))
|
||||
|
||||
expect(result.current[0]).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current[1]()
|
||||
})
|
||||
|
||||
expect(result.current[0]).toBe(true)
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith('oc:sidebar:collapsed:sessions', 'true')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -2,32 +2,42 @@ import { useState, useCallback } from 'react'
|
||||
|
||||
const STORAGE_KEY = 'oc:sidebar:collapsed'
|
||||
|
||||
export function useSidebarCollapsed(): [boolean, () => void] {
|
||||
const [collapsed, setCollapsed] = useState(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false
|
||||
}
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
if (stored === null) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored)
|
||||
return typeof parsed === 'boolean' ? parsed : false
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
function readStoredBoolean(key: string, fallback: boolean): boolean {
|
||||
if (typeof window === 'undefined') {
|
||||
return fallback
|
||||
}
|
||||
const stored = localStorage.getItem(key)
|
||||
if (stored === null) {
|
||||
return fallback
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored)
|
||||
return typeof parsed === 'boolean' ? parsed : fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => void] {
|
||||
const [value, setValue] = useState(() => readStoredBoolean(key, fallback))
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setCollapsed((prev: boolean) => {
|
||||
setValue((prev: boolean) => {
|
||||
const newValue = !prev
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(newValue))
|
||||
localStorage.setItem(key, JSON.stringify(newValue))
|
||||
}
|
||||
return newValue
|
||||
})
|
||||
}, [])
|
||||
}, [key])
|
||||
|
||||
return [collapsed, toggle]
|
||||
return [value, toggle]
|
||||
}
|
||||
|
||||
export function useSidebarCollapsed(): [boolean, () => void] {
|
||||
return usePersistentBoolean(STORAGE_KEY, false)
|
||||
}
|
||||
|
||||
export function useSidebarSectionCollapsed(section: string): [boolean, () => void] {
|
||||
return usePersistentBoolean(`${STORAGE_KEY}:${section}`, false)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useMemo } from 'react'
|
||||
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 type { Repo, Session } from '@/api/types'
|
||||
import {
|
||||
SIDEBAR_SESSIONS_PER_REPO,
|
||||
buildSidebarRepoGroups,
|
||||
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
|
||||
}): { groups: SidebarRepoGroup[]; isLoading: boolean; isError: boolean; hasMore: boolean } {
|
||||
const { repos, search } = input
|
||||
|
||||
const directories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
|
||||
|
||||
const { data: sessions, isLoading, isError, hasNextPage } = useSessionsAcrossDirectories(directories, {
|
||||
search,
|
||||
limit: SIDEBAR_SESSIONS_PER_REPO,
|
||||
})
|
||||
|
||||
const { data: sessionPins } = useSessionPins()
|
||||
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
|
||||
|
||||
const missingPins = useMemo(() => {
|
||||
if (search) return []
|
||||
const repoDirectories = new Set(directories)
|
||||
const fetchedKeys = new Set(
|
||||
sessions.map((session) => buildSessionKey(session.location.directory, session.id)),
|
||||
)
|
||||
return (sessionPins ?? []).filter(
|
||||
(pin) =>
|
||||
repoDirectories.has(pin.directory) &&
|
||||
!fetchedKeys.has(buildSessionKey(pin.directory, pin.sessionId)),
|
||||
)
|
||||
}, [directories, search, sessionPins, sessions])
|
||||
|
||||
const pinnedSessions = useQueries({
|
||||
queries: missingPins.map((pin) => sessionQueryOptions(pin.sessionId, pin.directory)),
|
||||
combine: combinePinnedSessions,
|
||||
})
|
||||
|
||||
const mergedSessions = useMemo(
|
||||
() => mergeSessions(sessions, pinnedSessions),
|
||||
[sessions, pinnedSessions],
|
||||
)
|
||||
|
||||
const groups = useMemo(
|
||||
() => buildSidebarRepoGroups({ repos, sessions: mergedSessions, pinnedKeys, now: Date.now() }),
|
||||
[repos, mergedSessions, pinnedKeys],
|
||||
)
|
||||
|
||||
return { groups, isLoading, isError, hasMore: Boolean(hasNextPage) }
|
||||
}
|
||||
|
||||
export function useNavigableRepos(enabled = true): { repos: Repo[]; isLoading: boolean; refetch: () => void } {
|
||||
const { data, isLoading, refetch } = useQuery({ queryKey: ['repos'], queryFn: listRepos, enabled })
|
||||
const repos = useMemo(() => selectNavigableRepos(data ?? []), [data])
|
||||
return { repos, isLoading, refetch: () => { void refetch() } }
|
||||
}
|
||||
Reference in new issue
Block a user