File size: 30,392 Bytes
6270070
 
 
 
 
 
 
 
1e24842
6270070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
6270070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
6270070
 
1e24842
 
6270070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6270070
1e24842
 
 
 
 
 
 
 
 
6270070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8085285
6270070
 
8085285
6270070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
6270070
 
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
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Bot, Send, Plus, Trash2, Edit3, Check, X, MessageSquare,
  Zap, SkipForward, RefreshCw, TestTube, AlertCircle,
  ChevronRight, Sparkles, Play, PlayCircle
} from 'lucide-react';
import { ChatService } from '../services/api';
import { useAppContext } from './AppContext';
import ModifyDiffModal from './workflow/ModifyDiffModal';

// ─────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────

const ACTION_ICONS = {
  execute_step:   <Play size={13} className="text-blue-400" />,
  run_all:        <PlayCircle size={13} className="text-emerald-400" />,
  retry_step:     <RefreshCw size={13} className="text-yellow-400" />,
  skip_step:      <SkipForward size={13} className="text-slate-400" />,
  modify_request: <Edit3 size={13} className="text-purple-400" />,
  explain:        <AlertCircle size={13} className="text-orange-400" />,
  generate_tests: <TestTube size={13} className="text-pink-400" />,
  reply:          <Bot size={13} className="text-[var(--accent-primary)]" />,
};

const ACTION_LABELS = {
  execute_step:   'Execute Step',
  run_all:        'Run Full Flow',
  retry_step:     'Retry Step',
  skip_step:      'Skip Step',
  modify_request: 'Modify Request',
  explain:        'Explanation',
  generate_tests: 'Test Cases',
  reply:          'Reply',
};

const ACTION_COLORS = {
  execute_step:   'border-blue-500/30 bg-blue-500/5',
  run_all:        'border-emerald-500/30 bg-emerald-500/5',
  retry_step:     'border-yellow-500/30 bg-yellow-500/5',
  skip_step:      'border-slate-500/30 bg-slate-500/5',
  modify_request: 'border-purple-500/30 bg-purple-500/5',
  explain:        'border-orange-500/30 bg-orange-500/5',
  generate_tests: 'border-pink-500/30 bg-pink-500/5',
  reply:          'border-[var(--border-subtle)] bg-transparent',
};

const QUICK_COMMANDS = [
  { label: 'Run full flow', icon: <PlayCircle size={13} /> },
  { label: 'Why did this fail?', icon: <AlertCircle size={13} /> },
  { label: 'Retry last step', icon: <RefreshCw size={13} /> },
  { label: 'Generate test cases', icon: <TestTube size={13} /> },
];

