File size: 28,164 Bytes
bdbcdab
571b292
 
854c261
 
723c24c
 
 
bdbcdab
 
 
571b292
 
bdbcdab
7e62dfa
bdbcdab
 
 
 
 
 
 
854c261
 
bdbcdab
 
 
 
 
854c261
bdbcdab
 
 
854c261
 
 
723c24c
bdbcdab
723c24c
 
bdbcdab
854c261
bdbcdab
 
 
723c24c
854c261
723c24c
854c261
723c24c
bdbcdab
 
 
723c24c
854c261
723c24c
854c261
bdbcdab
 
723c24c
854c261
723c24c
854c261
bdbcdab
 
 
723c24c
 
 
 
bdbcdab
 
723c24c
bdbcdab
 
723c24c
bdbcdab
 
854c261
bdbcdab
 
723c24c
 
 
 
bdbcdab
 
 
8d40f7c
472f63c
 
8d40f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472f63c
 
 
723c24c
 
bdbcdab
723c24c
 
bdbcdab
723c24c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdbcdab
 
 
723c24c
bdbcdab
 
 
 
 
 
 
854c261
 
723c24c
 
 
bdbcdab
 
 
723c24c
bdbcdab
723c24c
 
 
 
 
 
 
 
 
bdbcdab
 
723c24c
 
 
 
 
 
 
bdbcdab
723c24c
 
 
 
 
 
 
bdbcdab
723c24c
bdbcdab
723c24c
 
 
 
bdbcdab
 
 
723c24c
 
 
 
 
 
 
 
 
 
 
 
bdbcdab
723c24c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdbcdab
 
 
 
723c24c
bdbcdab
723c24c
 
 
 
 
 
 
 
 
 
bdbcdab
 
 
723c24c
bdbcdab
78f0201
472f63c
 
 
8d40f7c
 
 
 
 
472f63c
bdbcdab
d2c1b12
bdbcdab
 
 
 
 
854c261
571b292
bdbcdab
571b292
bdbcdab
 
571b292
bdbcdab
 
 
 
854c261
 
 
 
 
 
 
 
 
bdbcdab
854c261
bdbcdab
 
 
854c261
bdbcdab
 
 
 
 
854c261
bdbcdab
854c261
bdbcdab
 
 
1416398
 
 
 
571b292
 
 
 
bdbcdab
 
723c24c
854c261
723c24c
854c261
bdbcdab
 
 
 
 
 
 
854c261
7e62dfa
 
854c261
 
 
 
 
 
 
 
 
1416398
854c261
 
1416398
854c261
 
 
 
 
 
 
 
7e62dfa
854c261
 
 
 
d95f6cc
854c261
 
 
 
 
1416398
 
 
 
 
 
 
 
 
 
854c261
 
 
 
7e62dfa
 
 
c88804e
 
 
 
 
 
 
 
 
 
 
00a57cd
c88804e
 
00a57cd
 
 
 
 
c88804e
00a57cd
c88804e
00a57cd
 
c88804e
 
 
 
 
 
 
 
 
00a57cd
c88804e
 
 
 
 
00a57cd
c88804e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00a57cd
c88804e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d95f6cc
c88804e
 
 
 
 
 
 
 
 
 
 
 
 
d95f6cc
c88804e
 
 
 
 
 
 
 
 
00a57cd
 
c88804e
00a57cd
 
c88804e
 
 
 
 
 
 
 
 
d95f6cc
c88804e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d95f6cc
 
 
 
c88804e
 
d95f6cc
 
c88804e
 
 
 
 
 
 
 
 
00a57cd
c88804e
 
 
 
00a57cd
 
854c261
bdbcdab
 
854c261
bdbcdab
 
 
d95f6cc
bdbcdab
 
571b292
 
 
 
bdbcdab
 
 
 
 
571b292
 
 
 
 
 
 
 
 
 
 
 
 
bdbcdab
723c24c
bdbcdab
 
 
723c24c
bdbcdab
571b292
bdbcdab
 
571b292
 
 
 
 
 
f0c7e64
571b292
f0c7e64
 
 
 
 
 
 
 
571b292
 
723c24c
 
 
571b292
bdbcdab
723c24c
bdbcdab
 
d2c1b12
571b292
d2c1b12
 
 
 
