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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
#!/usr/bin/env python3
"""
ControlWave 现代化架构 - FastAPI + Viser 集成
"""

import asyncio
import contextlib
import os
import sys
from pathlib import Path
import threading
import json
from typing import Optional, Dict, Any
import signal
import numpy as np
import subprocess

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

# 添加当前目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from viser_backend import WaveVisualizationServer

# 自定义JSON编码器,处理numpy类型
class NumpyJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, (np.generic, np.number)):
            return obj.item()
        elif isinstance(obj, (np.floating, np.complexfloating)):
            return float(obj)
        elif isinstance(obj, (np.integer, np.bool_)):
            return int(obj)
        return super().default(obj)


class ModernControlWave:
    def __init__(self, frontend_port=8080, viser_port=8081):
        self.frontend_port = frontend_port
        self.viser_port = viser_port
        
        # FastAPI 应用
        self.app = FastAPI(title="ControlWave")
        self.setup_middleware()
        self.setup_routes()
        
        # Viser 服务器
        self.viser_server = None
        self.viser_thread = None
        
        # WebSocket 连接管理
        self.active_connections: list[WebSocket] = []
        
        # 系统状态
        self.is_shutting_down = False

    @staticmethod
    def _is_plugin_directory(folder: Path) -> bool:
        if folder.name.startswith('.') or folder.name.startswith('__'):
            return False
        if folder.is_dir():
            return True
        if folder.is_symlink():
            with contextlib.suppress(Exception):
                return folder.resolve().is_dir()
        return False
    
    def setup_middleware(self):
        """设置中间件"""
        self.app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    
    def setup_routes(self):
        """设置路由"""
        
        @self.app.get("/")
        async def root():
            """主页面"""
            # 读取 HTML 文件并添加时间戳
            with open("signerx_index.html", "r", encoding="utf-8") as f:
                html_content = f.read()
            
            # 在所有 script 和 link 标签中添加时间戳
            import time
            timestamp = int(time.time())
            
            # 添加时间戳到 script src
            html_content = html_content.replace('.js"', f'.js?t={timestamp}"')
            # 添加时间戳到 link href
            html_content = html_content.replace('.css"', f'.css?t={timestamp}"')
            
            return HTMLResponse(content=html_content)
        
        @self.app.get("/api/status")
        async def get_status():
            """获取系统状态"""
            return {
                "status": "running",
                "viser_port": self.viser_port,
                "viser_active": self.viser_server is not None
            }
        
        @self.app.get("/api/waves")
        async def get_waves():
            """获取波函数列表"""
            if self.viser_server:
                return {"waves": self.viser_server.waves}
            return {"waves": []}
        
        @self.app.get("/api/core_space/list")
        async def list_core_space():
            """列出所有训练结果目录"""
            core_space_path = Path("core_space")
            if not core_space_path.exists():
                return {"folders": []}
            
            folders = []
            for folder in sorted(core_space_path.iterdir(), reverse=True):
                if folder.is_dir() and not folder.name.startswith('.'):
                    # 解析文件夹名称
                    parts = folder.name.split('_')
                    
                    # 处理两种格式:
                    # 1. 旧格式:20250725_182640_epoch0_step100_stage0_waves1
                    # 2. 新格式:20250806_202510_step20_stage0_waves1
                    
                    folder_info = {
                        "name": folder.name,
                        "timestamp": parts[0] + '_' + parts[1] if len(parts) >= 2 else '',
                    }
                    
                    # 查找各个关键字的位置
                    epoch_idx = -1
                    step_idx = -1
                    stage_idx = -1
                    waves_idx = -1
                    
                    for i, part in enumerate(parts):
                        if 'epoch' in part:
                            epoch_idx = i
                        elif 'step' in part:
                            step_idx = i
                        elif 'stage' in part:
                            stage_idx = i
                        elif 'waves' in part:
                            waves_idx = i
                    
                    # 提取值
                    folder_info["epoch"] = parts[epoch_idx].replace('epoch', '') if epoch_idx != -1 else 'N/A'
                    folder_info["step"] = parts[step_idx].replace('step', '') if step_idx != -1 else 'N/A'
                    folder_info["stage"] = parts[stage_idx].replace('stage', '') if stage_idx != -1 else 'N/A'
                    folder_info["waves"] = parts[waves_idx].replace('waves', '') if waves_idx != -1 else '1'
                    
                    folders.append(folder_info)
            
            return {"folders": folders}
        
        @self.app.get("/api/core_space/samples/{folder}")
        async def list_samples(folder: str):
            """列出指定目录的样本"""
            folder_path = Path("core_space") / folder
            if not folder_path.exists():
                return {"samples": []}
            
            samples = set()
            for file in folder_path.iterdir():
                if file.name.startswith("sample_") and file.name.endswith("_text.txt"):
                    sample_id = file.name.replace("_text.txt", "")
                    samples.add(sample_id)
            
            return {"samples": sorted(list(samples))}
        
        @self.app.get("/api/plugins/scan")
        async def scan_plugins():
            """扫描插件文件夹并返回所有可用插件"""
            plugins_path = Path("plugins")
            if not plugins_path.exists():
                return {"plugins": [], "duplicates": []}
            
            plugins = []
            seen_ids = {}  # 记录已见过的ID
            duplicates = []  # 记录重复的插件
            
            # 扫描所有子文件夹
            for folder in sorted(plugins_path.iterdir()):
                if not self._is_plugin_directory(folder):
                    continue
                index_js = folder / "index.js"
                    
                if index_js.exists():
                    try:
                        # 读取index.js文件内容
                        with open(index_js, 'r', encoding='utf-8') as f:
                            content = f.read()
                        
                        mtime_tag = int(index_js.stat().st_mtime)
                        # 解析插件信息
                        plugin_info = {
                            "folder": folder.name,
                            "path": f"/plugins/{folder.name}/index.js?t={mtime_tag}",
                            "hasViserBackend": (folder / "viser_backend.py").exists(),
                            "hasApiHandler": (folder / "api_handler.py").exists()
                        }
                        
                        # 尝试提取ID和名称
                        # 查找 id: 'xxx' 或 id: "xxx"
                        import re
                        id_match = re.search(r"id\s*:\s*['\"]([^'\"]+)['\"]", content)
                        name_match = re.search(r"name\s*:\s*['\"]([^'\"]+)['\"]", content)
                        version_match = re.search(r"version\s*:\s*['\"]([^'\"]+)['\"]", content)
                        author_match = re.search(r"author\s*:\s*['\"]([^'\"]+)['\"]", content)
                        description_match = re.search(r"description\s*:\s*['\"]([^'\"]+)['\"]", content)
                        order_match = re.search(r"order\s*:\s*(\d+)", content)
                        
                        if id_match:
                            plugin_id = id_match.group(1)
                            plugin_info["id"] = plugin_id
                            
                            # 检查ID是否重复
                            if plugin_id in seen_ids:
                                duplicates.append({
                                    "id": plugin_id,
                                    "folders": [seen_ids[plugin_id]["folder"], folder.name],
                                    "message": f"插件ID '{plugin_id}' 在文件夹 '{seen_ids[plugin_id]['folder']}' 和 '{folder.name}' 中重复"
                                })
                                continue  # 跳过重复的插件
                            else:
                                seen_ids[plugin_id] = plugin_info
                        else:
                            # 如果没有找到ID,使用文件夹名作为ID
                            plugin_info["id"] = folder.name
                        
                        plugin_info["name"] = name_match.group(1) if name_match else folder.name
                        plugin_info["version"] = version_match.group(1) if version_match else "1.0.0"
                        plugin_info["author"] = author_match.group(1) if author_match else "Unknown"
                        plugin_info["description"] = description_match.group(1) if description_match else ""
                        plugin_info["order"] = int(order_match.group(1)) if order_match else 999
                        plugin_info["isLocal"] = True
                        plugin_info["isOfficial"] = False  # 可以根据作者判断
                        
                        plugins.append(plugin_info)
                        
                    except Exception as e:
                        print(f"❌ 无法解析插件 {folder.name}: {e}")
                        # 仍然添加这个插件,但使用默认值
                        plugins.append({
                            "id": folder.name,
                            "name": folder.name,
                            "folder": folder.name,
                            "path": f"/plugins/{folder.name}/index.js?t={mtime_tag}",
                            "version": "1.0.0",
                            "author": "Unknown",
                            "description": "",
                            "order": 999,
                            "hasViserBackend": (folder / "viser_backend.py").exists(),
                            "hasApiHandler": (folder / "api_handler.py").exists(),
                            "isLocal": True,
                            "isOfficial": False
                        })
            
            # 按order排序
            plugins.sort(key=lambda x: x.get("order", 999))
            
            return {"plugins": plugins, "duplicates": duplicates}
        
        @self.app.post("/api/plugins/download")
        async def download_plugin(request: Request):
            """从GitHub/Hugging Face URL下载插件"""
            import subprocess
            import shutil
            import tempfile
            from urllib.parse import urlparse
            
            # 获取请求体中的JSON数据
            data = await request.json()
            url = data.get('url', '')
            
            if not url:
                return {
                    "status": "error",
                    "message": "URL参数缺失"
                }
            
            def parse_repo_url(raw_url: str):
                parsed = urlparse(raw_url)
                if parsed.scheme not in ("http", "https") or not parsed.netloc:
                    return None, "请提供有效的GitHub或Hugging Face仓库URL"

                host = parsed.netloc.lower()
                if host.startswith("www."):
                    host = host[4:]

                allowed_hosts = {"github.com", "huggingface.co", "hf.co"}
                if host not in allowed_hosts:
                    return None, "请提供有效的GitHub或Hugging Face仓库URL"

                path_parts = [part for part in parsed.path.split('/') if part]
                if not path_parts:
                    return None, "仓库URL缺少路径"

                tree_index = path_parts.index("tree") if "tree" in path_parts else None
                subfolder_path = None

                if tree_index is not None:
                    if len(path_parts) <= tree_index + 1:
                        return None, "无效的仓库子文件夹URL"
                    subfolder_parts = path_parts[tree_index + 2:]
                    subfolder_path = "/".join(subfolder_parts) if subfolder_parts else None
                    base_parts = path_parts[:tree_index]
                else:
                    base_parts = path_parts

                if not base_parts:
                    return None, "仓库URL缺少仓库名"

                base_parts[-1] = base_parts[-1].removesuffix(".git")
                repo_name = base_parts[-1]

                if host == "github.com" and len(base_parts) < 2:
                    return None, "GitHub仓库URL应包含用户名和仓库名"

                if host in {"huggingface.co", "hf.co"}:
                    # 允许 spaces/datasets/models/<user>/<repo>
                    if base_parts[0] in {"spaces", "datasets", "models"}:
                        if len(base_parts) < 3:
                            return None, "Hugging Face仓库URL格式不完整"
                    # 其他路径直接继续,仍按 repo_name 处理

                repo_url = f"{parsed.scheme}://{parsed.netloc}/{'/'.join(base_parts)}"
                if host == "github.com" and not repo_url.endswith(".git"):
                    repo_url = f"{repo_url}.git"

                return {
                    "host": host,
                    "repo_url": repo_url,
                    "repo_name": repo_name,
                    "subfolder_path": subfolder_path
                }, None

            parsed_info, parse_error = parse_repo_url(url)
            if parse_error:
                return {
                    "status": "error",
                    "message": parse_error
                }
            
            try:
                repo_url = parsed_info["repo_url"]
                repo_name = parsed_info["repo_name"]
                subfolder_path = parsed_info["subfolder_path"]
                
                plugins_path = Path("plugins")
                plugins_path.mkdir(exist_ok=True)
                
                # 使用临时目录克隆仓库
                with tempfile.TemporaryDirectory() as temp_dir:
                    temp_path = Path(temp_dir)
                    
                    print(f"🔄 克隆仓库: {repo_url}")
                    
                    # 使用git clone命令
                    result = subprocess.run(
                        ['git', 'clone', '--depth', '1', repo_url, str(temp_path / repo_name)],
                        capture_output=True,
                        text=True
                    )
                    
                    if result.returncode != 0:
                        return {
                            "status": "error",
                            "message": f"Git克隆失败: {result.stderr}"
                        }
                    
                    # 确定源路径和目标路径
                    if subfolder_path:
                        source_path = temp_path / repo_name / subfolder_path
                        plugin_name = subfolder_path.split('/')[-1]
                    else:
                        source_path = temp_path / repo_name
                        plugin_name = repo_name
                    
                    # 检查源路径是否存在
                    if not source_path.exists():
                        return {
                            "status": "error",
                            "message": f"找不到插件路径: {source_path}"
                        }
                    
                    # 检查是否包含index.js
                    if not (source_path / "index.js").exists():
                        return {
                            "status": "error",
                            "message": "该目录不是有效的插件(缺少index.js文件)"
                        }
                    
                    # 目标路径
                    target_path = plugins_path / plugin_name
                    
                    # 如果目标已存在,询问是否覆盖
                    if target_path.exists():
                        # 为了API简单,直接覆盖
                        shutil.rmtree(target_path)
                    
                    # 复制插件文件夹(保留符号链接,忽略断开的链接)
                    shutil.copytree(source_path, target_path,
                                   symlinks=True,
                                   ignore_dangling_symlinks=True)

                    # 检测并修复虚拟环境(保留已安装的包,但更新符号链接)
                    venv_dirs = list(target_path.glob('.venv*')) + list(target_path.glob('venv*'))
                    for venv_dir in venv_dirs:
                        if venv_dir.is_dir() and (venv_dir / 'pyvenv.cfg').exists():
                            print(f"🔧 检测到虚拟环境 {venv_dir.name},正在修复符号链接...")
                            try:
                                bin_dir = venv_dir / 'bin'
                                if not bin_dir.exists():
                                    bin_dir = venv_dir / 'Scripts'  # Windows

                                if bin_dir.exists():
                                    # 删除所有断开的 python* 符号链接
                                    for link in bin_dir.glob('python*'):
                                        if link.is_symlink():
                                            link.unlink()

                                    # 重新创建符号链接指向当前系统的 Python
                                    python_exe = Path(sys.executable)
                                    (bin_dir / 'python').symlink_to(python_exe)
                                    (bin_dir / 'python3').symlink_to(python_exe)

                                    # 更新 pyvenv.cfg 中的 home 路径
                                    cfg_file = venv_dir / 'pyvenv.cfg'
                                    if cfg_file.exists():
                                        cfg_content = cfg_file.read_text()
                                        # 更新 home 为当前 Python 的路径
                                        import re
                                        python_home = str(python_exe.parent)
                                        cfg_content = re.sub(
                                            r'home = .*',
                                            f'home = {python_home}',
                                            cfg_content
                                        )
                                        cfg_file.write_text(cfg_content)

                                    print(f"✅ 虚拟环境 {venv_dir.name} 符号链接已修复")

                                    # 检查是否需要安装依赖
                                    setup_script = target_path / 'setup_venv.sh'
                                    requirements_file = target_path / 'requirements.txt'

                                    if setup_script.exists():
                                        print(f"📦 检测到 setup_venv.sh,正在运行安装脚本...")
                                        result = subprocess.run(
                                            ['bash', './setup_venv.sh'],
                                            cwd=str(target_path),
                                            capture_output=True,
                                            text=True,
                                            timeout=600  # 10分钟超时
                                        )
                                        if result.returncode == 0:
                                            print(f"✅ 依赖安装成功")
                                        else:
                                            print(f"⚠️  依赖安装失败: {result.stderr}")
                                    elif requirements_file.exists():
                                        print(f"📦 检测到 requirements.txt,正在安装依赖...")
                                        pip_exe = bin_dir / 'pip'
                                        if not pip_exe.exists():
                                            pip_exe = bin_dir / 'pip3'
                                        result = subprocess.run(
                                            [str(bin_dir / 'python'), '-m', 'pip', 'install', '-r', str(requirements_file)],
                                            cwd=str(target_path),
                                            capture_output=True,
                                            text=True,
                                            timeout=600
                                        )
                                        if result.returncode == 0:
                                            print(f"✅ 依赖安装成功")
                                        else:
                                            print(f"⚠️  依赖安装失败: {result.stderr}")
                                else:
                                    print(f"⚠️  虚拟环境 {venv_dir.name} 缺少 bin 目录")
                            except subprocess.TimeoutExpired:
                                print(f"⚠️  依赖安装超时(超过10分钟)")
                            except Exception as e:
                                print(f"⚠️  虚拟环境 {venv_dir.name} 修复失败: {str(e)}")

                    print(f"✅ 插件安装成功: {plugin_name}")
                    
                    # 如果没有 index.js,生成一个简单的 iframe 包装以便插件系统识别
                    index_js_path = target_path / "index.js"
                    if not index_js_path.exists():
                        iframe_src = f"/plugins/{plugin_name}/index.html"
                        wrapper = f"""import {{ ControlWavePlugin }} from '../plugin-loader.js';

export default class HFSpaceWrapper extends ControlWavePlugin {{
    constructor() {{
        super({{
            id: '{plugin_name}',
            name: '{plugin_name}',
            version: '0.0.1',
            author: 'HF Import',
            description: 'Imported from HF Space',
            needsViser: false
        }});
    }}

    async render(container) {{
        container.innerHTML = '';
        container.className = 'tab-content active';
        const frame = document.createElement('iframe');
        frame.style.width = '100%';
        frame.style.height = '100%';
        frame.style.border = 'none';
        frame.src = '{iframe_src}';
        container.appendChild(frame);
    }}
}}
"""
                        try:
                            index_js_path.write_text(wrapper, encoding="utf-8")
                            print(f"ℹ️ 插件缺少 index.js,已生成 iframe 包装指向 {iframe_src}")
                        except Exception as e:
                            print(f"⚠️ 生成包装 index.js 失败: {e}")
                    
                    # 读取插件信息
                    plugin_info = {"id": plugin_name, "name": plugin_name}
                    try:
                        with open(target_path / "index.js", 'r', encoding='utf-8') as f:
                            content = f.read()
                            
                        import re
                        id_match = re.search(r"id\s*:\s*['\"]([^'\"]+)['\"]", content)
                        name_match = re.search(r"name\s*:\s*['\"]([^'\"]+)['\"]", content)
                        
                        if id_match:
                            plugin_info["id"] = id_match.group(1)
                        if name_match:
                            plugin_info["name"] = name_match.group(1)
                    except:
                        pass
                    
                    return {
                        "status": "success",
                        "message": f"插件 '{plugin_info['name']}' 安装成功",
                        "pluginId": plugin_info["id"],
                        "pluginName": plugin_info["name"],
                        "pluginPath": str(target_path)
                    }
                    
            except subprocess.CalledProcessError as e:
                return {
                    "status": "error",
                    "message": f"执行git命令失败: {str(e)}"
                }
            except Exception as e:
                import traceback
                traceback.print_exc()
                return {
                    "status": "error",
                    "message": f"安装插件时发生错误: {str(e)}"
                }
        
        @self.app.delete("/api/plugins/{plugin_id}")
        async def delete_plugin(plugin_id: str):
            """删除插件文件夹"""
            import shutil
            
            try:
                plugins_path = Path("plugins")
                if not plugins_path.exists():
                    return {
                        "status": "error",
                        "message": "插件目录不存在"
                    }
                
                # 根据插件ID查找对应的文件夹
                plugin_folder = None
                
                # 扫描所有插件文件夹,寻找匹配的插件ID
                for folder in plugins_path.iterdir():
                    if self._is_plugin_directory(folder):
                        index_js = folder / "index.js"
                        
                        if index_js.exists():
                            try:
                                # 读取index.js文件内容
                                with open(index_js, 'r', encoding='utf-8') as f:
                                    content = f.read()
                                
                                # 提取插件ID
                                import re
                                id_match = re.search(r"id\s*:\s*['\"]([^'\"]+)['\"]", content)
                                
                                if id_match and id_match.group(1) == plugin_id:
                                    plugin_folder = folder
                                    break
                                elif folder.name == plugin_id:
                                    # 如果没有找到ID,使用文件夹名作为ID
                                    plugin_folder = folder
                                    break
                            except Exception:
                                # 如果无法解析插件,但文件夹名匹配,也可以删除
                                if folder.name == plugin_id:
                                    plugin_folder = folder
                                    break
                
                if not plugin_folder:
                    return {
                        "status": "error",
                        "message": f"未找到插件 '{plugin_id}'"
                    }
                
                if not plugin_folder.exists():
                    return {
                        "status": "error",
                        "message": f"插件文件夹不存在: {plugin_folder}"
                    }
                
                # 删除整个插件文件夹
                shutil.rmtree(plugin_folder)
                
                print(f"✅ 插件 {plugin_id} 已删除: {plugin_folder}")
                
                return {
                    "status": "success",
                    "message": f"插件 '{plugin_id}' 已成功删除",
                    "deletedPath": str(plugin_folder)
                }
                
            except PermissionError:
                return {
                    "status": "error",
                    "message": "没有权限删除插件文件夹,请检查文件权限"
                }
            except Exception as e:
                import traceback
                traceback.print_exc()
                return {
                    "status": "error",
                    "message": f"删除插件时发生错误: {str(e)}"
                }
        
        @self.app.get("/api/core_space/load/{folder}/{sample}")
        async def load_sample(folder: str, sample: str, frame: int = 0):
            """加载NPZ数据"""
            import numpy as np
            
            folder_path = Path("core_space") / folder
            if not folder_path.exists():
                return {"error": "Folder not found"}, 404
            
            result = {}
            
            # 加载文本
            text_file = folder_path / f"{sample}_text.txt"
            if text_file.exists():
                with open(text_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    lines = content.strip().split('\n')
                    
                    # 解析文本内容
                    result["text"] = ""
                    result["sequence"] = ""
                    result["world_info"] = {}
                    
                    for line in lines:
                        if line.startswith("Text:"):
                            result["text"] = line.replace("Text:", "").strip()
                        elif line.startswith("Sequence:"):
                            result["sequence"] = line.replace("Sequence:", "").strip()
                        elif line.startswith("Ground Truth:"):
                            if "world_scale_gt" not in result["world_info"]:
                                result["world_info"]["world_scale_gt"] = line.replace("Ground Truth:", "").strip()
                        elif line.startswith("Predicted (mean):"):
                            result["world_info"]["world_scale_pred_mean"] = line.replace("Predicted (mean):", "").strip()
                        elif line.startswith("Predicted (range):"):
                            result["world_info"]["world_scale_pred_range"] = line.replace("Predicted (range):", "").strip()
                        elif line.startswith("Error:"):
                            result["world_info"]["world_scale_error"] = line.replace("Error:", "").strip()
            
            # 加载生成的参数
            gen_file = folder_path / f"{sample}_generated.npz"
            if gen_file.exists():
                data = np.load(gen_file, allow_pickle=True)
                # 处理波参数 - 可能有多个维度
                wave_params = []
                if "wave_params" in data:
                    wp = data["wave_params"]
                    # 处理不同的维度格式
                    if wp.ndim == 3:  # (batch, num_waves, params)
                        wave_params = wp[0].tolist()  # 取第一个batch
                    elif wp.ndim == 2:  # (num_waves, params)
                        wave_params = wp.tolist()
                    else:
                        wave_params = []
                
                result["generated"] = {
                    "wave_params": wave_params,
                    "camera_position": data["camera_position"].tolist() if "camera_position" in data else [0, 0, 0],
                    "camera_rotation": data["camera_rotation"].tolist() if "camera_rotation" in data else [0, 0, 0],
                    "camera_fov": float(data["camera_fov"]) if "camera_fov" in data else 60.0,
                    "camera_near": float(data["camera_near"]) if "camera_near" in data else 0.1,
                    "camera_far": float(data["camera_far"]) if "camera_far" in data else 1000.0,
                    "camera_scene_scale": float(data["camera_scene_scale"]) if "camera_scene_scale" in data else 10.0,
                }
                
                # 解析decay_params(可能是列表或数组)
                if "decay_params" in data:
                    decay_params = data["decay_params"]
                    if isinstance(decay_params, list):
                        result["generated"]["decay_params"] = [
                            item.tolist() if hasattr(item, 'tolist') else item 
                            for item in decay_params
                        ]
                    else:
                        result["generated"]["decay_params"] = decay_params.tolist()
            
            # 初始化GT结果
            result["gt"] = {}
            
            # 首先尝试从COLMAP相机文件获取帧数
            cameras_bin_path = folder_path / f"{sample}_cameras.bin"
            images_bin_path = folder_path / f"{sample}_images.bin"
            images_folder = folder_path / f"{sample}_images"
            
            # 通过图像文件夹获取帧数
            if images_folder.exists():
                image_files = list(images_folder.glob("*.jpg")) + list(images_folder.glob("*.png"))
                result["gt"]["total_frames"] = len(image_files)
            else:
                result["gt"]["total_frames"] = 1
            
            result["gt"]["current_frame"] = frame
            
            # 加载GT数据(如果存在)
            gt_file = folder_path / f"{sample}_gt.npz"
            if gt_file.exists():
                data = np.load(gt_file)
                
                # 相机位姿
                if "camera_poses" in data:
                    poses = data["camera_poses"]
                    if len(poses.shape) == 3:  # [T, 4, 4]
                        result["gt"]["camera_poses"] = poses.tolist()  # 所有帧
                        # 更新帧数(如果相机位姿数组提供了更准确的信息)
                        result["gt"]["total_frames"] = poses.shape[0]
                    else:
                        result["gt"]["camera_poses"] = [poses.tolist()]  # 包装成列表
                
                # 原始VGGT相机数据 (如果存在)
                if "vggt_pose_enc" in data:
                    vggt_poses = data["vggt_pose_enc"]  # [T, 9] format
                    result["gt"]["vggt_pose_enc"] = vggt_poses.tolist()
                    # 解析VGGT格式: [T(3D), quaternion(4D), FoV(2D)]
                    if len(vggt_poses.shape) == 2 and vggt_poses.shape[1] == 9:
                        # 提取第一帧的信息用于显示
                        first_pose = vggt_poses[0]
                        result["gt"]["vggt_camera_info"] = {
                            "translation": first_pose[:3].tolist(),
                            "quaternion": first_pose[3:7].tolist(),  # [w, x, y, z]
                            "fov": first_pose[7:9].tolist()  # [fov_x, fov_y]
                        }
            else:
                # 如果没有GT文件,尝试从COLMAP读取相机位姿
                if images_bin_path.exists() and cameras_bin_path.exists():
                    try:
                        # 这里可以添加COLMAP读取逻辑
                        # 暂时返回空数组
                        result["gt"]["camera_poses"] = []
                    except:
                        result["gt"]["camera_poses"] = []
                else:
                    result["gt"]["camera_poses"] = []
            
            # 添加文件路径信息,供前端使用
            result["file_paths"] = {
                "ply": str(folder_path / f"{sample}_points.ply") if (folder_path / f"{sample}_points.ply").exists() else None,
                "cameras": str(folder_path / f"{sample}_cameras.bin") if (folder_path / f"{sample}_cameras.bin").exists() else None,
                "images": str(folder_path / f"{sample}_images.bin") if (folder_path / f"{sample}_images.bin").exists() else None,
                "images_folder": str(folder_path / f"{sample}_images") if (folder_path / f"{sample}_images").exists() else None,
            }
            
            return result
        
        @self.app.post("/api/generate")
        async def generate(params: Dict[str, Any]):
            """生成请求"""
            # 处理生成逻辑
            await self.broadcast({
                "type": "generation_started",
                "params": params
            })
            
            # TODO: 实际生成逻辑
            
            return {"status": "success", "message": "Generation started"}
        
        @self.app.websocket("/ws")
        async def websocket_endpoint(websocket: WebSocket):
            """WebSocket 连接"""
            await websocket.accept()
            self.active_connections.append(websocket)
            
            try:
                # 发送初始状态
                await self.send_json_with_numpy(websocket, {
                    "type": "connected",
                    "viser_port": self.viser_port
                })
                
                while True:
                    # 接收消息
                    data = await websocket.receive_json()
                    await self.handle_websocket_message(websocket, data)
                    
            except WebSocketDisconnect:
                self.active_connections.remove(websocket)
            except Exception as e:
                print(f"WebSocket error: {e}")
                if websocket in self.active_connections:
                    self.active_connections.remove(websocket)
        
        # 静态文件服务
        if Path("static").exists():
            self.app.mount("/static", StaticFiles(directory="static"), name="static")
        
        # 插件文件服务,确保符号链接指向的外部目录也能被访问
        plugins_dir = Path("plugins")
        if plugins_dir.exists():
            for folder in sorted(plugins_dir.iterdir()):
                if not self._is_plugin_directory(folder):
                    continue
                try:
                    resolved = folder.resolve()
                except FileNotFoundError:
                    continue
                if resolved.is_dir():
                    mount_path = f"/plugins/{folder.name}"
                    # 避免重复注册相同的挂载
                    if mount_path not in [route.path for route in self.app.routes if hasattr(route, "path")]:
                        self.app.mount(mount_path, StaticFiles(directory=str(resolved)), name=f"plugin-{folder.name}")

            # 兜底:plugins 目录本身(用于 plugin-system.js 等公共资源)
            self.app.mount("/plugins", StaticFiles(directory="plugins"), name="plugins")
        
        # JS 和 CSS 文件
        for ext in ["js", "css"]:
            if Path(ext).exists():
                self.app.mount(f"/{ext}", StaticFiles(directory=ext), name=ext)
    
    async def handle_websocket_message(self, websocket: WebSocket, data: Dict[str, Any]):
        """处理 WebSocket 消息"""
        msg_type = data.get("type")
        print(f"📨 收到WebSocket消息: {msg_type}")
        
        if msg_type == "update_visualization":
            # 转发到 Viser
            if self.viser_server:
                self.viser_server.update_visualization(
                    wave_index=data.get("waveIndex"),
                    time_value=data.get("time"),
                    use_phase_color=data.get("usePhaseColor")
                )
                await self.send_json_with_numpy(websocket, {
                    "type": "visualization_updated",
                    "status": "success"
                })
        
        elif msg_type == "get_viser_status":
            # 返回 Viser 状态
            await self.send_json_with_numpy(websocket, {
                "type": "viser_status",
                "active": self.viser_server is not None,
                "port": self.viser_port
            })
        
        elif msg_type == "plugin_message":
            # 通用插件消息处理
            if self.viser_server:
                try:
                    response = self.viser_server.handle_message(data)
                    await self.send_json_with_numpy(websocket, {
                        "type": "plugin_response",
                        "plugin": data.get("plugin"),
                        "action": data.get("action"),  # 添加action字段
                        "requestId": data.get("requestId"),  # 传递requestId
                        "status": "success",
                        "response": response
                    })
                except Exception as e:
                    await self.send_json_with_numpy(websocket, {
                        "type": "plugin_response",
                        "plugin": data.get("plugin"),
                        "requestId": data.get("requestId"),  # 传递requestId
                        "status": "error",
                        "message": str(e)
                    })
            else:
                await self.send_json_with_numpy(websocket, {
                    "type": "plugin_response",
                    "requestId": data.get("requestId"),  # 传递requestId
                    "status": "error",
                    "message": "Viser server not available"
                })
        
        elif msg_type == "update_training_visualization":
            # 向后兼容旧的消息格式
            # 转换为新格式并处理
            plugin_message = {
                "plugin": "training-visualization",
                "action": "update_visualization",
                "data": data.get("data", {})
            }
            
            if self.viser_server:
                try:
                    response = self.viser_server.handle_message(plugin_message)
                    await self.send_json_with_numpy(websocket, {
                        "type": "training_visualization_updated",
                        "status": "success"
                    })
                except Exception as e:
                    await self.send_json_with_numpy(websocket, {
                        "type": "training_visualization_updated",
                        "status": "error",
                        "message": str(e)
                    })
    
    async def send_json_with_numpy(self, websocket: WebSocket, data: Dict[str, Any]):
        """发送JSON数据,支持numpy类型"""
        json_str = json.dumps(data, cls=NumpyJSONEncoder)
        await websocket.send_text(json_str)
    
    async def broadcast(self, message: Dict[str, Any]):
        """广播消息到所有连接"""
        disconnected = []
        for connection in self.active_connections:
            try:
                await self.send_json_with_numpy(connection, message)
            except:
                disconnected.append(connection)
        
        # 清理断开的连接
        for conn in disconnected:
            if conn in self.active_connections:
                self.active_connections.remove(conn)
    
    def start_viser_backend(self):
        """启动 Viser 后端"""
        def run_viser():
            try:
                self.viser_server = WaveVisualizationServer(port=self.viser_port)
                self.viser_server.start_server(background_mode=False)
            except Exception as e:
                print(f"❌ Viser 启动失败: {e}")
        
        self.viser_thread = threading.Thread(target=run_viser, daemon=True)
        self.viser_thread.start()
        
        # 等待 Viser 启动
        import time
        time.sleep(3)
        print(f"✅ Viser 后端启动成功 (端口: {self.viser_port})")
    
    def run(self, open_browser=True):
        """运行系统"""
        print("🚀 启动 ControlWave 现代化系统...")
        
        # 启动 Viser
        self.start_viser_backend()
        
        # 获取本机 IP
        import socket
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            local_ip = s.getsockname()[0]
            s.close()
        except:
            local_ip = "localhost"
        
        print("\n" + "="*60)
        print("✅ ControlWave 启动成功!")
        print("="*60)
        print(f"🌐 主界面: http://localhost:{self.frontend_port}")
        print(f"🌐 网络访问: http://{local_ip}:{self.frontend_port}")
        print(f"🔧 Viser 3D: http://localhost:{self.viser_port}")
        print(f"📚 API 文档: http://localhost:{self.frontend_port}/docs")
        print("="*60)
        
        # 检测是否SSH连接
        is_ssh = bool(os.environ.get('SSH_CLIENT') or 
                     os.environ.get('SSH_TTY') or 
                     os.environ.get('SSH_CONNECTION'))
        
        # 自动打开浏览器
        if open_browser:
            import webbrowser
            import threading
            import time
            
            def open_browser_delayed():
                time.sleep(2)  # 等待服务器完全启动
                url = f"http://localhost:{self.frontend_port}"
                print(f"\n🌐 正在打开浏览器: {url}")
                try:
                    webbrowser.open(url)
                except Exception as e:
                    if is_ssh:
                        print(f"⚠️  SSH环境下无法打开浏览器,请使用网络地址访问")
                    else:
                        print(f"⚠️  无法自动打开浏览器: {e}")
            
            threading.Thread(target=open_browser_delayed, daemon=True).start()
            
        if is_ssh:
            print("\n💡 检测到SSH连接,请使用上方的网络地址访问")
        
        print("\n按 Ctrl+C 停止服务器\n")
        
        # 启动 FastAPI
        config = uvicorn.Config(
            self.app,
            host="0.0.0.0",
            port=self.frontend_port,
            log_level="info"
        )
        server = uvicorn.Server(config)
        
        # 设置信号处理
        def signal_handler(signum, frame):
            print("\n🛑 正在关闭服务器...")
            self.is_shutting_down = True
            if self.viser_server:
                self.viser_server.shutdown()
            server.should_exit = True
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        
        # 运行服务器
        server.run()



def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="ControlWave 现代化启动器")
    parser.add_argument("--frontend-port", type=int, default=8080, help="前端端口")
    parser.add_argument("--viser-port", type=int, default=8081, help="Viser 端口")
    parser.add_argument("--no-browser", action="store_true", help="不自动打开浏览器")
    
    args = parser.parse_args()
    
    # 检查依赖
    try:
        import fastapi
        import uvicorn
    except ImportError:
        print("❌ 请先安装依赖: pip install fastapi uvicorn[standard]")
        sys.exit(1)
    
    # 创建并运行系统
    system = ModernControlWave(
        frontend_port=args.frontend_port,
        viser_port=args.viser_port
    )
    system.run(open_browser=not args.no_browser)


if __name__ == "__main__":
    main()