|
| 1 | +import { renderHook, act, waitFor } from '@testing-library/react'; |
| 2 | +import { useBatchNotificationWatcher } from '@/hooks/useBatchNotificationWatcher'; |
| 3 | +import { batchesApi, tasksApi } from '@/lib/api'; |
| 4 | +import { getSelectedWorkspacePath } from '@/lib/workspace-storage'; |
| 5 | +import type { BatchListResponse, BatchResponse, Task } from '@/types'; |
| 6 | + |
| 7 | +jest.mock('@/lib/api'); |
| 8 | +jest.mock('@/lib/workspace-storage'); |
| 9 | + |
| 10 | +const mockList = batchesApi.list as jest.MockedFunction<typeof batchesApi.list>; |
| 11 | +const mockGetTask = tasksApi.getOne as jest.MockedFunction<typeof tasksApi.getOne>; |
| 12 | +const mockGetWorkspacePath = getSelectedWorkspacePath as jest.MockedFunction< |
| 13 | + typeof getSelectedWorkspacePath |
| 14 | +>; |
| 15 | + |
| 16 | +function batch(overrides: Partial<BatchResponse> = {}): BatchResponse { |
| 17 | + return { |
| 18 | + id: 'batch-1234abcd', |
| 19 | + workspace_id: 'ws-1', |
| 20 | + task_ids: ['t1'], |
| 21 | + status: 'RUNNING', |
| 22 | + strategy: 'serial', |
| 23 | + max_parallel: 1, |
| 24 | + on_failure: 'continue', |
| 25 | + started_at: null, |
| 26 | + completed_at: null, |
| 27 | + results: { t1: 'IN_PROGRESS' }, |
| 28 | + ...overrides, |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +function listResponse(batches: BatchResponse[]): BatchListResponse { |
| 33 | + return { batches, total: batches.length, by_status: {} }; |
| 34 | +} |
| 35 | + |
| 36 | +// Queue a sequence of list() responses, one per poll tick. |
| 37 | +function queueResponses(...responses: BatchListResponse[]) { |
| 38 | + mockList.mockReset(); |
| 39 | + responses.forEach((r) => mockList.mockResolvedValueOnce(r)); |
| 40 | + // Any further polls repeat the last response. |
| 41 | + if (responses.length > 0) { |
| 42 | + mockList.mockResolvedValue(responses[responses.length - 1]); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const INTERVAL = 1000; |
| 47 | + |
| 48 | +beforeEach(() => { |
| 49 | + jest.useFakeTimers(); |
| 50 | + jest.clearAllMocks(); |
| 51 | + mockGetWorkspacePath.mockReturnValue('/ws'); |
| 52 | + mockGetTask.mockResolvedValue({ id: 't1', title: 'Build login form' } as Task); |
| 53 | +}); |
| 54 | + |
| 55 | +afterEach(() => { |
| 56 | + jest.runOnlyPendingTimers(); |
| 57 | + jest.useRealTimers(); |
| 58 | +}); |
| 59 | + |
| 60 | +/** Run the immediate mount poll + flush its async work. */ |
| 61 | +async function flushPoll() { |
| 62 | + await act(async () => { |
| 63 | + await Promise.resolve(); |
| 64 | + await Promise.resolve(); |
| 65 | + }); |
| 66 | +} |
| 67 | + |
| 68 | +/** Advance one polling interval and flush async work. */ |
| 69 | +async function tick() { |
| 70 | + await act(async () => { |
| 71 | + jest.advanceTimersByTime(INTERVAL); |
| 72 | + await Promise.resolve(); |
| 73 | + await Promise.resolve(); |
| 74 | + }); |
| 75 | +} |
| 76 | + |
| 77 | +describe('useBatchNotificationWatcher', () => { |
| 78 | + it('does not notify for batches already terminal on the first poll (baseline)', async () => { |
| 79 | + const addNotification = jest.fn(); |
| 80 | + queueResponses(listResponse([batch({ status: 'COMPLETED', results: { t1: 'COMPLETED' } })])); |
| 81 | + |
| 82 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 83 | + await flushPoll(); |
| 84 | + |
| 85 | + expect(addNotification).not.toHaveBeenCalled(); |
| 86 | + }); |
| 87 | + |
| 88 | + it('fires batch.completed when a running batch transitions to a terminal state', async () => { |
| 89 | + const addNotification = jest.fn(); |
| 90 | + queueResponses( |
| 91 | + listResponse([batch({ status: 'RUNNING', results: { t1: 'IN_PROGRESS' } })]), |
| 92 | + listResponse([batch({ status: 'COMPLETED', results: { t1: 'COMPLETED' } })]) |
| 93 | + ); |
| 94 | + |
| 95 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 96 | + await flushPoll(); // baseline = RUNNING |
| 97 | + expect(addNotification).not.toHaveBeenCalled(); |
| 98 | + |
| 99 | + await tick(); // now COMPLETED |
| 100 | + |
| 101 | + expect(addNotification).toHaveBeenCalledTimes(1); |
| 102 | + expect(addNotification).toHaveBeenCalledWith( |
| 103 | + expect.objectContaining({ |
| 104 | + type: 'batch.completed', |
| 105 | + batchStatus: 'COMPLETED', |
| 106 | + batchId: 'batch-1234abcd', |
| 107 | + }) |
| 108 | + ); |
| 109 | + }); |
| 110 | + |
| 111 | + it('fires batch.completed only once across repeated polls', async () => { |
| 112 | + const addNotification = jest.fn(); |
| 113 | + queueResponses( |
| 114 | + listResponse([batch({ status: 'RUNNING', results: { t1: 'IN_PROGRESS' } })]), |
| 115 | + listResponse([batch({ status: 'FAILED', results: { t1: 'FAILED' } })]) |
| 116 | + ); |
| 117 | + |
| 118 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 119 | + await flushPoll(); |
| 120 | + await tick(); // FAILED |
| 121 | + await tick(); // still FAILED — must not re-fire |
| 122 | + |
| 123 | + expect(addNotification).toHaveBeenCalledTimes(1); |
| 124 | + expect(addNotification).toHaveBeenCalledWith( |
| 125 | + expect.objectContaining({ type: 'batch.completed', batchStatus: 'FAILED' }) |
| 126 | + ); |
| 127 | + }); |
| 128 | + |
| 129 | + it('fires blocker.created with the task title when a task transitions to BLOCKED', async () => { |
| 130 | + const addNotification = jest.fn(); |
| 131 | + queueResponses( |
| 132 | + listResponse([batch({ status: 'RUNNING', results: { t1: 'IN_PROGRESS' } })]), |
| 133 | + listResponse([batch({ status: 'RUNNING', results: { t1: 'BLOCKED' } })]) |
| 134 | + ); |
| 135 | + |
| 136 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 137 | + await flushPoll(); |
| 138 | + await tick(); |
| 139 | + |
| 140 | + await waitFor(() => |
| 141 | + expect(addNotification).toHaveBeenCalledWith( |
| 142 | + expect.objectContaining({ |
| 143 | + type: 'blocker.created', |
| 144 | + taskId: 't1', |
| 145 | + message: expect.stringContaining('Build login form'), |
| 146 | + }) |
| 147 | + ) |
| 148 | + ); |
| 149 | + }); |
| 150 | + |
| 151 | + it('does nothing when no workspace is selected', async () => { |
| 152 | + const addNotification = jest.fn(); |
| 153 | + mockGetWorkspacePath.mockReturnValue(null); |
| 154 | + queueResponses(listResponse([batch()])); |
| 155 | + |
| 156 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 157 | + await flushPoll(); |
| 158 | + |
| 159 | + expect(mockList).not.toHaveBeenCalled(); |
| 160 | + expect(addNotification).not.toHaveBeenCalled(); |
| 161 | + }); |
| 162 | + |
| 163 | + it('does not start an overlapping poll while one is still in flight', async () => { |
| 164 | + const addNotification = jest.fn(); |
| 165 | + // First list() never resolves during the test window — simulates a slow poll. |
| 166 | + let resolveSlow: (v: BatchListResponse) => void = () => {}; |
| 167 | + const slow = new Promise<BatchListResponse>((res) => { |
| 168 | + resolveSlow = res; |
| 169 | + }); |
| 170 | + mockList.mockReset(); |
| 171 | + mockList.mockReturnValueOnce(slow); |
| 172 | + mockList.mockResolvedValue(listResponse([batch()])); |
| 173 | + |
| 174 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 175 | + await flushPoll(); // immediate poll starts, awaiting `slow` |
| 176 | + await tick(); // interval fires but must be skipped (in-flight) |
| 177 | + await tick(); |
| 178 | + |
| 179 | + // Only the one still-pending call was made; no overlap. |
| 180 | + expect(mockList).toHaveBeenCalledTimes(1); |
| 181 | + |
| 182 | + // Let the slow poll finish; subsequent ticks resume normally. |
| 183 | + await act(async () => { |
| 184 | + resolveSlow(listResponse([batch()])); |
| 185 | + await Promise.resolve(); |
| 186 | + await Promise.resolve(); |
| 187 | + }); |
| 188 | + await tick(); |
| 189 | + expect(mockList.mock.calls.length).toBeGreaterThan(1); |
| 190 | + }); |
| 191 | + |
| 192 | + it('does not dispatch stale notifications when the workspace changes mid-poll', async () => { |
| 193 | + const addNotification = jest.fn(); |
| 194 | + // A slow poll for workspace /ws-a that resolves with a terminal transition. |
| 195 | + let resolveSlow: (v: BatchListResponse) => void = () => {}; |
| 196 | + const slow = new Promise<BatchListResponse>((res) => { |
| 197 | + resolveSlow = res; |
| 198 | + }); |
| 199 | + mockGetWorkspacePath.mockReturnValue('/ws-a'); |
| 200 | + mockList.mockReset(); |
| 201 | + // First poll (baseline) sees RUNNING; second poll returns the slow promise. |
| 202 | + mockList.mockResolvedValueOnce( |
| 203 | + listResponse([batch({ status: 'RUNNING', results: { t1: 'IN_PROGRESS' } })]) |
| 204 | + ); |
| 205 | + mockList.mockReturnValueOnce(slow); |
| 206 | + mockList.mockResolvedValue(listResponse([batch()])); |
| 207 | + |
| 208 | + renderHook(() => useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL })); |
| 209 | + await flushPoll(); // baseline RUNNING for /ws-a |
| 210 | + await tick(); // second poll starts, awaiting `slow` |
| 211 | + |
| 212 | + // Workspace switches away before the slow poll resolves. |
| 213 | + mockGetWorkspacePath.mockReturnValue('/ws-b'); |
| 214 | + await act(async () => { |
| 215 | + resolveSlow(listResponse([batch({ status: 'COMPLETED', results: { t1: 'COMPLETED' } })])); |
| 216 | + await Promise.resolve(); |
| 217 | + await Promise.resolve(); |
| 218 | + }); |
| 219 | + |
| 220 | + // The terminal transition belongs to /ws-a, which is no longer active. |
| 221 | + expect(addNotification).not.toHaveBeenCalled(); |
| 222 | + }); |
| 223 | + |
| 224 | + it('stops polling after unmount', async () => { |
| 225 | + const addNotification = jest.fn(); |
| 226 | + queueResponses(listResponse([batch()])); |
| 227 | + |
| 228 | + const { unmount } = renderHook(() => |
| 229 | + useBatchNotificationWatcher(addNotification, { intervalMs: INTERVAL }) |
| 230 | + ); |
| 231 | + await flushPoll(); |
| 232 | + const callsBefore = mockList.mock.calls.length; |
| 233 | + |
| 234 | + unmount(); |
| 235 | + await tick(); |
| 236 | + |
| 237 | + expect(mockList.mock.calls.length).toBe(callsBefore); |
| 238 | + }); |
| 239 | +}); |
0 commit comments