summaryrefslogtreecommitdiff
path: root/frontend/src/components/Sidebar.tsx
blob: 165028c26faed6a539243f8b473c49e844e2fb52 (plain)
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
import React, { useState, useEffect } from 'react';
import useFlowStore from '../store/flowStore';
import type { NodeData } from '../store/flowStore';
import ReactMarkdown from 'react-markdown';
import { Play, Settings, Info, Save, ChevronLeft, ChevronRight, Maximize2, Edit3, X, Check, FileText } from 'lucide-react';

interface SidebarProps {
  isOpen: boolean;
  onToggle: () => void;
}

const Sidebar: React.FC<SidebarProps> = ({ isOpen, onToggle }) => {
  const { nodes, selectedNodeId, updateNodeData, getActiveContext } = useFlowStore();
  const [activeTab, setActiveTab] = useState<'interact' | 'settings' | 'debug'>('interact');
  const [streamBuffer, setStreamBuffer] = useState('');
  
  // Response Modal & Edit states
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editedResponse, setEditedResponse] = useState('');
  
  // Summary states
  const [showSummaryModal, setShowSummaryModal] = useState(false);
  const [summaryModel, setSummaryModel] = useState('gpt-5-nano');
  const [isSummarizing, setIsSummarizing] = useState(false);

  const selectedNode = nodes.find((n) => n.id === selectedNodeId);

  // Reset stream buffer and modal states when node changes
  useEffect(() => {
    setStreamBuffer('');
    setIsModalOpen(false);
    setIsEditing(false);
  }, [selectedNodeId]);
  
  // Sync editedResponse when entering edit mode
  useEffect(() => {
    if (isEditing && selectedNode) {
      setEditedResponse(selectedNode.data.response || '');
    }
  }, [isEditing, selectedNode?.data.response]);

  if (!isOpen) {
    return (
      <div className="border-l border-gray-200 h-screen bg-white flex flex-col items-center py-4 w-12 z-10 transition-all duration-300">
        <button 
          onClick={onToggle}
          className="p-2 hover:bg-gray-100 rounded mb-4"
          title="Expand"
        >
          <ChevronLeft size={20} className="text-gray-500" />
        </button>
        {selectedNode && (
           <div className="writing-vertical text-xs font-bold text-gray-500 uppercase tracking-widest mt-4" style={{ writingMode: 'vertical-rl' }}>
             {selectedNode.data.label}
           </div>
        )}
      </div>
    );
  }

  if (!selectedNode) {
    return (
      <div className="w-96 border-l border-gray-200 h-screen flex flex-col bg-white shadow-xl z-10 transition-all duration-300">
        <div className="p-3 border-b border-gray-200 flex justify-between items-center bg-gray-50">
           <span className="text-sm font-medium text-gray-500">Details</span>
           <button onClick={onToggle} className="p-1 hover:bg-gray-200 rounded">
             <ChevronRight size={16} className="text-gray-500" />
           </button>
        </div>
        <div className="flex-1 p-4 bg-gray-50 text-gray-500 text-center flex flex-col justify-center">
          <p>Select a node to edit</p>
        </div>
      </div>
    );
  }

  const handleRun = async () => {
    if (!selectedNode) return;
    
    updateNodeData(selectedNode.id, { status: 'loading', response: '' });
    setStreamBuffer('');

    // Use getActiveContext which respects the user's selected traces
    const context = getActiveContext(selectedNode.id);
    
    try {
      const response = await fetch('http://localhost:8000/api/run_node_stream', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          node_id: selectedNode.id,
          incoming_contexts: [{ messages: context }], // Simple list wrap for now
          user_prompt: selectedNode.data.userPrompt,
          merge_strategy: selectedNode.data.mergeStrategy || 'smart',
          config: {
            provider: selectedNode.data.model.includes('gpt') || selectedNode.data.model === 'o3' ? 'openai' : 'google',
            model_name: selectedNode.data.model,
            temperature: selectedNode.data.temperature,
            system_prompt: selectedNode.data.systemPrompt,
            api_key: selectedNode.data.apiKey,
            enable_google_search: selectedNode.data.enableGoogleSearch !== false, // Default true
            reasoning_effort: selectedNode.data.reasoningEffort || 'medium',  // For reasoning models
          }
        })
      });

      if (!response.body) return;
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let fullResponse = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        const chunk = decoder.decode(value);
        fullResponse += chunk;
        setStreamBuffer(prev => prev + chunk);
        // We update the store less frequently or at the end to avoid too many re-renders
        // But for "live" feel we might want to update local state `streamBuffer` and sync to store at end
      }
      
      // Update final state
      // Append the new interaction to the node's output messages
      const newUserMsg = { 
        id: `msg_${Date.now()}_u`,
        role: 'user', 
        content: selectedNode.data.userPrompt 
      };
      const newAssistantMsg = { 
        id: `msg_${Date.now()}_a`,
        role: 'assistant', 
        content: fullResponse 
      };
      
      updateNodeData(selectedNode.id, { 
        status: 'success', 
        response: fullResponse,
        messages: [...context, newUserMsg, newAssistantMsg] as any 
      });
      
      // Auto-generate title using gpt-5-nano (async, non-blocking)
      // Always regenerate title after each query
      generateTitle(selectedNode.id, selectedNode.data.userPrompt, fullResponse);

    } catch (error) {
      console.error(error);
      updateNodeData(selectedNode.id, { status: 'error' });
    }
  };

  const handleChange = (field: keyof NodeData, value: any) => {
    updateNodeData(selectedNode.id, { [field]: value });
  };
  
  const handleSaveEdit = () => {
    if (!selectedNode) return;
    updateNodeData(selectedNode.id, { response: editedResponse });
    setIsEditing(false);
  };
  
  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditedResponse(selectedNode?.data.response || '');
  };
  
  // Summarize response
  const handleSummarize = async () => {
    if (!selectedNode?.data.response) return;
    
    setIsSummarizing(true);
    setShowSummaryModal(false);
    
    try {
      const res = await fetch('http://localhost:8000/api/summarize', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content: selectedNode.data.response,
          model: summaryModel
        })
      });
      
      if (res.ok) {
        const data = await res.json();
        if (data.summary) {
          // Replace response with summary
          updateNodeData(selectedNode.id, { response: data.summary });
        }
      }
    } catch (error) {
      console.error('Summarization failed:', error);
    } finally {
      setIsSummarizing(false);
    }
  };
  
  // Auto-generate title using gpt-5-nano
  const generateTitle = async (nodeId: string, userPrompt: string, response: string) => {
    try {
      const res = await fetch('http://localhost:8000/api/generate_title', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_prompt: userPrompt, response })
      });
      
      if (res.ok) {
        const data = await res.json();
        if (data.title) {
          updateNodeData(nodeId, { label: data.title });
        }
      }
    } catch (error) {
      console.error('Failed to generate title:', error);
      // Silently fail - keep the original title
    }
  };

  return (
    <div className="w-96 border-l border-gray-200 h-screen flex flex-col bg-white shadow-xl z-10 transition-all duration-300">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 bg-gray-50 flex flex-col gap-2">
        <div className="flex justify-between items-center">
           <input 
             type="text" 
             value={selectedNode.data.label}
             onChange={(e) => handleChange('label', e.target.value)}
             className="font-bold text-lg bg-transparent border-none focus:ring-0 focus:outline-none w-full"
           />
           <button onClick={onToggle} className="p-1 hover:bg-gray-200 rounded shrink-0">
             <ChevronRight size={16} className="text-gray-500" />
           </button>
        </div>
        <div className="flex items-center justify-between mt-1">
          <div className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded uppercase">
            {selectedNode.data.status}
          </div>
          <div className="text-xs text-gray-500">
             ID: {selectedNode.id}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200">
        <button 
          onClick={() => setActiveTab('interact')}
          className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'interact' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
        >
          <Play size={16} /> Interact
        </button>
        <button 
          onClick={() => setActiveTab('settings')}
          className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'settings' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
        >
          <Settings size={16} /> Settings
        </button>
        <button 
          onClick={() => setActiveTab('debug')}
          className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'debug' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
        >
          <Info size={16} /> Debug
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {activeTab === 'interact' && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Model</label>
              <select 
                value={selectedNode.data.model} 
                onChange={(e) => {
                  const newModel = e.target.value;
                  // Auto-set temperature to 1 for reasoning models
                  const reasoningModels = [
                    'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 
                    'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
                  ];
                  const isReasoning = reasoningModels.includes(newModel);
                  
                  if (isReasoning) {
                    handleChange('temperature', 1);
                  }
                  handleChange('model', newModel);
                }}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
              >
                <optgroup label="Gemini">
                  <option value="gemini-2.5-flash">gemini-2.5-flash</option>
                  <option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
                  <option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
                </optgroup>
                <optgroup label="OpenAI (Standard)">
                  <option value="gpt-4.1">gpt-4.1</option>
                  <option value="gpt-4o">gpt-4o</option>
                </optgroup>
                <optgroup label="OpenAI (Reasoning)">
                  <option value="gpt-5">gpt-5</option>
                  <option value="gpt-5-chat-latest">gpt-5-chat-latest</option>
                  <option value="gpt-5-mini">gpt-5-mini</option>
                  <option value="gpt-5-nano">gpt-5-nano</option>
                  <option value="gpt-5-pro">gpt-5-pro</option>
                  <option value="gpt-5.1">gpt-5.1</option>
                  <option value="gpt-5.1-chat-latest">gpt-5.1-chat-latest</option>
                  <option value="o3">o3</option>
                </optgroup>
              </select>
            </div>

            {/* Trace Selector */}
            {selectedNode.data.traces && selectedNode.data.traces.length > 0 && (
              <div className="bg-gray-50 p-2 rounded border border-gray-200">
                <label className="block text-xs font-bold text-gray-500 mb-2 uppercase">Select Context Traces</label>
                <div className="space-y-1 max-h-[150px] overflow-y-auto">
                  {selectedNode.data.traces.map((trace) => {
                    const isActive = selectedNode.data.activeTraceIds?.includes(trace.id);
                    return (
                      <div key={trace.id} className="flex items-start gap-2 text-sm p-1 hover:bg-white rounded cursor-pointer"
                           onClick={() => {
                             const current = selectedNode.data.activeTraceIds || [];
                             const next = [trace.id]; // Single select mode
                             handleChange('activeTraceIds', next);
                           }}
                      >
                        <input 
                          type="radio" 
                          checked={isActive || false}
                          readOnly
                          className="mt-1"
                        />
                        <div className="flex-1">
                           <div className="flex items-center gap-2">
                             <div className="w-2 h-2 rounded-full" style={{ backgroundColor: trace.color }}></div>
                             <span className="font-mono text-xs text-gray-400">#{trace.id.slice(-4)}</span>
                           </div>
                           <div className="text-xs text-gray-600 truncate">
                             From Node: {trace.sourceNodeId}
                           </div>
                           <div className="text-[10px] text-gray-400">
                             {trace.messages.length} msgs
                           </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">User Prompt</label>
              <textarea 
                value={selectedNode.data.userPrompt}
                onChange={(e) => handleChange('userPrompt', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm min-h-[100px]"
                placeholder="Type your message here..."
              />
            </div>

            <button 
              onClick={handleRun}
              disabled={selectedNode.data.status === 'loading'}
              className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:bg-blue-300 flex items-center justify-center gap-2"
            >
              {selectedNode.data.status === 'loading' ? <Loader2 className="animate-spin" size={16} /> : <Play size={16} />}
              Run Node
            </button>

            <div className="mt-6">
              <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-medium text-gray-700">Response</label>
                <div className="flex gap-1">
                  {selectedNode.data.response && (
                    <>
                      <button
                        onClick={() => setShowSummaryModal(true)}
                        disabled={isSummarizing}
                        className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700 disabled:opacity-50"
                        title="Summarize"
                      >
                        {isSummarizing ? <Loader2 className="animate-spin" size={14} /> : <FileText size={14} />}
                      </button>
                      <button
                        onClick={() => setIsEditing(true)}
                        className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
                        title="Edit Response"
                      >
                        <Edit3 size={14} />
                      </button>
                      <button
                        onClick={() => setIsModalOpen(true)}
                        className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
                        title="Expand"
                      >
                        <Maximize2 size={14} />
                      </button>
                    </>
                  )}
                </div>
              </div>
              
              {isEditing ? (
                <div className="space-y-2">
                  <textarea
                    value={editedResponse}
                    onChange={(e) => setEditedResponse(e.target.value)}
                    className="w-full border border-blue-300 rounded-md p-2 text-sm min-h-[200px] font-mono focus:ring-2 focus:ring-blue-500"
                  />
                  <div className="flex gap-2 justify-end">
                    <button
                      onClick={handleCancelEdit}
                      className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
                    >
                      <X size={14} /> Cancel
                    </button>
                    <button
                      onClick={handleSaveEdit}
                      className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
                    >
                      <Check size={14} /> Save
                    </button>
                  </div>
                </div>
              ) : (
                <div className="bg-gray-50 p-3 rounded-md border border-gray-200 min-h-[150px] text-sm prose prose-sm max-w-none">
                  <ReactMarkdown>{selectedNode.data.response || streamBuffer}</ReactMarkdown>
                </div>
              )}
            </div>
          </div>
        )}

        {activeTab === 'settings' && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Merge Strategy</label>
              <select 
                value={selectedNode.data.mergeStrategy || 'smart'} 
                onChange={(e) => handleChange('mergeStrategy', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
              >
                <option value="smart">Smart (Auto-merge roles)</option>
                <option value="raw">Raw (Concatenate)</option>
              </select>
              <p className="text-xs text-gray-500 mt-1">
                Smart merge combines consecutive messages from the same role to avoid API errors.
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Temperature ({selectedNode.data.temperature})
                {[
                  'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 
                  'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
                ].includes(selectedNode.data.model) && (
                  <span className="text-xs text-orange-500 ml-2">(Locked for Reasoning Model)</span>
                )}
              </label>
              <input 
                type="range" 
                min="0" 
                max="2" 
                step="0.1"
                value={selectedNode.data.temperature}
                onChange={(e) => handleChange('temperature', parseFloat(e.target.value))}
                disabled={[
                  'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 
                  'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
                ].includes(selectedNode.data.model)}
                className="w-full disabled:opacity-50 disabled:cursor-not-allowed"
              />
            </div>

            {/* Reasoning Effort - Only for OpenAI reasoning models (except chat-latest) */}
            {[
              'gpt-5', 'gpt-5-mini', 'gpt-5-nano', 
              'gpt-5-pro', 'gpt-5.1', 'o3'
            ].includes(selectedNode.data.model) && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Reasoning Effort
                </label>
                <select
                  value={selectedNode.data.reasoningEffort || 'medium'}
                  onChange={(e) => handleChange('reasoningEffort', e.target.value)}
                  className="w-full border border-gray-300 rounded-md p-2 text-sm"
                >
                  <option value="low">Low (Faster, less thorough)</option>
                  <option value="medium">Medium (Balanced)</option>
                  <option value="high">High (Slower, more thorough)</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">
                  Controls how much reasoning the model performs before responding. Higher = more tokens used.
                </p>
              </div>
            )}
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">API Key (Optional)</label>
              <input 
                type="password"
                value={selectedNode.data.apiKey || ''}
                onChange={(e) => handleChange('apiKey', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
                placeholder="Leave empty to use backend env var"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">System Prompt Override</label>
              <textarea 
                value={selectedNode.data.systemPrompt}
                onChange={(e) => handleChange('systemPrompt', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm min-h-[100px] font-mono"
                placeholder="Global system prompt will be used if empty..."
              />
            </div>

            {(selectedNode.data.model.startsWith('gemini') || 
              selectedNode.data.model.startsWith('gpt-5') || 
              ['o3', 'o4-mini', 'gpt-4o'].includes(selectedNode.data.model)) && (
              <div className="flex items-center gap-2 mt-4">
                <input 
                  type="checkbox" 
                  id="web-search"
                  checked={selectedNode.data.enableGoogleSearch !== false} // Default to true
                  onChange={(e) => handleChange('enableGoogleSearch', e.target.checked)}
                />
                <label htmlFor="web-search" className="text-sm font-medium text-gray-700 select-none cursor-pointer">
                  Enable Web Search
                </label>
              </div>
            )}
          </div>
        )}

        {activeTab === 'debug' && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Active Context (Sent to LLM)</label>
              <pre className="bg-gray-900 text-gray-100 p-2 rounded text-xs overflow-x-auto">
                {JSON.stringify(getActiveContext(selectedNode.id), null, 2)}
              </pre>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Node Traces (Incoming)</label>
              <pre className="bg-gray-900 text-gray-100 p-2 rounded text-xs overflow-x-auto">
                {JSON.stringify(selectedNode.data.traces, null, 2)}
              </pre>
            </div>
          </div>
        )}
      </div>
      
      {/* Response Modal */}
      {isModalOpen && selectedNode && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setIsModalOpen(false)}>
          <div 
            className="bg-white rounded-lg shadow-2xl w-[80vw] max-w-4xl max-h-[80vh] flex flex-col"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between p-4 border-b border-gray-200">
              <h3 className="font-semibold text-lg">{selectedNode.data.label} - Response</h3>
              <div className="flex gap-2">
                {!isEditing && (
                  <button
                    onClick={() => setIsEditing(true)}
                    className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
                  >
                    <Edit3 size={14} /> Edit
                  </button>
                )}
                <button
                  onClick={() => { setIsModalOpen(false); setIsEditing(false); }}
                  className="p-1 hover:bg-gray-200 rounded text-gray-500"
                >
                  <X size={18} />
                </button>
              </div>
            </div>
            
            {/* Modal Content */}
            <div className="flex-1 overflow-y-auto p-6">
              {isEditing ? (
                <textarea
                  value={editedResponse}
                  onChange={(e) => setEditedResponse(e.target.value)}
                  className="w-full h-full min-h-[400px] border border-gray-300 rounded-md p-3 text-sm font-mono focus:ring-2 focus:ring-blue-500 resize-y"
                />
              ) : (
                <div className="prose prose-sm max-w-none">
                  <ReactMarkdown>{selectedNode.data.response}</ReactMarkdown>
                </div>
              )}
            </div>
            
            {/* Modal Footer (only when editing) */}
            {isEditing && (
              <div className="flex justify-end gap-2 p-4 border-t border-gray-200">
                <button
                  onClick={handleCancelEdit}
                  className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
                >
                  <X size={14} /> Cancel
                </button>
                <button
                  onClick={() => { handleSaveEdit(); setIsModalOpen(false); }}
                  className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
                >
                  <Check size={14} /> Save Changes
                </button>
              </div>
            )}
          </div>
        </div>
      )}
      
      {/* Summary Model Selection Modal */}
      {showSummaryModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowSummaryModal(false)}>
          <div 
            className="bg-white rounded-lg shadow-2xl w-80 p-4"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="font-semibold text-lg mb-4">Summarize Response</h3>
            
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">Select Model</label>
              <select
                value={summaryModel}
                onChange={(e) => setSummaryModel(e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
              >
                <optgroup label="Fast (Recommended)">
                  <option value="gpt-5-nano">gpt-5-nano</option>
                  <option value="gpt-5-mini">gpt-5-mini</option>
                  <option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
                  <option value="gemini-2.5-flash">gemini-2.5-flash</option>
                </optgroup>
                <optgroup label="Standard">
                  <option value="gpt-4o">gpt-4o</option>
                  <option value="gpt-5">gpt-5</option>
                </optgroup>
              </select>
            </div>
            
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowSummaryModal(false)}
                className="px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded"
              >
                Cancel
              </button>
              <button
                onClick={handleSummarize}
                className="px-3 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
              >
                <FileText size={14} /> Summarize
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// Helper component for icon
const Loader2 = ({ className, size }: { className?: string, size?: number }) => (
  <svg 
    xmlns="http://www.w3.org/2000/svg" 
    width={size || 24} 
    height={size || 24} 
    viewBox="0 0 24 24" 
    fill="none" 
    stroke="currentColor" 
    strokeWidth="2" 
    strokeLinecap="round" 
    strokeLinejoin="round" 
    className={className}
  >
    <path d="M21 12a9 9 0 1 1-6.219-8.56" />
  </svg>
);

export default Sidebar;