function formatTime(ts) {
  if (!ts) return '';
  const d = new Date(ts);
  return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

// ─────────────────────────────────────────────
// MessageBubble
// ─────────────────────────────────────────────

function MessageBubble({ msg, onAction }) {
  const isUser = msg.role === 'user';
  const action = msg.action_json?.action || 'reply';
  const isActionable = !isUser && ['execute_step', 'run_all', 'retry_step', 'skip_step', 'modify_request'].includes(action);
  const assertions = msg.action_json?.assertions;
  const changes = msg.action_json?.changes;
  const explanation = msg.action_json?.explanation;
  const step = msg.action_json?.step;

  return (
    <div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-4 animate-in fade-in slide-in-from-bottom-2 duration-200`}>
      {!isUser && (
        <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--accent-primary)] to-[var(--accent-secondary)] flex items-center justify-center flex-shrink-0 mr-2 mt-1 shadow-md">
          <Bot size={14} className="text-white" />
        </div>
      )}

      <div className={`max-w-[78%] space-y-2 ${isUser ? 'items-end' : 'items-start'} flex flex-col`}>
        {/* Main bubble */}
        <div
          className={`px-3 py-2.5 rounded-xl text-sm leading-relaxed ${
            isUser
              ? 'bg-[var(--accent-primary)] text-white rounded-tr-sm shadow-md'
              : `bg-[var(--bg-secondary)] border ${ACTION_COLORS[action] || 'border-[var(--border-subtle)]'} text-[var(--text-primary)] rounded-tl-sm shadow-sm`
          }`}
        >
          {!isUser && action !== 'reply' && (
            <div className="flex items-center gap-1.5 mb-1.5 text-[10px] uppercase tracking-wider font-semibold opacity-70">
              {ACTION_ICONS[action]}
              <span>{ACTION_LABELS[action] || action}</span>
              {step && <span className="font-mono">β€” Step {step}</span>}
            </div>
          )}

          <p className="whitespace-pre-wrap">{msg.content}</p>
        </div>

        {/* Explanation block */}
        {explanation && (
          <div className="bg-[var(--bg-tertiary)] border border-orange-500/20 rounded-lg px-3 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed w-full">
            <div className="flex items-center gap-1 text-orange-400 font-semibold mb-1 text-[10px] uppercase tracking-wider">
              <AlertCircle size={11} /> Detailed Analysis
            </div>
            <p className="whitespace-pre-wrap">{explanation}</p>
          </div>
        )}

        {/* Changes block for modify_request */}
        {changes && Object.keys(changes).length > 0 && (
          <div className="bg-[var(--bg-tertiary)] border border-purple-500/20 rounded-lg px-3 py-2.5 text-xs w-full font-mono">
            <div className="text-purple-400 font-semibold mb-1 text-[10px] uppercase tracking-wider">Proposed Changes</div>
            {Object.entries(changes).map(([k, v]) => (
              <div key={k} className="flex gap-2">
                <span className="text-purple-400">{k}:</span>
                <span className="text-[var(--text-primary)]">"{String(v)}"</span>
              </div>
            ))}
          </div>
        )}

        {/* Test assertions block */}
        {assertions && assertions.length > 0 && (
          <div className="bg-[var(--bg-tertiary)] border border-pink-500/20 rounded-lg px-3 py-2.5 text-xs w-full">
            <div className="text-pink-400 font-semibold mb-2 text-[10px] uppercase tracking-wider flex items-center gap-1">
              <TestTube size={11} /> Generated Assertions
            </div>
            <ul className="space-y-1">
              {assertions.map((a, i) => (
                <li key={i} className="flex items-start gap-2 text-[var(--text-secondary)]">
                  <Check size={11} className="text-emerald-400 mt-0.5 flex-shrink-0" />
                  <span>{String(a)}</span>
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* Action button */}
        {isActionable && (
          <button
            onClick={() => onAction(msg.action_json)}
            className="flex items-center gap-2 text-xs px-3 py-1.5 rounded-lg border border-[var(--accent-primary)]/40 bg-[var(--accent-primary)]/10 text-[var(--accent-primary)] hover:bg-[var(--accent-primary)]/20 transition-all font-medium active:scale-95"
          >
            {ACTION_ICONS[action]}
            <span>
              {action === 'execute_step' && `Execute Step ${step}`}
              {action === 'run_all' && 'Run All Steps'}
              {action === 'retry_step' && `Retry Step ${step || 'last'}`}
              {action === 'skip_step' && `Skip Step ${step}`}
              {action === 'modify_request' && 'Apply & Execute'}
            </span>
            <ChevronRight size={12} />
          </button>
        )}

        <div className="text-[10px] text-[var(--text-secondary)] opacity-50 px-1">
          {formatTime(msg.timestamp)}
        </div>
      </div>

      {isUser && (
        <div className="w-7 h-7 rounded-full bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] flex items-center justify-center flex-shrink-0 ml-2 mt-1">
          <span className="text-[10px] font-bold text-[var(--text-secondary)]">U</span>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────
// TypingIndicator
// ─────────────────────────────────────────────

function TypingIndicator() {
  return (
    <div className="flex justify-start mb-4">
      <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--accent-primary)] to-[var(--accent-secondary)] flex items-center justify-center flex-shrink-0 mr-2 mt-1">
        <Bot size={14} className="text-white" />
      </div>
      <div className="bg-[var(--bg-secondary)] border border-[var(--border-subtle)] px-4 py-3 rounded-xl rounded-tl-sm shadow-sm">
        <div className="flex gap-1 items-center h-4">
          {[0, 150, 300].map((delay, i) => (
            <div
              key={i}
              className="w-1.5 h-1.5 rounded-full bg-[var(--accent-primary)] opacity-70"
              style={{ animation: `bounce 1s ${delay}ms infinite` }}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// ChatAssistant (main page + compact sidebar component)
// ─────────────────────────────────────────────

/**
 * Props:
 *   compact             (bool)   β€” When true: sessions sidebar is hidden.
 *   lastStepResultProp  (obj)    β€” Auto-injects the last executed step result from the parent.
 *   allStepResultsProp  (obj)    β€” Dict of ALL step results keyed by step number.
 *   executeStepFromChat (fn)     β€” Callback to trigger actual step execution from chat.
 */
export default function ChatAssistant({ executeStepFromChat, compact = false, lastStepResultProp = null, allStepResultsProp = null, onOpenInExecutionPanel = null }) {
  const {
    activeSpecId, activeSpecName, sessionId,
    executionPlan, sessionContextVars,
    globalChatId, setGlobalChatId
  } = useAppContext();

  const [chatSessions, setChatSessions] = useState([]);
  // activeChatId is replaced by globalChatId
  const [messages, setMessages] = useState([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isFetchingSessions, setIsFetchingSessions] = useState(false);
  const [lastStepResult, setLastStepResult] = useState(lastStepResultProp);
  const [allStepResults, setAllStepResults] = useState(allStepResultsProp || {});
  const [modifyDiff, setModifyDiff] = useState(null); // { stepDef, changes }

  // Sync externally-provided results
  useEffect(() => {
    if (lastStepResultProp) setLastStepResult(lastStepResultProp);
  }, [lastStepResultProp]);

  useEffect(() => {
    if (allStepResultsProp) setAllStepResults(allStepResultsProp);
  }, [allStepResultsProp]);

  // Inline rename state
  const [renamingId, setRenamingId] = useState(null);
  const [renameValue, setRenameValue] = useState('');

  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  // ── Scroll to bottom on new messages ──
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const fetchSessions = useCallback(async () => {
    setIsFetchingSessions(true);
    try {
      const data = await ChatService.getSessions(activeSpecId || null);
      setChatSessions(data);
    } catch (e) {
      console.error('Failed to fetch chat sessions', e);
    } finally {
      setIsFetchingSessions(false);
    }
  }, [activeSpecId]);

  const startNewChat = () => {
    setGlobalChatId(null);
    inputRef.current?.focus();
  };

  const loadSession = (id) => {
    setGlobalChatId(id);
  };

  // ── Re-fetch sessions and clear chat when active spec changes ──
  useEffect(() => {
    fetchSessions();
    startNewChat();
  }, [activeSpecId]);

  // ── Auto-load messages when globalChatId changes ──
  useEffect(() => {
    if (globalChatId) {
      ChatService.getSession(globalChatId).then(data => {
        setMessages(data.messages || []);
      }).catch(e => console.error('Failed to load session', e));
    } else {
      setMessages([]);
    }
  }, [globalChatId]);

  // ── Send a message ──
  const sendMessage = useCallback(async (text = inputText) => {
    const msg = text.trim();
    if (!msg || isLoading) return;

    setInputText('');

    const optimisticUserMsg = {
      id: `opt_${Date.now()}`,
      role: 'user',
      content: msg,
      timestamp: new Date().toISOString(),
    };
    setMessages(prev => [...prev, optimisticUserMsg]);
    setIsLoading(true);

    try {
      const payload = {
        message: msg,
        chat_session_id: globalChatId || undefined,
        spec_id: activeSpecId || undefined,
        spec_name: activeSpecName || undefined,
        session_id: sessionId || undefined,
        execution_plan: executionPlan || [],
        context_variables: sessionContextVars || {},
        last_step_result: lastStepResult || undefined,
        // Send ALL step results so the AI can diagnose any specific step
        all_step_results: Object.keys(allStepResults).length > 0 ? allStepResults : undefined,
      };

      const data = await ChatService.sendMessage(payload);

      if (!globalChatId || globalChatId !== data.chat_session_id) {
        setGlobalChatId(data.chat_session_id);
        await fetchSessions(); // Will now fetch using activeSpecId
      } else {
        setChatSessions(prev => prev.map(s =>
          s.id === data.chat_session_id ? { ...s, name: data.chat_session_name, updated_at: new Date().toISOString() } : s
        ));
      }

      const aiMsg = {
        id: `ai_${Date.now()}`,
        role: 'assistant',
        content: data.message,
        action_json: data,
        timestamp: new Date().toISOString(),
      };
      setMessages(prev => {
        const withoutOpt = prev.filter(m => m.id !== optimisticUserMsg.id);
        return [...withoutOpt, optimisticUserMsg, aiMsg];
      });

    } catch (e) {
      console.error('Chat send failed', e);
      const errMsg = {
        id: `err_${Date.now()}`,
        role: 'assistant',
        content: '❌ Failed to get a response. Please check the backend and try again.',
        timestamp: new Date().toISOString(),
      };
      setMessages(prev => [...prev, errMsg]);
    } finally {
      setIsLoading(false);
    }
  }, [inputText, isLoading, globalChatId, activeSpecId, activeSpecName, sessionId, executionPlan, sessionContextVars, lastStepResult, allStepResults, fetchSessions]);

  // ── Handle action button clicks ──
  const handleAction = useCallback(async (actionJson) => {
    const { action, step, changes } = actionJson;

    if (!executeStepFromChat) {
      sendMessage(`Please ${action === 'run_all' ? 'run all steps' : `execute step ${step}`} β€” go to the Testing page to trigger execution.`);
      return;
    }

    if (action === 'execute_step' && step) {
      const stepDef = (executionPlan || []).find(s => s.step === step);
      if (stepDef) {
        const result = await executeStepFromChat(stepDef, null);
        setLastStepResult(result);
        const confirmMsg = {
          id: `confirm_${Date.now()}`,
          role: 'user',
          content: `β–Ά Executed Step ${step}: ${stepDef.endpoint}`,
          timestamp: new Date().toISOString(),
        };
        setMessages(prev => [...prev, confirmMsg]);
        await sendMessage(`Step ${step} executed. Analyze the result and tell me if it succeeded or what went wrong.`);
      }
    } else if (action === 'run_all') {
      for (const stepDef of (executionPlan || [])) {
        const result = await executeStepFromChat(stepDef, null);
        setLastStepResult(result);
      }
      await sendMessage('All steps have been executed. Give me a summary of what passed and what failed.');
    } else if (action === 'retry_step') {
      const targetStep = step || Math.max(...Object.keys(allStepResults).map(Number));
      const stepDef = (executionPlan || []).find(s => s.step === targetStep);
      if (stepDef) {
        const result = await executeStepFromChat(stepDef, null);
        setLastStepResult(result);
        await sendMessage(`Step ${targetStep} retried. Did it succeed this time?`);
      }
    } else if (action === 'modify_request') {
      // Show diff preview first; actual execution happens when user confirms
      const targetStep = step || Math.max(...Object.keys(allStepResults).map(Number));
      const stepDef = (executionPlan || []).find(s => s.step === targetStep);
      if (stepDef && changes) {
        setModifyDiff({ stepDef, changes });
      }
    }
  }, [executionPlan, executeStepFromChat, sendMessage, allStepResults]);

  // ── Rename ──
  const startRename = (session) => {
    setRenamingId(session.id);
    setRenameValue(session.name);
  };
  const commitRename = async (id) => {
    if (!renameValue.trim()) return;
    try {
      await ChatService.renameSession(id, renameValue.trim());
      setChatSessions(prev => prev.map(s => s.id === id ? { ...s, name: renameValue.trim() } : s));
    } catch (e) { console.error(e); }
    setRenamingId(null);
  };

  // ── Delete session ──
  const deleteSession = async (id) => {
    try {
      await ChatService.deleteSession(id);
      setChatSessions(prev => prev.filter(s => s.id !== id));
      if (globalChatId === id) startNewChat();
    } catch (e) { console.error(e); }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // ─── RENDER ───────────────────────────────

  const handleDiffConfirm = async (modifiedStep) => {
    setModifyDiff(null);
    if (!executeStepFromChat) return;
    const result = await executeStepFromChat(modifiedStep, {});
    setLastStepResult(result);
    const confirmMsg = {
      id: `mod_${Date.now()}`,
      role: 'user',
      content: `Modified & re-executed Step ${modifiedStep.step}: ${modifiedStep.endpoint}`,
      timestamp: new Date().toISOString(),
    };
    setMessages(prev => [...prev, confirmMsg]);
    await sendMessage(`Step ${modifiedStep.step} was modified with your suggested changes and re-executed. Did it succeed?`);
  };

  return (
    <>
    {modifyDiff && (
      <ModifyDiffModal
        original={modifyDiff.stepDef}
        changes={modifyDiff.changes}
        onConfirm={handleDiffConfirm}
        onCancel={() => setModifyDiff(null)}
      />
    )}
    <div className="flex h-full min-h-0 overflow-hidden animate-in fade-in duration-300">

      {/* ── LEFT SIDEBAR: Sessions list (hidden in compact/embedded mode) ── */}
      {!compact && (
        <div className="w-64 flex-shrink-0 border-r border-[var(--border-subtle)] bg-[var(--bg-secondary)] flex flex-col">
          {/* Header */}
          <div className="h-10 flex items-center justify-between px-3 border-b border-[var(--border-subtle)] shrink-0">
            <div className="flex items-center gap-2">
              <Sparkles size={14} className="text-[var(--accent-primary)]" />
              <span className="text-xs font-semibold text-[var(--text-primary)] uppercase tracking-wider">Chats</span>
            </div>
            <button
              onClick={startNewChat}
              className="p-1 rounded-md text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] transition"
              title="New Chat"
            >
              <Plus size={15} />
            </button>
          </div>

          {/* Session list */}
          <div className="flex-1 overflow-y-auto py-2">
            {isFetchingSessions && (
              <div className="px-3 py-2 text-xs text-[var(--text-secondary)] opacity-50">Loading...</div>
            )}
            {!isFetchingSessions && chatSessions.length === 0 && (
              <div className="flex flex-col items-center justify-center h-32 text-center px-4">
                <MessageSquare size={24} className="text-[var(--text-secondary)] opacity-30 mb-2" />
                <p className="text-xs text-[var(--text-secondary)] opacity-50">No chats yet. Start a new conversation!</p>
              </div>
            )}
            {chatSessions.map(session => (
              <div
                key={session.id}
                onClick={() => loadSession(session.id)}
                className={`group flex items-center gap-2 px-3 py-2.5 cursor-pointer transition-colors border-l-2 ${
                  globalChatId === session.id
                    ? 'bg-[var(--accent-primary)]/10 border-[var(--accent-primary)] text-[var(--text-primary)]'
                    : 'border-transparent hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]'
                }`}
              >
                <MessageSquare size={13} className="flex-shrink-0 opacity-60" />

                <div className="flex-1 min-w-0">
                  {renamingId === session.id ? (
                    <input
                      autoFocus
                      value={renameValue}
                      onChange={e => setRenameValue(e.target.value)}
                      onBlur={() => commitRename(session.id)}
                      onKeyDown={e => {
                        if (e.key === 'Enter') commitRename(session.id);
                        if (e.key === 'Escape') setRenamingId(null);
                        e.stopPropagation();
                      }}
                      onClick={e => e.stopPropagation()}
                      className="w-full bg-[var(--bg-primary)] border border-[var(--accent-primary)] rounded px-1 py-0.5 text-xs text-[var(--text-primary)] outline-none"
                    />
                  ) : (
                    <>
                      <p className="text-xs font-medium truncate">{session.name}</p>
                      <p className="text-[10px] opacity-40 truncate">
                        {session.message_count} msg{session.message_count !== 1 ? 's' : ''} Β· {
                          session.updated_at ? new Date(session.updated_at).toLocaleDateString() : ''
                        }
                      </p>
                    </>
                  )}
                </div>

                {/* Actions */}
                <div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
                  <button
                    onClick={e => { e.stopPropagation(); startRename(session); }}
                    className="p-0.5 rounded hover:text-[var(--text-primary)] transition"
                    title="Rename"
                  >
                    <Edit3 size={11} />
                  </button>
                  <button
                    onClick={e => { e.stopPropagation(); deleteSession(session.id); }}
                    className="p-0.5 rounded hover:text-red-400 transition"
                    title="Delete"
                  >
                    <Trash2 size={11} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── MAIN PANEL: Chat messages ── */}
      <div className="flex-1 flex flex-col min-w-0 min-h-0">

        {/* Chat header */}
        <div className="h-10 flex items-center justify-between px-4 border-b border-[var(--border-subtle)] bg-[var(--bg-secondary)] shrink-0">
          <div className="flex items-center gap-2">
            <Bot size={15} className="text-[var(--accent-primary)]" />
            <span className="text-xs font-semibold text-[var(--text-primary)]">
              {globalChatId
                ? (chatSessions.find(s => s.id === globalChatId)?.name || 'Chat')
                : 'New Chat'}
            </span>
          </div>
          <div className="flex items-center gap-2">
            {/* Action button to continue in execution panel */}
            {!compact && globalChatId && onOpenInExecutionPanel && (
              <button
                onClick={() => onOpenInExecutionPanel(globalChatId)}
                className="flex items-center gap-1.5 px-2.5 py-1 text-[10px] uppercase tracking-wider font-semibold bg-[var(--accent-primary)]/10 text-[var(--accent-primary)] hover:bg-[var(--accent-primary)]/20 border border-[var(--accent-primary)]/30 rounded-md transition-all active:scale-95"
                title="Continue this chat in the Execution Panel"
              >
                Continue in Execution <Play size={11} />
              </button>
            )}

            {/* In compact mode show a new-chat button since sidebar is hidden */}
            {compact && (
              <button
                onClick={startNewChat}
                className="flex items-center gap-1 px-2 py-1 rounded text-[10px] font-semibold uppercase tracking-wider text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] transition active:scale-95"
                title="New Chat"
              >
                <Plus size={11} /> New Chat
              </button>
            )}
            {activeSpecName && activeSpecName !== 'None' && (
              <span className="text-[10px] text-[var(--accent-primary)] font-mono bg-[var(--accent-primary)]/10 px-2 py-0.5 rounded border border-[var(--accent-primary)]/20 truncate max-w-32">
                {activeSpecName}
              </span>
            )}
          </div>
        </div>

        {/* Messages area */}
        <div className="flex-1 overflow-y-auto px-3 py-3 min-h-0">
          {messages.length === 0 && (
            <div className="flex flex-col items-center justify-center h-full text-center space-y-4 pb-8">
              <div className={`rounded-2xl bg-gradient-to-br from-[var(--accent-primary)] to-[var(--accent-secondary)] flex items-center justify-center shadow-xl shadow-[var(--accent-primary)]/20 ${compact ? 'w-10 h-10' : 'w-16 h-16'}`}>
                <Bot size={compact ? 20 : 30} className="text-white" />
              </div>
              {!compact && (
                <div>
                  <h2 className="text-lg font-semibold text-[var(--text-primary)] mb-1">API Test Assistant</h2>
                  <p className="text-sm text-[var(--text-secondary)] max-w-sm">
                    Control your entire testing workflow through natural language. Execute steps, debug errors, modify requests β€” just ask.
                  </p>
                </div>
              )}
              {compact && (
                <p className="text-xs text-[var(--text-secondary)] opacity-60 max-w-[180px]">
                  Ask me to run steps, debug errors, or generate tests.
                </p>
              )}

              {/* Quick commands */}
              <div className={`grid gap-2 w-full ${compact ? 'grid-cols-1 max-w-full' : 'grid-cols-2 max-w-sm'}`}>
                {QUICK_COMMANDS.map(cmd => (
                  <button
                    key={cmd.label}
                    onClick={() => sendMessage(cmd.label)}
                    className="flex items-center gap-2 text-xs px-3 py-2 rounded-xl border border-[var(--border-subtle)] bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:border-[var(--accent-primary)]/40 hover:bg-[var(--accent-primary)]/5 transition-all active:scale-95 text-left"
                  >
                    <span className="text-[var(--accent-primary)]">{cmd.icon}</span>
                    <span>{cmd.label}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {messages.map(msg => (
            <MessageBubble
              key={msg.id || msg.timestamp}
              msg={msg}
              onAction={handleAction}
            />
          ))}

          {isLoading && <TypingIndicator />}
          <div ref={messagesEndRef} />
        </div>

        {/* Input bar */}
        <div className="px-3 py-2 border-t border-[var(--border-subtle)] bg-[var(--bg-primary)] shrink-0">
          <div className="flex items-end gap-2 bg-[var(--bg-secondary)] border border-[var(--border-subtle)] rounded-xl focus-within:border-[var(--accent-primary)] transition-all duration-200 shadow-sm p-2 group">
            <div className="ml-1 mb-0.5 text-[var(--accent-primary)] opacity-30 group-focus-within:opacity-100 transition-opacity">
              <Sparkles size={14} />
            </div>
            <textarea
              ref={inputRef}
              value={inputText}
              onChange={e => setInputText(e.target.value)}
              onKeyDown={handleKeyDown}
              disabled={isLoading}
              placeholder={
                !activeSpecId
                  ? 'Load a spec first...'
                  : compact
                    ? 'Ask about any step, diagnose errors, or request modifications...'
                    : 'Ask me to run tests, debug errors, modify requests...'
              }
              rows={1}
              className="flex-1 bg-transparent text-sm resize-none outline-none py-1 px-1 max-h-24 min-h-[22px] text-[var(--text-primary)] placeholder-[var(--text-secondary)] disabled:opacity-40"
              style={{ fieldSizing: 'content' }}
            />
            <button
              onClick={() => sendMessage()}
              disabled={!inputText.trim() || isLoading}
              className="p-1.5 mb-0.5 rounded-lg bg-[var(--accent-gradient)] hover:opacity-90 disabled:opacity-40 transition-all text-white shadow active:scale-95 flex-shrink-0"
            >
              {isLoading ? <RefreshCw size={14} className="animate-spin" /> : <Send size={14} />}
            </button>
          </div>
          {!compact && (
            <p className="text-[10px] text-[var(--text-secondary)] opacity-30 mt-1 px-1">
              Enter to send Β· Shift+Enter for new line
            </p>
          )}
        </div>
      </div>

      {/* CSS for dot bounce animation */}
      <style>{`
        @keyframes bounce {
          0%, 60%, 100% { transform: translateY(0); }
          30% { transform: translateY(-5px); }
        }
      `}</style>
    </div>
    </>
  );
}