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

// 插件配置 - 现在由 plugin-loader 的 scanLocalPlugins 处理
const PLUGIN_CONFIG = [];

// 初始化插件系统
async function initializePluginSystem() {
    console.log('🔧 初始化插件系统...');
    
    // 简化版本不需要预先初始化 Viser
    console.log('📋 使用简化的 Viser 管理器,将在需要时初始化');
    
    // 扫描本地插件并注册
    const localPlugins = await pluginLoader.scanLocalPlugins();
    for (const plugin of localPlugins) {
        await pluginLoader.registerPlugin({
            id: plugin.id,
            name: plugin.name,
            path: plugin.path,
            icon: plugin.icon,
            order: plugin.order || 999
        });
    }
    
    // 创建插件选项卡
    const tabsContainer = document.querySelector('.tabs-container');
    pluginLoader.createPluginTabs(tabsContainer);
    
    // 设置选项卡切换
    setupTabSwitching();
    
    // 获取第一个实际显示的插件选项卡并加载
    const firstVisibleTab = document.querySelector('.tab-button.draggable');
    if (firstVisibleTab) {
        const pluginId = firstVisibleTab.dataset.tab;
        await loadPlugin(pluginId);
    } else {
        // 如果没有插件,显示插件管理
        const pluginMgmtTab = document.querySelector('[data-tab="plugin-management"]');
        if (pluginMgmtTab) {
            pluginMgmtTab.click();
        }
    }
    
    // 静默更新插件管理界面(不显示)
    await updatePluginManagement();
    
    // 设置全局消息监听
    setupGlobalMessageHandling();
    
    console.log('✅ 插件系统初始化完成');
}

// 设置选项卡切换
function setupTabSwitching() {
    // 使用事件委托而不是直接绑定到按钮
    const tabsContainer = document.querySelector('.tabs-container');
    
    tabsContainer.addEventListener('click', async (e) => {
        // 检查是否点击了选项卡按钮
        const button = e.target.closest('.tab-button');
        if (!button) return;
        
        e.preventDefault();
        const targetTab = button.dataset.tab;
        
        // 更新所有按钮状态
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active');
        });
        button.classList.add('active');
        
        // 隐藏所有内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
            content.style.display = 'none';
        });
        
        // 如果是插件管理选项卡
        if (targetTab === 'plugin-management') {
            // 显示插件管理
            const pluginMgmt = document.getElementById('plugin-management');
            pluginMgmt.classList.add('active');
            pluginMgmt.style.display = 'flex';
            // 隐藏Viser iframe,因为插件管理不需要3D可视化
            viserManager.hideIframe();
        } else {
            // 确保插件管理内容被隐藏
            const pluginMgmt = document.getElementById('plugin-management');
            pluginMgmt.classList.remove('active');
            pluginMgmt.style.display = 'none';
            
            // 加载并显示插件
            await loadPlugin(targetTab);
            
            // 检查插件是否需要Viser可视化
            const plugin = pluginLoader.getPlugin(targetTab);
            const pluginInstance = plugin?.instance;
            const needsViser = pluginInstance?.needsViser === true;
            
            console.log(`🔍 插件 ${targetTab} 可视化需求检查:`, {
                hasPlugin: !!plugin,
                hasInstance: !!pluginInstance,
                needsViser: needsViser,
                rawNeedsViser: pluginInstance?.needsViser
            });
            
            if (needsViser) {
                // 只有明确需要Viser的插件才尝试附加
                console.log(`🔄 切换Viser到插件: ${targetTab}`);
                const pluginContainer = document.getElementById(targetTab);
                const targetContainer = pluginContainer?.querySelector('.visualization-content');
                const loadingElement = pluginContainer?.querySelector('[id*="loading"]');
                
                console.log(`🔍 选项卡切换 - 插件 ${targetTab} 容器状态:`, {
                    pluginContainer: !!pluginContainer,
                    targetContainer: !!targetContainer,
                    loadingElement: !!loadingElement,
                    needsViser: true
                });
                
                if (targetContainer) {
                    try {
                        await viserManager.attachToPlugin(targetTab, targetContainer, loadingElement);
                        
                        // 通知后端切换插件
                        if (window.controlWaveWebSocket && window.controlWaveWebSocket.isConnected) {
                            console.log(`📡 通知后端切换到插件: ${targetTab}`);
                            window.controlWaveWebSocket.send({
                                type: 'plugin_message',
                                plugin: 'viser_backend',
                                action: 'switch_plugin',
                                data: { plugin_id: targetTab }
                            });
                        }
                    } catch (error) {
                        console.error(`❌ 选项卡切换时附加Viser失败:`, error);
                    }
                } else {
                    console.warn(`⚠️ 选项卡切换 - 插件 ${targetTab} 没有可视化容器`);
                }
            } else {
                // 不需要Viser的插件,隐藏Viser
                console.log(`📝 插件 ${targetTab} 不需要Viser可视化,隐藏iframe`);
                viserManager.hideIframe();
            }
        }
    });
}

