-
-
Notifications
You must be signed in to change notification settings - Fork 274
Expand file tree
/
Copy pathmain.js
More file actions
3246 lines (2910 loc) · 108 KB
/
Copy pathmain.js
File metadata and controls
3246 lines (2910 loc) · 108 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
const remoteMain = require('@electron/remote/main')
const { app, BrowserWindow, ipcMain, screen, shell, dialog, Tray, Menu, session,globalShortcut} = require('electron')
const { clipboard, nativeImage,desktopCapturer } = require('electron')
const { autoUpdater } = require('electron-updater')
const path = require('path')
const { spawn } = require('child_process')
const { exec, execSync } = require('child_process');
const { download } = require('electron-dl');
const fs = require('fs')
const os = require('os')
const net = require('net') // 添加 net 模块用于端口检测
const dgram = require('dgram');
const osc = require('osc');
const chokidar = require('chokidar');
let workspaceWatcher = null; // 声明全局的 watcher 变量
// ★ VMC:UDP 收发资源
let vmcUdpPort = null; // osc.UDPPort 实例
let vmcReceiverActive = false; // 接收是否运行
let vrmWindows = [];
let thaWindows = [];
let soulxWindows = [];
let shotOverlay = null
let minimalWindow = null
let dynamicIslandWindow = null
let isMac = process.platform === 'darwin';
const vmcSendSocket = dgram.createSocket('udp4'); // 发送复用同一 socket
const MAX_LOG_LINES = 2000; // 保留最近2000行日志
let logBuffer = []; // 内存日志缓冲区
let activeDownloads = new Map();
function appendLogToBuffer(source, data) {
const timestamp = new Date().toLocaleTimeString();
const lines = data.toString().split(/\r?\n/);
lines.forEach(line => {
if (line.trim()) {
logBuffer.push(`[${timestamp}] [${source}] ${line}`);
}
});
// 清理旧日志,防止内存无限增长
if (logBuffer.length > MAX_LOG_LINES) {
logBuffer = logBuffer.slice(logBuffer.length - MAX_LOG_LINES);
}
}
async function cropDesktop(rect) {
if (!rect || typeof rect.x !== 'number' || typeof rect.y !== 'number' ||
typeof rect.width !== 'number' || typeof rect.height !== 'number') {
throw new Error('cropDesktop 需要 {x,y,width,height} 且均为数字')
}
const { width, height } = screen.getPrimaryDisplay().bounds
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: { width, height }
})
if (!sources.length) throw new Error('无法获取屏幕源')
// 1. 拿到全屏 PNG 缓冲区
const pngBuffer = sources[0].thumbnail.toPNG()
// 2. 用 Electron 自带的 nativeImage 裁
const img = nativeImage.createFromBuffer(pngBuffer)
const cropped = img.crop({
x: Math.floor(rect.x),
y: Math.floor(rect.y),
width: Math.floor(rect.width),
height: Math.floor(rect.height)
})
// 3. 直接返回 Buffer,下游无需改
return cropped.toPNG()
}
// ★ 替换原来的 startVMCReceiver
function startVMCReceiver(cfg) {
if (vmcReceiverActive) return;
vmcUdpPort = new osc.UDPPort({
localAddress: '0.0.0.0',
localPort: cfg.receive.port,
metadata: true,
});
vmcUdpPort.open();
vmcUdpPort.on('message', (oscMsg) => {
/* -------- 1. 骨骼 -------- */
if (oscMsg.address === '/VMC/Ext/Bone/Pos') {
if (!Array.isArray(oscMsg.args) || oscMsg.args.length < 8) return;
const [boneName, x, y, z, qx, qy, qz, qw] = oscMsg.args.map(v => v.value ?? v);
if (typeof boneName !== 'string') return;
vrmWindows.forEach(w => {
if (!w.isDestroyed()) {
w.webContents.send('vmc-bone', { boneName, position:{x,y,z}, rotation:{x:qx,y:qy,z:qz,w:qw} });
w.webContents.send('vmc-osc-raw', oscMsg);
}
});
return;
}
/* -------- 2. 表情 -------- */
if (oscMsg.address === '/VMC/Ext/Blend/Val') {
if (!Array.isArray(oscMsg.args) || oscMsg.args.length < 2) return;
vrmWindows.forEach(w => {
if (!w.isDestroyed()) w.webContents.send('vmc-osc-raw', oscMsg);
});
return;
}
/* -------- 3. 表情 Apply -------- */
if (oscMsg.address === '/VMC/Ext/Blend/Apply') {
// Apply 不带参数,长度 0 也合法
vrmWindows.forEach(w => {
if (!w.isDestroyed()) w.webContents.send('vmc-osc-raw', oscMsg);
});
}
});
vmcReceiverActive = true;
console.log(`[VMC] 接收已启动 @ ${cfg.receive.port}`);
}
function stopVMCReceiver() {
if (!vmcReceiverActive) return;
vmcUdpPort.close();
vmcUdpPort = null;
vmcReceiverActive = false;
console.log('[VMC] 接收已停止');
}
// 发送 VMC Bone -------------------------------------------------
function sendVMCBoneMain(data) {
if (!data) return;
const { boneName, position, rotation } = data;
if (!boneName || !position || !rotation) return;
const { host, port } = global.vmcCfg.send; // ← 面板配置
const oscMsg = osc.writePacket({
address: `/VMC/Ext/Bone/Pos`,
args: [
{ type: 's', value: boneName },
{ type: 'f', value: position.x || 0 },
{ type: 'f', value: position.y || 0 },
{ type: 'f', value: position.z || 0 },
{ type: 'f', value: rotation.x || 0 },
{ type: 'f', value: rotation.y || 0 },
{ type: 'f', value: rotation.z || 0 },
{ type: 'f', value: rotation.w || 1 },
],
});
vmcSendSocket.send(oscMsg, port, host, (err) => {
if (err) console.error('VMC send error:', err);
});
}
// 发送 VMC Blend ------------------------------------------------
function sendVMCBlendMain(data) {
if (!data) return;
const { blendName, weight } = data;
if (typeof blendName !== 'string' || typeof weight !== 'number') return;
const { host, port } = global.vmcCfg.send; // ← 面板配置
const oscMsg = osc.writePacket({
address: '/VMC/Ext/Blend/Val',
args: [
{ type: 's', value: blendName },
{ type: 'f', value: Math.max(0, Math.min(1, weight)) },
],
});
vmcSendSocket.send(oscMsg, port, host, (err) => {
if (err) console.error('VMC blend send error:', err);
});
}
// 发送 VMC Blend Apply ------------------------------------------
function sendVMCBlendApplyMain() {
const { host, port } = global.vmcCfg.send; // ← 面板配置
const oscMsg = osc.writePacket({
address: '/VMC/Ext/Blend/Apply',
args: [],
});
vmcSendSocket.send(oscMsg, port, host);
}
let pythonExec;
let isQuitting = false;
// 判断操作系统
if (os.platform() === 'win32') {
// Windows
pythonExec = path.join('.venv', 'Scripts', 'python.exe');
} else {
// macOS / Linux
pythonExec = path.join('.venv', 'bin', 'python3');
}
function getCleanUserAgent() {
const chromeVersion = '124.0.0.0'; // 必须与前端代码中的版本保持一致!
const baseUA = `Mozilla/5.0 ({os_info}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Safari/537.36`;
let osInfo = '';
// Node.js 环境直接用 process.platform
switch (process.platform) {
case 'darwin':
osInfo = 'Macintosh; Intel Mac OS X 10_15_7';
break;
case 'win32':
osInfo = 'Windows NT 10.0; Win64; x64';
break;
case 'linux':
osInfo = 'X11; Linux x86_64';
break;
default:
osInfo = 'Windows NT 10.0; Win64; x64';
}
return baseUA.replace('{os_info}', osInfo);
}
// 提前计算好,供后面使用
const REAL_CHROME_UA = getCleanUserAgent();
let mainWindow
let loadingWindow
let tray = null
let updateAvailable = false
let backendProcess = null
const HOST = '127.0.0.1'
let PORT = 3456 // 改为 let,允许修改
const DEFAULT_PORT = 3456 // 保存默认端口
const isDev = process.env.NODE_ENV === 'development'
const locales = {
'zh-CN': {
show: '显示窗口',
exit: '退出',
cut: '剪切',
copy: '复制',
paste: '粘贴',
copyImage: '复制图片',
copyImageLink: '复制图片链接',
saveImageAs: '图片另存为...',
supportedFiles: '支持的文件',
allFiles: '所有文件',
supportedimages: '支持的图片',
// 新增项
openNewTab: '在新标签页打开',
copyLink: '复制链接地址',
copyLinkText: '复制链接文本',
selectAll: '全选',
inspect: '检查元素'
},
'en-US': {
show: 'Show Window',
exit: 'Exit',
cut: 'Cut',
copy: 'Copy',
paste: 'Paste',
copyImage: 'Copy Image',
copyImageLink: 'Copy Image Link',
saveImageAs: 'Save Image As...',
supportedFiles: 'Supported Files',
allFiles: 'All Files',
supportedimages: 'Supported Images',
// 新增项
openNewTab: 'Open in new tab',
copyLink: 'Copy link address',
copyLinkText: 'Copy link text',
selectAll: 'Select All',
inspect: 'Inspect'
}
};
const ALLOWED_EXTENSIONS = [
// 办公文档
'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'pdf', 'pages',
'numbers', 'key', 'rtf', 'odt', 'epub',
// 编程开发
'js', 'ts', 'py', 'java', 'c', 'cpp', 'h', 'hpp', 'go', 'rs',
'swift', 'kt', 'dart', 'rb', 'php', 'html', 'css', 'scss', 'less',
'vue', 'svelte', 'jsx', 'tsx', 'json', 'xml', 'yml', 'yaml',
'sql', 'sh',
// 数据配置
'csv', 'tsv', 'txt', 'md', 'log', 'conf', 'ini', 'env', 'toml'
];
const ALLOWED_IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'];
const ALLOWED_VIDEO_EXTENSIONS =['mp4', 'webm', 'ogg', 'mov', 'avi'];
let currentLanguage = 'zh-CN';
// 构建菜单项
let menu;
// 配置日志文件路径
const logDir = path.join(app.getPath('userData'), 'logs')
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true })
}
// 获取配置文件路径
function getConfigPath() {
return path.join(app.getPath('userData'), 'config.json');
}
// 加载环境变量
function loadEnvVariables() {
const configPath = getConfigPath();
if (fs.existsSync(configPath)) {
try {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// 遍历配置加载到环境变量
for (const key in config) {
const val = config[key];
// ★ 同样只把基本类型加载到 env
if (typeof val === 'string' || typeof val === 'number') {
process.env[key] = val;
}
}
return config; // ★ 返回完整配置对象给 CDP 逻辑使用
} catch (e) {
console.error('加载配置失败:', e);
}
}
return {};
}
function saveEnvVariable(key, value) {
const configPath = getConfigPath();
let config = {};
// 1. 读取现有文件
try {
if (fs.existsSync(configPath)) {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
}
} catch (e) { console.error('配置文件读取出错:', e); }
// 2. 更新文件内容 (对象和字符串都能存)
config[key] = value;
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
// 3. ★ 关键改进:类型检查 ★
// 只有字符串或数字才写入 process.env,防止对象变 "[object Object]"
if (typeof value === 'string' || typeof value === 'number') {
process.env[key] = value;
}
}
const globalConfig = loadEnvVariables();
// ============================================================
// 多账户管理
// ============================================================
let currentAccountId = null;
let currentAccountDataPath = null;
let launchAccountId = null;
function getAccountsPath() {
return path.join(app.getPath('userData'), 'accounts.json');
}
function loadAccounts() {
const accountsPath = getAccountsPath();
if (fs.existsSync(accountsPath)) {
try {
const data = JSON.parse(fs.readFileSync(accountsPath, 'utf8'));
return {
accounts: data.accounts || [],
defaultAccountId: data.defaultAccountId || null
};
} catch (e) {
console.error('[Accounts] 加载账户列表失败:', e);
}
}
return { accounts: [], defaultAccountId: null };
}
function saveAccounts(data) {
const accountsPath = getAccountsPath();
const dir = path.dirname(accountsPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(accountsPath, JSON.stringify(data, null, 2), 'utf8');
console.log('[Accounts] 账户列表已保存');
}
function getAccountById(id) {
const data = loadAccounts();
return data.accounts.find(a => a.id === id) || null;
}
// ============================================================
// CLI 参数解析:--account=<id> 用于多账户启动
// ============================================================
const ACCOUNT_ARG_KEY = '--account=';
for (const arg of process.argv) {
if (arg.startsWith(ACCOUNT_ARG_KEY)) {
launchAccountId = arg.substring(ACCOUNT_ARG_KEY.length);
console.log('[Accounts] 检测到 --account 参数:', launchAccountId);
break;
}
}
// 定义全局变量
let SESSION_CDP_PORT = 0; // 初始为0
let IS_INTERNAL_MODE_ACTIVE = false;
// 始终启用内置 CDP 调试端口(127.0.0.1 不对外暴露),
// 避免运行时需重启才能使用浏览器控制功能。
// 工具是否可用由 chromeMCPSettings.enabled 前端开关控制。
app.commandLine.appendSwitch('remote-debugging-port', '0');
app.commandLine.appendSwitch('remote-debugging-address', '127.0.0.1');
app.commandLine.appendSwitch('remote-allow-origins', '*');
IS_INTERNAL_MODE_ACTIVE = true;
console.log('[CDP] 已请求系统自动分配内置浏览器调试端口...');
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=4096'); // 允许使用 4GB 内存
if (isDev) {
// 开发模式下禁用 HTTP 缓存,修改前端文件(JS/CSS/HTML)后立即生效
app.commandLine.appendSwitch('disable-http-cache');
console.log('[DEV] HTTP 缓存已关闭,前端修改即时生效');
}
// 新增:检测端口是否可用
function isPortAvailable(port) {
return new Promise((resolve) => {
const server = net.createServer()
server.listen(port, HOST, () => {
server.once('close', () => resolve(true))
server.close()
})
server.on('error', () => resolve(false))
})
}
// 新增:查找可用端口
async function findAvailablePort(startPort = DEFAULT_PORT, maxAttempts = 20000) {
for (let i = 0; i < maxAttempts; i++) {
const port = startPort + i
if (await isPortAvailable(port)) {
return port
}
}
throw new Error(`无法找到可用端口,已尝试 ${startPort} 到 ${startPort + maxAttempts - 1}`)
}
async function launchAppWithDebugging(appPath, port, forceNewInstance) {
try {
let profileDir = null;
const debugArgs = [
`--remote-debugging-port=${port}`,
'--remote-debugging-address=127.0.0.1',
];
if (forceNewInstance) {
profileDir = path.join(os.tmpdir(), `sap-cdp-profile-${port}`);
try { fs.mkdirSync(profileDir, { recursive: true }); } catch (e) {}
debugArgs.push(`--user-data-dir=${profileDir}`);
}
debugArgs.push('--no-first-run', '--no-default-browser-check');
let child;
if (process.platform === 'darwin' && appPath.endsWith('.app')) {
// macOS: 直接启动 .app bundle 内的可执行文件,避免 open -n 导致 child 进程
// 立即退出使 exitCode 检查误判,以及 NSApplication 实例路由问题
const macosDir = path.join(appPath, 'Contents', 'MacOS');
let execPath = appPath;
if (fs.existsSync(macosDir)) {
const files = fs.readdirSync(macosDir);
const electronBin = files.find(f => f === 'Electron');
const otherBin = files.find(f => !f.startsWith('.') && !f.endsWith('.plist') && f !== 'Electron');
const chosen = electronBin || otherBin || (files.length > 0 ? files[0] : null);
if (chosen) {
execPath = path.join(macosDir, chosen);
}
}
console.log('[LocalAppControl] 启动命令:', execPath, debugArgs.join(' '));
child = spawn(execPath, debugArgs, { detached: true, stdio: 'ignore' });
} else {
let execPath = appPath;
// Windows: appPath may be a directory (from start menu scan) or missing .exe; resolve to actual exe
if (process.platform === 'win32') {
// Try .exe extension if path doesn't exist directly
if (!fs.existsSync(appPath) && !appPath.toLowerCase().endsWith('.exe') && fs.existsSync(appPath + '.exe')) {
execPath = appPath + '.exe';
}
try {
const s = fs.statSync(execPath);
if (s.isDirectory()) {
const found = findElectronExe(execPath);
if (found) {
try {
if (fs.statSync(found).isFile()) { execPath = found; }
} catch (e) {}
}
if (execPath === appPath || (fs.existsSync(execPath) && fs.statSync(execPath).isDirectory())) {
// findElectronExe returned a directory; scan for any .exe inside
const entries = fs.readdirSync(execPath);
const skip = /uninstall|update|setup|crashpad|notifier/i;
let exe = entries.find(f => f.toLowerCase().endsWith('.exe') && !skip.test(f));
if (!exe) exe = entries.find(f => f.toLowerCase().endsWith('.exe'));
if (exe) execPath = path.join(execPath, exe);
}
}
} catch (e) {}
}
console.log('[LocalAppControl] 启动命令:', execPath, debugArgs.join(' '));
child = spawn(execPath, debugArgs, { detached: true, stdio: 'ignore' });
}
child.on('error', (err) => {
console.error('[LocalAppControl] 启动进程失败:', err.message);
});
child.on('exit', (code) => {
console.log('[LocalAppControl] 进程退出, code:', code);
});
child.unref();
// 轮询等待 CDP 端口就绪,最多 20 秒
let portReady = false;
for (let i = 0; i < 20; i++) {
await new Promise(r => setTimeout(r, 1000));
try {
await new Promise((resolve, reject) => {
const req = require('http').get(`http://127.0.0.1:${port}/json/version`, (res) => {
resolve(res.statusCode);
});
req.on('error', reject);
req.setTimeout(800, () => { req.destroy(); reject(new Error('timeout')); });
});
portReady = true;
console.log('[LocalAppControl] CDP 端口就绪, 耗时:', (i+1), '秒');
// 确认进程没有立刻退出
await new Promise(r => setTimeout(r, 2000));
if (child.exitCode !== null) {
console.log(`[LocalAppControl] 进程已退出 code=${child.exitCode},CDP 端口不可用`);
return { success: false, pid: child.pid, port: port, error: `进程退出 code=${child.exitCode}` };
}
break;
} catch (e) {}
}
if (!portReady) {
console.error('[LocalAppControl] CDP 端口超时未就绪 port:', port);
}
return { success: portReady, pid: child.pid, port: port };
} catch (e) {
return { success: false, error: e.message };
}
}
async function quitAppProcess(pid, appPath) {
try {
const platform = process.platform;
if (platform === 'darwin' && appPath) {
// macOS: 用 bundleId 或 app 名称优雅退出
const infoPlist = path.join(appPath, 'Contents', 'Info.plist');
let bundleId = '';
if (fs.existsSync(infoPlist)) {
try {
const json = execSync(`plutil -convert json -o - "${infoPlist}"`, { encoding: 'utf8', timeout: 2000 });
const plist = JSON.parse(json);
bundleId = plist.CFBundleIdentifier || '';
} catch (e) {}
}
if (bundleId) {
try { execSync(`osascript -e 'tell application id "${bundleId}" to quit'`, { timeout: 5000 }); } catch (e) {}
} else {
const appName = path.basename(appPath, '.app');
try { execSync(`osascript -e 'tell application "${appName}" to quit'`, { timeout: 5000 }); } catch (e) {}
}
await new Promise(r => setTimeout(r, 2000));
// 再强制杀残留进程
const name = path.basename(appPath, '.app');
try { execSync(`pkill -9 -f "${name}" 2>/dev/null || true`, { timeout: 3000 }); } catch (e) {}
await new Promise(r => setTimeout(r, 1000));
return { success: true };
}
if (pid && pid > 0) {
// Windows: use taskkill for proper process termination
if (platform === 'win32') {
try { execSync(`taskkill /PID ${pid} /F 2>nul`, { timeout: 5000 }); } catch (e) {}
} else {
try { process.kill(pid, 'SIGTERM'); } catch (e) {}
await new Promise(r => setTimeout(r, 1000));
try { process.kill(pid, 'SIGKILL'); } catch (e) {}
}
}
// Also try name-based kill (handles stale PIDs or PID=0 from scan)
if (appPath) {
const identifier = path.basename(appPath, '.app').replace(/\.exe$/i, '');
if (platform === 'win32') {
try { execSync(`taskkill /IM "${identifier}.exe" /F 2>nul`, { timeout: 5000 }); } catch (e) {}
} else if (platform !== 'darwin') {
try { execSync(`pkill -9 -f "${identifier}" 2>/dev/null || true`, { timeout: 3000 }); } catch (e) {}
}
}
if (platform === 'win32') await new Promise(r => setTimeout(r, 1000));
return { success: true };
} catch (e) {
return { success: false, error: e.message };
}
}
// ============================================================
// 获取已被其他账户占用的端口列表
// ============================================================
function getUsedPortsByOtherAccounts() {
const data = loadAccounts();
const used = [];
for (const acc of data.accounts) {
if (acc.lastPort && acc.id !== currentAccountId) {
used.push(acc.lastPort);
}
}
return used;
}
// ============================================================
// 获取账户的首选启动端口
// ============================================================
async function getStartPortForAccount(accountData) {
// 获取其他账户占用的端口
const usedPorts = getUsedPortsByOtherAccounts();
// 主账户(root)始终优先使用 DEFAULT_PORT (3456),不使用 lastPort
if (accountData.type === 'root') {
const available = await isPortAvailable(DEFAULT_PORT);
if (available) {
return DEFAULT_PORT;
}
let port = DEFAULT_PORT + 1;
while (usedPorts.includes(port) || !(await isPortAvailable(port))) {
port++;
if (port > DEFAULT_PORT + 20000) {
throw new Error('无法找到可用端口');
}
}
return port;
}
// user 账户:优先使用 lastPort
if (accountData.lastPort) {
if (!usedPorts.includes(accountData.lastPort)) {
const available = await isPortAvailable(accountData.lastPort);
if (available) {
return accountData.lastPort;
}
}
}
// 自动分配,从 DEFAULT_PORT 开始,避开已占用端口
let port = DEFAULT_PORT;
while (usedPorts.includes(port) || !(await isPortAvailable(port))) {
port++;
if (port > DEFAULT_PORT + 20000) {
throw new Error('无法找到可用端口');
}
}
return port;
}
// ============================================================
// 账户选择窗口
// ============================================================
async function showAccountSelectionWindow(registry) {
return new Promise((resolve) => {
const win = new BrowserWindow({
width: 480,
height: 520,
resizable: false,
frame: false,
titleBarStyle: 'hiddenInset',
show: false,
icon: path.join(__dirname, 'static/source/icon.png'),
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false,
}
});
const accountsHtml = registry.accounts.map(acc => {
const typeLabel = acc.type === 'root' ? 'Root' : 'User';
const lastLaunch = acc.lastLaunched
? new Date(acc.lastLaunched).toLocaleString()
: '从未启动';
const isDefault = acc.id === registry.defaultAccountId ? 'default' : '';
return `<div class="account-item ${isDefault}" data-id="${acc.id}">
<div class="acc-icon">${acc.type === 'root' ? '👑' : '👤'}</div>
<div class="acc-info">
<div class="acc-name">${acc.name} <span class="acc-type-badge ${acc.type}">${typeLabel}</span></div>
<div class="acc-path">${acc.dataPath}</div>
<div class="acc-last">上次启动: ${lastLaunch}</div>
</div>
</div>`;
}).join('');
const html = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
background: #1a1a2e;
color: #e0e0e0;
user-select: none;
-webkit-app-region: drag;
overflow: hidden;
}
.header {
padding: 24px 28px 16px;
text-align: center;
}
.header h1 { font-size: 20px; font-weight: 600; color: #fff; }
.header p { font-size: 13px; color: #888; margin-top: 6px; }
.account-list {
padding: 0 20px;
max-height: 320px;
overflow-y: auto;
}
.account-list::-webkit-scrollbar { width: 4px; }
.account-list::-webkit-scrollbar-thumb { background: #444; border-radius: 2px; }
.account-item {
display: flex;
align-items: center;
gap: 14px;
padding: 14px 16px;
margin-bottom: 8px;
background: #222244;
border: 2px solid transparent;
border-radius: 12px;
cursor: pointer;
-webkit-app-region: no-drag;
transition: all 0.2s;
}
.account-item:hover { background: #2a2a55; border-color: #4a4a8a; transform: translateY(-1px); }
.account-item.default { border-color: #4a90d9; }
.acc-icon { font-size: 28px; width: 42px; text-align: center; }
.acc-info { flex: 1; min-width: 0; }
.acc-name { font-size: 15px; font-weight: 600; color: #fff; }
.acc-type-badge { font-size: 10px; padding: 2px 8px; border-radius: 6px; margin-left: 6px; }
.acc-type-badge.root { background: #d4a017; color: #000; }
.acc-type-badge.user { background: #4a90d9; color: #fff; }
.acc-path { font-size: 11px; color: #666; margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.acc-last { font-size: 11px; color: #555; margin-top: 2px; }
.footer {
padding: 16px 28px;
border-top: 1px solid #2a2a3e;
display: flex;
align-items: center;
-webkit-app-region: no-drag;
}
.footer label { font-size: 13px; color: #888; cursor: pointer; display: flex; align-items: center; gap: 8px; }
.footer input[type="checkbox"] { accent-color: #4a90d9; width: 15px; height: 15px; }
.close-btn {
position: absolute;
top: 12px; right: 16px;
width: 28px; height: 28px;
background: transparent;
border: none;
color: #888;
font-size: 18px;
cursor: pointer;
border-radius: 6px;
-webkit-app-region: no-drag;
}
.close-btn:hover { background: #333; color: #fff; }
</style>
</head>
<body>
<button class="close-btn" onclick="window.close()">×</button>
<div class="header">
<h1>选择账户</h1>
<p>选择一个账户以启动 Super Agent Party</p>
</div>
<div class="account-list" id="accountList">
${accountsHtml}
</div>
<div class="footer">
<label><input type="checkbox" id="rememberChoice"> 记住我的选择(设为默认账户)</label>
</div>
<script>
const { ipcRenderer } = require('electron');
document.querySelectorAll('.account-item').forEach(item => {
item.addEventListener('click', () => {
const accountId = item.dataset.id;
const remember = document.getElementById('rememberChoice').checked;
ipcRenderer.send('account-selected', { accountId, remember });
});
});
</script>
</body>
</html>`;
win.loadURL('data:text/html;charset=utf-8,' + encodeURIComponent(html));
ipcMain.once('account-selected', (event, { accountId, remember }) => {
const account = registry.accounts.find(a => a.id === accountId);
if (remember && account) {
const data = loadAccounts();
data.defaultAccountId = accountId;
saveAccounts(data);
}
if (!win.isDestroyed()) win.close();
resolve(account);
});
win.on('close', () => {
if (!win.isDestroyed()) win.destroy();
resolve(null);
});
win.once('ready-to-show', () => {
win.show();
});
});
}
// 创建骨架屏窗口
function createSkeletonWindow() {
const { width, height } = screen.getPrimaryDisplay().workAreaSize
mainWindow = new BrowserWindow({
width: width,
height: height,
frame: false,
titleBarStyle: 'hiddenInset', // macOS 特有:隐藏标题栏但仍显示原生按钮
trafficLightPosition: { x: 10, y: 12 }, // 自定义按钮位置(可选)
show: true,
icon: 'static/source/icon.png',
webPreferences: {
preload: path.join(__dirname, 'static/js/preload.js'),
nodeIntegration: false,
sandbox: false,
contextIsolation: true,
enableRemoteModule: false,
webSecurity: false,
devTools: isDev,
partition: 'persist:main-session',
webviewTag: true,
}
})
remoteMain.enable(mainWindow.webContents)
// 加载骨架屏页面
mainWindow.loadFile(path.join(__dirname, 'static/skeleton.html'))
// 设置自动更新
setupAutoUpdater()
// 窗口状态同步
mainWindow.on('maximize', () => {
mainWindow.webContents.send('window-state', 'maximized')
})
mainWindow.on('unmaximize', () => {
mainWindow.webContents.send('window-state', 'normal')
})
// 窗口关闭事件处理 - 最小化到托盘而不是退出
mainWindow.on('close', (event) => {
if (!app.isQuitting) {
event.preventDefault()
mainWindow.hide()
return false
}
return true
})
}
function getAcpxPath() {
if (app.isPackaged) {
return path.join(process.resourcesPath, 'acpx');
} else {
return path.join(__dirname, 'node_modules', 'acpx');
}
}
// 修改后的启动后端函数
/**
* 启动后端服务
* 逻辑:传 port 0 -> 捕获 REAL_PORT_FOUND -> 返回真实端口
*/
async function startBackend(startPort = DEFAULT_PORT, dataDir = null) {
return new Promise((resolve, reject) => {
try {
console.log('🔍 准备启动后端进程...');
const npmCliPath = isDev
? path.join(__dirname, 'node_modules', 'npm', 'bin', 'npm-cli.js')
: path.join(process.resourcesPath, 'npm', 'bin', 'npm-cli.js');
const spawnOptions = {
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
env: {
...process.env,
NODE_ENV: isDev ? 'development' : 'production',
PYTHONIOENCODING: 'utf-8',
PYTHONUNBUFFERED: '1',
ELECTRON_NODE_EXEC: process.execPath,
ELECTRON_NPM_CLI: npmCliPath,
ELECTRON_RESOURCES_PATH: app.isPackaged ? process.resourcesPath : path.join(__dirname),
ELECTRON_ACPM_PATH: getAcpxPath(),
}
};
// 多账户:仅对非 root 账户通过环境变量强制数据目录
// root 账户使用 Python 后端默认机制(path_config.json 或系统默认目录)
if (dataDir && currentAccountId) {
const acct = getAccountById(currentAccountId);
if (acct && acct.type !== 'root') {
spawnOptions.env.SUPER_AGENT_PARTY_DATA_DIR = dataDir;
console.log(`[Accounts] 注入 user 账户数据目录: ${dataDir}`);
}
}
if (process.platform === 'win32') {
spawnOptions.windowsHide = !isDev;
}
const BACKEND_HOST = (globalConfig?.networkVisible === 'global') ? '0.0.0.0' : '127.0.0.1';
let execPath = "";
let backendArgs = [];
const portStr = String(startPort);
if (isDev) {
execPath = pythonExec;
backendArgs = ['-u', 'server.py', '--host', BACKEND_HOST, '--port', portStr];
} else {
const serverExecutable = process.platform === 'win32' ? 'server.exe' : 'server';
const resourcesPath = process.resourcesPath || path.join(process.execPath, '..', 'resources');
execPath = path.join(resourcesPath, 'server', serverExecutable);
backendArgs = ['--host', BACKEND_HOST, '--port', portStr];
spawnOptions.cwd = path.dirname(execPath);
}
// 传递数据目录给后端
if (dataDir) {
backendArgs.push('--data-dir', dataDir);
}
console.log(`🚀 执行路径: ${execPath}`);
backendProcess = spawn(execPath, backendArgs, spawnOptions);
let isHandshaked = false;
// 核心监听逻辑
const onData = (data) => {
const output = data.toString();
// 1. 依然保留日志缓冲,供前端查看
appendLogToBuffer('BACKEND', output);
if (isDev) {
// 开发模式下在控制台打印原始输出,方便排查
process.stdout.write(`[PY] ${output}`);
}
// 2. 尝试解析端口握手信号
const match = output.match(/REAL_PORT_FOUND:(\d+)/);
if (match && !isHandshaked) {
const actualPort = parseInt(match[1], 10);
if (actualPort > 0) {
isHandshaked = true;
PORT = actualPort; // 更新全局 PORT 变量
console.log(`✅ 握手成功!后端运行端口: ${PORT}`);
resolve(PORT);
}
}
};
backendProcess.stdout.on('data', onData);
backendProcess.stderr.on('data', onData);
// 进程错误处理
backendProcess.on('error', (err) => {
console.error('❌ 后端启动失败:', err);
reject(err);
});
// 进程意外退出处理
backendProcess.on('close', (code) => {
console.log(`ℹ️ 后端进程已退出 (code ${code})`);
if (!isHandshaked) {
reject(new Error(`后端进程在分配端口前已关闭,退出码: ${code}`));
}
});
// 5分钟超时保护
setTimeout(() => {
if (!isHandshaked) {
if (backendProcess) backendProcess.kill();
reject(new Error('后端启动超时:未能从 Python 日志捕获 REAL_PORT_FOUND 信号'));
}
}, 360000*5);
} catch (err) {
reject(err);