571b292
d2c1b12
571b292
6d4d388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdbcdab
 
 
571b292
bdbcdab
 
6d4d388
bdbcdab
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/**
 * Central hook wiring the Vercel AI SDK's useChat with our SSE-based
 * ChatTransport.
 *
 * In the per-session architecture, each session mounts its own instance
 * of this hook. Side-channel callbacks always update the session's own
 * state via `updateSession()`. If the session is currently active, the
 * store automatically mirrors updates to the flat global fields.
 */
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useChat } from '@ai-sdk/react';
import { type UIMessage, lastAssistantMessageIsCompleteWithApprovalResponses } from 'ai';
import { SSEChatTransport, type SideChannelCallbacks } from '@/lib/sse-chat-transport';
import { loadMessages, saveMessages } from '@/lib/chat-message-store';
import { llmMessagesToUIMessages } from '@/lib/convert-llm-messages';
import { apiFetch } from '@/utils/api';
import { useAgentStore } from '@/store/agentStore';
import { useSessionStore } from '@/store/sessionStore';
import { useLayoutStore } from '@/store/layoutStore';
import { logger } from '@/utils/logger';

interface UseAgentChatOptions {
  sessionId: string;
  isActive: boolean;
  onReady?: () => void;
  onError?: (error: string) => void;
  onSessionDead?: (sessionId: string) => void;
}

