forked from lioensky/VCPChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1496 lines (1311 loc) · 64.3 KB
/
main.js
File metadata and controls
1496 lines (1311 loc) · 64.3 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 主窗口
// --- 模块加载性能诊断 ---
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, ipcMain, nativeTheme, globalShortcut, screen, clipboard, shell, dialog, protocol, Tray, Menu } = require('electron'); // Added screen, clipboard, and shell
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 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 { 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 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 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
// speechRecognizer is now lazy-loaded
const canvasHandlers = require('./modules/ipc/canvasHandlers'); // Import canvas handlers
const desktopHandlers = require('./modules/ipc/desktopHandlers'); // Import VCPdesktop handlers
const desktopRemoteHandlers = require('./modules/ipc/desktopRemoteHandlers'); // Import desktop remote control handlers
const { PRELOAD_ROLES, resolveProjectPreload } = require('./modules/services/preloadPaths');
// chokidar is now lazy-loaded
// --- File Watcher ---
let historyWatcher = null;
let lastInternalSaveTime = 0; // 🔧 改为时间戳记录
let internalSaveTimeout = null; // 🔧 超时保护
let isEditingInProgress = false; // 🔧 编辑状态标识
const INTERNAL_SAVE_WINDOW_MS = 2000; // 🔧 内部保存时间窗口(2秒)
const fileWatcher = {
watchFile: (filePath, callback) => {
if (historyWatcher) {
historyWatcher.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: () => {
if (historyWatcher) {
console.log('[FileWatcher] Stopping file watch.');
historyWatcher.close();
historyWatcher = null;
}
// 🔧 清理状态
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}`);
}
};
// --- Configuration Paths ---
// Data storage will be within the project's 'AppData' directory
const PROJECT_ROOT = __dirname; // __dirname is the directory of main.js
const APP_DATA_ROOT_IN_PROJECT = path.join(PROJECT_ROOT, 'AppData');
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 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 translatorWindow = null; // To hold the single instance of the translator window
let appSettingsManager = 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;
// --- 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 rustBinaryPath = path.join(__dirname, 'audio_engine', binaryName);
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 () => {
if (distributedServer) {
console.log('[Main] Stopping distributed server...');
try {
await distributedServer.stop();
} finally {
distributedServer = null;
}
}
await stopAudioEngine();
})();
return appQuitCleanupPromise;
}
// --- Main Window Creation ---
function createWindow() {
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),
contextIsolation: true, // 恢复: 开启上下文隔离
nodeIntegration: false, // 恢复: 关闭Node.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
});
mainWindow.loadFile('main.html');
// 拦截主窗口内的直接导航(防止在应用内打开外部网页)
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).
mainWindow = null;
if (process.platform !== 'darwin' && BrowserWindow.getAllWindows().length === 0) {
app.quit();
}
});
mainWindow.once('ready-to-show', () => {
// Signal the native splash screen to close by creating the ready file.
const readyFile = path.join(__dirname, '.vcp_ready');
fs.ensureFileSync(readyFile);
// Clean up the file after a few seconds to prevent it from lingering.
setTimeout(() => {
if (fs.existsSync(readyFile)) {
fs.unlinkSync(readyFile);
}
}, 3000); // 3-second delay
mainWindow.show();
});
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error('[Main] Main window did-fail-load', errorCode, errorDescription, validatedURL);
});
mainWindow.webContents.on('render-process-gone', (event, details) => {
console.error('[Main] Main window render-process-gone', details);
});
// 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 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;
};
const toggleRagObserverVisibility = async () => {
const ragObserverWindow = ragHandlers.getRagObserverWindow();
const ragOverlayWindow = ragHandlers.getRagOverlayWindow();
if (ragObserverWindow && !ragObserverWindow.isDestroyed()) {
if (ragObserverWindow.isVisible()) {
ragObserverWindow.hide();
if (ragOverlayWindow && !ragOverlayWindow.isDestroyed()) {
ragOverlayWindow.hide();
}
} else {
if (ragObserverWindow.isMinimized()) ragObserverWindow.restore();
ragObserverWindow.show();
ragObserverWindow.focus();
}
return true;
}
await ragHandlers.openRagObserverWindow();
return true;
};
const handleTrayPrimaryAction = async () => {
if (toggleMainWindowVisibility()) return;
await toggleRagObserverVisibility();
};
const contextMenu = Menu.buildFromTemplate([
{
label: '显示/隐藏主窗口',
click: () => {
toggleMainWindowVisibility();
}
},
{
label: '显示/隐藏信息流监听器',
click: () => {
void toggleRagObserverVisibility();
}
},
{
label: '打开 VCP 桌面',
click: () => {
desktopHandlers.openDesktopWindow();
}
},
{ type: 'separator' },
{
label: '退出',
click: () => {
app.isQuitting = true;
app.quit();
}
}
]);
tray.setToolTip('VCP AI 聊天客户端');
// 平台特定行为调整:macOS 左键点击只显示/隐藏,右键点击才显示菜单
if (process.platform === 'darwin') {
// macOS: 左键点击 (tray.on('click')) 负责显示/隐藏窗口
tray.on('click', () => {
void handleTrayPrimaryAction();
});
// macOS: 右键点击 (tray.on('right-click')) 负责显示菜单
tray.on('right-click', () => {
tray.popUpContextMenu(contextMenu);
});
// 注意:在 macOS 上,不调用 tray.setContextMenu(),以确保左键点击不弹出菜单。
} else {
// Windows/Linux: 默认行为。
tray.setContextMenu(contextMenu);
tray.on('click', () => {
void handleTrayPrimaryAction();
});
}
}
// --- App Lifecycle ---
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', async (event, commandLine, workingDirectory) => {
const wantsRagOnly = commandLine.includes('--rag-observer-only');
const wantsDesktop = commandLine.includes('--desktop-only');
// 如果第二实例请求的是 RAG 独立模式,则直接打开/聚焦 RAG 窗口
if (wantsRagOnly) {
await ragHandlers.openRagObserverWindow();
return;
}
// 如果第二实例带 --desktop-only 参数,打开/聚焦桌面窗口
if (wantsDesktop) {
await desktopHandlers.openDesktopWindow();
// 同时确保主窗口也显示出来
if (mainWindow && !mainWindow.isDestroyed()) {
if (!mainWindow.isVisible()) mainWindow.show();
mainWindow.focus();
}
return;
}
// 默认聚焦主窗口
if (mainWindow && !mainWindow.isDestroyed()) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
return;
}
const ragObserverWindow = ragHandlers.getRagObserverWindow();
if (ragObserverWindow && !ragObserverWindow.isDestroyed()) {
if (ragObserverWindow.isMinimized()) ragObserverWindow.restore();
if (!ragObserverWindow.isVisible()) ragObserverWindow.show();
ragObserverWindow.focus();
}
});
app.whenReady().then(async () => { // Make the function async
// 全局处理所有窗口的新窗口打开请求,确保外部链接在系统浏览器中打开
app.on('web-contents-created', (event, contents) => {
contents.setWindowOpenHandler(({ url }) => {
if (url.startsWith('http:') || url.startsWith('https:')) {
shell.openExternal(url);
return { action: 'deny' };
}
return { action: 'allow' };
});
});
// Handle the emergency close request from the splash screen
ipcMain.on('close-app', () => {
console.log('[Main] Received close-app request from splash screen. Quitting.');
app.quit();
});
// The native splash screen is started by the batch file, so no action is needed here.
// Pre-warm the audio engine in the background. This doesn't block the main window.
startAudioEngine().catch(err => {
console.error('[Main] Failed to pre-warm audio engine on startup:', err);
// We don't need to show a dialog here, as it will be handled when the
// music window is actually opened.
});
// Register a custom protocol to handle loading local app files securely.
fs.ensureDirSync(APP_DATA_ROOT_IN_PROJECT); // Ensure the main AppData directory in project exists
fs.ensureDirSync(AGENT_DIR);
fs.ensureDirSync(USER_DATA_DIR);
fs.ensureDirSync(MUSIC_COVER_CACHE_DIR);
fs.ensureDirSync(WALLPAPER_THUMBNAIL_CACHE_DIR); // Ensure the thumbnail cache directory exists
fs.ensureDirSync(RESAMPLE_CACHE_DIR); // Ensure the resample cache directory exists
fs.ensureDirSync(CANVAS_CACHE_DIR); // Ensure the canvas cache directory exists
fileManager.initializeFileManager(USER_DATA_DIR, AGENT_DIR); // Initialize FileManager
groupChat.initializePaths({ APP_DATA_ROOT_IN_PROJECT, AGENT_DIR, USER_DATA_DIR, SETTINGS_FILE }); // Initialize GroupChat paths
const AppSettingsManager = require('./modules/utils/appSettingsManager');
const AgentConfigManager = require('./modules/utils/agentConfigManager');
appSettingsManager = new AppSettingsManager(SETTINGS_FILE);
const agentConfigManager = new AgentConfigManager(AGENT_DIR);
appSettingsManager.startCleanupTimer();
appSettingsManager.startAutoBackup(USER_DATA_DIR); // Start auto backup
agentConfigManager.startCleanupTimer(); // Start agent config cleanup
settingsHandlers.initialize({ SETTINGS_FILE, USER_AVATAR_FILE, AGENT_DIR, settingsManager: appSettingsManager, agentConfigManager }); // Initialize settings handlers
ragHandlers.initialize({ mainWindow, openChildWindows, settingsManager: appSettingsManager, SETTINGS_FILE });
// RAG 独立模式:不创建主窗口,仅初始化 RAG 所需 IPC 并直接打开 RAG 窗口
if (isRagObserverOnlyMode) {
console.log('[Main] Starting in RAG observer only mode.');
windowHandlers.initialize(mainWindow, openChildWindows);
themeHandlers.initialize({ mainWindow, openChildWindows, projectRoot: PROJECT_ROOT, APP_DATA_ROOT_IN_PROJECT, settingsManager: appSettingsManager });
ipcMain.handle('get-platform', () => process.platform);
// 关键:独立模式也必须创建系统托盘,否则"最小化到托盘"后无法召回窗口。
createTray();
await ragHandlers.openRagObserverWindow();
return;
}
// 注意:原 desktop-only 模式已移除。--desktop-only 参数现在仅作为
// "启动后自动打开桌面窗口"的标志,所有 IPC 始终完整初始化。
// Function to fetch and cache models from the VCP server
async function fetchAndCacheModels() {
console.log('[Main] fetchAndCacheModels called');
try {
const settings = await appSettingsManager.readSettings();
const vcpServerUrl = settings.vcpServerUrl;
const vcpApiKey = settings.vcpApiKey; // Get the API key
if (!vcpServerUrl) {
console.warn('[Main] VCP Server URL is not configured. Cannot fetch models.');
cachedModels = []; // Clear cache if URL is not set
return;
}
// Correctly construct the base URL by removing known API paths.
const urlObject = new URL(vcpServerUrl);
const baseUrl = `${urlObject.protocol}//${urlObject.host}`;
const modelsUrl = new URL('/v1/models', baseUrl).toString();
console.log(`[Main] Fetching models from: ${modelsUrl}`);
const response = await fetch(modelsUrl, {
headers: {
'Authorization': `Bearer ${vcpApiKey}` // Add the Authorization header
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
cachedModels = data.data || []; // Assuming the response has a 'data' field containing the models array
console.log('[Main] Models fetched and cached successfully:', cachedModels.map(m => m.id));
} catch (error) {
console.error('[Main] Failed to fetch and cache models:', error);
cachedModels = []; // Clear cache on error
}
}
// Create the main window first to give immediate feedback to the user.
createWindow();
createTray();
// --- Application Menu ---
const isMac = process.platform === 'darwin';
const menuTemplate = [
...(isMac ? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideothers' },
{ role: 'unhide' },
{ type: 'separator' },
{
label: '退出 VCPChat',
accelerator: 'Command+Q',
click: () => {
app.isQuitting = true;
app.quit();
}
}
]
}] : []),
{
label: '文件',
submenu: [
{
label: '新建无锁话题',
accelerator: 'CommandOrControl+Shift+N',
click: () => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('create-unlocked-topic');
}
}
}
]
},
{
label: '编辑',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
...(isMac ? [
{ role: 'pasteAndMatchStyle' },
{ role: 'delete' },
{ role: 'selectAll' },
{ type: 'separator' },
{
label: '语音',
submenu: [
{ role: 'startSpeaking' },
{ role: 'stopSpeaking' }
]
}
] : [
{ role: 'delete' },
{ type: 'separator' },
{ role: 'selectAll' }
])
]
},
{
label: '视图',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
},
{
label: '窗口',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
...(isMac ? [
{ role: 'close' },
{ type: 'separator' },
{ role: 'front' },
{ type: 'separator' },
{ role: 'window' }
] : [
{ role: 'close' }
])
]
},
{
label: '开发者',
submenu: [
{
label: '切换开发者工具',
accelerator: 'Ctrl+Shift+I',
click: (item, focusedWindow) => {
if (focusedWindow) {
focusedWindow.webContents.toggleDevTools();
}
}
}
]
}
];
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
// Fetch models in the background and notify the renderer when done.
console.log('[Main] Fetching models in the background...');
fetchAndCacheModels().then(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
console.log('[Main] Background model fetch complete. Notifying renderer.');
mainWindow.webContents.send('models-updated', cachedModels);
}
}).catch(error => {
console.error('[Main] Background model fetch failed:', error);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('models-update-failed', error.message);
}
});
// IPC handler to provide cached models to the renderer process
ipcMain.handle('get-cached-models', () => {
return cachedModels;
});
// IPC handler to get hot models (top N most used models)
ipcMain.handle('get-hot-models', async () => {
try {
const modelUsageTracker = require('./modules/modelUsageTracker');
return await modelUsageTracker.getHotModels(10);
} catch (error) {
console.error('[Main] Failed to get hot models:', error);
return [];
}
});
// IPC handler to get favorite models
ipcMain.handle('get-favorite-models', async () => {
try {
const modelUsageTracker = require('./modules/modelUsageTracker');
return await modelUsageTracker.getFavoriteModels();
} catch (error) {
console.error('[Main] Failed to get favorite models:', error);
return [];
}
});
// IPC handler to toggle a model's favorite status
ipcMain.handle('toggle-favorite-model', async (event, modelId) => {
try {
const modelUsageTracker = require('./modules/modelUsageTracker');
return await modelUsageTracker.toggleFavoriteModel(modelId);
} catch (error) {
console.error('[Main] Failed to toggle favorite model:', error);
return { favorited: false };
}
});
// IPC handler to trigger a refresh of the model list
ipcMain.handle('refresh-models', async (event) => {
console.log('[Main] Received refresh-models request. Re-fetching models...');
await fetchAndCacheModels();
const result = {
success: Array.isArray(cachedModels) && cachedModels.length > 0,
models: cachedModels,
count: Array.isArray(cachedModels) ? cachedModels.length : 0
};
if (event?.sender && !event.sender.isDestroyed()) {
event.sender.send('models-updated', cachedModels);
}
if (mainWindow && !mainWindow.isDestroyed() && event?.sender !== mainWindow.webContents) {
mainWindow.webContents.send('models-updated', cachedModels);
}
return result;
});
// Add IPC handler for path operations
ipcMain.handle('path:dirname', (event, p) => {
return path.dirname(p);
});
// Add IPC handler for getting the extension name of a path
ipcMain.handle('path:extname', (event, p) => {
return path.extname(p);
});
ipcMain.handle('path:basename', (event, p) => {
return path.basename(p);
});
// Group Chat IPC Handlers are now in modules/ipc/groupChatHandlers.js
notesHandlers.initialize({
openChildWindows,
APP_DATA_ROOT_IN_PROJECT,
SETTINGS_FILE
});
// Translator IPC Handlers
const TRANSLATOR_DIR = path.join(APP_DATA_ROOT_IN_PROJECT, 'Translatormodules');
fs.ensureDirSync(TRANSLATOR_DIR); // Ensure the Translator directory exists
ipcMain.handle('open-translator-window', async (event) => {
if (translatorWindow && !translatorWindow.isDestroyed()) {
if (!translatorWindow.isVisible()) {
translatorWindow.show();
}
translatorWindow.focus();
return;
}
translatorWindow = new BrowserWindow({
width: 1000,
height: 700,
minWidth: 800,
minHeight: 600,
title: '翻译',
frame: false, // 移除原生窗口框架
...(process.platform === 'darwin' ? {} : { titleBarStyle: 'hidden' }),
modal: false,
webPreferences: {
preload: resolveProjectPreload(__dirname, PRELOAD_ROLES.UTILITY),
contextIsolation: true,
nodeIntegration: false,
devTools: true
},
icon: path.join(__dirname, 'assets', 'icon.png'),
show: false
});
let settings = {};
try {
if (await fs.pathExists(SETTINGS_FILE)) {
settings = await fs.readJson(SETTINGS_FILE);
}
} catch (readError) {
console.error('Failed to read settings file for translator window:', readError);
}
const vcpServerUrl = settings.vcpServerUrl || '';
const vcpApiKey = settings.vcpApiKey || '';
const translatorUrl = `file://${path.join(__dirname, 'Translatormodules', 'translator.html')}?vcpServerUrl=${encodeURIComponent(vcpServerUrl)}&vcpApiKey=${encodeURIComponent(vcpApiKey)}`;
console.log(`[Main Process] Attempting to load URL in translator window: ${translatorUrl.substring(0, 200)}...`);
translatorWindow.webContents.on('did-start-loading', () => {
console.log(`[Main Process] translatorWindow webContents did-start-loading for URL: ${translatorUrl.substring(0, 200)}`);
});
translatorWindow.webContents.on('dom-ready', () => {
console.log(`[Main Process] translatorWindow webContents dom-ready for URL: ${translatorWindow.webContents.getURL()}`);
});
translatorWindow.webContents.on('did-finish-load', () => {
console.log(`[Main Process] translatorWindow webContents did-finish-load for URL: ${translatorWindow.webContents.getURL()}`);
});
translatorWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error(`[Main Process] translatorWindow webContents did-fail-load: Code ${errorCode}, Desc: ${errorDescription}, URL: ${validatedURL}`);
});
translatorWindow.loadURL(translatorUrl)
.then(() => {
console.log(`[Main Process] translatorWindow successfully initiated URL loading (loadURL resolved): ${translatorUrl.substring(0, 200)}`);
})
.catch((err) => {
console.error(`[Main Process] translatorWindow FAILED to initiate URL loading (loadURL rejected): ${translatorUrl.substring(0, 200)}`, err);
});
openChildWindows.push(translatorWindow);
translatorWindow.setMenu(null);
translatorWindow.once('ready-to-show', () => {
console.log(`[Main Process] translatorWindow is ready-to-show. Window Title: "${translatorWindow.getTitle()}". Calling show().`);
translatorWindow.show();
console.log('[Main Process] translatorWindow show() called.');
});
translatorWindow.on('close', (event) => {
if (process.platform === 'darwin' && !app.isQuitting) {
event.preventDefault();
translatorWindow.hide();
}
});
translatorWindow.on('closed', () => {
console.log('[Main Process] translatorWindow has been closed.');
openChildWindows = openChildWindows.filter(win => win !== translatorWindow);
translatorWindow = null;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.focus(); // 聚焦主窗口
}
});
});
// open-rag-observer-window handler is registered once above and reuses openRagObserverWindow()
windowHandlers.initialize(mainWindow, openChildWindows);
forumHandlers.initialize({ USER_DATA_DIR }); // Initialize forum handlers
memoHandlers.initialize({ USER_DATA_DIR }); // Initialize memo handlers
// ⚠️ agentHandlers 必须在 assistantHandlers 之前初始化
// 因为 assistantHandlers 依赖 getAgentConfigById 函数,该函数需要 AGENT_DIR_CACHE 已被初始化
agentHandlers.initialize({
AGENT_DIR,
USER_DATA_DIR,
SETTINGS_FILE,
USER_AVATAR_FILE,
getSelectionListenerStatus: assistantHandlers.getSelectionListenerStatus,
stopSelectionListener: assistantHandlers.stopSelectionListener,
startSelectionListener: assistantHandlers.startSelectionListener,
settingsManager: appSettingsManager,
agentConfigManager
});
await assistantHandlers.initialize({ SETTINGS_FILE });