| 198 | }; |
| 199 | |
| 200 | const connect = async (): Promise<void> => { |
| 201 | if (stopped) { |
| 202 | return; |
| 203 | } |
| 204 | controller = new AbortController(); |
| 205 | const url = `/api/agent-events?project=${encodeURIComponent(project)}&after=${cursor.current}&limit=200`; |
| 206 | requests.current += 1; |
| 207 | if (cursor.current === 0) announce({ state: 'connecting', error: '' }); |
| 208 | try { |
| 209 | const response = await doFetch(url, { signal: controller.signal }); |
| 210 | if (!response.ok) throw new Error(`daemon activity: HTTP ${response.status}`); |
| 211 | const page = await response.json() as { |
| 212 | events: unknown[]; cursor: number; generation: string; reset: boolean; |
| 213 | has_more: boolean; truncated: boolean; retained: number; |
| 214 | }; |
| 215 | if (!Array.isArray(page.events) || !Number.isSafeInteger(page.cursor) |
| 216 | || page.cursor < 0 || typeof page.generation !== 'string') { |
| 217 | throw new Error('Invalid daemon activity response'); |
| 218 | } |
| 219 | if (stopped) return; |
| 220 | if (page.reset || (generation.current !== undefined && generation.current !== page.generation)) { |
| 221 | stateRef.current = emptyAgentsState(); |
| 222 | cursor.current = 0; |
| 223 | incomplete.current = false; |
| 224 | generation.current = page.generation; |
| 225 | setReading({ project, value: stateRef.current }); |
| 226 | timer = setTimeout(() => void connect(), 0); |
| 227 | return; |
| 228 | } |
| 229 | generation.current = page.generation; |
| 230 | let next = stateRef.current; |
| 231 | for (const raw of page.events) { |
| 232 | const event = readAgentEvent(raw); |
| 233 | if (event !== undefined) next = withEvent(next, event); |
| 234 | else next = { ...next, unreadable: next.unreadable + 1 }; |
| 235 | } |
| 236 | stateRef.current = next; |
| 237 | cursor.current = page.cursor; |
| 238 | incomplete.current ||= page.truncated; |
| 239 | setReading({ project, value: next }); |
| 240 | announce({ state: 'connected', error: incomplete.current |
| 241 | ? 'Older activity expired from local retention; this history is incomplete.' : '', |
| 242 | hello: { mode: 'live', file: 'daemon SQLite activity', events: page.retained, unreadable: next.unreadable } }); |
| 243 | timer = setTimeout(() => void connect(), page.has_more ? 0 : POLL_MS); |
| 244 | } catch (failure) { |
| 245 | if (stopped) return; |
| 246 | drops.current += 1; |
| 247 | announce({ state: 'no-source', error: failure instanceof Error ? failure.message : String(failure) }); |
| 248 | timer = setTimeout(() => void connect(), RECONNECT_MS); |
| 249 | } |
| 250 | }; |
| 251 | |
| 252 | void connect(); |
| 253 | return () => { |