// 加载插件
async function loadPlugin(pluginId) {
    const mainContent = document.querySelector('.main-content');
    
    // 更新选项卡按钮状态
    document.querySelectorAll('.tab-button').forEach(btn => {
        btn.classList.remove('active');
    });
    const activeTab = document.querySelector(`[data-tab="${pluginId}"]`);
    if (activeTab) {
        activeTab.classList.add('active');
    }
    
    // 隐藏所有内容,包括插件管理
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.remove('active');
        content.style.display = 'none';
    });
    
    // 确保插件管理界面被隐藏
    const pluginMgmt = document.getElementById('plugin-management');
    if (pluginMgmt) {
        pluginMgmt.classList.remove('active');
        pluginMgmt.style.display = 'none';
    }
    
    // 检查插件容器是否存在
    let pluginContainer = document.getElementById(pluginId);
    if (!pluginContainer) {
        pluginContainer = document.createElement('div');
        pluginContainer.id = pluginId;
        pluginContainer.className = 'tab-content';
        mainContent.appendChild(pluginContainer);
    }
    
    // 激活插件容器
    pluginContainer.classList.add('active');
    pluginContainer.style.display = 'flex';
    
    // 加载插件内容
    await pluginLoader.initializePluginContent(pluginId, pluginContainer);
    
    // 重要:只有当插件是当前活跃插件且需要Viser时,才附加Viser
    const isActiveTab = document.querySelector(`[data-tab="${pluginId}"]`)?.classList.contains('active');
    const plugin = pluginLoader.getPlugin(pluginId);
    const pluginInstance = plugin?.instance;
    const needsViser = pluginInstance?.needsViser;
    
    console.log(`🔍 检查插件 ${pluginId} 是否需要附加Viser:`, {
        isActiveTab,
        needsViser,
        hasVisualizationContent: !!pluginContainer.querySelector('.visualization-content')
    });
    
    if (isActiveTab && needsViser) {
        console.log(`🎯 ${pluginId} 是活跃插件且需要Viser,附加Viser...`);
        const targetContainer = pluginContainer.querySelector('.visualization-content');
        const loadingElement = pluginContainer.querySelector('[id*="loading"]');
        if (targetContainer) {
            try {
                await viserManager.attachToPlugin(pluginId, targetContainer, loadingElement);
            } catch (error) {
                console.error(`❌ 附加Viser到插件 ${pluginId} 失败:`, error);
            }
        } else {
            console.warn(`⚠️ 插件 ${pluginId} 没有找到 .visualization-content 容器`);
        }
    } else if (isActiveTab && !needsViser) {
        console.log(`📝 插件 ${pluginId} 是活跃插件但不需要Viser,隐藏iframe`);
        viserManager.hideIframe();
    }
}

// 默认插件顺序
const DEFAULT_PLUGIN_ORDER = [
    'wave-space',
    'preview', 
    'full-render',
    'training-visualization-v2'
];

// 获取保存的插件顺序
function getSavedPluginOrder() {
    const saved = localStorage.getItem('controlwave_plugin_order');
    if (saved) {
        try {
            return JSON.parse(saved);
        } catch (e) {
            console.error('解析保存的插件顺序失败:', e);
        }
    }
    return DEFAULT_PLUGIN_ORDER;
}

// 保存插件顺序
function savePluginOrder(order) {
    localStorage.setItem('controlwave_plugin_order', JSON.stringify(order));
}

// 更新插件管理界面
async function updatePluginManagement() {
    const tableBody = document.getElementById('plugin-table-body');
    if (!tableBody) return;
    
    tableBody.innerHTML = '';
    
    // 获取所有可用插件(包括本地扫描的)
    const allPlugins = await pluginLoader.getAllPluginsWithLocal();
    
    allPlugins.forEach(plugin => {
        const row = createPluginTableRow(plugin);
        tableBody.appendChild(row);
    });
    
    // 更新默认插件顺序列表
    updateDefaultPluginsList();
    
    // 设置事件监听器
    setupPluginManagementEvents();
}

