Repository navigation
Expand file tree
/
Copy pathextension.js
More file actions
2270 lines (2156 loc) · 96 KB
/
Copy pathextension.js
File metadata and controls
2270 lines (2156 loc) · 96 KB
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
// MiniBT Charts —— 在 VS Code 编辑器页(WebviewPanel)里跑 minibt 策略图表。
//
// 做法:用子进程跑 `runner/vscode_runner.py`,它把策略里的图表强制切到可嵌入的
// 引擎(pylightcharts 网页版 / bokeh server),并把结果报回来:
//
// MINIBT_URL=http://127.0.0.1:PORT/ → 本地服务,用 <iframe> 嵌进编辑器页签
// MINIBT_HTML=/path/to/chart.html → 自包含 HTML,直接当页签内容(静态快照)
//
// 页签先显示"正在启动图表服务…",探测到端口后才把 iframe 换进来 —— 这样策略算
// 指标算得久也不会看到 ERR_CONNECTION_REFUSED;如果最后只等来 HTML,就自动变成
// 静态快照页签。
//
// 为什么不能嵌"纯 pylightcharts(原生窗口)":原生窗口是 PyQt6 + WebView2 的
// 独立操作系统窗口,没法放进 VS Code 的 webview;而网页引擎用的是同一套
// lightweight-charts + pylightcharts bundle,画出来的图完全一样。
const vscode = require('vscode');
const cp = require('child_process');
const fs = require('fs');
const net = require('net');
const os = require('os');
const path = require('path');
/** 本扩展版本(自查用:输出面板第一行会打印它)。 */
const VERSION = require('./package.json').version;
/** 看盘终端(minibt desk)的纯逻辑:参数 / 体检 / 状态文字 ✓ */
const desk = require('./desk');
/** VS Code 反向桥(PI / Copilot 用 desk_vscode 操作编辑器 ✓ v0.3.12) */
const { VscodeBridge } = require('./vscode-bridge');
/** PI 助手:原生对话(Chat Participant)+ 会话树 ✓ */
const { PiChat } = require('./pi-chat');
const { PiPanel } = require('./pi-panel');
const { PiSessionsProvider, listSessions: piSessionsList,
isTestSession: piIsTestSession, deleteSession: piSessionsDelete }
= require('./pi-sessions');
/**
* 依赖版本门槛(v0.3.12 新增)。
*
* 为什么要它:0.3.11 之前只探「装没装 rich / pylightcharts」,不探版本。
* minibt 1.3.7 起 desk 的告警中心 / 定时任务页 / PI 助手 / 资讯中心全部在
* **pylightcharts 0.2.1+** 的 desk.js 里 —— 老版本前端照样能打开,但界面会
* 少一大半、也不报错,用户会以为是扩展坏了 ✗。
*/
const MIN_VERSIONS = { minibt: '1.3.8', pylightcharts: '0.2.2' };
/** 只有「PI 面板 / @minibt 对话 / AI 操作 VS Code」才需要 1.3.8 的工具 ✓ */
const PI_MIN_MINIBT = '1.3.8';
/**
* 探测脚本:**不 import minibt**(那要 10s),只用 importlib.metadata 读版本;
* 顺便验 rich / pylightcharts 能不能 import(缺依赖时给出明确原因 ✓)。
*/
const PROBE_CODE = [
'import json',
'import sys',
'from importlib.metadata import version, PackageNotFoundError',
'def ver(name):',
' try:',
' return version(name)',
' except PackageNotFoundError:',
' return ""',
' except Exception:',
' return ""',
'out = {}',
'for name in ("pylightcharts", "rich"):',
' try:',
' __import__(name)',
' out[name] = ver(name)',
' except Exception:',
' out[name] = None',
'out["minibt"] = ver("minibt")',
'out["python"] = "%d.%d" % (sys.version_info[0], sys.version_info[1])',
'try:',
' __import__("minibt")',
' out["minibt_import"] = True',
'except Exception:',
' out["minibt_import"] = False',
'print(json.dumps(out))',
].join('\n');
/** `cmd+args` → 探测结果(避免每次启动都跑一遍解释器 ✓) */
const probeCache = new Map();
/** 当前会话。 */
let session = null;
/** 看盘终端会话 `{process, panel, url, settings, stopping}` */
let deskSession = null;
/** 状态栏「MiniBT 看盘」 */
let deskStatus = null;
/** VS Code 反向桥(`desk_vscode` 工具的服务端 ✓) */
let vscodeBridge = null;
/** PI 助手:原生对话(Chat Participant)+ 会话树 + 右侧面板 */
let piChat = null;
let piSessions = null;
let piPanel = null;
/** 共用的输出面板(VS Code 底部「输出」里的 MiniBT)。 */
let output = null;
function getOutput() {
if (!output) output = vscode.window.createOutputChannel('MiniBT');
return output;
}
// --------------------------------------------------------------- 解释器解析
/**
* 找一个真能 `import minibt, pylightcharts` 的解释器。
*
* VS Code 里的 `python` 往往不是工作区配的那个(PATH 上可能是 3.14,而 minibt
* 装在 3.12)—— 子进程会报 `ModuleNotFoundError: No module named 'rich'`
* (rich 是 minibt 的依赖),看上去像扩展坏了。
*
* 顺序:显式配置的 minibt.pythonPath 优先(不再探测)→ VS Code/Python 扩展设的
* `python.defaultInterpreterPath` → Windows `py -0p` 列出的全部 → `python`/
* `python3`。选第一个依赖齐(rich / pylightcharts)的;都不行就退回 `python`,
* 让 runner 报清楚的错。
*/
/**
* 给一个解释器打分(**这是"为什么会选中 Python 3.9"的根因修复** ✓ v0.3.12)
*
* 以前只判「rich + pylightcharts 能 import」——Python 3.9 完全满足
* (`pylightcharts` 支持 3.9,`rich` 更不用说),于是被选中;可 **minibt 要求
* Python ≥ 3.12**,装不上也用不了 ✗。
*
* 现在的权重(分高者优先):
* +100 能 `import minibt`(真正的目标)
* +60 Python ≥ 3.12(minibt 的硬要求)
* +20 装了 pylightcharts(画图必需)
* +10 装了 rich
* -1000 连 pylightcharts 都没有(画不了图,直接排除)
*/
function probeScore(info) {
if (!info) return -1;
if (info.pylightcharts === null) return -1000;
let score = 0;
if (info.minibt_import) score += 100;
if (pythonAtLeast(info.python, '3.12')) score += 60;
if (info.pylightcharts) score += 20;
if (info.rich) score += 10;
return score;
}
/** `'3.12' >= '3.10'` 之类(按数字比 ✓) */
function pythonAtLeast(version, want) {
return !versionLess(version || '0', want);
}
/** 挑解释器(打分 + 记录每个候选的得分,排查时一眼看到为什么 ✓) */
function resolvePython(config) {
const configured =
String(config.get('pythonPath', 'python') || '').trim() || 'python';
if (configured !== 'python') {
const info = probeVersions({ cmd: configured, args: [] });
getOutput().appendLine(`[env] 用设置里的解释器 ${configured} → `
+ (info ? `python ${info.python} / minibt ${info.minibt || '未装'}`
: '探测失败'));
return { cmd: configured, args: [] };
}
const channel = getOutput();
const candidates = [];
const seen = new Set();
const add = (cmd, args) => {
args = args || [];
const key = cmd + ' ' + args.join(' ');
if (cmd && !seen.has(key)) {
seen.add(key);
candidates.push({ cmd, args });
}
};
// 1) VS Code / Python 扩展设的解释器(存在才用)
try {
const setting = String(vscode.workspace.getConfiguration('python')
.get('defaultInterpreterPath', '') || '').trim();
if (setting && fs.existsSync(setting)) add(setting);
} catch (error) { /* 设置读不到就跳过 */ }
// 2) Windows 的 py 启动器:列出所有已装版本(`py -0p`)
if (process.platform === 'win32') {
try {
const out = cp.execFileSync('py', ['-0p'], {
encoding: 'utf8', timeout: 5000,
stdio: ['ignore', 'pipe', 'ignore'],
});
for (const line of out.split(String.fromCharCode(10))) {
const match = /^\s*-V:\S+\s+\*?\s*(.+?)\s*$/.exec(line);
if (match && fs.existsSync(match[1])) add(match[1]);
}
} catch (error) { /* 没装 py 就算了 */ }
}
// 3) PATH 上的名字
add('python');
if (process.platform !== 'win32') add('python3');
// 打分挑最优(高分优先;同分按候选顺序 = 用户配置优先 ✓)
let best = null;
let bestScore = -Infinity;
for (const cand of candidates) {
const info = probeVersions(cand);
const score = probeScore(info);
const label = [cand.cmd].concat(cand.args).join(' ');
channel.appendLine(`[env] 候选 ${label} → `
+ (info
? `python ${info.python} · minibt ${info.minibt || '未装'}`
+ `${info.minibt_import ? '(可导入)' : ''} · pylightcharts `
+ `${info.pylightcharts || '未装'}(得分 ${score})`
: '探测失败(跳过)'));
if (score > bestScore) {
best = cand;
bestScore = score;
}
}
if (best && bestScore > 0) {
const label = [best.cmd].concat(best.args).join(' ');
channel.appendLine(`[env] 选中 ${label}(得分 ${bestScore})`);
if (label !== 'python') {
channel.appendLine(
`[minibt] minibt.pythonPath 未配置,自动选了:${label}`);
}
return best;
}
channel.appendLine('[env] ⚠ 没有找到「装了 minibt 且 Python ≥ 3.12」的解释器;'
+ '请用 `py -0p` 看有哪些版本,或在设置里填 minibt.pythonPath');
return { cmd: 'python', args: [] };
}
/**
* 探这个解释器能不能跑 minibt。
*
* 探的是**依赖**(rich / pylightcharts),不是 `import minibt` —— 后者一跑就是
* ~10s(pandas / pandas_ta 一大堆),会把启动拖死;而真正会缺的就是这些依赖
* (比如 PATH 上的 python 是另一个版本,没装 rich)。
*/
function probeInterpreter(cand) {
return !!probeVersions(cand);
}
/**
* 探一个解释器:`{pylightcharts, rich, minibt}`(缺依赖的项是 `null`)。
*
* 结果**按解释器缓存**:`resolvePython()` 每次启动都会探一轮,不缓存的话
* 每点一次命令都要多花 1~3 秒。
*/
function probeVersions(cand) {
const key = cand.cmd + ' ' + cand.args.join(' ');
if (probeCache.has(key)) return probeCache.get(key);
let info = null;
try {
const out = cp.execFileSync(cand.cmd, cand.args.concat(
['-c', PROBE_CODE]), {
cwd: os.tmpdir(), // 别被工作区里的本地包“骗”到
timeout: 30000,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
env: Object.assign({}, process.env, { PYTHONIOENCODING: 'utf-8' }),
});
const text = String(out).trim();
const cut = Math.max(text.lastIndexOf(String.fromCharCode(13)),
text.lastIndexOf(String.fromCharCode(10)));
info = JSON.parse(cut >= 0 ? text.slice(cut + 1) : text);
} catch (error) {
info = null;
}
probeCache.set(key, info);
return info;
}
/** `1.3.7` vs `1.3.10` 按数字比(字符串比会错 ✗) */
function versionLess(a, b) {
const left = String(a || '0').split('.').map((x) => Number(x) || 0);
const right = String(b || '0').split('.').map((x) => Number(x) || 0);
for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
const l = left[i] || 0;
const r = right[i] || 0;
if (l !== r) return l < r;
}
return false;
}
/** 版本问题清单(空 = 合格 ✓);`forDesk` 才检查 minibt(图表只需要前端) */
function versionProblems(info, options) {
const opts = options || {};
const problems = [];
if (!info) return ['查不到 Python 依赖(解释器跑不起来?)'];
// ★ v0.3.12:**Python 版本**也算门槛 —— minibt 要求 ≥ 3.12。
// 以前只判「rich + pylightcharts 能 import」,Python 3.9 照样通过,
// 于是升级命令在 3.9 上必失败(用户实测:`Requires-Python >=3.12` ✗)
if (opts.forDesk && info.python && !pythonAtLeast(info.python, '3.12')) {
problems.push(`Python ${info.python} 太旧(minibt 需要 ≥ 3.12)`);
}
if (info.rich === null) problems.push('缺依赖 rich(`pip install rich`)');
if (info.pylightcharts === null) {
problems.push('没装 pylightcharts(`pip install pylightcharts`)');
} else if (versionLess(info.pylightcharts, MIN_VERSIONS.pylightcharts)) {
problems.push(`pylightcharts ${info.pylightcharts} 太旧`
+ `(需要 ≥ ${MIN_VERSIONS.pylightcharts}:desk 的告警中心 / `
+ '定时任务 / PI 助手都在新版前端里)');
}
if (opts.forDesk) {
if (!info.minibt) {
problems.push('这个解释器里没装 minibt(`pip install minibt`)');
if (info.minibt_import === false) {
// 之前 pip 装失败会留下空目录 → `minibt` 变成 namespace package
// (`__file__` 为空 / `cannot import name ... (unknown location)`)
problems.push('若刚在旧 Python 里 `pip install` 失败过,先 '
+ '`pip uninstall -y minibt` 清掉残留空目录');
}
} else if (versionLess(info.minibt, MIN_VERSIONS.minibt)) {
problems.push(`minibt ${info.minibt} 太旧`
+ `(需要 ≥ ${MIN_VERSIONS.minibt})`);
}
}
return problems;
}
/**
* 启动前检查版本;不合格就**问用户**(升级 / 仍然继续 / 复制命令),不硬拦。
*
* @returns {Promise<boolean>} true = 继续启动
*/
async function ensureVersions(context, python, options) {
const opts = options || {};
const info = probeVersions(python);
const problems = versionProblems(info, opts);
const label = [python.cmd].concat(python.args).join(' ');
const channel = opts.forDesk ? getDeskOutput() : getOutput();
const versionLine = info
? `minibt=${info.minibt || '未装'} pylightcharts=${
info.pylightcharts || '未装'}`
: '(探测失败)';
channel.appendLine(`[env] ${label} → ${versionLine}`);
if (!problems.length) return true;
channel.appendLine(`[env] 版本检查:${problems.join(';')}`);
// ★ v0.3.12:**只有"装没装"是硬错误**;"版本旧"只做提示(不拦启动)——
// 否则 1.3.7 / pylightcharts 0.2.0 的用户一点 desk 就吃个模态框,
// 看起来像"按钮失效"✗。新功能(PI 面板)另有能力探测单独把关 ✓
const hard = problems.filter((text) => /没装|缺依赖|跑不起来/.test(text));
if (!hard.length) {
if (vscode.window.setStatusBarMessage) {
vscode.window.setStatusBarMessage(
'MiniBT:环境提示 — ' + problems.join(';'), 6000);
}
return true;
}
const command = `${label} -m pip install -U "minibt>=${PI_MIN_MINIBT}" `
+ `"pylightcharts>=${MIN_VERSIONS.pylightcharts}"`;
const pythonOld = !!(info && info.python
&& !pythonAtLeast(info.python, '3.12'));
if (pythonOld) {
// pip 升不了 Python 本身 → 直接给出"换解释器"的动作,别让用户白跑 ✗
const answer = await vscode.window.showWarningMessage(
`MiniBT:这个解释器是 Python ${info.python},而 minibt 需要 ≥ 3.12`
+ `(候选:${label})。请选一个 3.12+ 的解释器(py -0p 可看清单)。`,
'选择解释器', '仍然继续', '看看用哪个解释器');
if (answer === '选择解释器') {
vscode.commands.executeCommand('python.setInterpreter');
return false;
}
if (answer === '看看用哪个解释器') {
channel.show(true);
return false;
}
return true;
}
const answer = await vscode.window.showWarningMessage(
`MiniBT:Python 环境不满足要求 — ${problems.join(';')}`,
'升级依赖', '仍然继续', '复制升级命令', '看看用哪个解释器');
if (answer === '升级依赖') {
const terminal = vscode.window.createTerminal('MiniBT 升级依赖');
terminal.show(true);
terminal.sendText(command, true);
return false;
}
if (answer === '复制升级命令') {
await vscode.env.clipboard.writeText(command);
vscode.window.showInformationMessage('MiniBT:升级命令已复制到剪贴板');
return false;
}
if (answer === '看看用哪个解释器') {
getOutput().show(true);
channel.show(true);
return false;
}
return true;
}
/**
* 把版本信息写进输出面板(图表流程只记录、不弹窗 —— 画图不依赖 1.3.7 ✓)。
*/
function logVersions(python, forDesk) {
const info = probeVersions(python);
const channel = forDesk ? getDeskOutput() : getOutput();
if (!info) {
channel.appendLine('[env] 解释器探测失败(可能没装 Python / 依赖)');
return info;
}
channel.appendLine(`[env] python=${info.python || '?'}`
+ ` minibt=${info.minibt || '未装'}`
+ `${info.minibt_import ? '' : '(导入失败)'}`
+ ` pylightcharts=${info.pylightcharts || '未装'}`
+ ` rich=${info.rich === null ? '缺' : (info.rich || '已装')}`);
if (info.pylightcharts && versionLess(info.pylightcharts,
MIN_VERSIONS.pylightcharts)) {
channel.appendLine(`[env] ⚠ pylightcharts ${info.pylightcharts} 低于`
+ ` ${MIN_VERSIONS.pylightcharts}:desk 的告警中心 / 定时任务 /`
+ ' PI 助手会缺失(不影响画图)');
}
return info;
}
// --------------------------------------------------------------------- 工具
/** 只做 TCP 连接探测:不 GET,避免给 bokeh 造出一个"幽灵会话"。 */
function waitForPort(url, timeoutMs) {
let host = '127.0.0.1';
let port = 0;
try {
const parsed = new URL(url);
host = parsed.hostname;
port = Number(parsed.port);
} catch (error) {
return Promise.resolve(false);
}
const deadline = Date.now() + timeoutMs;
return new Promise((resolve) => {
const attempt = () => {
const socket = net.connect({ host, port });
socket.setTimeout(700);
socket.once('connect', () => {
socket.destroy();
resolve(true);
});
const retry = () => {
socket.destroy();
if (Date.now() > deadline) resolve(false);
else setTimeout(attempt, 350);
};
socket.once('error', retry);
socket.once('timeout', retry);
};
attempt();
});
}
/** 从策略输出里认进度:`进度 12/100`、`37%`、`[3/8]`。 */
function parseProgress(line) {
let match = /进度\s*([\d,]+)\s*\/\s*([\d,]+)/.exec(line);
if (match) {
const done = Number(match[1].replace(/,/g, ''));
const total = Number(match[2].replace(/,/g, ''));
if (total > 0) {
return {
percent: Math.max(0, Math.min(100, (done / total) * 100)),
label: `进度 ${done}/${total}`,
};
}
}
match = /(?:^|[^\d.])(\d{1,3}(?:\.\d+)?)\s*%/.exec(line);
if (match) {
return { percent: Number(match[1]), label: `进度 ${match[1]}%` };
}
match = /\[(\d+)\s*\/\s*(\d+)\]/.exec(line);
if (match) {
const total = Number(match[2]);
if (total > 0) {
return {
percent: (Number(match[1]) / total) * 100,
label: `进度 ${match[1]}/${total}`,
};
}
}
if (/开始回测|正在回测/.test(line)) return { percent: 0, label: '回测中…' };
if (/回放/.test(line)) return { percent: 0, label: '回放中…' };
if (/实时/.test(line)) return { percent: 0, label: '实时行情中…' };
if (/优化/.test(line)) return { percent: 0, label: '参数优化中…' };
return null;
}
function lineLevel(line) {
if (/Traceback|Error|Exception|错误|失败|异常/.test(line)) return 'error';
if (/Warn|警告/.test(line)) return 'warn';
return 'info';
}
function nonceOf() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let text = '';
for (let i = 0; i < 32; i += 1) {
text += chars[Math.floor(Math.random() * chars.length)];
}
return text;
}
// ------------------------------------------------------------------ 日志页签
function logPanelHtml(nonce) {
return `<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}';">
<style>
:root { color-scheme: light dark; }
body { margin: 0; font-family: var(--vscode-font-family); }
#bar { display: flex; align-items: center; gap: 8px; padding: 6px 10px;
position: sticky; top: 0; background: var(--vscode-editor-background);
border-bottom: 1px solid var(--vscode-panel-border); }
#track { flex: 1; height: 8px; border-radius: 4px; overflow: hidden;
background: var(--vscode-input-background, #8883); }
#fill { height: 100%; width: 0%; background: var(--vscode-progressBar-background,
#0a7); transition: width .2s ease; }
#fill.indeterminate { width: 100% !important;
background: linear-gradient(90deg, transparent, #0a7, transparent);
animation: slide 1.2s linear infinite; }
@keyframes slide { from { transform: translateX(-100%); }
to { transform: translateX(100%); } }
#ptext { font-size: 12px; opacity: .8; white-space: nowrap; }
#log { margin: 0; padding: 8px 10px; font-family: var(--vscode-editor-font-family,
monospace); font-size: 12px; line-height: 1.45; white-space: pre-wrap;
word-break: break-all; }
#log div.error { color: var(--vscode-errorForeground, #d33); }
#log div.warn { color: var(--vscode-editorWarning-foreground, #b80); }
#log div.info { color: var(--vscode-editor-foreground); }
</style></head>
<body>
<div id="bar">
<div id="track"><div id="fill" class="indeterminate"></div></div>
<span id="ptext">等待策略输出…</span>
</div>
<div id="log"></div>
<script nonce="${nonce}">
const log = document.getElementById('log');
const fill = document.getElementById('fill');
const ptext = document.getElementById('ptext');
window.addEventListener('message', (event) => {
const msg = event.data || {};
if (msg.type === 'lines') {
const stick = log.scrollTop + log.clientHeight >= log.scrollHeight - 24;
for (const item of msg.lines) {
const row = document.createElement('div');
row.className = item.level;
row.textContent = item.text;
log.appendChild(row);
}
while (log.childElementCount > 4000) log.removeChild(log.firstChild);
if (stick) log.scrollTop = log.scrollHeight;
} else if (msg.type === 'progress') {
if (msg.percent === null || msg.percent === undefined) {
fill.classList.add('indeterminate');
} else {
fill.classList.remove('indeterminate');
fill.style.width = Math.max(0, Math.min(100, msg.percent)) + '%';
}
ptext.textContent = msg.label || '';
} else if (msg.type === 'clear') {
log.textContent = '';
}
});
</script>
</body></html>`;
}
/**
* 图表/日志页签应该开在哪一列。
*
* `minibt.openBeside=false`(默认)→ 命令发起时所在的**代码列**:
* 代码、日志、图表都是同一页签组里的标签,页面不会被拆成左右两半 ✓
* `true` → `ViewColumn.Beside`(右侧新开一列,左右分屏)。
*
* ★ 不能直接用 `ViewColumn.Active`:日志先以「旁边」打开后,active 就变成
* 右边那一列了,之后图表也跟着跑到右边,于是“整个页面宽度减半”(用户反馈 ✗)。
* 所以优先用命令发起时记下的 `session.column`。
*/
function panelColumn() {
const beside = vscode.workspace.getConfiguration('minibt')
.get('openBeside', false);
if (beside) return vscode.ViewColumn.Beside;
return (session && session.column) || vscode.ViewColumn.One;
}
/**
* 命令发起时代码所在的列(返回一个**具体**的列,不能用 `ViewColumn.Active`:
* 它会在日志页签打开后漂移)。优先当前聚焦的编辑器,其次可见的 .py 编辑器。
*/
function sourceColumn() {
const editor = vscode.window.activeTextEditor;
if (editor && editor.viewColumn) return editor.viewColumn;
const visible = vscode.window.visibleTextEditors.find(
(item) => item.document.fileName.endsWith('.py') && item.viewColumn);
if (visible) return visible.viewColumn;
return vscode.ViewColumn.One;
}
function openLogPanel(context, title) {
const column = panelColumn();
if (session && session.logPanel) {
session.logPanel.reveal(column, true);
session.logPanel.title = title || session.logPanel.title;
return session.logPanel;
}
const panel = vscode.window.createWebviewPanel(
'minibtLog', title || 'MiniBT 策略日志', column,
{ enableScripts: true, retainContextWhenHidden: true },
);
panel.webview.html = logPanelHtml(nonceOf());
for (const item of (session && session.logLines) || []) {
postLog([item]);
}
const ownSession = session;
panel.onDidDispose(() => {
if (session && session === ownSession) session.logPanel = null;
});
if (session) session.logPanel = panel;
return panel;
}
function postLog(items) {
if (session && session.logPanel) {
session.logPanel.webview.postMessage({ type: 'lines', lines: items });
}
}
function postProgress(progress) {
if (session && session.logPanel) {
session.logPanel.webview.postMessage({
type: 'progress',
percent: progress.percent,
label: progress.label,
});
}
}
// ---------------------------------------------------------------- 图表页签
/** 图表页签的外壳:先显示状态,收到 URL 才把 iframe 换进来。 */
function chartShellHtml(nonce, title) {
return `<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; frame-src http://127.0.0.1:* http://localhost:*;">
<style>
:root { color-scheme: light dark; }
html, body { margin: 0; height: 100%; overflow: hidden; }
iframe { border: 0; width: 100%; height: 100%; display: none; background: #000; }
#status { font-family: var(--vscode-font-family); padding: 1.2em;
color: var(--vscode-descriptionForeground); }
#status h3 { margin: 0 0 .4em; font-weight: 600;
color: var(--vscode-editor-foreground); }
#status code { color: var(--vscode-textPreformat-foreground, #c60); }
.spin { display: inline-block; width: 12px; height: 12px; margin-right: 8px;
border: 2px solid var(--vscode-descriptionForeground);
border-top-color: transparent; border-radius: 50%;
animation: turn 1s linear infinite; vertical-align: -2px; }
@keyframes turn { to { transform: rotate(360deg); } }
</style></head>
<body>
<iframe id="frame" allow="clipboard-read; clipboard-write"></iframe>
<div id="status">
<h3>${title || 'MiniBT 图表'}</h3>
<p><span class="spin"></span><span id="text">正在启动图表服务…</span></p>
</div>
<script nonce="${nonce}">
const frame = document.getElementById('frame');
const status = document.getElementById('status');
const text = document.getElementById('text');
// Ctrl+C:停止策略进程(等同「停止策略进程」按钮)。
// 这里只覆盖“焦点在外壳上”的情况;图表在跨域 iframe 里时,由注入到图表页
// 里的监听器(见 runner/vscode_runner.py)负责。两处都发 {type:'stop'}。
let vscodeApi = null;
try { vscodeApi = acquireVsCodeApi(); } catch (err) { vscodeApi = null; }
window.addEventListener('keydown', (event) => {
if ((event.ctrlKey || event.metaKey)
&& (event.key === 'c' || event.key === 'C')) {
event.preventDefault();
try { if (vscodeApi) vscodeApi.postMessage({ type: 'stop' }); }
catch (err) { /* 桥没就绪:忽略 */ }
}
}, true);
window.addEventListener('message', (event) => {
const msg = event.data || {};
if (msg.type === 'url') {
// 每次换 URL 都带上时间戳,避免 webview 复用旧页面
frame.src = msg.url + (msg.url.includes('?') ? '&' : '?') + '_vscode=' + Date.now();
frame.style.display = 'block';
status.style.display = 'none';
} else if (msg.type === 'status') {
frame.style.display = 'none';
status.style.display = 'block';
text.textContent = msg.text || '';
} else if (msg.type === 'error') {
frame.style.display = 'none';
status.style.display = 'block';
status.innerHTML = '<h3>图表没起来</h3><p></p>';
const detail = document.createElement('p');
detail.textContent = msg.text || '';
status.appendChild(detail);
const hint = document.createElement('p');
hint.innerHTML = '看 <b>MiniBT</b> 输出面板里的报错;'
+ '确认 <b>minibt.pythonPath</b> 的解释器里装了 minibt。';
status.appendChild(hint);
}
});
</script>
</body></html>`;
}
function panelOptions() {
return {
enableScripts: true, // 外壳脚本要把 iframe 换进来
retainContextWhenHidden: true, // 切走再回来不重载图表
localResourceRoots: [],
};
}
/** 建/复用图表页签(先显示等待状态,不直接甩 iframe 错误页)。 */
function openChartPanel(context, title) {
const column = panelColumn();
if (session && session.panel) {
session.panel.title = title;
session.panel.reveal(column, false);
if (session.kind !== 'live') {
session.kind = 'live';
session.panel.webview.html = chartShellHtml(nonceOf(), title);
}
return session.panel;
}
const panel = vscode.window.createWebviewPanel(
'minibtChart', title, column, panelOptions());
panel.iconPath = new vscode.ThemeIcon('graph');
panel.webview.html = chartShellHtml(nonceOf(), title);
attachPanel(context, panel, 'live', null);
return panel;
}
function postChart(message) {
if (session && session.panel) {
session.panel.webview.postMessage(message);
}
}
/** 静态快照:自包含 HTML 直接当页签内容(离线、可缩放、不占端口)。 */
function showStaticPanel(context, htmlPath, title) {
let html;
try {
html = fs.readFileSync(htmlPath, 'utf8');
} catch (error) {
vscode.window.showWarningMessage(
`MiniBT:读取 ${htmlPath} 失败:${error.message}`);
return null;
}
let panel = session && session.panel;
if (!panel) {
panel = vscode.window.createWebviewPanel(
'minibtChart', title, panelColumn(), panelOptions());
panel.iconPath = new vscode.ThemeIcon('file-media');
attachPanel(context, panel, 'static', htmlPath);
} else {
session.kind = 'static';
session.panel.title = title;
session.panel.reveal(panelColumn(), false);
session.panel.iconPath = new vscode.ThemeIcon('file-media');
}
panel.webview.html = html;
if (session) session.htmlPath = htmlPath;
return panel;
}
function attachPanel(context, panel, kind, target) {
if (!session) session = {};
// 捕获本会话:旧页签的 dispose 回调不能去动“下一次运行”的新会话
const ownSession = session;
session.panel = panel;
session.kind = kind;
if (kind === 'live') session.url = target;
else session.htmlPath = target;
vscode.commands.executeCommand('setContext', 'minibt.chartOpen', true);
// 外壳里的 Ctrl+C(见 chartShellHtml)会 post 过来:停掉策略进程
panel.webview.onDidReceiveMessage((message) => {
if (message && message.type === 'stop' && session === ownSession) {
stopSession();
}
});
panel.onDidDispose(() => {
vscode.commands.executeCommand('setContext', 'minibt.chartOpen', false);
if (!session || session !== ownSession) return;
session.panel = null;
const keep = vscode.workspace.getConfiguration('minibt')
.get('keepAliveOnClose', false);
if (!keep) stopSession();
});
}
/** 杀掉整棵策略进程树(同步:确认停了再交给调用方)。 */
function stopChildProcess(child) {
if (!child || child.exitCode !== null) return;
getOutput().appendLine('[minibt] 停止策略进程 …');
try {
if (process.platform === 'win32') {
cp.execFileSync('taskkill',
['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore' });
} else {
child.kill('SIGTERM');
}
} catch (error) {
try { child.kill(); } catch (error2) { /* 已经没了 */ }
}
}
function stopSession() {
if (!session || session.stopping) return;
// 标记停止中:面板的 onDidDispose 会回调 stopSession,免得递归
session.stopping = true;
const child = session.process;
const panels = [session.panel, session.logPanel];
session.process = null;
session.panel = null;
session.logPanel = null;
// ★ 顺序:**先停服务**(同步杀进程,杀掉后才往下走),**再关页面**。
// 否则先把图表/日志页签 dispose 掉,页面没了但本地服务还在跑 ✗。
stopChildProcess(child);
for (const target of panels) {
if (!target) continue;
try { target.dispose(); } catch (error) { /* 已经关了 */ }
}
vscode.commands.executeCommand('setContext', 'minibt.chartOpen', false);
}
// ------------------------------------------------------------------ 启动
async function pickScript() {
const editor = vscode.window.activeTextEditor;
if (editor && editor.document.fileName.endsWith('.py')) {
if (editor.document.isDirty) await editor.document.save();
return editor.document.fileName;
}
const picked = await vscode.window.showOpenDialog({
canSelectMany: false,
filters: { 'Python 策略': ['py'] },
openLabel: '运行这个策略',
});
return picked && picked.length ? picked[0].fsPath : undefined;
}
/**
* 跑一次策略:把图表开在编辑器页签里(本地服务 + iframe,实时刷新)✓。
*/
async function start(context, scriptArg) {
// ★ 先记下“命令发起时”的代码列:日志/图表之后都要回到这一列,
// 同一个页签组内按标签切换,不拆分页面(用户要求)。
const invokedColumn = sourceColumn();
// ★ v0.3.12:Codelens 会带 Uri 进来(点哪一行就跑哪个文件);
// 没带才回退到“当前编辑器 / 让用户选” ✓
let script = scriptArg
? (scriptArg.fsPath || String(scriptArg))
: await pickScript();
if (!script) return false;
stopSession();
const config = vscode.workspace.getConfiguration('minibt');
const python = resolvePython(config); // { cmd, args }:能跑 minibt 的
logVersions(python, false);
const pythonLabel = [python.cmd].concat(python.args).join(' ');
const engine = config.get('engine', 'auto');
const port = Number(config.get('port', 0)) || 0;
const extra = config.get('extraPythonArgs', []) || [];
const folders = vscode.workspace.workspaceFolders;
const cwd = config.get('cwd', '') ||
(folders && folders.length ? folders[0].uri.fsPath : path.dirname(script));
const openBrowser = config.get('openBrowser', false);
// VS Code 深浅色主题:用户没显式指定 theme 时,图表默认跟着 VS Code 走
const colorTheme = vscode.window.activeColorTheme;
const vsCodeTheme = (colorTheme &&
(colorTheme.kind === 2 || colorTheme.kind === 3)) ? 'dark' : 'light';
const runner = path.join(context.extensionPath, 'runner', 'vscode_runner.py');
const env = Object.assign({}, process.env, {
PYTHONPATH: [path.join(context.extensionPath, 'runner'), cwd,
process.env.PYTHONPATH || ''].filter(Boolean).join(path.delimiter),
PYTHONIOENCODING: 'utf-8',
MINIBT_VSCODE: '1',
});
const name = path.basename(script);
session = {
process: null, panel: null, kind: null, url: null, htmlPath: null,
logPanel: null, logLines: [], progress: null, script: script,
column: invokedColumn,
};
const channel = getOutput();
channel.clear();
channel.appendLine(
`[minibt] MiniBT Charts v${VERSION} · ${pythonLabel} → ${name}`
+ `(engine=${engine})`);
// ★ 不主动 show 输出面板:日志只在**编辑器页签**里显示(MiniBT 策略日志),
// 否则底部的「输出」面板会被自动打开,同一份日志出现两遍(用户反馈 ✗)。
// 输出面板仍保留内容,需要时可用命令「显示策略输出(原始日志)」手动查看。
if (config.get('openLog', true)) {
openLogPanel(context, `MiniBT 策略日志 — ${name}`);
}
const args = ['-u'].concat(extra, [runner, script, '--engine', engine,
'--theme', vsCodeTheme, '--port', String(port), '--cwd', cwd]);
if (openBrowser) args.push('--open');
const child = cp.spawn(python.cmd, python.args.concat(args),
{ cwd, env });
session.process = child;
const onLine = (line) => {
if (line.trim() === 'MINIBT_STOP') {
// 图表页(跨域 iframe)里按了 Ctrl+C:停掉策略进程。
// runner 收到图表页的回调后会打印这一行(见 vscode_runner.py)。
// 内部信令,不写进日志。
stopSession();
return;
}
channel.appendLine(line);
session.logLines.push({ text: line, level: lineLevel(line) });
postLog([session.logLines[session.logLines.length - 1]]);
const progress = parseProgress(line);
if (progress) {
session.progress = progress;
postProgress(progress);
}
const urlMatch = /^MINIBT_URL=(\S+)$/.exec(line.trim());
if (urlMatch) {
const url = urlMatch[1];
const title = `MiniBT 图表 — ${name}`;
openChartPanel(context, title);
postChart({ type: 'status', text: '正在启动图表服务…' });
waitForPort(url, 60000).then((ready) => {
if (!session || session.process !== child) return;
if (ready) {
session.url = url;
getOutput().appendLine(`[minibt] 图表服务已就绪:${url}`);
postChart({ type: 'url', url: url });
} else if (!session.htmlPath) {
postChart({
type: 'error',
text: `图表服务没起来(${url})。`,
});
}
});
}
const htmlMatch = /^MINIBT_HTML=(\S.*)$/.exec(line.trim());
if (htmlMatch) {
const htmlPath = htmlMatch[1].trim();
if (!fs.existsSync(htmlPath)) return;
getOutput().appendLine(`[minibt] 静态图表页:${htmlPath}`);
showStaticPanel(context, htmlPath, `MiniBT 图表(快照)— ${name}`);
}
};
let buffer = '';
child.stdout.on('data', (chunk) => {
buffer += chunk.toString();
let index;
while ((index = buffer.indexOf('\n')) >= 0) {
onLine(buffer.slice(0, index).replace(/\r$/, ''));
buffer = buffer.slice(index + 1);
}
});
child.stderr.on('data', (chunk) => {
const text = chunk.toString();
channel.append(text);
for (const line of text.split('\n')) {
if (line.trim()) {
session.logLines.push({ text: line, level: lineLevel(line) });
postLog([session.logLines[session.logLines.length - 1]]);
}
}
});
child.on('error', (error) => {
vscode.window.showErrorMessage(
`MiniBT:启动 ${pythonLabel} 失败 —— ${error.message}`
+ '(检查 minibt.pythonPath)');
});
child.on('exit', (code) => {
channel.appendLine(`[minibt] 策略进程退出,code=${code}`);
if (!session || session.process !== child) return;
session.process = null;
postProgress({
percent: code === 0 ? 100 : null,
label: code === 0 ? '已完成' : `已退出(code=${code})`,
});
if (session.panel && session.kind === 'live') {
postChart({
type: 'status',
text: `策略已结束(code=${code})。想重跑按 Ctrl+Alt+M。`,
});
} else if (!session.panel && !session.htmlPath) {
vscode.window.showInformationMessage(
`MiniBT:${name} 跑完了,但没看到图表(策略里 isplot=False?)`);
}
});
return true;
}