Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
2294 lines (2085 loc) · 107 KB
/
Copy pathmain.js
File metadata and controls
2294 lines (2085 loc) · 107 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
// main.js - Electron 主窗口
// Bootstrap-only fatal evidence. The monitor does not consume the exception,
// so Electron keeps its existing crash behavior while managed/packed launches
// receive a machine-readable cause instead of a silent ready timeout.
if (process.env.VCPCHAT_BOOTSTRAP_OPERATION_ID && process.env.VCPCHAT_STATE_DIR) {
process.on('uncaughtExceptionMonitor', (error, origin) => {
try {
const bootstrapFs = require('fs');
const bootstrapPath = require('path');
const diagnostics = bootstrapPath.join(process.env.VCPCHAT_STATE_DIR, 'diagnostics');
bootstrapFs.mkdirSync(diagnostics, { recursive: true });
const safeOperationId = process.env.VCPCHAT_BOOTSTRAP_OPERATION_ID.replace(/[^a-z0-9_-]/gi, '-');
bootstrapFs.writeFileSync(bootstrapPath.join(diagnostics, `fatal-${safeOperationId}.json`), `${JSON.stringify({
schemaVersion: 1,
operationId: process.env.VCPCHAT_BOOTSTRAP_OPERATION_ID,
origin,
name: error?.name || 'Error',
message: error?.message || String(error),
stack: error?.stack || null,
at: new Date().toISOString(),
}, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' });
} catch { /* the original fatal error remains authoritative */ }
});
}
// --- 核心流式守卫:挂载 stdout 与 stderr 的 EPIPE 错误静默吸收守卫 ---
['stdout', 'stderr'].forEach((streamName) => {
if (process[streamName] && typeof process[streamName].on === 'function') {
process[streamName].on('error', (err) => {
if (err.code === 'EPIPE') return;
});
}
});
// 启动标记:每个启动阶段相对进程启动的毫秒时刻,不管有没有外部启动器都记;lifecycle:get-main-snapshot.launch 带出
const { createLaunchMarks } = require('./modules/launchMarks');
const launchMarks = createLaunchMarks({ processStartedAt: Date.now() - Math.round(process.uptime() * 1000) });
function reportLauncherProgress(stage, progress, message) {
launchMarks.mark(stage);
if (process.env.VCP_LAUNCHER_PROTOCOL !== '1') return;
const payload = JSON.stringify({ stage, progress, message });
process.stdout.write(`VCP_STARTUP:${payload}\n`);
}
reportLauncherProgress('process-started', 0.08, 'VChat 进程已启动');
// --- 模块加载性能诊断 ---
const originalRequire = require;
require = function (id) {
const start = Date.now();
const result = originalRequire(id);
const duration = Date.now() - start;
if (duration > 50) { // 只显示超过 50ms 的模块
console.log(`⏱️ require('${id}') took ${duration}ms`);
}
return result;
};
const { app, BrowserWindow, webContents, ipcMain, nativeTheme, globalShortcut, screen, clipboard, shell, dialog, protocol, Tray, Menu, powerMonitor } = require('electron'); // Added screen, clipboard, and shell
// 不再对整个应用关闭 Chromium 的后台节流(background-timer-throttling / renderer-backgrounding /
// backgrounding-occluded-windows)和挂起监视器:那组开关让所有窗口、所有 <webview> 和 GPU 进程在后台
// 也全速运转,并且让卡死的渲染进程再也不会被发现。流式回复在隐藏页面里的推进由
// modules/renderer/streamManager.js 自己处理(隐藏时走定时器并整段排空,重新可见时切回 rAF)。
const path = require('path');
const crypto = require('crypto');
const fs = require('fs-extra'); // Using fs-extra for convenience
const os = require('os');
const { spawn } = require('child_process'); // For executing local python
const { Worker } = require('worker_threads');
const bootstrapLaunchProtocol = require('./modules/bootstrap/launch-protocol');
const fileManager = require('./modules/fileManager'); // Import the new file manager
const groupChat = require('./Groupmodules/groupchat'); // Import the group chat module
const windowHandlers = require('./modules/ipc/windowHandlers'); // Import window IPC handlers
const settingsHandlers = require('./modules/ipc/settingsHandlers'); // Import settings IPC handlers
const fileDialogHandlers = require('./modules/ipc/fileDialogHandlers'); // Import file dialog handlers
const deepWikiHandlers = require('./modules/ipc/deepWikiHandlers'); // Ask Nova DeepWiki MCP handlers
const { getAgentConfigById, ...agentHandlers } = require('./modules/ipc/agentHandlers'); // Import agent handlers
const regexHandlers = require('./modules/ipc/regexHandlers'); // Import regex handlers
const chatHandlers = require('./modules/ipc/chatHandlers'); // Import chat handlers
const { createDiagnosticsExporter } = require('./modules/diagnosticsSnapshot'); // 一次性诊断导出(进程指标 + 窗口状态 + 生命周期快照)
const groupChatHandlers = require('./modules/ipc/groupChatHandlers'); // Import group chat handlers
const sovitsHandlers = require('./modules/ipc/sovitsHandlers'); // Import SovitsTTS IPC handlers
const promptHandlers = require('./modules/ipc/promptHandlers'); // Import prompt handlers
const notesHandlers = require('./modules/ipc/notesHandlers'); // Import notes handlers
const workspaceHandlers = require('./modules/ipc/workspaceHandlers'); // 工作区索引与实时引用
const projectForgeHandlers = require('./modules/ipc/projectForgeHandlers'); // ProjectForge 施工图 GUI(只读 + 署名回退)
const { createSidePaneSenderGuard, guardIpcMain } = require('./modules/ipc/sidePaneIpcPolicy'); // 侧栏相关 IPC 的调用方窗口策略
const gitHandlers = require('./modules/ipc/gitHandlers'); // ProjectForge Git 源代码管理侧栏
const sourceHandlers = require('./modules/ipc/sourceHandlers'); // ProjectForge 源码浏览 / 轻量编辑侧栏
// 侧栏终端、调用轨迹、旁聊的 IPC 由领域激活器按需加载(见下方 domainActivator.register),这里不预先 require
const browserHandlers = require('./modules/ipc/browserHandlers'); // 侧栏浏览器(<webview> 的安全围栏)
const { createDomainActivator, channelsForDomain } = require('./modules/ipc/domainActivator');
const { describeApis } = require('./preloads/core/registry');
const { configureSharedRecorder } = require('./modules/modelTrajectory');
const domainActivator = createDomainActivator({ ipcMain });
// 主进程推送按窗口订阅:只发给订阅了某个主题的窗口(V工程窗口、主窗口的状态面板和侧栏)
const { createStateSubscriptions } = require('./modules/ipc/stateSubscriptions');
const stateSubscriptions = createStateSubscriptions();
const assistantHandlers = require('./modules/ipc/assistantHandlers'); // Import assistant handlers
const musicHandlers = require('./modules/ipc/musicHandlers'); // Import music handlers
const diceHandlers = require('./modules/ipc/diceHandlers'); // Import dice handlers
const themeHandlers = require('./modules/ipc/themeHandlers'); // Import theme handlers
const emoticonHandlers = require('./modules/ipc/emoticonHandlers'); // Import emoticon handlers
const forumHandlers = require('./modules/ipc/forumHandlers'); // Import forum handlers
const memoHandlers = require('./modules/ipc/memoHandlers'); // Import memo handlers
const ragHandlers = require('./modules/ipc/ragHandlers'); // Import RAG handlers
const translatorHandlers = require('./modules/ipc/translatorHandlers'); // Import translator handlers
const voiceHandlers = require('./modules/ipc/voiceHandlers'); // Import voice chat handlers
const localSttHandlers = require('./modules/ipc/localSttHandlers'); // 本地 SenseVoice 语音识别
// speechRecognizer is now lazy-loaded
const canvasHandlers = require('./modules/ipc/canvasHandlers'); // Import canvas handlers
const chartHandlers = require('./modules/ipc/chartHandlers'); // Agent 图表工作台与持久化服务
const desktopHandlers = require('./modules/ipc/desktopHandlers'); // Import VCPdesktop handlers
const desktopRemoteHandlers = require('./modules/ipc/desktopRemoteHandlers'); // Import desktop remote control handlers
const tavernHandlers = require('./modules/ipc/tavernHandlers'); // Import VCPChatTarven (advanced reply) handlers
const { ScriptoriumAgentControlService } = require('./modules/services/scriptoriumAgentControlService');
const { GlobalJevService } = require('./modules/services/globalJevService');
// docxHandlers 依赖链较重(mammoth/cheerio/marked/jszip 等),冷启动不加载。
// 仅在首次真正使用文坊时(IPC 打开、V 桌面图标、Agent 调用)按需加载。
const windowService = require('./modules/services/windowService');
const WINDOW_APP_IDS = require('./modules/services/windowAppIds');
let docxHandlersModule = null;
let docxHandlersLoadPromise = null;
let docxHandlersInitializeOptions = null;
let docxOpenBootstrapRegistered = false;
function loadDocxHandlers() {
if (docxHandlersModule) return Promise.resolve(docxHandlersModule);
if (docxHandlersLoadPromise) return docxHandlersLoadPromise;
if (!docxHandlersInitializeOptions) {
return Promise.reject(new Error('[Main] docxHandlers 尚未配置。'));
}
docxHandlersLoadPromise = new Promise((resolve, reject) => {
// 将同步 CommonJS 模块解析移出当前初始化调用栈,避免阻塞主窗口创建。
setImmediate(() => {
try {
// 初始化真实模块前移除临时打开桥接,避免重复注册同名 IPC。
if (docxOpenBootstrapRegistered) {
ipcMain.removeHandler('open-docx-window');
docxOpenBootstrapRegistered = false;
}
const handlers = require('./modules/ipc/docxHandlers');
handlers.initialize(docxHandlersInitializeOptions);
docxHandlersModule = handlers;
console.log('[Main] docxHandlers loaded asynchronously.');
resolve(handlers);
} catch (error) {
// 允许后续按需调用重试,同时恢复临时打开入口。
docxHandlersLoadPromise = null;
registerDocxOpenBootstrap();
console.error('[Main] Failed to load docxHandlers:', error);
reject(error);
}
});
});
return docxHandlersLoadPromise;
}
function registerDocxOpenBootstrap() {
if (docxOpenBootstrapRegistered || docxHandlersModule) return;
ipcMain.handle('open-docx-window', async (_event, options = {}) => {
const handlers = await loadDocxHandlers();
return handlers.openDocxWindow(options);
});
docxOpenBootstrapRegistered = true;
}
function configureDocxHandlers(options) {
docxHandlersInitializeOptions = options;
registerDocxOpenBootstrap();
// V 桌面等入口通过 windowService 打开文坊,不经过 open-docx-window IPC。
// 预先登记轻量占位;真实模块 initialize() 时会以同一 appId 覆盖 open/getWindow。
windowService.register(WINDOW_APP_IDS.DOCX, {
owner: 'main:docx-lazy',
getWindow: () => docxHandlersModule?.getDocxWindow() || null,
open: async (openOptions = {}) => {
const handlers = await loadDocxHandlers();
return handlers.openDocxWindow(openOptions);
},
readyTimeoutMs: 20000,
});
}
// 提供稳定对象给控制服务;异步方法在真实模块就绪前自动等待。
const docxHandlers = {
openDocxWindow: (...args) =>
loadDocxHandlers().then((handlers) => handlers.openDocxWindow(...args)),
requestAgentOperation: (...args) =>
loadDocxHandlers().then((handlers) => handlers.requestAgentOperation(...args)),
writeProjectArtifact: (...args) =>
loadDocxHandlers().then((handlers) => handlers.writeProjectArtifact(...args)),
getSystemFonts: (...args) =>
loadDocxHandlers().then((handlers) => handlers.getSystemFonts(...args)),
getDocxWindow: () => docxHandlersModule?.getDocxWindow() || null,
};
const loomManagerModule = require('./modules/loom/VCPLoomManager');
const { PRELOAD_ROLES, resolveProjectPreload } = require('./modules/services/preloadPaths');
const { createEmbeddedAppSessionManager } = require('./modules/services/embeddedAppSessionManager');
const { SenderTaskRegistry } = require('./modules/services/senderTaskRegistry');
const { ChatDataServiceFacade } = require('./modules/services/chatDataService');
const { createHistoryWatcherLeaseManager } = require('./modules/services/historyWatcherLeaseManager');
const { HistoryMutationQueue } = require('./modules/services/historyMutationQueue');
const { PluginAgentOperationService } = require('./modules/services/pluginAgentOperationService');
// chokidar is now lazy-loaded
// --- File Watcher ---
let historyWatcher = null;
let embeddedAppSessions = null;
let embeddedAppTasks = null;
let lastInternalSaveTime = 0; // 🔧 改为时间戳记录
let internalSaveTimeout = null; // 🔧 超时保护
let isEditingInProgress = false; // 🔧 编辑状态标识
const INTERNAL_SAVE_WINDOW_MS = 2000; // 🔧 内部保存时间窗口(2秒)
const fileWatcher = {
watchFile: async (filePath, callback) => {
if (historyWatcher) {
const watcherToClose = historyWatcher;
historyWatcher = null;
await watcherToClose.close();
}
console.log(`[FileWatcher] Watching new file: ${filePath}`);
const chokidar = require('chokidar'); // Lazy load
historyWatcher = chokidar.watch(filePath, {
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 300, // 🔧 增加稳定性阈值
pollInterval: 100
}
});
historyWatcher.on('all', (event, path) => {
// 🔧 改进:使用时间窗口而非一次性标志
const now = Date.now();
const isWithinSaveWindow = (now - lastInternalSaveTime) < INTERNAL_SAVE_WINDOW_MS;
if (isWithinSaveWindow || isEditingInProgress) {
console.log(`[FileWatcher] Ignored ${isWithinSaveWindow ? 'internal save' : 'editing'} event '${event}' for: ${path} (time since last save: ${now - lastInternalSaveTime}ms)`);
return;
}
console.log(`[FileWatcher] Detected external event '${event}' for: ${path}`);
callback(path);
});
historyWatcher.on('error', error => console.error(`[FileWatcher] Error: ${error}`));
},
stopWatching: async () => {
if (historyWatcher) {
console.log('[FileWatcher] Stopping file watch.');
const watcherToClose = historyWatcher;
historyWatcher = null;
await watcherToClose.close();
}
// 🔧 清理状态
isEditingInProgress = false;
lastInternalSaveTime = 0; // 重置时间戳
if (internalSaveTimeout) {
clearTimeout(internalSaveTimeout);
internalSaveTimeout = null;
}
},
signalInternalSave: () => {
// 🔧 记录内部保存时间戳
lastInternalSaveTime = Date.now();
console.log('[FileWatcher] Internal save signaled at:', lastInternalSaveTime);
// 🔧 设置超时保护,防止时间窗口失效(虽然理论上不需要了)
if (internalSaveTimeout) clearTimeout(internalSaveTimeout);
internalSaveTimeout = setTimeout(() => {
// 这个超时主要是为了调试,正常情况下时间窗口会自然过期
const timeSinceLastSave = Date.now() - lastInternalSaveTime;
if (timeSinceLastSave >= INTERNAL_SAVE_WINDOW_MS) {
console.log('[FileWatcher] Internal save window naturally expired');
}
}, INTERNAL_SAVE_WINDOW_MS + 1000);
},
// 🔧 新增:编辑状态管理
setEditingMode: (editing) => {
isEditingInProgress = editing;
console.log(`[FileWatcher] Editing mode set to: ${editing}`);
}
};
const historyWatcherLeases = createHistoryWatcherLeaseManager({
startWatching: ({ filePath, callback }) => fileWatcher.watchFile(filePath, callback),
stopWatching: () => fileWatcher.stopWatching()
});
const historyWatcherSenderOwners = new WeakMap();
let historyWatcherSenderSequence = 0;
function getHistoryWatcherOwner(sender) {
const existing = historyWatcherSenderOwners.get(sender);
if (existing) return existing;
// Electron may reuse numeric WebContents IDs. Include a main-process
// generation so a late destroyed event cannot revoke a newer renderer.
const ownerId = `${sender.id}:${++historyWatcherSenderSequence}`;
historyWatcherSenderOwners.set(sender, ownerId);
sender.once('destroyed', () => {
void historyWatcherLeases.revoke(ownerId).catch((error) => {
console.warn('[FileWatcher] Failed to release destroyed renderer lease:', error);
});
});
return ownerId;
}
// --- Configuration Paths ---
// Data storage will be within the project's 'AppData' directory
const PROJECT_ROOT = __dirname; // __dirname is the directory of main.js
const isolatedAppDataRoot = process.env.VCPCHAT_APP_DATA_DIR?.trim();
if (isolatedAppDataRoot) app.setPath('userData', path.resolve(isolatedAppDataRoot));
const APP_DATA_ROOT_IN_PROJECT = isolatedAppDataRoot
? path.resolve(isolatedAppDataRoot)
: path.join(PROJECT_ROOT, 'AppData');
const NATIVE_SPLASH_READY_FILE = app.isPackaged
? path.join(APP_DATA_ROOT_IN_PROJECT, '.vcp_ready')
: path.join(__dirname, '.vcp_ready');
const AGENT_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'Agents');
const USER_DATA_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'UserData'); // For chat histories and attachments
const SETTINGS_FILE = path.join(APP_DATA_ROOT_IN_PROJECT, 'settings.json');
const TERMINAL_EXECUTOR_PATH = path.join(PROJECT_ROOT, 'VCPDistributedServer', 'Plugin', 'PowerShellExecutor', 'PowerShellExecutor.js');
const USER_AVATAR_FILE = path.join(USER_DATA_DIR, 'user_avatar.png'); // Standardized user avatar file
const MUSIC_PLAYLIST_FILE = path.join(APP_DATA_ROOT_IN_PROJECT, 'songlist.json');
const MUSIC_COVER_CACHE_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'MusicCoverCache');
const NETWORK_NOTES_CACHE_FILE = path.join(APP_DATA_ROOT_IN_PROJECT, 'network-notes-cache.json'); // Cache for network notes
const WALLPAPER_THUMBNAIL_CACHE_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'WallpaperThumbnailCache');
const RESAMPLE_CACHE_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'ResampleCache');
const CANVAS_CACHE_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'canvas'); // Canvas cache directory
// Define a specific agent ID for notes attachments
const NOTES_AGENT_ID = 'notes_attachments_agent';
let audioEngineProcess = null; // To hold the python audio engine process
let mainWindow;
let tray = null;
let vcpLogWebSocket;
let vcpLogReconnectInterval;
let openChildWindows = [];
let distributedServer = null; // To hold the distributed server instance
let distributedServerStartPromise = null;
let chatDataService = null; // Optional VCP-CDS shadow service.
let historyMutationQueue = null;
let pluginAgentOperationService = null;
let chartService = null;
let gameService = null;
let appSettingsManager = null;
let globalJevService = null;
let loomManager = null;
let scriptoriumAgentControl = null;
let networkNotesTreeCache = null; // In-memory cache for the network notes
let cachedModels = []; // Cache for models fetched from VCP server
const NOTES_MODULE_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'Notemodules');
const isRagObserverOnlyMode = process.argv.includes('--rag-observer-only');
const isAutoOpenDesktop = process.argv.includes('--desktop-only');
let audioEngineStopPromise = null;
let isAudioEngineStopping = false;
let appQuitCleanupPromise = null;
let isFinalizingQuit = false;
const MAIN_RENDERER_CRASH_WINDOW_MS = 60_000;
const MAIN_RENDERER_STABLE_RESET_MS = 30_000;
const MAIN_RENDERER_MAX_RECOVERIES = 3;
let mainRendererCrashTimes = [];
let mainRendererRecoveryTimer = null;
let mainRendererStableTimer = null;
let mainRendererFailurePromptOpen = false;
const managedBootstrapOperationId = process.env.VCPCHAT_BOOTSTRAP_OPERATION_ID?.trim() || null;
const managedBootstrapStateRoot = process.env.VCPCHAT_STATE_DIR?.trim() || null;
const nativeLauncherProgressEnabled = process.env.VCP_LAUNCHER_PROTOCOL === '1';
let managedBootstrapReadyPublished = false;
let nativeLauncherReadyReported = false;
function publishManagedBootstrapReady(checks) {
if (!managedBootstrapOperationId || !managedBootstrapStateRoot || managedBootstrapReadyPublished) return false;
try {
bootstrapLaunchProtocol.writeReadyRecord({
stateRoot: managedBootstrapStateRoot,
operationId: managedBootstrapOperationId,
buildId: process.env.VCPCHAT_BUILD_ID?.trim() || null,
checks,
});
managedBootstrapReadyPublished = true;
console.log(`[Main] Published managed bootstrap ready for ${managedBootstrapOperationId}.`);
return true;
} catch (error) {
console.warn('[Main] Failed to publish managed bootstrap ready:', error.message);
return false;
}
}
async function publishManagedBootstrapReadyAfterRenderer() {
const managedReadyPending =
Boolean(managedBootstrapOperationId && managedBootstrapStateRoot) &&
!managedBootstrapReadyPublished;
const nativeLauncherReadyPending =
nativeLauncherProgressEnabled && !nativeLauncherReadyReported;
const distributedServerReadyPending =
!distributedServerStartPromise && !distributedServer;
if (
(!managedReadyPending && !nativeLauncherReadyPending && !distributedServerReadyPending) ||
!mainWindow ||
mainWindow.isDestroyed()
) return;
const deadline = Date.now() + 20_000;
while (Date.now() < deadline && mainWindow && !mainWindow.isDestroyed()) {
try {
const ready = await mainWindow.webContents.executeJavaScript(
"document.documentElement.dataset.vcpRendererReady === 'true'",
true
);
if (ready) {
if (mainWindow.isMinimized()) mainWindow.restore();
if (!mainWindow.isVisible()) mainWindow.show();
mainWindow.focus();
mainWindow.moveTop();
if (!mainWindow.isVisible()) {
await new Promise(resolve => setTimeout(resolve, 100));
continue;
}
if (managedReadyPending) {
publishManagedBootstrapReady({
mainWindow: 'visible',
preload: 'ready',
renderer: 'ready',
});
}
if (nativeLauncherReadyPending) {
nativeLauncherReadyReported = true;
reportLauncherProgress('renderer-ready', 1, '准备完成');
}
// MobileSync 的首次索引可能包含大量同步 SQLite/哈希工作。
// 必须在真实渲染就绪和 Splash 完成信号之后再启动,避免与首屏争抢
// Electron 主线程;后续启动由 history_source_state 差异化跳过。
setImmediate(() => {
void startDistributedServerAfterRenderer();
});
return;
}
} catch (error) {
if (mainWindow?.webContents?.isDestroyed()) return;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
console.warn('[Main] Renderer did not reach launcher readiness before the publication deadline.');
}
function clearMainRendererRecoveryTimers() {
if (mainRendererRecoveryTimer) clearTimeout(mainRendererRecoveryTimer);
if (mainRendererStableTimer) clearTimeout(mainRendererStableTimer);
mainRendererRecoveryTimer = null;
mainRendererStableTimer = null;
}
function markMainRendererStable() {
void publishManagedBootstrapReadyAfterRenderer();
if (mainRendererStableTimer) clearTimeout(mainRendererStableTimer);
mainRendererStableTimer = setTimeout(() => {
mainRendererCrashTimes = [];
mainRendererStableTimer = null;
}, MAIN_RENDERER_STABLE_RESET_MS);
}
async function showMainRendererFailurePrompt(details) {
if (mainRendererFailurePromptOpen || isFinalizingQuit || app.isQuitting) return;
mainRendererFailurePromptOpen = true;
try {
const options = {
type: 'error',
title: 'VCPChat 界面连续崩溃',
message: '主界面在短时间内多次异常退出,已停止自动恢复以避免崩溃循环。',
detail: details?.reason ? `最后一次退出原因:${details.reason}` : '',
buttons: ['重试一次', '退出应用'],
defaultId: 0,
cancelId: 1,
noLink: true,
};
const result = mainWindow && !mainWindow.isDestroyed()
? await dialog.showMessageBox(mainWindow, options)
: await dialog.showMessageBox(options);
if (result.response === 0 && mainWindow && !mainWindow.isDestroyed()) {
mainRendererCrashTimes = [];
scheduleMainRendererRecovery({ reason: 'manual-retry' });
} else {
app.quit();
}
} finally {
mainRendererFailurePromptOpen = false;
}
}
function scheduleMainRendererRecovery(details = {}) {
if (isFinalizingQuit || app.isQuitting || !mainWindow || mainWindow.isDestroyed()) return;
if (mainRendererRecoveryTimer) return;
const now = Date.now();
mainRendererCrashTimes = mainRendererCrashTimes.filter(timestamp => now - timestamp < MAIN_RENDERER_CRASH_WINDOW_MS);
if (mainRendererCrashTimes.length >= MAIN_RENDERER_MAX_RECOVERIES) {
void showMainRendererFailurePrompt(details);
return;
}
mainRendererCrashTimes.push(now);
mainRendererRecoveryTimer = setTimeout(() => {
mainRendererRecoveryTimer = null;
if (isFinalizingQuit || app.isQuitting || !mainWindow || mainWindow.isDestroyed()) return;
console.warn(`[Main] Recovering main renderer (${mainRendererCrashTimes.length}/${MAIN_RENDERER_MAX_RECOVERIES}) after ${details.reason || 'unknown failure'}.`);
mainWindow.loadFile('main.html').catch(error => {
console.error('[Main] Failed to recover main renderer:', error);
scheduleMainRendererRecovery({ reason: 'reload-failed' });
});
}, 250);
}
function startDistributedServerAfterRenderer() {
if (distributedServerStartPromise || distributedServer || isFinalizingQuit || app.isQuitting) {
return distributedServerStartPromise;
}
distributedServerStartPromise = (async () => {
let server = null;
try {
const settings = await appSettingsManager?.readSettings();
if (!settings?.enableDistributedServer) {
console.log('[Main] Distributed server is disabled in settings.');
return null;
}
if (isFinalizingQuit || app.isQuitting || !mainWindow || mainWindow.isDestroyed()) {
return null;
}
console.log('[Main] Renderer is ready. Initializing distributed server in the background...');
const DistributedServer = require('./VCPDistributedServer/VCPDistributedServer.js');
server = new DistributedServer({
mainServerUrl: settings.vcpLogUrl,
vcpKey: settings.vcpLogKey,
serverName: 'VCPChat-Desktop-Client-Distributed-Server',
debugMode: true,
rendererProcess: mainWindow.webContents,
handleMusicControl: musicHandlers.handleMusicControl,
handleDiceControl: diceHandlers.handleDiceControl,
handleCanvasControl: desktopRemoteHandlers.handleCanvasControl,
handleFlowlockControl: desktopRemoteHandlers.handleFlowlockControl,
handleDesktopRemoteControl: desktopRemoteHandlers.handleDesktopRemoteControl,
chatDataService,
loomManager,
scriptoriumAgentControl,
pluginAgentOperationService,
chartService,
gameService,
// 工作区只读门面:direct 插件据此动态获取写入白名单
workspaceService: workspaceHandlers.workspaceService
});
distributedServer = server;
await server.initialize();
return isFinalizingQuit || app.isQuitting ? null : server;
} catch (error) {
// 启动失败也需清理已加载的插件和可能创建的监听器。
if (server) {
await server.stop().catch(cleanupError => {
console.warn('[Main] Failed to clean up distributed server startup:', cleanupError);
});
}
if (distributedServer === server) distributedServer = null;
console.error('[Main] Failed to initialize distributed server after renderer readiness:', error);
return null;
}
})();
return distributedServerStartPromise;
}
function toggleDevToolsForWindow(focusedWindow) {
if (!focusedWindow || focusedWindow.isDestroyed()) return;
if (loomManager?.toggleDevToolsForWindow(focusedWindow)) return;
const contents = focusedWindow.webContents;
if (contents && !contents.isDestroyed()) contents.toggleDevTools();
}
// --- Audio Engine Management ---
// Now uses the Rust native audio engine instead of Python
function startAudioEngine() {
return new Promise((resolve, reject) => {
// --- Uniqueness Check ---
if (audioEngineProcess && !audioEngineProcess.killed) {
console.log('[Main] Audio Engine process is already running.');
resolve(); // Already running, so we can consider it "ready"
return;
}
// Use the Rust audio server binary (moved to audio_engine directory)
const binaryName = process.platform === 'win32' ? 'audio_server.exe' : 'audio_server';
const platformDirectory = `${process.platform}-${process.arch}`;
const audioRoot = app.isPackaged
? path.join(process.resourcesPath, 'app.asar.unpacked', 'audio_engine')
: path.join(__dirname, 'audio_engine');
const platformBinaryPath = path.join(audioRoot, 'bin', platformDirectory, binaryName);
const legacyBinaryPath = path.join(audioRoot, binaryName);
const legacyMatchesPlatform = process.platform === 'win32' || (process.platform === 'linux' && process.arch === 'x64');
const rustBinaryPath = fs.existsSync(platformBinaryPath)
? platformBinaryPath
: legacyMatchesPlatform ? legacyBinaryPath : platformBinaryPath;
console.log(`[Main] Starting Rust Audio Engine from: ${rustBinaryPath}`);
// Check if the binary exists
if (!fs.existsSync(rustBinaryPath)) {
const errorMsg = `Rust audio engine binary not found at: ${rustBinaryPath}. Please run 'cargo build --release' in rust_audio_engine directory.`;
console.error(`[Main] ${errorMsg}`);
reject(new Error(errorMsg));
return;
}
audioEngineStopPromise = null;
isAudioEngineStopping = false;
const args = ['--port', '63789'];
audioEngineProcess = spawn(rustBinaryPath, args);
const readyTimeout = setTimeout(() => {
console.error('[Main] Audio Engine failed to start within 10 seconds.');
reject(new Error('Audio Engine timed out.'));
}, 10000); // 10-second timeout (Rust starts faster)
audioEngineProcess.stdout.on('data', (data) => {
const output = data.toString().trim();
console.log(`[AudioEngine STDOUT]: ${output}`);
// Check for our ready signal from Rust server
if (output.includes('RUST_AUDIO_ENGINE_READY')) {
console.log('[Main] Rust Audio Engine is ready.');
clearTimeout(readyTimeout);
resolve();
}
});
audioEngineProcess.stderr.on('data', (data) => {
const logLine = data.toString().trim();
if (logLine && !logLine.includes('GET /state HTTP/1.1')) {
const logMethod = isAudioEngineStopping ? console.warn : console.error;
logMethod(`[AudioEngine STDERR]: ${logLine}`);
}
});
audioEngineProcess.on('close', (code) => {
console.log(`[Main] Audio Engine process exited with code ${code}`);
clearTimeout(readyTimeout);
audioEngineProcess = null;
audioEngineStopPromise = null;
isAudioEngineStopping = false;
});
audioEngineProcess.on('error', (err) => {
console.error('[Main] Failed to start Audio Engine process.', err);
clearTimeout(readyTimeout);
reject(err);
});
});
}
async function stopAudioEngine() {
if (!audioEngineProcess || audioEngineProcess.killed) {
return;
}
if (audioEngineStopPromise) {
return audioEngineStopPromise;
}
console.log('[Main] Stopping Rust Audio Engine...');
isAudioEngineStopping = true;
const processRef = audioEngineProcess;
const exitPromise = new Promise((resolve) => {
processRef.once('close', () => resolve());
});
audioEngineStopPromise = (async () => {
try {
const controller = new AbortController();
const shutdownTimer = setTimeout(() => controller.abort(), 2000);
try {
await fetch('http://127.0.0.1:63789/shutdown', {
method: 'POST',
signal: controller.signal
});
} catch (error) {
if (error.name !== 'AbortError') {
console.warn(`[Main] Audio Engine shutdown request failed: ${error.message}`);
}
} finally {
clearTimeout(shutdownTimer);
}
await Promise.race([
exitPromise,
new Promise((resolve) => setTimeout(resolve, 2500))
]);
if (audioEngineProcess === processRef && !processRef.killed) {
console.warn('[Main] Audio Engine did not exit after graceful shutdown request. Force killing process.');
processRef.kill();
await Promise.race([
exitPromise,
new Promise((resolve) => setTimeout(resolve, 2000))
]);
}
} finally {
if (audioEngineProcess !== processRef || processRef.killed) {
audioEngineStopPromise = null;
}
}
})();
return audioEngineStopPromise;
}
async function performQuitCleanup() {
if (appQuitCleanupPromise) {
return appQuitCleanupPromise;
}
appQuitCleanupPromise = (async () => {
await historyWatcherLeases.dispose();
try {
localSttHandlers.shutdown();
await voiceHandlers.shutdownVoiceInputEngine();
} catch (error) {
console.warn('[Main] Failed to shut down native voice input engine:', error.message || error);
}
if (distributedServer) {
console.log('[Main] Stopping distributed server...');
try {
await distributedServer.stop();
} finally {
distributedServer = null;
}
}
if (chatDataService) {
console.log('[Main] Stopping VCP-CDS...');
try {
await chatDataService.stop();
} finally {
chatDataService = null;
}
}
if (loomManager) {
console.log('[Main] Stopping VCP Loom...');
try {
await loomManager.shutdown();
} finally {
loomManager = null;
}
}
workspaceHandlers.dispose();
await historyMutationQueue?.dispose?.();
historyMutationQueue = null;
pluginAgentOperationService = null;
if (chartService) {
try {
await chartHandlers.shutdown();
} finally {
chartService = null;
}
}
await stopAudioEngine();
})();
return appQuitCleanupPromise;
}
// --- Main Window Creation ---
// 一次性诊断导出。exporter 在生命周期快照通道注册时创建(它复用同一份快照),菜单项和 IPC 都走这里。
let diagnosticsExporter = null;
async function exportDiagnosticsSnapshot() {
if (!diagnosticsExporter) return { success: false, error: '诊断导出尚未就绪。' };
try {
return await diagnosticsExporter.exportToFile();
} catch (error) {
console.error('[Main] Diagnostics export failed:', error);
return { success: false, error: error?.message || String(error) };
}
}
// 主窗口响应性记录:只记状态与时间,不保存任何聊天内容。
const mainWindowResponsiveness = {
unresponsive: false,
unresponsiveCount: 0,
lastUnresponsiveAt: null,
lastResponsiveAt: null,
lastSource: null,
};
// 稳定性日志:无响应 / 恢复(按停滞时长分级)、渲染进程退出、子进程退出,写到 userData/diagnostics/stability.log,
// 最近条目随 lifecycle:get-main-snapshot.stability 与诊断导出带出。目录在第一次写入时才解析,不受 userData 改路径顺序影响。
const { createStabilityLog } = require('./modules/stabilityLog');
const stabilityLog = createStabilityLog({
resolveDirectory: () => path.join(app.getPath('userData'), 'diagnostics'),
});
stabilityLog.note('session-start', { pid: process.pid, version: app.getVersion(), electron: process.versions.electron });
app.on('child-process-gone', (event, details) => {
stabilityLog.recordChildProcessGone(details);
if (details?.reason !== 'clean-exit') console.warn('[Main] child-process-gone', details?.type, details?.serviceName || '', details?.reason, details?.exitCode);
});
function recordMainWindowResponsiveness(responsive, source) {
const at = Date.now();
mainWindowResponsiveness.lastSource = source;
if (responsive) {
if (mainWindowResponsiveness.unresponsive) {
const stalledMs = mainWindowResponsiveness.lastUnresponsiveAt ? at - mainWindowResponsiveness.lastUnresponsiveAt : null;
console.warn('[Main] Main window responsive again after ' + (stalledMs ?? '?') + ' ms (' + source + ').');
stabilityLog.recordResponsive(source);
}
mainWindowResponsiveness.unresponsive = false;
mainWindowResponsiveness.lastResponsiveAt = at;
return;
}
if (!mainWindowResponsiveness.unresponsive) {
mainWindowResponsiveness.unresponsiveCount += 1;
mainWindowResponsiveness.lastUnresponsiveAt = at;
console.warn('[Main] Main window unresponsive (' + source + '); keeping it alive, see lifecycle:get-main-snapshot.mainWindowResponsiveness.');
stabilityLog.recordUnresponsive(source);
}
mainWindowResponsiveness.unresponsive = true;
}
function createWindow({ deferLoad = false } = {}) {
mainWindow = new BrowserWindow({
width: 1300,
height: 800,
minWidth: 900,
minHeight: 600,
frame: false, // 移除原生窗口框架
...(process.platform === 'darwin' ? {} : { titleBarStyle: 'hidden' }),
webPreferences: {
preload: resolveProjectPreload(__dirname, PRELOAD_ROLES.CHAT),
sandbox: false, // preloads/* 需要 require 本地模块,沙箱内不可用,见 preloads/README.md
contextIsolation: true, // 恢复: 开启上下文隔离
nodeIntegration: false, // 恢复: 关闭Node.js集成在渲染进程
webviewTag: true, // 仅供侧栏浏览器的 <webview>;其创建参数由 browserHandlers.attachToWindow 强制收紧
// 主窗口沿用 Chromium 默认的后台节流:ipcRenderer 收流式事件不受节流影响,
// 渲染端的流式帧循环在隐藏时自行改走定时器(见 streamManager.js)。
spellcheck: true, // Enable spellcheck for input fields
},
icon: path.join(__dirname, 'assets', 'icon.png'), // Add an icon
title: 'VCP AI 聊天客户端',
show: false, // Don't show until ready
});
browserHandlers.attachToWindow(mainWindow);
if (!deferLoad) {
loadMainWindow();
}
// 拦截主窗口内的直接导航(防止在应用内打开外部网页)
mainWindow.webContents.on('will-navigate', (event, url) => {
if (url !== mainWindow.webContents.getURL() && (url.startsWith('http:') || url.startsWith('https:'))) {
event.preventDefault();
shell.openExternal(url);
}
});
// 当主窗口关闭时的处理逻辑:
// 1. macOS 上始终隐藏而非关闭
// 2. 当桌面窗口存在时,隐藏到托盘而非退出(偷天换日!)
// 3. 其他情况正常退出
mainWindow.on('close', (event) => {
if (app.isQuitting) {
// 应用正在退出,允许关闭
return;
}
// macOS 始终隐藏
if (process.platform === 'darwin') {
event.preventDefault();
mainWindow.hide();
return;
}
// Windows/Linux:如果桌面窗口存在,隐藏到托盘
const dw = desktopHandlers.getDesktopWindow();
if (dw && !dw.isDestroyed()) {
event.preventDefault();
mainWindow.hide();
console.log('[Main] Desktop window active — main window hidden to tray instead of closing.');
}
// 否则允许正常关闭(触发 closed 事件)
});
// This will be triggered when the app is quitting, after the window is closed.
mainWindow.on('closed', () => {
// When the main window is closed, we should only quit on non-macOS
// when there are no remaining windows (e.g. RAG Observer may still be open).
clearMainRendererRecoveryTimers();
mainRendererCrashTimes = [];
mainWindow = null;
if (process.platform !== 'darwin' && BrowserWindow.getAllWindows().length === 0) {
app.quit();
}
});
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error('[Main] Main window did-fail-load', errorCode, errorDescription, validatedURL);
});
mainWindow.webContents.on('did-start-loading', () => {
embeddedAppSessions?.suspend?.();
});
mainWindow.webContents.on('render-process-gone', (event, details) => {
embeddedAppSessions?.suspend?.();
if (mainRendererStableTimer) {
clearTimeout(mainRendererStableTimer);
mainRendererStableTimer = null;
}
console.error('[Main] Main window render-process-gone', details);
stabilityLog.recordRenderProcessGone('main-window', details);
if (details?.reason !== 'clean-exit') scheduleMainRendererRecovery(details);
});
mainWindow.webContents.on('did-finish-load', markMainRendererStable);
// 渲染进程被 Chromium 判定无响应时不弹窗、不杀进程,但要记下来:lifecycle:get-main-snapshot 会带出
// 这份记录,用户反馈"卡住"时可以对照时间点。以前这里连同挂起监视器一起被静默掉了。
mainWindow.on('unresponsive', () => recordMainWindowResponsiveness(false, 'window'));
mainWindow.on('responsive', () => recordMainWindowResponsiveness(true, 'window'));
mainWindow.webContents.on('unresponsive', () => recordMainWindowResponsiveness(false, 'webContents'));
mainWindow.webContents.on('responsive', () => recordMainWindowResponsiveness(true, 'webContents'));
// mainWindow.setMenu(null); // 移除应用程序菜单栏 - 注释掉以启用macOS的标准菜单
// Set theme source to 'system' by default. The renderer will send the saved preference on launch.
nativeTheme.themeSource = 'system';
// Listen for window events to notify renderer
mainWindow.on('maximize', () => {
if (mainWindow && mainWindow.webContents && !mainWindow.webContents.isDestroyed()) {
mainWindow.webContents.send('window-maximized');
}
});
mainWindow.on('unmaximize', () => {
if (mainWindow && mainWindow.webContents && !mainWindow.webContents.isDestroyed()) {
mainWindow.webContents.send('window-unmaximized');
}
});
// Listen for theme changes and notify all relevant windows
}
function loadMainWindow() {
mainWindow.webContents.once('did-finish-load', () => {
launchMarks.mark('main-window-loaded');
const readyFile = NATIVE_SPLASH_READY_FILE;
fs.ensureFileSync(readyFile);
setTimeout(() => {
if (fs.existsSync(readyFile)) {
fs.unlinkSync(readyFile);
}
}, 3000);
mainWindow.show();
});
return mainWindow.loadFile('main.html');
}
function createTray() {
const iconPath = path.join(__dirname, 'assets', 'icon.png');
// 修复图标体积问题:在 macOS 上,使用 nativeImage 调整图标大小
const { nativeImage } = require('electron');
let icon = nativeImage.createFromPath(iconPath);
// 假设 macOS 菜单栏图标的理想尺寸是 16x16 或 20x20
if (process.platform === 'darwin') {
// 尝试使用模板图像,并调整大小以适应菜单栏
icon = icon.resize({ width: 16, height: 16 });
icon.setTemplateImage(true); // 告诉 macOS 这是一个模板图像,用于深色/浅色模式切换
}
tray = new Tray(icon);
const toggleMainWindowVisibility = () => {
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.show();
mainWindow.focus();
}
return true;
}
return false;
};