// 更新默认插件顺序列表
function updateDefaultPluginsList() {
    const listContainer = document.getElementById('default-plugins-list');
    if (!listContainer) return;
    
    const savedOrder = getSavedPluginOrder();
    const installedPlugins = pluginLoader.getInstalledPlugins();
    
    // 清空列表
    listContainer.innerHTML = '';
    
    // 只显示已安装的默认插件
    savedOrder.forEach(pluginId => {
        const plugin = installedPlugins.find(p => p.id === pluginId);
        if (plugin) {
            const item = createSortableItem(plugin);
            listContainer.appendChild(item);
        }
    });
    
    // 启用拖拽排序
    enableDragAndDrop(listContainer);
}

// 创建可排序的插件项
function createSortableItem(plugin) {
    const item = document.createElement('div');
    item.className = 'sortable-item';
    item.draggable = true;
    item.dataset.pluginId = plugin.id;
    
    item.innerHTML = `
        <span class="drag-handle">≡</span>
        <span class="plugin-name">${plugin.name}</span>
        <span class="plugin-id">(${plugin.id})</span>
    `;
    
    return item;
}

// 启用拖拽排序功能
function enableDragAndDrop(container) {
    let draggedElement = null;
    
    container.addEventListener('dragstart', (e) => {
        if (e.target.classList.contains('sortable-item')) {
            draggedElement = e.target;
            e.target.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/html', e.target.innerHTML);
        }
    });
    
    container.addEventListener('dragend', (e) => {
        if (e.target.classList.contains('sortable-item')) {
            e.target.classList.remove('dragging');
        }
    });
    
    container.addEventListener('dragover', (e) => {
        e.preventDefault();
        const afterElement = getDragAfterElement(container, e.clientY);
        
        if (afterElement == null) {
            container.appendChild(draggedElement);
        } else {
            container.insertBefore(draggedElement, afterElement);
        }
    });
    
    container.addEventListener('drop', (e) => {
        e.preventDefault();
        
        // 保存新的顺序
        const items = [...container.querySelectorAll('.sortable-item')];
        const newOrder = items.map(item => item.dataset.pluginId);
        savePluginOrder(newOrder);
        
        // 重新创建选项卡以应用新顺序
        const tabsContainer = document.querySelector('.tabs-container');
        pluginLoader.createPluginTabs(tabsContainer);
        setupTabSwitching();
        
        console.log('插件顺序已更新:', newOrder);
    });
}

// 获取拖拽后的位置
function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.sortable-item:not(.dragging)')];
    
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}

// 创建插件表格行
function createPluginTableRow(plugin) {
    const row = document.createElement('tr');
    const isInstalled = pluginLoader.installedPlugins.has(plugin.id);
    
    row.innerHTML = `
        <td>
            <div style="display: flex; align-items: center; gap: 8px;">
                <span>${plugin.name}</span>
                ${plugin.isOfficial ? '<span class="plugin-status official">官方</span>' : ''}
                ${plugin.isLocal ? '<span class="plugin-status local">本地</span>' : ''}
            </div>
        </td>
        <td>${plugin.version}</td>
        <td>${plugin.author}</td>
        <td>
            <span class="plugin-status ${isInstalled ? 'installed' : 'not-installed'}">
                ${isInstalled ? '已安装' : '未安装'}
            </span>
        </td>
        <td>
            ${plugin.repository ? `<a href="${plugin.repository}" target="_blank" class="repository-link">${getShortUrl(plugin.repository)}</a>` : (plugin.isLocal ? '<span class="repository-link">本地插件</span>' : 'N/A')}
        </td>
        <td>
            ${createActionButtons(plugin.id, isInstalled)}
        </td>
    `;
    
    return row;
}

// 创建操作按钮
function createActionButtons(pluginId, isInstalled) {
    if (isInstalled) {
        return `<button class="action-btn uninstall" onclick="handleUninstallPlugin('${pluginId}')">卸载</button>`;
    } else {
        return `<button class="action-btn install" onclick="handleInstallPlugin('${pluginId}')">安装</button>`;
    }
}

// 获取短URL
function getShortUrl(url) {
    try {
        const urlObj = new URL(url);
        const parts = urlObj.pathname.split('/');
        if (parts.length >= 3) {
            return `${parts[1]}/${parts[2]}`;
        }
        return urlObj.hostname;
    } catch (e) {
        return url.substring(0, 30) + '...';
    }
}

