mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +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
@@ -5,12 +5,14 @@ import type { ReactNode } from 'react'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { FormInfo, PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { EventProvider, useEventContext, useForms, usePermissions, useSSEHealth } from './EventContext'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listRepos: vi.fn(),
|
||||
listPendingPermissions: vi.fn(),
|
||||
listPendingForms: vi.fn(),
|
||||
listActiveSessions: vi.fn(),
|
||||
replyPermission: vi.fn(),
|
||||
replyForm: vi.fn(),
|
||||
cancelForm: vi.fn(),
|
||||
@@ -23,6 +25,7 @@ vi.mock('@/api/repos', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
listActiveSessions: mocks.listActiveSessions,
|
||||
listPendingPermissions: mocks.listPendingPermissions,
|
||||
listPendingForms: mocks.listPendingForms,
|
||||
replyPermission: mocks.replyPermission,
|
||||
@@ -126,6 +129,14 @@ function createTestQueryClient() {
|
||||
})
|
||||
}
|
||||
|
||||
function createDeferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function createWrapper(queryClient = createTestQueryClient()) {
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<MemoryRouter>
|
||||
@@ -153,10 +164,12 @@ describe('EventProvider permissions and forms', () => {
|
||||
mocks.listRepos.mockResolvedValue([])
|
||||
mocks.listPendingPermissions.mockResolvedValue([])
|
||||
mocks.listPendingForms.mockResolvedValue([])
|
||||
mocks.listActiveSessions.mockResolvedValue({})
|
||||
mocks.replyPermission.mockResolvedValue(undefined)
|
||||
mocks.replyForm.mockResolvedValue(undefined)
|
||||
mocks.cancelForm.mockResolvedValue(undefined)
|
||||
mocks.getHealth.mockReturnValue({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false })
|
||||
useSessionStatus.setState({ statuses: new Map(), statusCache: new Map(), statusRevisions: new Map(), revision: 0 })
|
||||
mocks.subscribeGlobalMonitor.mockReturnValue({
|
||||
dispose: vi.fn(),
|
||||
updateDirectories: vi.fn(),
|
||||
@@ -956,4 +969,381 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(afterBooleanChange).toBe(initialRenderCount + 1)
|
||||
expect(renderCount).toBe(afterBooleanChange)
|
||||
})
|
||||
|
||||
it('applies a session.status event from the global monitor to the status store', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'session.status',
|
||||
data: { sessionID: 'session-9', status: { type: 'busy' } },
|
||||
directory: '/repo',
|
||||
})
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
it('applies execution lifecycle and idle events from the global monitor to the status store', async () => {
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-9' }, directory: '/repo' })
|
||||
})
|
||||
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'busy' })
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.execution.succeeded', data: { sessionID: 'session-9' }, directory: '/repo' })
|
||||
})
|
||||
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' })
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-9' }, directory: '/repo' })
|
||||
onEvent({ type: 'session.idle', data: { sessionID: 'session-9' }, directory: '/repo' })
|
||||
})
|
||||
expect(useSessionStatus.getState().getStatus('session-9')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('reconciles the global active snapshot on reconnect and clears omitted sessions', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listActiveSessions.mockResolvedValue({ 'session-other': { type: 'running' } })
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
act(() => {
|
||||
useSessionStatus.getState().setStatus('session-other', { type: 'busy' })
|
||||
useSessionStatus.getState().setStatus('session-stale', { type: 'busy' })
|
||||
})
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().getStatus('session-other')).toEqual({ type: 'busy' })
|
||||
expect(useSessionStatus.getState().getStatus('session-stale')).toEqual({ type: 'idle' })
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores a superseded connect snapshot that resolves after a newer reconnect snapshot', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
|
||||
const first = createDeferred<Record<string, unknown>>()
|
||||
const second = createDeferred<Record<string, unknown>>()
|
||||
mocks.listActiveSessions
|
||||
.mockReturnValueOnce(first.promise)
|
||||
.mockReturnValueOnce(second.promise)
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(false)
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(2)
|
||||
|
||||
await act(async () => {
|
||||
second.resolve({ 'session-new': { type: 'running' } })
|
||||
await second.promise
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().getStatus('session-new')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
first.resolve({ 'session-old': { type: 'running' } })
|
||||
await first.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-new')).toEqual({ type: 'busy' })
|
||||
expect(useSessionStatus.getState().getStatus('session-old')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('does not apply a global snapshot that resolves after unmount', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
|
||||
const deferred = createDeferred<Record<string, unknown>>()
|
||||
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
|
||||
|
||||
const { unmount } = render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
unmount()
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve({ 'session-late': { type: 'running' } })
|
||||
await deferred.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-late')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('does not let a deferred connect snapshot revert an idle event received while it was in flight', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
|
||||
const deferred = createDeferred<Record<string, unknown>>()
|
||||
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.status', data: { sessionID: 'session-a', status: { type: 'busy' } }, directory: '/repo' })
|
||||
onEvent({ type: 'session.idle', data: { sessionID: 'session-a' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve({ 'session-a': { type: 'running' } })
|
||||
await deferred.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('does not let a deferred empty connect snapshot erase a session that started while it was in flight', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
|
||||
const deferred = createDeferred<Record<string, unknown>>()
|
||||
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.execution.started', data: { sessionID: 'session-a' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve({})
|
||||
await deferred.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-a')).toEqual({ type: 'busy' })
|
||||
})
|
||||
|
||||
it('does not let a deferred connect snapshot resurrect an unknown session that went idle', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
|
||||
const deferred = createDeferred<Record<string, unknown>>()
|
||||
mocks.listActiveSessions.mockReturnValueOnce(deferred.promise)
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.idle', data: { sessionID: 'session-unseen' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve({ 'session-unseen': { type: 'running' } })
|
||||
await deferred.promise
|
||||
})
|
||||
|
||||
expect(useSessionStatus.getState().getStatus('session-unseen')).toEqual({ type: 'idle' })
|
||||
})
|
||||
|
||||
it('debounces a session list invalidation on session lifecycle events', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.created', data: { sessionID: 'session-9' }, directory: '/repo' })
|
||||
onEvent({ type: 'session.renamed', data: { sessionID: 'session-9', title: 'Renamed' }, directory: '/repo' })
|
||||
onEvent({ type: 'session.deleted', data: { sessionID: 'session-9' }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(true)
|
||||
})
|
||||
expect(invalidateQueries).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('invalidates only the session list for the event directory', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
queryClient.setQueryData(['opencode', 'sessions', '/repo-a'], { pages: [], pageParams: [] })
|
||||
queryClient.setQueryData(['opencode', 'sessions', '/repo-b'], { pages: [], pageParams: [] })
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.created', data: { sessionID: 'session-9' }, directory: '/repo-a' })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo-a'])?.isInvalidated).toBe(true)
|
||||
})
|
||||
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo-b'])?.isInvalidated).toBe(false)
|
||||
})
|
||||
|
||||
it('does not invalidate session lists on session.usage.updated', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
queryClient.setQueryData(['opencode', 'sessions', '/repo'], { pages: [], pageParams: [] })
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper(queryClient) })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
invalidateQueries.mockClear()
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.usage.updated', data: { sessionID: 'session-9', cost: 0, tokens: {} }, directory: '/repo' })
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
})
|
||||
|
||||
expect(invalidateQueries).not.toHaveBeenCalled()
|
||||
expect(queryClient.getQueryState(['opencode', 'sessions', '/repo'])?.isInvalidated).toBe(false)
|
||||
})
|
||||
|
||||
it('fetches the active session snapshot on connect and polls every 5 seconds while connected', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listActiveSessions.mockResolvedValue({})
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(2)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(5000)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(3)
|
||||
|
||||
act(() => {
|
||||
handleStatusChange(false)
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(15000)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(3)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('stops polling the active session snapshot after unmount', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listActiveSessions.mockResolvedValue({})
|
||||
|
||||
const { unmount } = render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const handleStatusChange = lastSubscribeCall[0].onStatusChange as (connected: boolean) => void
|
||||
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
act(() => {
|
||||
handleStatusChange(true)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
unmount()
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(15000)
|
||||
})
|
||||
expect(mocks.listActiveSessions).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useQueryClient, useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
cancelForm,
|
||||
listActiveSessions,
|
||||
listPendingForms,
|
||||
listPendingPermissions,
|
||||
replyForm,
|
||||
@@ -15,7 +16,15 @@ import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
import { invalidateProviderCachesDebounced, invalidateQueryKeysDebounced, invalidateRepoGitCachesDebounced } from '@/lib/queryInvalidation'
|
||||
import { busyStatusesFromActiveSessions, useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import {
|
||||
invalidateProviderCachesDebounced,
|
||||
invalidateQueryKeysDebounced,
|
||||
invalidateRepoGitCachesDebounced,
|
||||
invalidateSessionListCachesDebounced,
|
||||
} from '@/lib/queryInvalidation'
|
||||
|
||||
const STATUS_POLL_INTERVAL_MS = 5000
|
||||
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
type FormsBySession = Record<string, FormInfo[]>
|
||||
@@ -150,6 +159,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const sessionDirectoriesRef = useRef<Map<string, string>>(new Map())
|
||||
const prevPermissionCountRef = useRef(0)
|
||||
const initialFetchDoneRef = useRef(false)
|
||||
const statusSyncVersionRef = useRef(0)
|
||||
const statusPollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
|
||||
const reposRef = useRef<typeof repos>(null)
|
||||
|
||||
@@ -371,6 +382,41 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
await reconcilePendingActionsForDirectories([...new Set(reposToUse.map(r => r.fullPath))])
|
||||
}, [reconcilePendingActionsForDirectories])
|
||||
|
||||
const fetchInitialSessionStatuses = useCallback(async () => {
|
||||
const syncVersion = ++statusSyncVersionRef.current
|
||||
const snapshotToken = useSessionStatus.getState().beginStatusSnapshot()
|
||||
|
||||
try {
|
||||
const active = await listActiveSessions()
|
||||
if (statusSyncVersionRef.current !== syncVersion) {
|
||||
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
|
||||
return
|
||||
}
|
||||
useSessionStatus.getState().replaceStatuses(
|
||||
busyStatusesFromActiveSessions(active),
|
||||
snapshotToken,
|
||||
)
|
||||
} catch (error) {
|
||||
useSessionStatus.getState().endStatusSnapshot(snapshotToken)
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('Failed to fetch active sessions:', error)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const stopStatusPoll = useCallback(() => {
|
||||
if (statusPollIntervalRef.current === null) return
|
||||
clearInterval(statusPollIntervalRef.current)
|
||||
statusPollIntervalRef.current = null
|
||||
}, [])
|
||||
|
||||
const startStatusPoll = useCallback(() => {
|
||||
stopStatusPoll()
|
||||
statusPollIntervalRef.current = setInterval(() => {
|
||||
void fetchInitialSessionStatuses()
|
||||
}, STATUS_POLL_INTERVAL_MS)
|
||||
}, [fetchInitialSessionStatuses, stopStatusPoll])
|
||||
|
||||
const syncPermissionsForSession = useCallback(async (directory: string, sessionID: string) => {
|
||||
const pendingPermissions = await listPendingPermissions(directory)
|
||||
rememberSessionDirectory(sessionID, directory)
|
||||
@@ -413,6 +459,33 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
removeForm(id, sessionID)
|
||||
break
|
||||
}
|
||||
case 'session.status': {
|
||||
const { sessionID, status } = event.data
|
||||
useSessionStatus.getState().setStatus(sessionID, status)
|
||||
break
|
||||
}
|
||||
case 'session.idle': {
|
||||
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
|
||||
break
|
||||
}
|
||||
case 'session.execution.started': {
|
||||
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'busy' })
|
||||
break
|
||||
}
|
||||
case 'session.execution.succeeded':
|
||||
case 'session.execution.failed':
|
||||
case 'session.execution.interrupted': {
|
||||
useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' })
|
||||
invalidateSessionListCachesDebounced(queryClient, event.directory)
|
||||
break
|
||||
}
|
||||
case 'session.created':
|
||||
case 'session.renamed':
|
||||
case 'session.deleted':
|
||||
case 'session.moved':
|
||||
case 'session.metadata.updated':
|
||||
invalidateSessionListCachesDebounced(queryClient, event.directory)
|
||||
break
|
||||
case 'credential.updated':
|
||||
case 'credential.switched':
|
||||
case 'integration.updated':
|
||||
@@ -455,6 +528,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
if (connected) {
|
||||
initialFetchDoneRef.current = false
|
||||
fetchInitialPendingData()
|
||||
fetchInitialSessionStatuses()
|
||||
startStatusPoll()
|
||||
} else {
|
||||
statusSyncVersionRef.current += 1
|
||||
stopStatusPoll()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,10 +551,12 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
subscriptionRef.current = subscription
|
||||
|
||||
return () => {
|
||||
statusSyncVersionRef.current += 1
|
||||
stopStatusPoll()
|
||||
subscription.dispose()
|
||||
subscriptionRef.current = null
|
||||
}
|
||||
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories])
|
||||
}, [addPermission, removePermission, addForm, removeForm, rememberSessionDirectory, fetchInitialPendingData, fetchInitialSessionStatuses, startStatusPoll, stopStatusPoll, queryClient, handleHealthChange, reconcilePendingActionsForDirectories, collectTrackedDirectories])
|
||||
|
||||
useEffect(() => {
|
||||
reposRef.current = repos
|
||||
|
||||
Reference in new issue
Block a user