mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Merge pull request #431 from chriswritescode-dev/fix/stale-background-activity
fix(session): stop the background activity indicator going stale
This commit is contained in:
7 files changed
+422
-48
No files matched your search
@@ -514,7 +514,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
|
||||
@@ -527,7 +527,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
|
||||
act(() => {
|
||||
onResync?.()
|
||||
onResync?.([])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -549,7 +549,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/repo' })
|
||||
@@ -562,7 +562,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
|
||||
act(() => {
|
||||
onResync?.()
|
||||
onResync?.([])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -588,7 +588,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'permission.asked', data: pendingPermission, directory: '/worktrees/wt-1' })
|
||||
@@ -599,7 +599,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
|
||||
act(() => {
|
||||
onResync?.()
|
||||
onResync?.([])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -1010,10 +1010,10 @@ describe('EventProvider permissions and forms', () => {
|
||||
invalidateQueries.mockClear()
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
onResync?.()
|
||||
onResync?.([])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -1097,10 +1097,10 @@ describe('EventProvider permissions and forms', () => {
|
||||
mocks.listPendingForms.mockClear()
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
onResync?.()
|
||||
onResync?.([])
|
||||
})
|
||||
|
||||
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/repo-a')
|
||||
@@ -1671,7 +1671,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
const onResync = lastSubscribeCall[0].onResync as (() => void) | undefined
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'session.execution.started', data: { sessionID: 'child-1' }, directory: '/repo' })
|
||||
@@ -1679,7 +1679,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(useSessionStatus.getState().getStatus('child-1')).toEqual({ type: 'busy' })
|
||||
|
||||
act(() => {
|
||||
onResync?.()
|
||||
onResync?.([])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -2326,11 +2326,18 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onDirectoriesSubscribed(['/repo'])
|
||||
})
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
|
||||
act(() => {
|
||||
onEvent({ type: 'shell.exited', data: { id: 'shell-1', status: 'exited' }, directory: '/repo' })
|
||||
})
|
||||
@@ -2350,11 +2357,18 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
|
||||
const onEvent = lastSubscribeCall[0].onEvent as (data: unknown) => void
|
||||
|
||||
act(() => {
|
||||
onDirectoriesSubscribed(['/repo'])
|
||||
})
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
|
||||
act(() => {
|
||||
onEvent({
|
||||
type: 'shell.created',
|
||||
@@ -2374,7 +2388,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves ancestry for a shell owner from the directory snapshot', async () => {
|
||||
it('resolves ancestry for a shell owner from a newly subscribed directory snapshot', async () => {
|
||||
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
|
||||
mocks.listShells.mockResolvedValue([
|
||||
{ id: 'shell-1', status: 'running', metadata: { sessionID: 'child-1' } },
|
||||
@@ -2387,6 +2401,15 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
|
||||
|
||||
act(() => {
|
||||
onDirectoriesSubscribed(['/repo'])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(useSessionStatus.getState().parents.get('child-1')).toBe('parent-1')
|
||||
})
|
||||
@@ -2428,6 +2451,12 @@ describe('EventProvider permissions and forms', () => {
|
||||
it('syncs running shells for a directory whose repo arrives after connect', async () => {
|
||||
const reposDeferred = createDeferred<Array<{ id: number; fullPath: string }>>()
|
||||
mocks.listRepos.mockReturnValueOnce(reposDeferred.promise)
|
||||
mocks.subscribeGlobalMonitor.mockImplementation((input: { onDirectoriesSubscribed?: (directories: string[]) => void }) => ({
|
||||
dispose: vi.fn(),
|
||||
updateDirectories: (directories: string[]) => input.onDirectoriesSubscribed?.(directories),
|
||||
reconnect: vi.fn(),
|
||||
reportVisibility: vi.fn(),
|
||||
}))
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
@@ -2449,4 +2478,64 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
await waitFor(() => expect(mocks.listShells).toHaveBeenCalledWith('/repo'))
|
||||
})
|
||||
|
||||
it('reconciles newly subscribed directories reported by the stream', async () => {
|
||||
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
|
||||
mocks.listPendingForms.mockResolvedValue([pendingForm])
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onDirectoriesSubscribed = lastSubscribeCall[0].onDirectoriesSubscribed as (directories: string[]) => void
|
||||
|
||||
act(() => {
|
||||
useSessionStatus.getState().setShellRunning('shell-stale', 'session-1', '/session-dir')
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
onDirectoriesSubscribed(['/session-dir'])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listShells).toHaveBeenCalledWith('/session-dir')
|
||||
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/session-dir')
|
||||
expect(mocks.listPendingForms).toHaveBeenCalledWith('/session-dir')
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(false)
|
||||
expect(screen.getByTestId('permission-count').textContent).toBe('1')
|
||||
expect(screen.getByTestId('count').textContent).toBe('1')
|
||||
})
|
||||
|
||||
it('reconciles subscribed directories reported by a resync even when they are not tracked', async () => {
|
||||
mocks.listPendingPermissions.mockResolvedValue([pendingPermission])
|
||||
mocks.listPendingForms.mockResolvedValue([pendingForm])
|
||||
|
||||
render(<Harness />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(mocks.subscribeGlobalMonitor).toHaveBeenCalled())
|
||||
|
||||
const lastSubscribeCall = mocks.subscribeGlobalMonitor.mock.calls[mocks.subscribeGlobalMonitor.mock.calls.length - 1]
|
||||
const onResync = lastSubscribeCall[0].onResync as ((directories: string[]) => void) | undefined
|
||||
|
||||
act(() => {
|
||||
useSessionStatus.getState().setShellRunning('shell-stale', 'session-1', '/unregistered-dir')
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
onResync?.(['/unregistered-dir'])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.listShells).toHaveBeenCalledWith('/unregistered-dir')
|
||||
expect(mocks.listPendingPermissions).toHaveBeenCalledWith('/unregistered-dir')
|
||||
expect(mocks.listPendingForms).toHaveBeenCalledWith('/unregistered-dir')
|
||||
})
|
||||
expect(useSessionStatus.getState().runningShells.has('shell-stale')).toBe(false)
|
||||
expect(screen.getByTestId('permission-count').textContent).toBe('1')
|
||||
expect(screen.getByTestId('count').textContent).toBe('1')
|
||||
})
|
||||
})
|
||||
@@ -269,7 +269,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const statusPollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
const subscriptionRef = useRef<ReturnType<typeof openCodeEventStream.subscribeGlobalMonitor> | null>(null)
|
||||
const reposRef = useRef<typeof repos>(null)
|
||||
const trackedRepoDirectoriesRef = useRef<Set<string>>(new Set())
|
||||
const ancestryInFlightRef = useRef<Set<string>>(new Set())
|
||||
|
||||
const { data: repos } = useQuery({
|
||||
@@ -805,10 +804,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}
|
||||
|
||||
const handleResync = () => {
|
||||
void reconcilePendingActionsForDirectories(collectTrackedDirectories())
|
||||
const handleResync = (subscribedDirectories: string[]) => {
|
||||
const directories = [...new Set([...collectTrackedDirectories(), ...subscribedDirectories])]
|
||||
void reconcilePendingActionsForDirectories(directories)
|
||||
void fetchInitialSessionStatuses()
|
||||
void syncRunningShells(collectTrackedDirectories())
|
||||
void syncRunningShells(directories)
|
||||
invalidateChildSessionCaches(queryClient)
|
||||
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
|
||||
}
|
||||
@@ -820,6 +820,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
onStatusChange: handleStatusChange,
|
||||
onHealthChange: handleHealthChange,
|
||||
onResync: handleResync,
|
||||
onDirectoriesSubscribed: (directories) => {
|
||||
void reconcilePendingActionsForDirectories(directories)
|
||||
void syncRunningShells(directories)
|
||||
},
|
||||
})
|
||||
subscriptionRef.current = subscription
|
||||
|
||||
@@ -834,16 +838,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
useEffect(() => {
|
||||
reposRef.current = repos
|
||||
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
|
||||
const previousDirectories = trackedRepoDirectoriesRef.current
|
||||
const addedDirectories = directories.filter((directory) => !previousDirectories.has(directory))
|
||||
trackedRepoDirectoriesRef.current = new Set(directories)
|
||||
const sub = subscriptionRef.current
|
||||
if (!sub) return
|
||||
sub.updateDirectories(directories)
|
||||
if (addedDirectories.length > 0) {
|
||||
void syncRunningShells(addedDirectories)
|
||||
}
|
||||
}, [repos, syncRunningShells])
|
||||
subscriptionRef.current?.updateDirectories(directories)
|
||||
}, [repos])
|
||||
|
||||
useEffect(() => {
|
||||
if (!repos || repos.length === 0) return
|
||||
|
||||
@@ -174,6 +174,40 @@ describe('useSSE', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the cached session query on session.moved so the page follows the new directory', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
queryClient.setQueryData(['opencode', 'session', 'session-1', '/repo'], { id: 'session-1' })
|
||||
|
||||
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-1', projectID: 'proj-1', subpath: '', location: { directory: '/elsewhere' } },
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'session', 'session-1'] })
|
||||
})
|
||||
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('invalidates the cached session query on session.renamed', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
|
||||
@@ -80,6 +80,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
|
||||
break
|
||||
|
||||
case 'session.renamed':
|
||||
case 'session.moved':
|
||||
invalidateSessionQueryIfCached(queryClient, event.data.sessionID)
|
||||
break
|
||||
|
||||
|
||||
@@ -2,6 +2,30 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OpenCodeEventStream, TestEventStreamTransport } from '..'
|
||||
import type { EventStreamHealthState } from '..'
|
||||
|
||||
class RejectingSubscribeTransport extends TestEventStreamTransport {
|
||||
override async post(path: string, body: unknown): Promise<boolean> {
|
||||
this.posts.push({ path, body })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
class DeferredSubscribeTransport extends TestEventStreamTransport {
|
||||
private resolvers: Array<(value: boolean) => void> = []
|
||||
|
||||
override post(path: string, body: unknown): Promise<boolean> {
|
||||
this.posts.push({ path, body })
|
||||
return new Promise<boolean>((resolve) => {
|
||||
this.resolvers.push(resolve)
|
||||
})
|
||||
}
|
||||
|
||||
resolvePosts(success = true): void {
|
||||
const resolvers = this.resolvers
|
||||
this.resolvers = []
|
||||
resolvers.forEach((resolve) => resolve(success))
|
||||
}
|
||||
}
|
||||
|
||||
describe('OpenCodeEventStream', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
@@ -169,6 +193,7 @@ describe('OpenCodeEventStream', () => {
|
||||
transport.resync()
|
||||
|
||||
expect(onResync).toHaveBeenCalledTimes(1)
|
||||
expect(onResync).toHaveBeenCalledWith(['/repo'])
|
||||
})
|
||||
|
||||
it('reports visibility through the transport adapter', async () => {
|
||||
@@ -186,4 +211,100 @@ describe('OpenCodeEventStream', () => {
|
||||
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1' },
|
||||
})
|
||||
})
|
||||
|
||||
it('notifies the global monitor with directories subscribed mid-connection', async () => {
|
||||
const transport = new TestEventStreamTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
const onDirectoriesSubscribed = vi.fn()
|
||||
|
||||
const subscription = stream.subscribeGlobalMonitor({
|
||||
directories: ['/repo-a'],
|
||||
onEvent: vi.fn(),
|
||||
onDirectoriesSubscribed,
|
||||
})
|
||||
transport.openConnection()
|
||||
transport.connected('client-1')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
onDirectoriesSubscribed.mockClear()
|
||||
|
||||
subscription.updateDirectories(['/repo-a', '/repo-b'])
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(onDirectoriesSubscribed).toHaveBeenCalledWith(['/repo-b'])
|
||||
})
|
||||
|
||||
it('notifies the global monitor for pending directories flushed after connect', async () => {
|
||||
const transport = new TestEventStreamTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
const onDirectoriesSubscribed = vi.fn()
|
||||
|
||||
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn(), onDirectoriesSubscribed })
|
||||
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
|
||||
|
||||
transport.openConnection()
|
||||
transport.connected('client-1')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(onDirectoriesSubscribed).toHaveBeenCalledWith(['/repo'])
|
||||
})
|
||||
|
||||
it('does not notify the global monitor when the subscribe request fails', async () => {
|
||||
const transport = new RejectingSubscribeTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
const onDirectoriesSubscribed = vi.fn()
|
||||
|
||||
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn(), onDirectoriesSubscribed })
|
||||
transport.openConnection()
|
||||
transport.connected('client-1')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores a subscribe response that resolves after the stream reconnected', async () => {
|
||||
const transport = new DeferredSubscribeTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
const onDirectoriesSubscribed = vi.fn()
|
||||
|
||||
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn(), onDirectoriesSubscribed })
|
||||
transport.openConnection()
|
||||
transport.connected('client-1')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(transport.posts).toContainEqual({
|
||||
path: '/api/sse/subscribe',
|
||||
body: { clientId: 'client-1', directories: ['/repo'] },
|
||||
})
|
||||
|
||||
transport.fail()
|
||||
transport.openConnection()
|
||||
transport.connected('client-2')
|
||||
|
||||
transport.resolvePosts()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not notify a directory removed while its subscribe request is in flight', async () => {
|
||||
const transport = new DeferredSubscribeTransport()
|
||||
const stream = new OpenCodeEventStream({ transport })
|
||||
const onDirectoriesSubscribed = vi.fn()
|
||||
|
||||
const subscription = stream.subscribeGlobalMonitor({
|
||||
directories: ['/repo'],
|
||||
onEvent: vi.fn(),
|
||||
onDirectoriesSubscribed,
|
||||
})
|
||||
transport.openConnection()
|
||||
transport.connected('client-1')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
subscription.updateDirectories([])
|
||||
|
||||
transport.resolvePosts()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
|
||||
expect(onDirectoriesSubscribed).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -14,10 +14,20 @@ interface Subscriber {
|
||||
onEvent: OpenCodeEventHandler
|
||||
onStatusChange?: EventStreamStatusHandler
|
||||
onHealthChange?: (state: EventStreamHealthState) => void
|
||||
onResync?: () => void
|
||||
onResync?: (subscribedDirectories: string[]) => void
|
||||
onDirectoriesSubscribed?: (directories: string[]) => void
|
||||
directories: Set<string>
|
||||
}
|
||||
|
||||
interface SubscriberInput {
|
||||
onEvent: OpenCodeEventHandler
|
||||
onStatusChange?: EventStreamStatusHandler
|
||||
onHealthChange?: (state: EventStreamHealthState) => void
|
||||
directories: string[]
|
||||
onResync?: (subscribedDirectories: string[]) => void
|
||||
onDirectoriesSubscribed?: (directories: string[]) => void
|
||||
}
|
||||
|
||||
interface OpenCodeEventStreamOptions {
|
||||
transport?: EventStreamTransport
|
||||
}
|
||||
@@ -45,14 +55,8 @@ export class OpenCodeEventStream {
|
||||
this.transport = options.transport ?? createBrowserEventStreamTransport()
|
||||
}
|
||||
|
||||
subscribeGlobalMonitor(input: {
|
||||
directories: string[]
|
||||
onEvent: OpenCodeEventHandler
|
||||
onStatusChange?: EventStreamStatusHandler
|
||||
onHealthChange?: (state: EventStreamHealthState) => void
|
||||
onResync?: () => void
|
||||
}): GlobalMonitorSubscription {
|
||||
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange, input.directories, input.onResync)
|
||||
subscribeGlobalMonitor(input: SubscriberInput): GlobalMonitorSubscription {
|
||||
const id = this.addSubscriber(input)
|
||||
|
||||
return {
|
||||
updateDirectories: (directories) => this.updateSubscriberDirectories(id, directories),
|
||||
@@ -66,13 +70,8 @@ export class OpenCodeEventStream {
|
||||
return this.buildHealth()
|
||||
}
|
||||
|
||||
private addSubscriber(
|
||||
onEvent: OpenCodeEventHandler,
|
||||
onStatusChange?: EventStreamStatusHandler,
|
||||
onHealthChange?: (state: EventStreamHealthState) => void,
|
||||
directories: string[] = [],
|
||||
onResync?: () => void,
|
||||
): string {
|
||||
private addSubscriber(input: SubscriberInput): string {
|
||||
const { onEvent, onStatusChange, onHealthChange, directories, onResync, onDirectoriesSubscribed } = input
|
||||
const id = `sub_${++this.subscriberIdCounter}`
|
||||
|
||||
const initialDirectories = new Set(directories.filter(Boolean))
|
||||
@@ -96,6 +95,7 @@ export class OpenCodeEventStream {
|
||||
onStatusChange,
|
||||
onHealthChange,
|
||||
onResync,
|
||||
onDirectoriesSubscribed,
|
||||
directories: initialDirectories,
|
||||
})
|
||||
|
||||
@@ -400,9 +400,10 @@ export class OpenCodeEventStream {
|
||||
|
||||
private handleResync(): void {
|
||||
this.markActivity()
|
||||
const directories = Array.from(this.directoryRefCounts.keys())
|
||||
this.subscribers.forEach((subscriber) => {
|
||||
try {
|
||||
subscriber.onResync?.()
|
||||
subscriber.onResync?.(directories)
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
@@ -422,15 +423,35 @@ export class OpenCodeEventStream {
|
||||
private async subscribeToRemoteDirectories(directories: string[]): Promise<void> {
|
||||
if (!this.clientId || directories.length === 0) return
|
||||
|
||||
const clientId = this.clientId
|
||||
|
||||
const success = await this.transport.post('/api/sse/subscribe', {
|
||||
clientId: this.clientId,
|
||||
clientId,
|
||||
directories,
|
||||
})
|
||||
|
||||
if (this.clientId !== clientId) return
|
||||
|
||||
if (!success) {
|
||||
directories.forEach((directory) => this.pendingDirectories.add(directory))
|
||||
this.reconnect()
|
||||
return
|
||||
}
|
||||
|
||||
const subscribedDirectories = directories.filter((directory) => this.directoryRefCounts.has(directory))
|
||||
if (subscribedDirectories.length === 0) return
|
||||
|
||||
this.notifyDirectoriesSubscribed(subscribedDirectories)
|
||||
}
|
||||
|
||||
private notifyDirectoriesSubscribed(directories: string[]): void {
|
||||
this.subscribers.forEach((subscriber) => {
|
||||
try {
|
||||
subscriber.onDirectoriesSubscribed?.(directories)
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private flushPendingDirectories(): void {
|
||||
|
||||
Reference in new issue
Block a user