// 设置插件管理事件
function setupPluginManagementEvents() {
    // URL安装按钮
    const installFromUrlBtn = document.getElementById('install-from-url-btn');
    const installLocalBtn = document.getElementById('install-local-btn');
    const refreshBtn = document.getElementById('refresh-plugins-btn');
    const clearCacheBtn = document.getElementById('clear-cache-btn');
    
    if (installFromUrlBtn) {
        installFromUrlBtn.addEventListener('click', handleInstallFromUrl);
    }
    
    if (installLocalBtn) {
        installLocalBtn.addEventListener('click', handleInstallLocal);
    }
    
    if (refreshBtn) {
        refreshBtn.addEventListener('click', async () => {
            await updatePluginManagement();
            console.log('🔄 插件列表已刷新(包含本地扫描)');
        });
    }
    
    if (clearCacheBtn) {
        clearCacheBtn.addEventListener('click', () => {
            localStorage.removeItem('controlwave_plugins');
            console.log('🗑️ 插件缓存已清除');
        });
    }
}

// 处理从URL安装插件
async function handleInstallFromUrl() {
    const urlInput = document.getElementById('plugin-url');
    const url = urlInput.value.trim();
    
    if (!url) {
        alert('请输入有效的URL');
        return;
    }
    
    try {
        console.log(`📥 正在从URL安装插件: ${url}`);
        
        // 显示加载状态
        const installBtn = document.getElementById('install-from-url-btn');
        const originalText = installBtn.textContent;
        installBtn.textContent = '安装中...';
        installBtn.disabled = true;
        
        // 调用服务器API下载插件
        const response = await fetch('/api/plugins/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ url })
        });
        
        const result = await response.json();
        
        if (result.status === 'not_implemented') {
            // 临时提示
            alert('GitHub插件下载功能正在开发中\n\n手动安装步骤:\n1. 下载插件仓库\n2. 将插件文件夹复制到 plugins/ 目录\n3. 刷新页面');
        } else if (result.status === 'success') {
            alert(`插件安装成功!\n\n插件ID: ${result.pluginId}\n插件名称: ${result.pluginName}`);
            urlInput.value = '';
            
            // 刷新插件列表
            await updatePluginManagement();
            
            // 重新创建选项卡
            const tabsContainer = document.querySelector('.tabs-container');
            pluginLoader.createPluginTabs(tabsContainer);
            setupTabSwitching();
        } else {
            alert('安装失败: ' + (result.message || '未知错误'));
        }
        
        // 恢复按钮状态
        installBtn.textContent = originalText;
        installBtn.disabled = false;
        
    } catch (error) {
        console.error('安装插件失败:', error);
        alert('安装插件失败: ' + error.message);
        
        // 恢复按钮状态
        const installBtn = document.getElementById('install-from-url-btn');
        installBtn.textContent = '从URL安装';
        installBtn.disabled = false;
    }
}

// 处理本地安装
async function handleInstallLocal() {
    // 检查浏览器是否支持 File System Access API
    if ('showDirectoryPicker' in window) {
        try {
            const directoryHandle = await window.showDirectoryPicker();
            
            // 验证选择的文件夹是否为有效插件
            const isValidPlugin = await validatePluginDirectory(directoryHandle);
            
            if (isValidPlugin) {
                // 这里应该调用后端API将插件复制到plugins目录
                alert(`插件文件夹 "${directoryHandle.name}" 验证成功!\n\n实际部署时将:\n1. 复制插件到plugins目录\n2. 验证插件结构\n3. 重新加载插件列表`);
            } else {
                alert('选择的文件夹不是有效的插件目录\n\n有效插件目录应包含:\n- index.js 文件\n- 符合插件规范的代码结构');
            }
        } catch (error) {
            if (error.name !== 'AbortError') {
                console.error('选择文件夹失败:', error);
                alert('选择文件夹失败: ' + error.message);
            }
        }
    } else {
        // 回退方案:使用文件输入
        const input = document.createElement('input');
        input.type = 'file';
        input.webkitdirectory = true;
        input.multiple = true;
        
        input.addEventListener('change', (event) => {
            const files = Array.from(event.target.files);
            if (files.length === 0) return;
            
            // 检查是否包含 index.js
            const hasIndexJs = files.some(file => file.name === 'index.js');
            
            if (hasIndexJs) {
                const folderName = files[0].webkitRelativePath.split('/')[0];
                alert(`插件文件夹 "${folderName}" 验证成功!\n\n实际部署时将:\n1. 上传插件文件\n2. 解析插件结构\n3. 重新加载插件列表`);
            } else {
                alert('选择的文件夹不是有效的插件目录\n\n有效插件目录应包含 index.js 文件');
            }
        });
        
        input.click();
    }
}