export function useAgentChat({ sessionId, isActive, onReady, onError, onSessionDead }: UseAgentChatOptions) {
  const callbacksRef = useRef({ onReady, onError, onSessionDead });
  callbacksRef.current = { onReady, onError, onSessionDead };

  const isActiveRef = useRef(isActive);
  isActiveRef.current = isActive;

  const { setNeedsAttention } = useSessionStore();

  // Helper: update this session's state (mirrors to globals if active)
  const updateSession = useAgentStore.getState().updateSession;

  // -- Build side-channel callbacks (stable ref) --------------------------
  const sideChannel = useMemo<SideChannelCallbacks>(
    () => ({
      onReady: () => {
        updateSession(sessionId, { isProcessing: false });
        if (isActiveRef.current) {
          useAgentStore.getState().setConnected(true);
        }
        useSessionStore.getState().setSessionActive(sessionId, true);
        callbacksRef.current.onReady?.();
      },
      onShutdown: () => {
        updateSession(sessionId, { isProcessing: false });
        if (isActiveRef.current) {
          useAgentStore.getState().setConnected(false);
        }
      },
      onError: (error: string) => {
        updateSession(sessionId, { isProcessing: false });
        if (isActiveRef.current) {
          useAgentStore.getState().setError(error);
        }
        callbacksRef.current.onError?.(error);
      },
      onProcessing: () => {
        updateSession(sessionId, {
          isProcessing: true,
          activityStatus: { type: 'thinking' },
        });
      },
      onProcessingDone: () => {
        updateSession(sessionId, { isProcessing: false });
      },
      onUndoComplete: () => {
        updateSession(sessionId, { isProcessing: false });
      },
      onCompacted: (oldTokens: number, newTokens: number) => {
        logger.log(`Context compacted: ${oldTokens} -> ${newTokens} tokens`);
      },
      onPlanUpdate: (plan) => {
        const typed = plan as Array<{ id: string; content: string; status: 'pending' | 'in_progress' | 'completed' }>;
        updateSession(sessionId, { plan: typed });
        if (isActiveRef.current && !useLayoutStore.getState().isRightPanelOpen) {
          useLayoutStore.getState().setRightPanelOpen(true);
        }
      },
      onToolLog: (tool: string, log: string) => {
        // Research sub-agent: parse stats vs step logs
        if (tool === 'research') {
          const sessState = useAgentStore.getState().getSessionState(sessionId);
          const stats = { ...sessState.researchStats };

          if (log === 'Starting research sub-agent...') {
            updateSession(sessionId, {
              researchSteps: [],
              researchStats: { toolCount: 0, tokenCount: 0, startedAt: Date.now(), finalElapsed: null },
              activityStatus: { type: 'tool', toolName: 'research', description: log },
            });
          } else if (log.startsWith('tokens:')) {
            stats.tokenCount = parseInt(log.slice(7), 10);
            updateSession(sessionId, { researchStats: stats });
          } else if (log.startsWith('tools:')) {
            stats.toolCount = parseInt(log.slice(6), 10);
            updateSession(sessionId, { researchStats: stats });
          } else if (log === 'Research complete.') {
            const elapsed = stats.startedAt
              ? Math.round((Date.now() - stats.startedAt) / 1000)
              : null;
            updateSession(sessionId, {
              researchStats: { ...stats, startedAt: null, finalElapsed: elapsed },
              activityStatus: { type: 'tool', toolName: 'research', description: log },
            });
          } else {
            // Regular tool call step — append
            const steps = [...sessState.researchSteps, log];
            updateSession(sessionId, {
              researchSteps: steps,
              activityStatus: { type: 'tool', toolName: 'research', description: log },
            });
          }
          return;
        }

        const STREAMABLE_TOOLS = new Set(['hf_jobs', 'sandbox', 'bash']);
        if (!STREAMABLE_TOOLS.has(tool)) return;

        const sessState = useAgentStore.getState().getSessionState(sessionId);
        const existingOutput = sessState.panelData?.output?.content || '';

        const newContent = existingOutput
          ? existingOutput + '\n' + log
          : log;

        if (!sessState.panelData) {
          const title = tool === 'bash' ? 'Sandbox' : tool === 'sandbox' ? 'Sandbox' : 'Job Output';
          updateSession(sessionId, {
            panelData: { title, output: { content: newContent, language: 'text' } },
            panelView: 'output',
          });
        } else {
          updateSession(sessionId, {
            panelData: { ...sessState.panelData, output: { content: newContent, language: 'text' } },
            panelView: 'output',
          });
        }

        if (isActiveRef.current && !useLayoutStore.getState().isRightPanelOpen) {
          useLayoutStore.getState().setRightPanelOpen(true);
        }
      },
      onConnectionChange: (connected: boolean) => {
        if (isActiveRef.current) useAgentStore.getState().setConnected(connected);
      },
      onSessionDead: (deadSessionId: string) => {
        logger.warn(`Session ${deadSessionId} dead, removing`);
        callbacksRef.current.onSessionDead?.(deadSessionId);
      },
      onApprovalRequired: (tools) => {
        if (!tools.length) return;
        setNeedsAttention(sessionId, true);

        updateSession(sessionId, { activityStatus: { type: 'waiting-approval' } });

        // Build panel data for this session's pending approval
        const firstTool = tools[0];
        const args = firstTool.arguments as Record<string, string | undefined>;

        let panelUpdate: Partial<import('@/store/agentStore').PerSessionState> | undefined;
        if (firstTool.tool === 'hf_jobs' && args.script) {
          panelUpdate = {
            panelData: {
              title: 'Script',
              script: { content: args.script, language: 'python' },
              parameters: firstTool.arguments as Record<string, unknown>,
            },
            panelView: 'script' as const,
            panelEditable: true,
          };
        } else if (firstTool.tool === 'hf_repo_files' && args.content) {
          const filename = args.path || 'file';
          panelUpdate = {
            panelData: {
              title: filename.split('/').pop() || 'Content',
              script: { content: args.content, language: filename.endsWith('.py') ? 'python' : 'text' },
              parameters: firstTool.arguments as Record<string, unknown>,
            },
          };
        } else {
          panelUpdate = {
            panelData: {
              title: firstTool.tool,
              output: { content: JSON.stringify(firstTool.arguments, null, 2), language: 'json' },
            },
            panelView: 'output' as const,
          };
        }
        if (panelUpdate) updateSession(sessionId, panelUpdate);

        if (isActiveRef.current) {
          useLayoutStore.getState().setRightPanelOpen(true);
          useLayoutStore.getState().setLeftSidebarOpen(false);
        }
      },
      onToolCallPanel: (toolName: string, args: Record<string, unknown>) => {
        if (toolName === 'hf_jobs' && args.operation && args.script) {
          updateSession(sessionId, {
            panelData: {
              title: 'Script',
              script: { content: String(args.script), language: 'python' },
              parameters: args,
            },
            panelView: 'script',
          });
          if (isActiveRef.current) {
            useLayoutStore.getState().setRightPanelOpen(true);
            useLayoutStore.getState().setLeftSidebarOpen(false);
          }
        } else if (toolName === 'hf_repo_files' && args.operation === 'upload' && args.content) {
          updateSession(sessionId, {
            panelData: {
              title: `File Upload: ${String(args.path || 'unnamed')}`,
              script: { content: String(args.content), language: String(args.path || '').endsWith('.py') ? 'python' : 'text' },
              parameters: args,
            },
          });
          if (isActiveRef.current) {
            useLayoutStore.getState().setRightPanelOpen(true);
            useLayoutStore.getState().setLeftSidebarOpen(false);
          }
        } else if (toolName === 'bash' && args.command) {
          updateSession(sessionId, {
            panelData: {
              title: 'Sandbox',
              script: { content: String(args.command), language: 'bash' },
            },
            panelView: 'output',
          });
        }
      },
      onToolOutputPanel: (toolName: string, _toolCallId: string, output: string, success: boolean) => {
        const sessState = useAgentStore.getState().getSessionState(sessionId);
        if (toolName === 'hf_jobs' && output) {
          updateSession(sessionId, {
            panelData: sessState.panelData
              ? { ...sessState.panelData, output: { content: output, language: 'markdown' } }
              : { title: 'Output', output: { content: output, language: 'markdown' } },
            panelView: !success ? 'output' : sessState.panelView,
          });
        } else if (toolName === 'bash') {
          if (!success) {
            updateSession(sessionId, { panelView: 'output' });
          }
        }
      },
      onStreaming: () => {
        updateSession(sessionId, { activityStatus: { type: 'streaming' } });
      },
      onToolRunning: (toolName: string, description?: string) => {
        const updates: Partial<import('@/store/agentStore').PerSessionState> = {
          activityStatus: { type: 'tool', toolName, description },
        };
        // Clear research steps + stats when a new research call starts
        if (toolName === 'research') {
          updates.researchSteps = [];
          updates.researchStats = { toolCount: 0, tokenCount: 0, startedAt: null, finalElapsed: null };
        }
        updateSession(sessionId, updates);
      },
      onInterrupted: () => { /* no-op — handled by stop() caller */ },
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [sessionId],
  );

  // -- Create transport (one per session, stable for lifetime) ------------
  const transportRef = useRef<SSEChatTransport | null>(null);
  if (!transportRef.current) {
    transportRef.current = new SSEChatTransport(sessionId, sideChannel);
  }

  // Keep side-channel callbacks in sync
  useEffect(() => {
    transportRef.current?.updateSideChannel(sideChannel);
  }, [sideChannel]);

  // Destroy transport on unmount
  useEffect(() => {
    return () => {
      transportRef.current?.destroy();
      transportRef.current = null;
    };
  }, []);

  // -- Restore persisted messages for this session ------------------------
  const initialMessages = useMemo(
    () => loadMessages(sessionId),
    [sessionId],
  );

  // -- Ref for chat actions (used by sideChannel callbacks) ---------------
  const chatActionsRef = useRef<{
    setMessages: ((msgs: UIMessage[]) => void) | null;
    messages: UIMessage[];
  }>({ setMessages: null, messages: [] });

  // -- useChat from Vercel AI SDK -----------------------------------------
  const chat = useChat({
    id: sessionId,
    messages: initialMessages,
    transport: transportRef.current!,
    experimental_throttle: 80,
    // On mount, the SDK calls transport.reconnectToStream() which checks
    // is_processing and subscribes to the live event stream if the agent
    // is mid-turn.  Without this, page refresh kills live updates.
    resume: true,
    // After all approval responses are set, auto-send to continue the agent loop.
    // Without this, addToolApprovalResponse only updates the UI — it won't trigger
    // sendMessages on the transport.
    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
    onError: (error) => {
      logger.error('useChat error:', error);
      updateSession(sessionId, { isProcessing: false });
      if (isActiveRef.current) {
        useAgentStore.getState().setError(error.message);
      }
    },
  });

  // Keep chatActionsRef in sync every render
  chatActionsRef.current.setMessages = chat.setMessages;
  chatActionsRef.current.messages = chat.messages;

  // -- Hydrate from backend on mount (page refresh recovery) --------------
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [msgsRes, infoRes] = await Promise.all([
          apiFetch(`/api/session/${sessionId}/messages`),
          apiFetch(`/api/session/${sessionId}`),
        ]);
        if (cancelled) return;

        let pendingIds: Set<string> | undefined;
        let backendIsProcessing = false;
        if (infoRes.ok) {
          const info = await infoRes.json();
          backendIsProcessing = !!info.is_processing;
          if (info.pending_approval && Array.isArray(info.pending_approval)) {
            pendingIds = new Set(
              info.pending_approval.map((t: { tool_call_id: string }) => t.tool_call_id)
            );
            if (pendingIds.size > 0) {
              setNeedsAttention(sessionId, true);
            }
          }
        }

        if (msgsRes.ok) {
          const data = await msgsRes.json();
          if (cancelled || !Array.isArray(data) || data.length === 0) return;
          const uiMsgs = llmMessagesToUIMessages(data, pendingIds, chatActionsRef.current.messages);
          if (uiMsgs.length > 0) {
            chat.setMessages(uiMsgs);
            saveMessages(sessionId, uiMsgs);
          }
        }

        // Use the backend's is_processing flag as the source of truth.
        // Message-based inference doesn't work because completed tool
        // results make tools look "done" even when the agent is still
        // mid-turn and about to call more tools.
        if (backendIsProcessing) {
          updateSession(sessionId, { isProcessing: true, activityStatus: { type: 'thinking' } });
        } else if (pendingIds && pendingIds.size > 0) {
          updateSession(sessionId, { activityStatus: { type: 'waiting-approval' } });
        }
      } catch {
        /* backend unreachable -- localStorage fallback is fine */
      }
    })();
    return () => { cancelled = true; };
  }, [sessionId]); // eslint-disable-line react-hooks/exhaustive-deps

  // -- Re-hydrate + reconnect on wake from sleep ----------------------------
  // The Vercel AI SDK only calls reconnectToStream() on mount, NOT on
  // visibility change.  So when the browser wakes from sleep and the SSE
  // stream is dead, we must manually:
  //   1. Re-hydrate messages (one-shot fetch from backend)
  //   2. Subscribe to live events via GET /api/events/{sessionId}
  //   3. Pipe those events through the side-channel callbacks for real-time UI
  //   4. Poll messages every few seconds so chat.setMessages stays in sync
  const reconnectAbortRef = useRef<AbortController | null>(null);
  const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    /** Fetch latest messages from backend and push into the SDK. */
    const hydrateMessages = async () => {
      try {
        const [msgsRes, infoRes] = await Promise.all([
          apiFetch(`/api/session/${sessionId}/messages`),
          apiFetch(`/api/session/${sessionId}`),
        ]);
        if (!msgsRes.ok) return null;
        const data = await msgsRes.json();
        if (!Array.isArray(data) || data.length === 0) return null;

        let pendingIds: Set<string> | undefined;
        if (infoRes.ok) {
          const info = await infoRes.json();
          if (info.pending_approval && Array.isArray(info.pending_approval)) {
            pendingIds = new Set(
              info.pending_approval.map((t: { tool_call_id: string }) => t.tool_call_id)
            );
            if (pendingIds.size > 0) setNeedsAttention(sessionId, true);
          }
          return { data, pendingIds, info };
        }
        return { data, pendingIds, info: null };
      } catch {
        return null;
      }
    };

    /** Stop any running reconnection (event stream + poll). */
    const stopReconnect = () => {
      reconnectAbortRef.current?.abort();
      reconnectAbortRef.current = null;
      if (pollTimerRef.current) {
        clearInterval(pollTimerRef.current);
        pollTimerRef.current = null;
      }
    };

    /** Read the event stream from GET /api/events and forward to side-channel. */
    const consumeEventStream = async (signal: AbortSignal) => {
      try {
        const res = await apiFetch(`/api/events/${sessionId}`, {
          headers: { 'Accept': 'text/event-stream' },
          signal,
        });
        if (!res.ok || !res.body) return;

        const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
        let buf = '';
        while (true) {
          const { value, done } = await reader.read();
          if (done || signal.aborted) break;
          buf += value;
          const lines = buf.split('\n');
          buf = lines.pop() || '';
          for (const line of lines) {
            const trimmed = line.trim();
            if (!trimmed.startsWith('data: ')) continue;
            try {
              const event = JSON.parse(trimmed.slice(6));
              // Forward to side-channel for real-time UI updates
              const et = event.event_type as string;
              if (et === 'processing') sideChannel.onProcessing();
              else if (et === 'assistant_chunk') sideChannel.onStreaming();
              else if (et === 'tool_call') {
                const t = event.data?.tool as string;
                const d = event.data?.arguments?.description as string | undefined;
                sideChannel.onToolRunning(t, d);
                sideChannel.onToolCallPanel(t, (event.data?.arguments || {}) as Record<string, unknown>);
              } else if (et === 'tool_output') {
                sideChannel.onToolOutputPanel(
                  event.data?.tool as string,
                  event.data?.tool_call_id as string,
                  event.data?.output as string,
                  event.data?.success as boolean,
                );
              } else if (et === 'tool_state_change') {
                const state = event.data?.state as string;
                const toolName = event.data?.tool as string;
                if (state === 'running' && toolName) sideChannel.onToolRunning(toolName);
              } else if (et === 'turn_complete' || et === 'error' || et === 'interrupted') {
                sideChannel.onProcessingDone();
                stopReconnect();
                // Final hydration to get the complete message state
                const result = await hydrateMessages();
                if (result) {
                  const uiMsgs = llmMessagesToUIMessages(result.data, result.pendingIds, chatActionsRef.current.messages);
                  if (uiMsgs.length > 0) {
                    chat.setMessages(uiMsgs);
                    saveMessages(sessionId, uiMsgs);
                  }
                }
                return;
              } else if (et === 'approval_required') {
                sideChannel.onApprovalRequired(
                  (event.data?.tools || []) as Array<{ tool: string; arguments: Record<string, unknown>; tool_call_id: string }>,
                );
                stopReconnect();
                const result = await hydrateMessages();
                if (result) {
                  const uiMsgs = llmMessagesToUIMessages(result.data, result.pendingIds, chatActionsRef.current.messages);
                  if (uiMsgs.length > 0) {
                    chat.setMessages(uiMsgs);
                    saveMessages(sessionId, uiMsgs);
                  }
                }
                return;
              }
            } catch { /* ignore parse errors */ }
          }
        }
      } catch {
        /* stream ended or aborted */
      }
    };

    const onVisible = async () => {
      if (document.visibilityState !== 'visible') return;

      // Always re-hydrate messages on wake
      const result = await hydrateMessages();
      if (!result) return;

      const { data, pendingIds, info } = result;
      const uiMsgs = llmMessagesToUIMessages(data, pendingIds, chatActionsRef.current.messages);
      if (uiMsgs.length > 0) {
        chat.setMessages(uiMsgs);
        saveMessages(sessionId, uiMsgs);
      }

      // If the backend is still processing, reconnect to the live event stream
      if (info?.is_processing) {
        updateSession(sessionId, { isProcessing: true, activityStatus: { type: 'thinking' } });

        // Stop any previous reconnection
        stopReconnect();

        // Start live event subscription
        const abort = new AbortController();
        reconnectAbortRef.current = abort;
        consumeEventStream(abort.signal);

        // Poll messages every 3 s so the chat message list stays up-to-date
        // (the event stream gives us real-time status but not full message diffs)
        pollTimerRef.current = setInterval(async () => {
          const fresh = await hydrateMessages();
          if (!fresh) return;
          const msgs = llmMessagesToUIMessages(fresh.data, fresh.pendingIds, chatActionsRef.current.messages);

          const currentCount = chatActionsRef.current.messages.length;
          if (msgs.length > currentCount || currentCount === 0) {
            chat.setMessages(msgs);
            saveMessages(sessionId, msgs);
          } 

          // If backend stopped processing, clean up
          if (fresh.info && !fresh.info.is_processing) {
            updateSession(sessionId, { isProcessing: false });
            stopReconnect();
          }
        }, 3000);
      }
    };

    document.addEventListener('visibilitychange', onVisible);
    return () => {
      document.removeEventListener('visibilitychange', onVisible);
      stopReconnect();
    };
  }, [sessionId]); // eslint-disable-line react-hooks/exhaustive-deps

  // -- Persist messages ---------------------------------------------------
  const prevLenRef = useRef(initialMessages.length);
  useEffect(() => {
    if (chat.messages.length === 0) return;
    if (chat.messages.length !== prevLenRef.current) {
      prevLenRef.current = chat.messages.length;
      saveMessages(sessionId, chat.messages);
    } 
  }, [sessionId, chat.messages]);

  // -- Undo last turn (REST call + client-side message removal) -----------
  // With SSE there's no persistent connection to receive the undo_complete
  // event, so we handle message removal on the frontend after a successful
  // REST call to the backend.
  const undoLastTurn = useCallback(async () => {
    try {
      const res = await apiFetch(`/api/undo/${sessionId}`, { method: 'POST' });
      if (!res.ok) {
        logger.error('Undo API returned', res.status);
        return;
      }
      // Remove the last user turn + assistant response from the UI
      const msgs = chatActionsRef.current.messages;
      const setMsgs = chatActionsRef.current.setMessages;
      if (setMsgs && msgs.length > 0) {
        let lastUserIdx = -1;
        for (let i = msgs.length - 1; i >= 0; i--) {
          if (msgs[i].role === 'user') { lastUserIdx = i; break; }
        }
        const updated = lastUserIdx > 0 ? msgs.slice(0, lastUserIdx) : [];
        setMsgs(updated);
        saveMessages(sessionId, updated);
      }
      updateSession(sessionId, { isProcessing: false });
    } catch (e) {
      logger.error('Undo failed:', e);
    }
  }, [sessionId, updateSession]);

  // -- Approve tools ------------------------------------------------------
  const approveTools = useCallback(
    async (approvals: Array<{ tool_call_id: string; approved: boolean; feedback?: string | null; edited_script?: string | null }>) => {
      // Store edited scripts so the transport can read them when sendMessages is called
      for (const a of approvals) {
        if (a.edited_script) {
          useAgentStore.getState().setEditedScript(a.tool_call_id, a.edited_script);
        }
      }

      // Update SDK tool state — this triggers sendMessages() via the transport
      for (const a of approvals) {
        chat.addToolApprovalResponse({
          id: `approval-${a.tool_call_id}`,
          approved: a.approved,
          reason: a.approved ? undefined : (a.feedback || 'Rejected by user'),
        });
      }

      setNeedsAttention(sessionId, false);
      const hasApproved = approvals.some(a => a.approved);
      if (hasApproved) {
        updateSession(sessionId, { isProcessing: true });
      }
      return true;
    },
    [sessionId, chat, updateSession, setNeedsAttention],
  );

  // -- Stop (interrupt backend agent loop, keep SSE open for events) --------
  const stop = useCallback(() => {
    // Don't call chat.stop() — keep the SSE stream open so the backend's
    // tool_state_change(cancelled) and interrupted events reach the frontend.
    // The stream closes naturally when the backend sends finish events.
    updateSession(sessionId, { isProcessing: false });
    apiFetch(`/api/interrupt/${sessionId}`, { method: 'POST' }).catch(() => {});
  }, [sessionId, updateSession]);

  // -- Edit message + regenerate from that point ----------------------------
  const editAndRegenerate = useCallback(async (messageId: string, newText: string) => {
    try {
      const msgs = chatActionsRef.current.messages;
      const setMsgs = chatActionsRef.current.setMessages;
      if (!setMsgs) return;

      // Find the target message and compute user message index (0-indexed, skipping system)
      const msgIndex = msgs.findIndex(m => m.id === messageId);
      if (msgIndex < 0) return;

      let userMsgIndex = 0;
      for (let i = 0; i < msgIndex; i++) {
        if (msgs[i].role === 'user') userMsgIndex++;
      }

      // 1. Truncate backend history
      const res = await apiFetch(`/api/truncate/${sessionId}`, {
        method: 'POST',
        body: JSON.stringify({ user_message_index: userMsgIndex }),
        headers: { 'Content-Type': 'application/json' },
      });
      if (!res.ok) {
        logger.error('Truncate API returned', res.status);
        return;
      }

      // 2. Truncate frontend messages
      const truncated = msgs.slice(0, msgIndex);
      setMsgs(truncated);
      saveMessages(sessionId, truncated);

      // 3. Send the edited message (reuses existing transport + /api/chat)
      chat.sendMessage({ text: newText, metadata: { createdAt: new Date().toISOString() } });
    } catch (e) {
      logger.error('Edit and regenerate failed:', e);
    }
  }, [sessionId, chat]);

  return {
    messages: chat.messages,
    sendMessage: chat.sendMessage,
    stop,
    status: chat.status,
    undoLastTurn,
    editAndRegenerate,
    approveTools,
  };
}