diff --git a/src/main/runtime/rpc/methods/files.test.ts b/src/main/runtime/rpc/methods/files.test.ts index 701871033..9d91ca093 100644 --- a/src/main/runtime/rpc/methods/files.test.ts +++ b/src/main/runtime/rpc/methods/files.test.ts @@ -194,6 +194,53 @@ describe('file RPC methods', () => { expect(replies).toEqual([]) }) + it('drops queued file watch events when aborted before setup resolves', async () => { + vi.useFakeTimers() + try { + type WatchCallback = ( + events: { kind: 'update'; absolutePath: string; isDirectory?: boolean }[] + ) => void + const unwatch = vi.fn() + let resolveWatch: (value: () => void) => void = () => {} + const watchFileExplorer = vi.fn((_worktree: string, callback: WatchCallback) => { + callback([{ kind: 'update', absolutePath: '/repo/queued.ts', isDirectory: false }]) + return new Promise<() => void>((resolve) => { + resolveWatch = resolve + }) + }) + const runtime = { + getRuntimeId: () => 'test-runtime', + watchFileExplorer, + registerSubscriptionCleanup: vi.fn() + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: FILE_METHODS }) + const abortController = new AbortController() + const replies: unknown[] = [] + + const dispatch = dispatcher.dispatchStreaming( + makeRequest('files.watch', { worktree: 'id:wt-1' }), + (response) => replies.push(JSON.parse(response)), + { connectionId: 'conn-1', signal: abortController.signal } + ) + await vi.waitFor(() => { + expect(watchFileExplorer).toHaveBeenCalled() + }) + + abortController.abort() + await dispatch + await vi.runOnlyPendingTimersAsync() + resolveWatch(unwatch) + await vi.waitFor(() => { + expect(unwatch).toHaveBeenCalled() + }) + + expect(runtime.registerSubscriptionCleanup).not.toHaveBeenCalled() + expect(replies).toEqual([]) + } finally { + vi.useRealTimers() + } + }) + it('reads a relative file path for a selected worktree', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/files.ts b/src/main/runtime/rpc/methods/files.ts index b4ba19db6..520a48cdf 100644 --- a/src/main/runtime/rpc/methods/files.ts +++ b/src/main/runtime/rpc/methods/files.ts @@ -300,6 +300,9 @@ export const FILE_METHODS: RpcAnyMethod[] = [ if (unwatch) { cleanup() } else { + // Why: watch setup may have queued events before resolving its + // unwatch callback. Dispose that transient batcher on early abort. + eventBatcher.dispose() finish() } } @@ -313,6 +316,7 @@ export const FILE_METHODS: RpcAnyMethod[] = [ // Why: the connection can close while watch setup is still // resolving. Tear down the late watcher immediately instead of // registering cleanup on a connection that was already reaped. + eventBatcher.dispose() nextUnwatch() return }