// 验证插件目录
async function validatePluginDirectory(directoryHandle) {
    try {
        // 检查是否存在 index.js 文件
        const indexJsHandle = await directoryHandle.getFileHandle('index.js');
        
        // 可以进一步验证文件内容
        const file = await indexJsHandle.getFile();
        const content = await file.text();
        
        // 简单验证:检查是否包含插件类定义
        const hasPluginClass = content.includes('ControlWavePlugin') || content.includes('export default');
        
        return hasPluginClass;
    } catch (error) {
        return false;
    }
}

// 处理安装插件
async function handleInstallPlugin(pluginId) {
    try {
        await pluginLoader.installPlugin(pluginId);
        
        // 重新创建选项卡
        const tabsContainer = document.querySelector('.tabs-container');
        pluginLoader.createPluginTabs(tabsContainer);
        setupTabSwitching();
        
        // 更新插件管理界面
        updatePluginManagement();
        
        alert(`插件 ${pluginId} 安装成功!`);
    } catch (error) {
        console.error('安装插件失败:', error);
        alert('安装插件失败: ' + error.message);
    }
}

// 处理卸载插件
async function handleUninstallPlugin(pluginId) {
    // 显示强烈的警告对话框
    const confirmMessage = `⚠️ 警告:即将永久删除插件文件夹!

插件ID: ${pluginId}

此操作将:
• 从文件系统中完全删除插件文件夹
• 删除所有插件文件和数据
• 此操作无法撤销

确定要继续吗?`;

    if (!confirm(confirmMessage)) {
        return;
    }
    
    // 二次确认
    if (!confirm(`最后确认:真的要永久删除插件 "${pluginId}" 的所有文件吗?`)) {
        return;
    }
    
    try {
        // 显示加载状态
        const uninstallButtons = document.querySelectorAll(`button[onclick="handleUninstallPlugin('${pluginId}')"]`);
        uninstallButtons.forEach(btn => {
            btn.textContent = '删除中...';
            btn.disabled = true;
        });
        
        console.log(`🗑️ 正在删除插件: ${pluginId}`);
        
        // 调用后端API删除插件文件夹
        const response = await fetch(`/api/plugins/${encodeURIComponent(pluginId)}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            console.log(`✅ 插件删除成功: ${result.message}`);
            
            // 从插件加载器中卸载插件
            await pluginLoader.uninstallPlugin(pluginId);
            
            // 重新创建选项卡
            const tabsContainer = document.querySelector('.tabs-container');
            pluginLoader.createPluginTabs(tabsContainer);
            setupTabSwitching();
            
            // 更新插件管理界面
            updatePluginManagement();
            
            // 如果当前显示的是被卸载的插件,切换到插件管理
            const currentTab = document.querySelector('.tab-button.active');
            if (currentTab && currentTab.dataset.tab === pluginId) {
                document.querySelector('[data-tab="plugin-management"]').click();
            }
            
            alert(`插件 "${pluginId}" 已成功删除!\n\n删除路径: ${result.deletedPath}`);
        } else {
            console.error('删除插件失败:', result.message);
            alert(`删除插件失败: ${result.message}`);
        }
        
    } catch (error) {
        console.error('卸载插件时发生错误:', error);
        alert(`删除插件时发生错误: ${error.message}`);
    } finally {
        // 恢复按钮状态
        const uninstallButtons = document.querySelectorAll(`button[onclick="handleUninstallPlugin('${pluginId}')"]`);
        uninstallButtons.forEach(btn => {
            btn.textContent = '卸载';
            btn.disabled = false;
        });
    }
}

// 设置全局消息处理
function setupGlobalMessageHandling() {
    // 监听来自 Viser iframe 的消息
    window.addEventListener('message', (event) => {
        // 确保是来自 Viser 的消息
        if (event.origin.includes('localhost') && event.data) {
            // 广播给所有插件
            viserManager.broadcastToPlugins(event.data);
            
            // 处理状态同步消息
            if (event.data.type === 'cameraStateChange' || event.data.type === 'sceneStateChange') {
                console.log('🔄 Viser 状态变化,广播给所有插件:', event.data);
            }
        }
    });
    
    console.log('📡 全局消息处理已设置');
}

// 导出全局函数
window.handleInstallPlugin = handleInstallPlugin;
window.handleUninstallPlugin = handleUninstallPlugin;

// 监听插件顺序变化事件
window.addEventListener('plugin-order-changed', (event) => {
    const newOrder = event.detail;
    // 更新默认插件顺序列表
    updateDefaultPluginsList();
    console.log('插件顺序已同步更新:', newOrder);
});

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 先调用旧的初始化函数(如果需要)
    if (typeof initializeApp === 'function') {
        initializeApp();
    }
    
    // 初始化插件系统
    initializePluginSystem();
});