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
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI学习助手</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --accent-color: #4cc9f0;
            --success-color: #4caf50;
            --warning-color: #ff9800;
            --danger-color: #f44336;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --border-color: #dee2e6;
            --border-radius: 0.375rem;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            height: 100vh;
            background-color: #f5f7fa;
            color: #333;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background-color: #fff;
            border-bottom: 1px solid var(--border-color);
            padding: 1rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }
        
        .header-content {
            max-width: 1600px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            margin: 0;
            font-size: 1.5rem;
            color: var(--primary-color);
        }
        
        .main-container {
            flex: 1;
            display: flex;
            max-width: 1600px;
            margin: 0 auto;
            padding: 1rem;
            width: 100%;
            box-sizing: border-box;
            height: calc(100vh - 70px); /* Header height + padding */
            overflow: hidden;
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #fff;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            border: 1px solid var(--border-color);
            overflow: hidden;
            height: 100%;
            max-width: 800px;
            margin: 0 auto;
        }
        
        /* When plugins are active, adjust the chat container */
        .main-container.with-plugin .chat-container {
            margin: 0;
            max-width: 350px;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            display: flex;
            flex-direction: column;
        }
        
        .message {
            max-width: 90%;
            margin-bottom: 1rem;
            padding: 0.75rem 1rem;
            border-radius: var(--border-radius);
            position: relative;
        }
        
        .user-message {
            background-color: #e3f2fd;
            align-self: flex-end;
            color: #0d47a1;
        }
        
        .bot-message {
            background-color: #f5f5f5;
            align-self: flex-start;
            color: #333;
            border-left: 3px solid var(--primary-color);
        }
        
        .input-container {
            padding: 1rem;
            border-top: 1px solid var(--border-color);
            background-color: #f9f9f9;
        }
        
        .input-row {
            display: flex;
            gap: 0.5rem;
        }
        
        .input-field {
            flex: 1;
            padding: 0.75rem 1rem;
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            resize: none;
            font-size: 0.95rem;
        }
        
        .input-field:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.1);
        }
        
        .send-button {
            padding: 0.75rem 1.5rem;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
        }
        
        .send-button:hover {
            background-color: var(--secondary-color);
        }
        
        .send-button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .plugin-container {
            display: none;
            flex-direction: column;
            background-color: #fff;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            border: 1px solid var(--border-color);
            overflow: hidden;
            height: 100%;
            flex: 2;
            margin-left: 1rem;
        }
        
        .plugin-header {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid var(--border-color);
            background-color: #f9f9f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .plugin-title {
            margin: 0;
            font-size: 1rem;
            font-weight: 500;
        }
        
        .plugin-close {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1rem;
            color: #777;
        }
        
        .plugin-content {
            flex: 1;
            overflow-y: auto;
        }
        
        /* 代码执行插件样式 */
        .code-plugin .plugin-content {
            padding: 0;
        }
        
        /* 可视化插件样式 */
        .visualization-plugin .visualization-form {
            margin-bottom: 1rem;
            padding: 1rem;
        }
        
        .visualization-plugin .visualization-result {
            margin-top: 1rem;
            text-align: center;
            padding: 0 1rem;
        }
        
        .visualization-plugin .visualization-image {
            max-width: 100%;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        /* 思维导图插件样式 */
        .mindmap-plugin .mindmap-form {
            margin-bottom: 1rem;
            padding: 1rem;
        }
        
        .mindmap-plugin .mindmap-result {
            margin-top: 1rem;
            text-align: center;
            padding: 0 1rem;
        }
        
        .mindmap-plugin .mindmap-image {
            max-width: 100%;
            border-radius: var(--border-radius);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        
        /* 参考资料样式 */
        .reference-container {
            margin-top: 10px;
            border-top: 1px dashed #ddd;
            padding-top: 10px;
        }
        
        .reference-toggle {
            color: #666;
            font-size: 0.9rem;
            cursor: pointer;
            display: flex;
            align-items: center;
        }
        
        .reference-content {
            display: none;
            margin-top: 10px;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
            font-size: 0.85rem;
        }
        
        /* 代码样式 */
        pre {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 12px;
            margin: 10px 0;
            overflow-x: auto;
            border: 1px solid #eee;
        }
        
        code {
            font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
            font-size: 14px;
        }
        
        /* 响应式样式 */
        @media (max-width: 1200px) {
            .main-container.with-plugin .chat-container {
                max-width: 300px;
            }
        }
        
        @media (max-width: 992px) {
            .main-container {
                flex-direction: column;
            }
            
            .main-container.with-plugin .chat-container {
                max-width: 100%;
                margin-bottom: 1rem;
                height: 40vh;
            }
            
            .plugin-container {
                margin-left: 0;
                height: calc(60vh - 32px);
            }
        }
        
        @media (max-width: 768px) {
            .main-container {
                padding: 0.5rem;
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="header-content">
            <h1>{{ agent_name }}</h1>
            <div>
                <span class="badge bg-primary">AI学习助手</span>
            </div>
        </div>
    </header>
    
    <div class="main-container" id="main-container">
        <div class="chat-container">
            <div class="chat-messages" id="chat-messages">
                <div class="message bot-message">
                    <p>你好!我是{{ agent_name }},有什么可以帮助你的吗?</p>
                    {% if agent_description %}
                    <p>{{ agent_description }}</p>
                    {% endif %}
                </div>
            </div>
            
            <div class="input-container">
                <div class="input-row">
                    <textarea class="input-field" id="user-input" placeholder="输入您的问题..." rows="2"></textarea>
                    <button class="send-button" id="send-button">
                        <i class="bi bi-send"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 代码执行插件 -->
        <div class="plugin-container code-plugin" id="code-plugin">
            <div class="plugin-header">
                <h3 class="plugin-title">Python代码执行</h3>
                <button class="plugin-close" id="close-code-plugin">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="plugin-content">
                <iframe id="code-execution-frame" src="" style="width: 100%; height: 100%; border: none;"></iframe>
            </div>
        </div>
        
        <!-- 3D可视化插件 -->
        <div class="plugin-container visualization-plugin" id="visualization-plugin">
            <div class="plugin-header">
                <h3 class="plugin-title">3D可视化</h3>
                <button class="plugin-close" id="close-visualization-plugin">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="plugin-content">
                <div class="visualization-result" id="visualization-result">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-3">正在准备3D可视化...</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 思维导图插件 -->
        <div class="plugin-container mindmap-plugin" id="mindmap-plugin">
            <div class="plugin-header">
                <h3 class="plugin-title">思维导图</h3>
                <button class="plugin-close" id="close-mindmap-plugin">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="plugin-content">
                <div class="mindmap-result" id="mindmap-result">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-3">正在生成思维导图...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 全局变量
        const agentId = "{{ agent_id }}";
        const token = "{{ token }}";
        let executionContext = null;
        const mainContainer = document.getElementById('main-container');
        
        // DOM元素
        const chatMessages = document.getElementById('chat-messages');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        
        // 代码执行插件元素
        const codePlugin = document.getElementById('code-plugin');
        const closeCodePlugin = document.getElementById('close-code-plugin');
        const codeExecutionFrame = document.getElementById('code-execution-frame');
        
        // 3D可视化插件元素
        const visualizationPlugin = document.getElementById('visualization-plugin');
        const closeVisualizationPlugin = document.getElementById('close-visualization-plugin');
        const visualizationResult = document.getElementById('visualization-result');
        
        // 思维导图插件元素
        const mindmapPlugin = document.getElementById('mindmap-plugin');
        const closeMindmapPlugin = document.getElementById('close-mindmap-plugin');
        const mindmapResult = document.getElementById('mindmap-result');
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化发送按钮事件
            sendButton.addEventListener('click', sendMessage);
            
            // 初始化输入框回车事件
            userInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 初始化插件关闭事件
            closeCodePlugin.addEventListener('click', () => {
                codePlugin.style.display = 'none';
                // 清空iframe源以停止任何运行中的代码
                codeExecutionFrame.src = '';
                updateMainContainerLayout();
            });
            
            closeVisualizationPlugin.addEventListener('click', () => {
                visualizationPlugin.style.display = 'none';
                updateMainContainerLayout();
            });
            
            closeMindmapPlugin.addEventListener('click', () => {
                mindmapPlugin.style.display = 'none';
                updateMainContainerLayout();
            });
        });
        
        // 更新主容器布局
        function updateMainContainerLayout() {
            // 检查是否有任何插件处于显示状态
            const isAnyPluginVisible = 
                codePlugin.style.display === 'flex' || 
                visualizationPlugin.style.display === 'flex' || 
                mindmapPlugin.style.display === 'flex';
            
            // 更新主容器类名
            if (isAnyPluginVisible) {
                mainContainer.classList.add('with-plugin');
            } else {
                mainContainer.classList.remove('with-plugin');
            }
        }
        
        // 发送消息
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;
            
            // 添加用户消息
            addMessage(message, true);
            
            // 清空输入框
            userInput.value = '';
            
            // 禁用发送按钮
            sendButton.disabled = true;
            
            try {
                // 发送请求
                const response = await fetch(`/api/student/chat/${agentId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: message,
                        token: token
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 处理回复内容,移除参考来源部分
                    const processedContent = processResponseContent(data.message);
                    
                    // 添加机器人回复
                    const messageElement = addMessage(processedContent, false);
                    
                    // 添加参考信息(如果有)
                    if (data.references && data.references.length > 0) {
                        addReferences(messageElement, data.references);
                    }
                    
                    // 检查是否需要显示工具
                    if (data.tools && data.tools.length > 0) {
                        // 隐藏所有插件
                        hideAllPlugins();
                        
                        // 使用新的插件激活函数
                        activatePlugins(data.message, data.tools);
                    }
                } else {
                    // 添加错误消息
                    addMessage(`错误: ${data.message}`, false);
                }
            } catch (error) {
                console.error('发送请求出错:', error);
                addMessage('发送请求时出错,请重试', false);
            } finally {
                // 恢复发送按钮
                sendButton.disabled = false;
            }
        }
        
        // 处理回复内容,移除参考来源部分
        function processResponseContent(content) {
            // 移除 "===参考来源开始===" 到 "===参考来源结束===" 之间的内容
            return content.replace(/===参考来源开始===[\s\S]*?===参考来源结束===/, '');
        }
        
        // 添加参考信息显示函数
        function addReferences(messageElement, references) {
            // 创建参考容器
            const referenceContainer = document.createElement('div');
            referenceContainer.className = 'reference-container';
            
            // 创建参考切换按钮
            const toggleButton = document.createElement('div');
            toggleButton.className = 'reference-toggle';
            toggleButton.textContent = '参考来源';
            toggleButton.style.color = '#666';
            toggleButton.style.fontSize = '0.9rem';
            toggleButton.style.cursor = 'pointer';
            toggleButton.style.display = 'flex';
            toggleButton.style.alignItems = 'center';
            
            // 创建参考内容
            const referenceContent = document.createElement('div');
            referenceContent.className = 'reference-content';
            
            // 添加参考项
            references.forEach(ref => {
                const refItem = document.createElement('div');
                refItem.style.marginBottom = '8px';
                refItem.style.paddingBottom = '8px';
                refItem.style.borderBottom = '1px solid #eee';
                
                refItem.innerHTML = `
                    <div><strong>[${ref.index}]</strong> ${ref.summary}</div>
                    <div><small>来源: ${ref.file_name}</small></div>
                `;
                
                referenceContent.appendChild(refItem);
            });
            
            // 添加切换功能
            toggleButton.addEventListener('click', () => {
                if (referenceContent.style.display === 'none') {
                    referenceContent.style.display = 'block';
                    toggleButton.textContent = '折叠参考来源';
                } else {
                    referenceContent.style.display = 'none';
                    toggleButton.textContent = '参考来源';
                }
            });
            
            // 组装并添加到消息
            referenceContainer.appendChild(toggleButton);
            referenceContainer.appendChild(referenceContent);
            messageElement.appendChild(referenceContainer);
        }
        
        // 添加消息函数
        function addMessage(content, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = isUser ? 'message user-message' : 'message bot-message';
            
            // 处理内容中的换行符和代码块
            const processedContent = processMessageContent(content);
            messageDiv.innerHTML = processedContent;
            
            chatMessages.appendChild(messageDiv);
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
            
            // 对代码块应用高亮
            if (!isUser) {
                applySyntaxHighlighting(messageDiv);
            }
            
            return messageDiv;
        }
        
        // 处理消息内容中的换行符和代码块
        function processMessageContent(content) {
            // 先替换代码块,保护它们不受其他替换的影响
            const codeBlocks = [];
            let processedContent = content.replace(/```(\w*)\n([\s\S]*?)\n```/g, function(match, language, code) {
                const id = codeBlocks.length;
                codeBlocks.push({ language, code });
                return `__CODE_BLOCK_${id}__`;
            });
            
            // 替换普通换行符
            processedContent = processedContent.replace(/\n/g, '<br>');
            
            // 恢复代码块
            processedContent = processedContent.replace(/__CODE_BLOCK_(\d+)__/g, function(match, id) {
                const { language, code } = codeBlocks[id];
                const langClass = language ? ` class="language-${language}"` : '';
                return `<pre><code${langClass}>${escapeHtml(code)}</code></pre>`;
            });
            
            return processedContent;
        }
        
        // 应用语法高亮
        function applySyntaxHighlighting(element) {
            // 检查是否已加载highlight.js
            if (typeof hljs !== 'undefined') {
                // 找出所有代码块并应用高亮
                element.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightBlock(block);
                });
            }
        }
        
        // 转义HTML字符
        function escapeHtml(text) {
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
        
        // 隐藏所有插件
        function hideAllPlugins() {
            codePlugin.style.display = 'none';
            visualizationPlugin.style.display = 'none';
            mindmapPlugin.style.display = 'none';
            updateMainContainerLayout();
        }
        
        // 提取代码块
        function extractCodeBlocks(message) {
            const codeBlocks = [];
            const codeRegex = /```python\n([\s\S]*?)\n```/g;
            
            let match;
            while ((match = codeRegex.exec(message)) !== null) {
                codeBlocks.push(match[1]);
            }
            
            return codeBlocks;
        }
        
        // 提取3D可视化函数代码
        function extract3DVisualizationCode(message) {
            // 尝试提取函数代码块
            const codeRegex = /```python\s*(import[\s\S]*?def create_3d_plot\(\):[\s\S]*?return[\s\S]*?})\s*```/i;
            const match = codeRegex.exec(message);
            
            if (match) {
                return match[1].trim();
            }
            
            return null;
        }
        
        // 提取思维导图内容
        function extractMindmapContent(message) {
            // 尝试提取@startmindmap和@endmindmap之间的内容
            const mindmapRegex = /@startmindmap\n([\s\S]*?)@endmindmap/;
            const match = mindmapRegex.exec(message);
            
            if (match) {
                return `@startmindmap\n${match[1]}\n@endmindmap`;
            }
            
            return null;
        }
        
        // 激活代码执行插件
        function activateCodePlugin(message) {
            // 提取代码块
            const codeBlocks = extractCodeBlocks(message);
            
            if (codeBlocks.length > 0) {
                const isAlreadyVisible = codePlugin.style.display === 'flex';
                
                // 显示插件容器
                codePlugin.style.display = 'flex';
                updateMainContainerLayout();
                
                // 获取iframe
                const iframe = document.getElementById('code-execution-frame');
                
                // 如果插件已经可见且iframe已加载
                if (isAlreadyVisible && iframe.contentWindow) {
                    // 发送新代码到现有iframe
                    iframe.contentWindow.postMessage({
                        type: 'setCode',
                        code: codeBlocks[0]
                    }, '*');
                } else {
                    // 设置iframe源
                    let src = '/code_execution.html';
                    if (codeBlocks.length > 0) {
                        src += `?code=${encodeURIComponent(codeBlocks[0])}`;
                    }
                    
                    iframe.src = src;
                    
                    // 设置iframe加载事件处理程序
                    iframe.onload = function() {
                        if (codeBlocks.length > 0) {
                            iframe.contentWindow.postMessage({
                                type: 'setCode',
                                code: codeBlocks[0]
                            }, '*');
                        }
                    };
                }
            }
        }
        
        // 激活3D可视化插件
        // 激活3D可视化插件
function activate3DVisualization(message) {
    const code = extract3DVisualizationCode(message);
    
    if (code) {
        // 显示插件容器
        visualizationPlugin.style.display = 'flex';
        updateMainContainerLayout();
        
        // 显示加载状态
        visualizationResult.innerHTML = `
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">生成中...</span>
                </div>
                <p class="mt-3">正在生成3D图形,请稍候...</p>
            </div>
        `;
        
        // 自动生成可视化
        fetch('/api/visualization/3d-surface', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ code: code })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 直接嵌入HTML
                visualizationResult.innerHTML = `
                    <div class="visualization-iframe-container" style="width:100%; height:500px;">
                        <iframe src="${data.html_url}" style="width:100%; height:100%; border:none;"></iframe>
                    </div>
                    <div class="text-center mt-3">
                        <p>3D图形生成成功</p>
                        <a href="${data.html_url}" class="btn btn-sm btn-outline-primary" target="_blank">
                            <i class="bi bi-arrows-fullscreen"></i> 全屏查看
                        </a>
                    </div>
                `;
            } else {
                visualizationResult.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        生成失败: ${data.message}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('生成3D图形出错:', error);
            visualizationResult.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    生成3D图形时发生错误,请重试
                </div>
            `;
        });
    }
}
        // 激活思维导图插件
        function activateMindmap(message) {
            const content = extractMindmapContent(message);
            
            if (content) {
                // 显示插件容器
                mindmapPlugin.style.display = 'flex';
                updateMainContainerLayout();
                
                // 显示加载状态
                mindmapResult.innerHTML = `
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">生成中...</span>
                        </div>
                        <p class="mt-3">正在生成思维导图,请稍候...</p>
                    </div>
                `;
                
                // 自动生成思维导图
                fetch('/api/visualization/mindmap', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content: content })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        mindmapResult.innerHTML = `
                            <div class="text-center">
                                <img src="${data.url}" class="mindmap-image" alt="思维导图">
                                <p class="mt-3">生成成功!</p>
                            </div>
                        `;
                    }
                else {
                        mindmapResult.innerHTML = `
                            <div class="alert alert-danger">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                生成失败: ${data.message}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('生成思维导图出错:', error);
                    mindmapResult.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-triangle-fill me-2"></i>
                            生成思维导图时发生错误,请重试
                        </div>
                    `;
                });
            }
        }
        
        // 根据消息内容激活适当的插件
        function activatePlugins(message, tools) {
            // 检查并激活代码执行插件
            if (tools.includes('code') && message.includes('```python')) {
                activateCodePlugin(message);
            }
            
            // 检查并激活3D可视化插件
            if (tools.includes('visualization') && 
                (message.includes('def create_3d_plot') || 
                 message.includes('3D') || message.includes('可视化'))) {
                activate3DVisualization(message);
            }
            
            // 检查并激活思维导图插件
            if (tools.includes('mindmap') && 
                (message.includes('@startmindmap') || 
                 message.includes('思维导图'))) {
                activateMindmap(message);
            }
        }
    </script>
    
    <!-- 添加highlight.js用于代码高亮 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/languages/python.min.js"></script>
    <script>
        // 初始化代码高亮
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof hljs !== 'undefined') {
                hljs.configure({
                    languages: ['python']
                });
            }
        });
    </script>
</body>
</html>