From 37b4ab89f067b29d715ddd60c92f1d082abd0a91 Mon Sep 17 00:00:00 2001 From: Chris Scott <> Date: Thu, 15 Oct 2026 13:00:08 +0000 Subject: [PATCH] fix(background-activity): reconcile shells for directories subscribed by the stream The background activity indicator went stale for sessions living in a directory that is not a registered repo. Running shells were only synced for repo directories derived from the repos query, so session directories subscribed over the event stream were never reconciled, leaving the indicator visible after the shell had exited. Report the directories actually subscribed (mid-connection updates and pending directories flushed after connect) from the event stream through onDirectoriesSubscribed, and reconcile running shells and pending permissions/forms for them in the event context. --- e2e/background-activity.spec.ts | 80 +++++++++++++++++++ frontend/src/contexts/EventContext.test.tsx | 65 ++++++++++++++- frontend/src/contexts/EventContext.tsx | 17 ++-- .../__tests__/openCodeEventStream.test.ts | 56 +++++++++++++ .../openCodeEventStream.ts | 43 ++++++---- 5 files changed, 232 insertions(+), 29 deletions(-) diff --git a/e2e/background-activity.spec.ts b/e2e/background-activity.spec.ts index ddd6d44a..1e4f6be6 100644 --- a/e2e/background-activity.spec.ts +++ b/e2e/background-activity.spec.ts @@ -1,5 +1,9 @@ +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' import type { APIRequestContext, Page } from '@playwright/test' import { test, expect } from './fixtures' +import { E2E_TMP } from './env' const SHELL_COMMAND = 'sleep 300' @@ -54,12 +58,38 @@ async function removeShell(request: APIRequestContext, directory: string, shellI } const createdShells: Array<{ directory: string; id: string }> = [] +const createdDirectories: string[] = [] +let directoryCounter = 0 + +function createUnregisteredDirectory(name: string): string { + directoryCounter += 1 + const directory = path.join(E2E_TMP, `background-${name}-${process.pid}-${directoryCounter}`) + fs.mkdirSync(directory, { recursive: true }) + fs.writeFileSync(path.join(directory, 'README.md'), '# background activity fixture\n') + + const git = (...args: string[]) => execFileSync('git', args, { cwd: directory, stdio: 'pipe' }) + git('-c', 'init.defaultBranch=main', 'init', '-q') + git('-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'add', '-A') + git('-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'commit', '-q', '-m', 'init') + + createdDirectories.push(directory) + return directory +} + +async function navigateWithinApp(page: Page, url: string): Promise { + await page.evaluate((target) => { + window.history.pushState({}, '', target) + window.dispatchEvent(new PopStateEvent('popstate')) + }, url) +} test.afterEach(async ({ request }) => { const shells = createdShells.splice(0) const results = await Promise.allSettled(shells.map(({ directory, id }) => removeShell(request, directory, id))) const failures = results.flatMap((result) => (result.status === 'rejected' ? [String(result.reason)] : [])) expect(failures, 'background shell cleanup failed').toEqual([]) + + createdDirectories.splice(0).forEach((directory) => fs.rmSync(directory, { recursive: true, force: true })) }) test.describe('session background activity', () => { @@ -138,4 +168,54 @@ test.describe('session background activity', () => { await expect(backgroundIndicator(page)).toHaveCount(0) await expect(backgroundStatus(page)).toHaveCount(0) }) + + test('shows the indicator for a shell started in an unregistered session directory before page load', async ({ + page, + request, + repo, + }) => { + const directory = createUnregisteredDirectory('preload') + const sessionId = await createSession(request, directory) + const shellId = await startBackgroundShell(request, directory, sessionId) + createdShells.push({ directory, id: shellId }) + + await page.goto(`/repos/${repo.id}/sessions/${sessionId}`) + await expect(page.getByPlaceholder('Send a message...')).toBeVisible() + + await expect(backgroundIndicator(page)).toBeVisible() + + await removeShell(request, directory, shellId) + + await expect(backgroundIndicator(page)).toBeHidden() + }) + + test('clears the indicator for a shell that exits while an unregistered session directory is unsubscribed', async ({ + page, + request, + repo, + }) => { + const directory = createUnregisteredDirectory('stale') + const sessionId = await createSession(request, directory) + const subscribed = page.waitForResponse((response) => + response.url().includes('/api/sse/subscribe') && (response.request().postData() ?? '').includes(directory), + ) + + await page.goto(`/repos/${repo.id}/sessions/${sessionId}`) + await expect(page.getByPlaceholder('Send a message...')).toBeVisible() + await subscribed + + const shellId = await startBackgroundShell(request, directory, sessionId) + createdShells.push({ directory, id: shellId }) + + await expect(backgroundIndicator(page)).toBeVisible() + + await navigateWithinApp(page, '/') + await page.waitForTimeout(3_000) + await removeShell(request, directory, shellId) + await page.waitForTimeout(3_000) + await navigateWithinApp(page, `/repos/${repo.id}/sessions/${sessionId}`) + + await expect(page.getByPlaceholder('Send a message...')).toBeVisible() + await expect(backgroundIndicator(page)).toBeHidden({ timeout: 20_000 }) + }) }) diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index e8b93176..d3d2ee7a 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -1865,11 +1865,18 @@ describe('EventProvider permissions and forms', () => { render(, { 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' }) }) @@ -1889,11 +1896,18 @@ describe('EventProvider permissions and forms', () => { render(, { 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', @@ -1913,7 +1927,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' } }, @@ -1926,6 +1940,15 @@ describe('EventProvider permissions and forms', () => { render(, { 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') }) @@ -1967,6 +1990,12 @@ describe('EventProvider permissions and forms', () => { it('syncs running shells for a directory whose repo arrives after connect', async () => { const reposDeferred = createDeferred>() 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(, { wrapper: createWrapper() }) @@ -1988,4 +2017,34 @@ 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(, { 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') + }) }) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 30745182..e8db0e53 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -206,7 +206,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const statusPollIntervalRef = useRef | null>(null) const subscriptionRef = useRef | null>(null) const reposRef = useRef(null) - const trackedRepoDirectoriesRef = useRef>(new Set()) const ancestryInFlightRef = useRef>(new Set()) const { data: repos } = useQuery({ @@ -725,6 +724,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 @@ -739,16 +742,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 diff --git a/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts b/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts index 5d41f0bf..20255f7b 100644 --- a/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts +++ b/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts @@ -2,6 +2,13 @@ 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 { + this.posts.push({ path, body }) + return false + } +} + describe('OpenCodeEventStream', () => { beforeEach(() => { vi.useFakeTimers() @@ -186,4 +193,53 @@ 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() + }) }) diff --git a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts index 715f058a..8846f1df 100644 --- a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts +++ b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts @@ -15,9 +15,19 @@ interface Subscriber { onStatusChange?: EventStreamStatusHandler onHealthChange?: (state: EventStreamHealthState) => void onResync?: () => void + onDirectoriesSubscribed?: (directories: string[]) => void directories: Set } +interface SubscriberInput { + onEvent: OpenCodeEventHandler + onStatusChange?: EventStreamStatusHandler + onHealthChange?: (state: EventStreamHealthState) => void + directories: string[] + onResync?: () => 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, }) @@ -430,7 +430,20 @@ export class OpenCodeEventStream { if (!success) { directories.forEach((directory) => this.pendingDirectories.add(directory)) this.reconnect() + return } + + this.notifyDirectoriesSubscribed(directories) + } + + private notifyDirectoriesSubscribed(directories: string[]): void { + this.subscribers.forEach((subscriber) => { + try { + subscriber.onDirectoriesSubscribed?.(directories) + } catch { + void 0 + } + }) } private flushPendingDirectories(): void {