forked from lioensky/VCPChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
executable file
·2447 lines (2184 loc) · 121 KB
/
renderer.js
File metadata and controls
executable file
·2447 lines (2184 loc) · 121 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
// --- Globals ---
let globalSettings = {
sidebarWidth: 260,
enableMiddleClickQuickAction: false,
middleClickQuickAction: '',
enableMiddleClickAdvanced: false,
middleClickAdvancedDelay: 1000,
notificationsSidebarWidth: 300,
userName: '用户', // Default username
doNotDisturbLogMode: false, // 勿扰模式状态(已废弃,保留兼容性)
filterEnabled: false, // 过滤总开关状态
filterRules: [], // 过滤规则列表
enableRegenerateConfirmation: true, // 重新回复确认机制开关
flowlockContinueDelay: 5, // 心流锁续写延迟(秒)
enableThoughtChainInjection: false, // 元思考注入上下文开关
fileKey: '',
enableWideChatLayout: false,
chatBubbleMaxWidthDefault: 82,
chatBubbleMaxWidthNotifications: 90,
chatBubbleMaxWidthNarrow: 85,
chatBubbleMaxWidthWideDefault: 92,
chatBubbleMaxWidthWideNotifications: 96,
chatBubbleMaxWidthWideNarrow: 92,
chatFontPreset: 'system',
chatFontCustom: '',
chatCodeFontPreset: 'consolas',
chatCodeFontCustom: '',
chatDiaryFontPreset: 'serif',
chatDiaryFontCustom: '',
chatToolFontPreset: 'system',
chatToolFontCustom: '',
enableUserChatBubbleUi: true,
showUserMetaInChatBubbleUi: true,
voiceMode: 'local',
speechRecognizerBrowserPath: '',
speechRecognizerPagePath: 'Voicechatmodules/recognizer.html',
voiceLocalSettings: {
sovitsUrl: '',
sovitsKey: ''
},
voiceNetworkSettings: {
providerUrl: 'https://api.siliconflow.cn',
providerKey: ''
}
};
// Unified selected item state
let currentSelectedItem = {
id: null, // Can be agentId or groupId
type: null, // 'agent' or 'group'
name: null,
avatarUrl: null,
config: null // Store full config object for the selected item
};
let currentTopicId = null;
let currentChatHistory = [];
window.__vcpRendererReady = false;
window.__vcpPendingTopicSelection = null;
const chatAPI = window.chatAPI || window.electronAPI;
// 暴露到window对象以便其他模块访问
window.currentSelectedItem = currentSelectedItem;
window.currentTopicId = currentTopicId;
let attachedFiles = [];
let audioContext = null;
let currentAudioSource = null;
let ttsAudioQueue = []; // 新增:TTS音频播放队列
let isTtsPlaying = false; // 新增:TTS播放状态标志
let currentPlayingMsgId = null; // 新增:跟踪当前播放的msgId以控制UI
let currentTtsSessionId = -1; // 新增:会话ID,用于处理异步时序问题
// --- DOM Elements ---
const itemListUl = document.getElementById('agentList'); // Renamed from agentListUl to itemListUl
const currentChatNameH3 = document.getElementById('currentChatAgentName'); // Will show Agent or Group name
const chatMessagesDiv = document.getElementById('chatMessages');
const messageInput = document.getElementById('messageInput');
const sendMessageBtn = document.getElementById('sendMessageBtn');
const attachFileBtn = document.getElementById('attachFileBtn');
const emoticonTriggerBtn = document.getElementById('emoticonTriggerBtn');
const quickNewTopicBtn = document.getElementById('quickNewTopicBtn');
const attachmentPreviewArea = document.getElementById('attachmentPreviewArea');
const chatInputCard = document.querySelector('.chat-input-card');
const globalSettingsBtn = document.getElementById('globalSettingsBtn');
// 模态框及其内部元素现在延迟加载,不再在顶层缓存引用
let globalSettingsForm = null;
let userAvatarInput = null;
let userAvatarPreview = null;
const createNewAgentBtn = document.getElementById('createNewAgentBtn'); // Text will change
const createNewGroupBtn = document.getElementById('createNewGroupBtn'); // New button
const itemSettingsContainerTitle = document.getElementById('agentSettingsContainerTitle'); // Will be itemSettingsContainerTitle
const selectedItemNameForSettingsSpan = document.getElementById('selectedAgentNameForSettings'); // Will show Agent or Group name
// Agent specific settings elements (will be hidden if a group is selected)
const agentSettingsContainer = document.getElementById('agentSettingsContainer');
const agentSettingsForm = document.getElementById('agentSettingsForm');
const editingAgentIdInput = document.getElementById('editingAgentId');
const agentNameInput = document.getElementById('agentNameInput');
const agentAvatarInput = document.getElementById('agentAvatarInput');
const agentAvatarPreview = document.getElementById('agentAvatarPreview');
const agentSystemPromptTextarea = document.getElementById('agentSystemPrompt');
const agentModelInput = document.getElementById('agentModel');
const agentTemperatureInput = document.getElementById('agentTemperature');
const agentContextTokenLimitInput = document.getElementById('agentContextTokenLimit');
const agentMaxOutputTokensInput = document.getElementById('agentMaxOutputTokens');
// Group specific settings elements (placeholder, grouprenderer.js will populate)
const groupSettingsContainer = document.getElementById('groupSettingsContainer'); // This should be the div renderer creates
const selectItemPromptForSettings = document.getElementById('selectAgentPromptForSettings'); // Will be "Select an item..."
console.log('[Renderer EARLY CHECK] selectItemPromptForSettings element:', selectItemPromptForSettings); // 添加日志
const deleteItemBtn = document.getElementById('deleteAgentBtn'); // Will be deleteItemBtn for agent or group
const currentItemActionBtn = document.getElementById('currentAgentSettingsBtn'); // Text will change (e.g. "New Topic" / "New Group Topic")
const clearCurrentChatBtn = document.getElementById('clearCurrentChatBtn');
const openForumBtn = document.getElementById('openForumBtn');
const themeToggleBtn = document.getElementById('themeToggleBtn');
const toggleNotificationsBtn = document.getElementById('toggleNotificationsBtn');
const notificationsSidebar = document.getElementById('notificationsSidebar');
const vcpLogConnectionStatusDiv = document.getElementById('vcpLogConnectionStatus');
const notificationsListUl = document.getElementById('notificationsList');
const clearNotificationsBtn = document.getElementById('clearNotificationsBtn');
const doNotDisturbBtn = document.getElementById('doNotDisturbBtn');
const sidebarTabButtons = document.querySelectorAll('.sidebar-tab-button');
const sidebarTabContents = document.querySelectorAll('.sidebar-tab-content');
const tabContentTopics = document.getElementById('tabContentTopics');
const tabContentSettings = document.getElementById('tabContentSettings');
const topicSearchInput = document.getElementById('topicSearchInput'); // Should be in tabContentTopics
const DEFAULT_SEND_BUTTON_HTML = sendMessageBtn?.innerHTML || '';
const INTERRUPT_SEND_BUTTON_HTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
fill="none" stroke="none" aria-hidden="true">
<rect x="4" y="4" width="16" height="16" rx="3" fill="currentColor"></rect>
</svg>
`;
function isContextForCurrentChat(context) {
if (!context || !currentSelectedItem?.id || !currentTopicId) return false;
const contextItemId = context.groupId || context.agentId;
return contextItemId === currentSelectedItem.id && context.topicId === currentTopicId;
}
function getInterruptibleMessageForCurrentChat() {
if (Array.isArray(currentChatHistory) && currentChatHistory.length > 0) {
for (let i = currentChatHistory.length - 1; i >= 0; i--) {
const message = currentChatHistory[i];
if (!message || message.role !== 'assistant') continue;
const messageItem = chatMessagesDiv?.querySelector(`.message-item[data-message-id="${message.id}"]`);
const isStreaming = Boolean(messageItem?.classList.contains('streaming'));
if (message.isThinking === true || isStreaming) {
return { ...message, isStreaming };
}
}
}
const activeStreamingMessageId = window.streamManager?.getActiveStreamingMessageId?.();
const activeStreamingContext = window.streamManager?.getActiveStreamingContext?.();
if (!activeStreamingMessageId || !isContextForCurrentChat(activeStreamingContext)) {
return null;
}
const activeStreamingMessage = currentChatHistory.find(
(message) => message?.id === activeStreamingMessageId && message.role === 'assistant'
);
if (activeStreamingMessage) {
return { ...activeStreamingMessage, isStreaming: true };
}
return {
id: activeStreamingMessageId,
role: 'assistant',
name: activeStreamingContext.agentName || currentSelectedItem?.name || currentSelectedItem?.id,
agentId: activeStreamingContext.agentId,
groupId: activeStreamingContext.groupId,
isGroupMessage: activeStreamingContext.isGroupMessage === true,
avatarUrl: activeStreamingContext.avatarUrl || currentSelectedItem?.avatarUrl,
avatarColor: activeStreamingContext.avatarColor || currentSelectedItem?.config?.avatarCalculatedColor,
isStreaming: true
};
}
function updateSendButtonState() {
if (!sendMessageBtn) return;
const nextMode = getInterruptibleMessageForCurrentChat() ? 'interrupt' : 'send';
sendMessageBtn.dataset.mode = nextMode;
sendMessageBtn.classList.toggle('interrupt-mode', nextMode === 'interrupt');
sendMessageBtn.innerHTML = nextMode === 'interrupt' ? INTERRUPT_SEND_BUTTON_HTML : DEFAULT_SEND_BUTTON_HTML;
sendMessageBtn.title = nextMode === 'interrupt' ? '中止回复' : '发送消息 (Ctrl+Enter)';
}
async function interruptActiveResponseFromSendButton() {
const activeMessage = getInterruptibleMessageForCurrentChat();
if (!activeMessage) return false;
const isGroupMessage = activeMessage.isGroupMessage === true || currentSelectedItem?.type === 'group';
const messageContext = {
agentId: activeMessage.agentId || (isGroupMessage ? null : currentSelectedItem?.id),
groupId: activeMessage.groupId || (isGroupMessage ? currentSelectedItem?.id : null),
topicId: currentTopicId,
isGroupMessage,
agentName: activeMessage.name || currentSelectedItem?.name || currentSelectedItem?.id,
avatarUrl: activeMessage.avatarUrl || currentSelectedItem?.avatarUrl,
avatarColor: activeMessage.avatarColor || currentSelectedItem?.config?.avatarCalculatedColor
};
let result = { success: false, error: '无法发送中止请求。' };
if (isGroupMessage) {
if (chatAPI && typeof chatAPI.interruptGroupRequest === 'function') {
result = await chatAPI.interruptGroupRequest(activeMessage.id);
} else {
result = { success: false, error: '群聊中止接口不可用。' };
}
} else if (interruptHandler && typeof interruptHandler.interrupt === 'function') {
result = await interruptHandler.interrupt(activeMessage.id);
}
if (window.messageRenderer && typeof window.messageRenderer.finalizeStreamedMessage === 'function') {
await window.messageRenderer.finalizeStreamedMessage(
activeMessage.id,
'cancelled_by_user',
messageContext,
{ error: '用户已中止回复。' }
);
}
updateSendButtonState();
if (result.success) {
uiHelperFunctions?.showToastNotification?.('已发送中止信号。', 'success');
return true;
}
uiHelperFunctions?.showToastNotification?.(`中止失败:${result.error || '未知错误'}`, 'error');
return true;
}
async function handleSendButtonAction() {
if (getInterruptibleMessageForCurrentChat()) {
await interruptActiveResponseFromSendButton();
return;
}
if (window.chatManager && typeof window.chatManager.handleSendMessage === 'function') {
await window.chatManager.handleSendMessage();
}
}
window.updateSendButtonState = updateSendButtonState;
window.handleSendButtonAction = handleSendButtonAction;
updateSendButtonState();
const leftSidebar = document.querySelector('.sidebar');
const rightNotificationsSidebar = document.getElementById('notificationsSidebar');
const resizerLeft = document.getElementById('resizerLeft');
const resizerRight = document.getElementById('resizerRight');
const minimizeBtn = document.getElementById('minimize-btn');
const maximizeBtn = document.getElementById('maximize-btn');
const restoreBtn = document.getElementById('restore-btn');
const closeBtn = document.getElementById('close-btn');
const settingsBtn = document.getElementById('settings-btn'); // DevTools button
const minimizeToTrayBtn = document.getElementById('minimize-to-tray-btn');
const agentSearchInput = document.getElementById('agentSearchInput');
// Cropped file state is now managed within modules/ui-helpers.js
const notificationTitleElement = document.getElementById('notificationTitle');
const digitalClockElement = document.getElementById('digitalClock');
const dateDisplayElement = document.getElementById('dateDisplay');
let inviteAgentButtonsContainerElement; // 新增:邀请发言按钮容器的引用
// Assistant settings elements
const toggleAssistantBtn = document.getElementById('toggleAssistantBtn'); // New button
// 模态框内部元素延迟加载
let assistantAgentContainer = null;
let assistantAgentSelect = null;
// Model selection elements
const openModelSelectBtn = document.getElementById('openModelSelectBtn');
let modelSelectModal = null;
let modelList = null;
let modelSearchInput = null;
let refreshModelsBtn = null;
// UI Helper functions to be passed to modules
// The main uiHelperFunctions object is now defined in modules/ui-helpers.js
// We can reference it directly from the window object.
const uiHelperFunctions = window.uiHelperFunctions;
import searchManager from './modules/searchManager.js';
import { initialize as initializeEmoticonFixer } from './modules/renderer/emoticonUrlFixer.js';
import * as interruptHandler from './modules/interruptHandler.js';
import { setupEventListeners } from './modules/event-listeners.js';
// --- Initialization ---
document.addEventListener('DOMContentLoaded', async () => {
// Initialize Emoticon Manager
if (window.emoticonManager) {
window.emoticonManager.initialize({
emoticonPanel: document.getElementById('emoticonPanel'),
messageInput: document.getElementById('messageInput'),
});
} else {
console.error('[RENDERER_INIT] emoticonManager module not found!');
}
// Initialize App Tray Manager
if (window.trayManager) {
window.trayManager.init();
} else {
console.error('[RENDERER_INIT] trayManager module not found!');
}
// 确保在GroupRenderer初始化之前,其容器已准备好
uiHelperFunctions.prepareGroupSettingsDOM();
inviteAgentButtonsContainerElement = document.getElementById('inviteAgentButtonsContainer'); // 新增:获取容器引用
// Initialize ItemListManager first as other modules might depend on the item list
if (window.itemListManager) {
window.itemListManager.init({
elements: {
itemListUl: itemListUl,
},
electronAPI: chatAPI,
refs: {
currentSelectedItemRef: { get: () => currentSelectedItem },
},
mainRendererFunctions: {
selectItem: (itemId, itemType, itemName, itemAvatarUrl, itemFullConfig) => {
// Delayed binding - chatManager will be available when this is called
if (window.chatManager) {
return window.chatManager.selectItem(itemId, itemType, itemName, itemAvatarUrl, itemFullConfig);
} else {
console.error('[ItemListManager] chatManager not available for selectItem');
}
},
},
uiHelper: uiHelperFunctions // Pass the entire uiHelper object
});
} else {
console.error('[RENDERER_INIT] itemListManager module not found!');
}
if (window.GroupRenderer) {
const mainRendererElementsForGroupRenderer = {
topicListUl: document.getElementById('topicList'),
messageInput: messageInput,
sendMessageBtn: sendMessageBtn,
attachFileBtn: attachFileBtn,
currentChatNameH3: currentChatNameH3,
currentItemActionBtn: currentItemActionBtn,
clearCurrentChatBtn: clearCurrentChatBtn,
agentSettingsContainer: agentSettingsContainer,
groupSettingsContainer: document.getElementById('groupSettingsContainer'),
selectItemPromptForSettings: selectItemPromptForSettings, // 这个是我们关心的
selectedItemNameForSettingsSpan: selectedItemNameForSettingsSpan, // 新增:传递这个引用
itemListUl: itemListUl,
};
console.log('[Renderer PRE-INIT GroupRenderer] mainRendererElements to be passed:', mainRendererElementsForGroupRenderer);
console.log('[Renderer PRE-INIT GroupRenderer] selectItemPromptForSettings within that object:', mainRendererElementsForGroupRenderer.selectItemPromptForSettings);
window.GroupRenderer.init({
electronAPI: chatAPI,
globalSettingsRef: { get: () => globalSettings, set: (newSettings) => globalSettings = newSettings },
currentSelectedItemRef: {
get: () => currentSelectedItem,
set: (val) => {
currentSelectedItem = val;
window.currentSelectedItem = val;
}
},
currentTopicIdRef: {
get: () => currentTopicId,
set: (val) => {
currentTopicId = val;
window.currentTopicId = val;
}
},
messageRenderer: window.messageRenderer, // Will be initialized later, pass ref
uiHelper: uiHelperFunctions,
mainRendererElements: mainRendererElementsForGroupRenderer, // 使用构造好的对象
mainRendererFunctions: { // Pass shared functions with delayed binding
loadItems: () => window.itemListManager ? window.itemListManager.loadItems() : console.error('[GroupRenderer] itemListManager not available'),
selectItem: (itemId, itemType, itemName, itemAvatarUrl, itemFullConfig) => {
if (window.chatManager) {
return window.chatManager.selectItem(itemId, itemType, itemName, itemAvatarUrl, itemFullConfig);
} else {
console.error('[GroupRenderer] chatManager not available for selectItem');
}
},
highlightActiveItem: (itemId, itemType) => window.itemListManager ? window.itemListManager.highlightActiveItem(itemId, itemType) : console.error('[GroupRenderer] itemListManager not available'),
displaySettingsForItem: () => window.settingsManager ? window.settingsManager.displaySettingsForItem() : console.error('[GroupRenderer] settingsManager not available'),
loadTopicList: () => window.topicListManager ? window.topicListManager.loadTopicList() : console.error('[GroupRenderer] topicListManager not available'),
getAttachedFiles: () => attachedFiles,
clearAttachedFiles: () => { attachedFiles.length = 0; },
updateAttachmentPreview: () => uiHelperFunctions.updateAttachmentPreview(attachedFiles, attachmentPreviewArea),
setCroppedFile: uiHelperFunctions.setCroppedFile,
getCroppedFile: uiHelperFunctions.getCroppedFile,
setCurrentChatHistory: (history) => currentChatHistory = history,
displayTopicTimestampBubble: (itemId, itemType, topicId) => {
if (window.chatManager) {
return window.chatManager.displayTopicTimestampBubble(itemId, itemType, topicId);
} else {
console.error('[GroupRenderer] chatManager not available for displayTopicTimestampBubble');
}
},
switchToTab: (tab) => window.uiManager ? window.uiManager.switchToTab(tab) : console.error('[GroupRenderer] uiManager not available'),
// saveItemOrder is now in itemListManager
},
inviteAgentButtonsContainerRef: { get: () => inviteAgentButtonsContainerElement }, // 新增:传递引用
});
console.log('[Renderer POST-INIT GroupRenderer] window.GroupRenderer.init has been called.');
} else {
console.error('[RENDERER_INIT] GroupRenderer module not found!');
}
// Initialize other modules after GroupRenderer, in case they depend on its setup
if (window.messageRenderer) {
interruptHandler.initialize(chatAPI);
window.messageRenderer.initializeMessageRenderer({
currentChatHistoryRef: { get: () => currentChatHistory, set: (val) => currentChatHistory = val },
currentSelectedItemRef: {
get: () => currentSelectedItem,
set: (val) => {
currentSelectedItem = val;
window.currentSelectedItem = val;
}
},
currentTopicIdRef: {
get: () => currentTopicId,
set: (val) => {
currentTopicId = val;
window.currentTopicId = val;
}
},
globalSettingsRef: { get: () => globalSettings, set: (newSettings) => globalSettings = newSettings },
chatMessagesDiv: chatMessagesDiv,
electronAPI: chatAPI,
markedInstance: markedInstance, // Assuming marked.js is loaded
uiHelper: uiHelperFunctions,
interruptHandler: interruptHandler, // Pass the handler
summarizeTopicFromMessages: (messages, agentName) => {
// Directly use the function from the summarizer module, which should be on the window scope
if (typeof window.summarizeTopicFromMessages === 'function') {
return window.summarizeTopicFromMessages(messages, agentName);
} else {
console.error('[MessageRenderer] summarizeTopicFromMessages function not found on window scope.');
return `关于 "${messages.find(m=>m.role==='user')?.content.substring(0,15) || '...'}" (备用)`;
}
},
handleCreateBranch: (selectedMessage) => {
if (window.chatManager) {
return window.chatManager.handleCreateBranch(selectedMessage);
} else {
console.error('[MessageRenderer] chatManager not available for handleCreateBranch');
}
}
});
// Pass the new function to the context menu
window.messageRenderer.setContextMenuDependencies({
showForwardModal: showForwardModal,
});
} else {
console.error('[RENDERER_INIT] messageRenderer module not found!');
}
if (window.inputEnhancer) {
window.inputEnhancer.initializeInputEnhancer({
messageInput: messageInput,
dropTargetElement: chatInputCard,
electronAPI: chatAPI,
attachedFiles: { get: () => attachedFiles, set: (val) => attachedFiles = val },
updateAttachmentPreview: () => uiHelperFunctions.updateAttachmentPreview(attachedFiles, attachmentPreviewArea),
getCurrentAgentId: () => currentSelectedItem.id, // Corrected: pass a function that returns the ID
getCurrentTopicId: () => currentTopicId,
uiHelper: uiHelperFunctions,
});
} else {
console.error('[RENDERER_INIT] inputEnhancer module not found!');
}
chatAPI.onVCPLogStatus((statusUpdate) => {
if (window.notificationRenderer) {
window.notificationRenderer.updateVCPLogStatus(statusUpdate, vcpLogConnectionStatusDiv);
}
});
chatAPI.onVCPLogMessage((logData) => {
if (window.notificationRenderer) {
const computedStyle = getComputedStyle(document.body);
const themeColors = {
notificationBg: computedStyle.getPropertyValue('--notification-bg').trim(),
accentBg: computedStyle.getPropertyValue('--accent-bg').trim(),
highlightText: computedStyle.getPropertyValue('--highlight-text').trim(),
borderColor: computedStyle.getPropertyValue('--border-color').trim(),
primaryText: computedStyle.getPropertyValue('--primary-text').trim(),
secondaryText: computedStyle.getPropertyValue('--secondary-text').trim()
};
// 修复:只传递一个 logData 参数,第二个参数显式传递 null,以匹配 preload 定义
window.notificationRenderer.renderVCPLogNotification(logData, null, notificationsListUl, themeColors);
}
});
// Unified listener for all VCP stream events (agent and group)
chatAPI.onVCPStreamEvent(async (eventData) => {
if (!window.messageRenderer) {
console.error("onVCPStreamEvent: messageRenderer not available.");
return;
}
const { type, messageId, context, chunk, error, finish_reason, fullResponse } = eventData;
if (!messageId) {
console.error("onVCPStreamEvent: Received event without a messageId. Cannot process.", eventData);
return;
}
// --- Asynchronous Logic: Update data model regardless of UI state ---
// This is where you would update a global or context-specific data store
// For now, we pass the context to the messageRenderer which handles the history array.
// --- UI Logic: Only render if the message's context matches the current view ---
// Directly use the global variables `currentSelectedItem` and `currentTopicId` from the renderer's scope.
// The `...Ref` objects are not defined in this scope.
const isRelevantToCurrentView = context &&
currentSelectedItem && // Ensure currentSelectedItem is not null
(context.groupId ? context.groupId === currentSelectedItem.id : context.agentId === currentSelectedItem.id) &&
context.topicId === currentTopicId;
// console.log(`[onVCPStreamEvent] Received event type '${type}' for msg ${messageId}. Relevant to current view: ${isRelevantToCurrentView}`, context);
// Data model updates should ALWAYS happen, regardless of the current view.
// UI updates (creating new DOM elements) should only happen if the view is relevant.
switch (type) {
case 'data':
window.messageRenderer.appendStreamChunk(messageId, chunk, context);
break;
case 'end':
window.messageRenderer.finalizeStreamedMessage(
messageId,
finish_reason || 'completed',
context,
{ fullResponse, error }
);
if (context && !context.isGroupMessage) {
// This can run in the background
await window.chatManager.attemptTopicSummarizationIfNeeded();
}
// --- Flowlock: 检查是否需要自动触发续写 ---
if (window.flowlockManager) {
const flowlockState = window.flowlockManager.getState();
console.log('[Flowlock] End event received. State:', flowlockState, 'isRelevantToCurrentView:', isRelevantToCurrentView);
if (flowlockState.isActive && !flowlockState.isProcessing && isRelevantToCurrentView) {
console.log('[Flowlock] ✓ All conditions met, triggering continue writing...');
// 使用全局设置中的延迟
const delaySeconds = globalSettings.flowlockContinueDelay !== undefined ? globalSettings.flowlockContinueDelay : 5;
const delayMilliseconds = delaySeconds * 1000;
console.log(`[Flowlock] Using delay of ${delaySeconds}s (${delayMilliseconds}ms)`);
// 延迟指定时间确保消息完全渲染,然后直接调用续写函数
setTimeout(() => {
if (window.flowlockManager && window.flowlockManager.getState().isActive) {
console.log('[Flowlock] Calling handleContinueWriting now...');
// 触发心跳动画
const chatNameElement = document.getElementById('currentChatAgentName');
if (chatNameElement) {
chatNameElement.classList.add('flowlock-heartbeat');
// 动画结束后移除类
setTimeout(() => {
chatNameElement.classList.remove('flowlock-heartbeat');
}, 800);
}
// 获取输入框内容作为提示词
const messageInput = document.getElementById('messageInput');
const customPrompt = messageInput ? messageInput.value.trim() : '';
console.log('[Flowlock] Using custom prompt from input:', customPrompt || '(empty, will use default)');
// 直接调用续写函数,使用输入框内容或空字符串(将使用默认提示词)
if (window.handleContinueWriting) {
window.flowlockManager.isProcessing = true;
window.handleContinueWriting(customPrompt).then(() => {
console.log('[Flowlock] Continue writing completed');
window.flowlockManager.isProcessing = false;
window.flowlockManager.retryCount = 0; // 重置重试计数
}).catch((error) => {
console.error('[Flowlock] Continue writing failed:', error);
window.flowlockManager.isProcessing = false;
window.flowlockManager.retryCount++;
if (window.flowlockManager.retryCount >= window.flowlockManager.maxRetries) {
console.error('[Flowlock] Max retries reached, stopping flowlock');
if (window.uiHelperFunctions && window.uiHelperFunctions.showToastNotification) {
window.uiHelperFunctions.showToastNotification('心流锁续写失败次数过多,已自动停止', 'error');
}
window.flowlockManager.stop();
} else {
console.log(`[Flowlock] Retry ${window.flowlockManager.retryCount}/${window.flowlockManager.maxRetries}`);
if (window.uiHelperFunctions && window.uiHelperFunctions.showToastNotification) {
window.uiHelperFunctions.showToastNotification(`心流锁续写失败,正在重试 (${window.flowlockManager.retryCount}/${window.flowlockManager.maxRetries})`, 'warning');
}
}
});
} else {
console.error('[Flowlock] handleContinueWriting function not found!');
}
} else {
console.log('[Flowlock] Flowlock was stopped before timeout, skipping continue writing');
}
}, delayMilliseconds);
} else {
console.log('[Flowlock] Conditions not met:', {
isActive: flowlockState.isActive,
isProcessing: flowlockState.isProcessing,
isRelevantToCurrentView: isRelevantToCurrentView
});
}
}
break;
case 'error':
console.error('VCP Stream Error on ID', messageId, ':', error, 'Context:', context);
// --- Recovery Logic: Use accumulated text from main if fullResponse is missing ---
let finalContent = fullResponse || eventData.accumulatedResponse || "";
if (finalContent && finalContent.trim() !== "") {
// Add a visual indicator that the stream was cut short
finalContent += "\n\n> [!WARNING]\n> **流式响应中断**: " + (error || "未知连接错误") + "。已保存已接收的部分内容。";
}
window.messageRenderer.finalizeStreamedMessage(
messageId,
'error',
context,
{ fullResponse: finalContent, error }
);
// --- Flowlock: 处理错误情况,重置状态并可能触发下一次续写 ---
if (window.flowlockManager) {
const flowlockState = window.flowlockManager.getState();
console.log('[Flowlock] Error event received. State:', flowlockState, 'isRelevantToCurrentView:', isRelevantToCurrentView);
// 重置processing状态
if (window.flowlockManager.isProcessing) {
console.log('[Flowlock] Resetting isProcessing state due to error');
window.flowlockManager.isProcessing = false;
}
// 如果心流锁仍然激活且相关,触发下一次续写(即使出错也继续)
if (flowlockState.isActive && isRelevantToCurrentView) {
console.log('[Flowlock] Flowlock still active after error, will trigger next continue writing');
const errorDelaySeconds = globalSettings.flowlockContinueDelay !== undefined ? globalSettings.flowlockContinueDelay : 5;
const errorDelayMilliseconds = errorDelaySeconds * 1000;
console.log(`[Flowlock] Using error recovery delay of ${errorDelaySeconds}s (${errorDelayMilliseconds}ms)`);
setTimeout(() => {
if (window.flowlockManager && window.flowlockManager.getState().isActive) {
console.log('[Flowlock] Triggering continue writing after error...');
// 触发心跳动画
const chatNameElement = document.getElementById('currentChatAgentName');
if (chatNameElement) {
chatNameElement.classList.add('flowlock-heartbeat');
setTimeout(() => {
chatNameElement.classList.remove('flowlock-heartbeat');
}, 800);
}
// 获取输入框内容作为提示词
const messageInput = document.getElementById('messageInput');
const customPrompt = messageInput ? messageInput.value.trim() : '';
console.log('[Flowlock] Using custom prompt from input:', customPrompt || '(empty, will use default)');
// 触发续写
if (window.handleContinueWriting) {
window.flowlockManager.isProcessing = true;
window.handleContinueWriting(customPrompt).then(() => {
console.log('[Flowlock] Continue writing completed after error recovery');
window.flowlockManager.isProcessing = false;
window.flowlockManager.retryCount = 0;
}).catch((error) => {
console.error('[Flowlock] Continue writing failed after error recovery:', error);
window.flowlockManager.isProcessing = false;
window.flowlockManager.retryCount++;
if (window.flowlockManager.retryCount >= window.flowlockManager.maxRetries) {
console.error('[Flowlock] Max retries reached, stopping flowlock');
if (window.uiHelperFunctions && window.uiHelperFunctions.showToastNotification) {
window.uiHelperFunctions.showToastNotification('心流锁续写失败次数过多,已自动停止', 'error');
}
window.flowlockManager.stop();
}
});
}
}
}, errorDelayMilliseconds);
}
}
if (isRelevantToCurrentView) {
const errorMsgItem = document.querySelector(`.message-item[data-message-id="${messageId}"] .md-content`);
if (errorMsgItem) {
errorMsgItem.innerHTML += `<p><strong style="color: red;">流错误: ${error}</strong></p>`;
} else {
window.messageRenderer.renderMessage({
role: 'system',
content: `流处理错误 (ID: ${messageId}): ${error}`,
timestamp: Date.now(),
id: `err_${messageId}`
});
}
}
break;
// These events create new message bubbles, so they should only execute if the view is relevant.
case 'agent_thinking':
// Use startStreamingMessage for both visible and non-visible chats to ensure proper initialization
console.log(`[Renderer onVCPStreamEvent AGENT_THINKING] Initializing streaming for ${context.agentName} (msgId: ${messageId})`);
// 直接调用 streamManager 的 startStreamingMessage,它会处理所有初始化
if (window.streamManager && typeof window.streamManager.startStreamingMessage === 'function') {
window.streamManager.startStreamingMessage({
id: messageId,
role: 'assistant',
name: context.agentName,
agentId: context.agentId,
avatarUrl: context.avatarUrl,
avatarColor: context.avatarColor,
content: '思考中...',
timestamp: Date.now(),
isThinking: true,
isGroupMessage: context.isGroupMessage || false,
groupId: context.groupId,
topicId: context.topicId,
context: context // Pass the full context
});
} else if (window.messageRenderer && typeof window.messageRenderer.startStreamingMessage === 'function') {
// Fallback to messageRenderer if streamManager not available
window.messageRenderer.startStreamingMessage({
id: messageId,
role: 'assistant',
name: context.agentName,
agentId: context.agentId,
avatarUrl: context.avatarUrl,
avatarColor: context.avatarColor,
content: '思考中...',
timestamp: Date.now(),
isThinking: true,
isGroupMessage: context.isGroupMessage || false,
groupId: context.groupId,
topicId: context.topicId,
context: context
});
}
break;
case 'start':
// START事件时,思考消息应该已经存在了
// 我们只需要确保消息已经初始化,如果没有则初始化
console.log(`[Renderer onVCPStreamEvent START] Processing start event for ${context.agentName} (msgId: ${messageId})`);
// 确保消息被初始化(如果agent_thinking被跳过)
if (window.streamManager && typeof window.streamManager.startStreamingMessage === 'function') {
// streamManager 会检查消息是否已存在,避免重复初始化
window.streamManager.startStreamingMessage({
id: messageId,
role: 'assistant',
name: context.agentName,
agentId: context.agentId,
avatarUrl: context.avatarUrl,
avatarColor: context.avatarColor,
content: '',
timestamp: Date.now(),
isThinking: false,
isGroupMessage: context.isGroupMessage || false,
groupId: context.groupId,
topicId: context.topicId,
context: context
});
} else if (window.messageRenderer && typeof window.messageRenderer.startStreamingMessage === 'function') {
window.messageRenderer.startStreamingMessage({
id: messageId,
role: 'assistant',
name: context.agentName,
agentId: context.agentId,
avatarUrl: context.avatarUrl,
avatarColor: context.avatarColor,
content: '',
timestamp: Date.now(),
isThinking: false,
isGroupMessage: context.isGroupMessage || false,
groupId: context.groupId,
topicId: context.topicId,
context: context
});
}
if (isRelevantToCurrentView) {
console.log(`[Renderer onVCPStreamEvent START] UI updated for visible chat ${context.agentName} (msgId: ${messageId})`);
} else {
console.log(`[Renderer onVCPStreamEvent START] History updated for non-visible chat ${context.agentName} (msgId: ${messageId})`);
}
break;
case 'full_response':
// This also needs to update history unconditionally and render only if relevant.
// `renderFullMessage` should handle this logic.
if (isRelevantToCurrentView) {
console.log(`[Renderer onVCPStreamEvent FULL_RESPONSE] Rendering for ${context.agentName} (msgId: ${messageId})`);
window.messageRenderer.renderFullMessage(messageId, fullResponse, context.agentName, context.agentId);
} else {
// If not relevant, we need a way to update the history without rendering.
// Let's assume `renderFullMessage` needs a flag or we need a new function.
// For now, let's add a placeholder to history.
console.log(`[Renderer onVCPStreamEvent FULL_RESPONSE] History update for non-visible chat needed for msgId: ${messageId}`);
// This part is tricky. The message might not exist in history yet.
// Let's ensure `renderFullMessage` can handle this.
window.messageRenderer.renderFullMessage(messageId, fullResponse, context.agentName, context.agentId);
}
break;
case 'no_ai_response':
console.log(`[onVCPStreamEvent] No AI response needed for messageId: ${messageId}. Message: ${eventData.message}`);
break;
case 'remove_message':
if (isRelevantToCurrentView) {
console.log(`[onVCPStreamEvent] Removing message ${messageId} from UI.`);
window.messageRenderer.removeMessageById(messageId, false); // false: don't save history again
}
break;
default:
console.warn(`[onVCPStreamEvent] Received unhandled event type: '${type}'`, eventData);
}
});
// Listener for group topic title updates
chatAPI.onVCPGroupTopicUpdated(async (eventData) => {
const { groupId, topicId, newTitle, topics } = eventData;
console.log(`[Renderer] Received topic update for group ${groupId}, topic ${topicId}: "${newTitle}"`);
if (currentSelectedItem.id === groupId && currentSelectedItem.type === 'group') {
// Update the currentSelectedItem's config if it's the active group
const config = currentSelectedItem.config || currentSelectedItem;
if (config && config.topics) {
const topicIndex = config.topics.findIndex(t => t.id === topicId);
if (topicIndex !== -1) {
config.topics[topicIndex].name = newTitle;
} else { // Topic might be new or ID changed, replace topics array
config.topics = topics;
}
} else if (config) {
config.topics = topics;
}
// If the topics tab is active, reload the list
if (document.getElementById('tabContentTopics').classList.contains('active')) {
await window.topicListManager.loadTopicList();
}
// Removed toast notification as per user feedback
// if (uiHelperFunctions && uiHelperFunctions.showToastNotification) {
// uiHelperFunctions.showToastNotification(`群组 "${currentSelectedItem.name}" 的话题 "${newTitle}" 已自动总结并更新。`);
// }
console.log(`群组 "${currentSelectedItem.name}" 的话题 "${newTitle}" 已自动总结并更新 (通知已移除).`);
}
});
// Initialize TopicListManager
if (window.topicListManager) {
window.topicListManager.init({
elements: {
topicListContainer: tabContentTopics,
},
electronAPI: chatAPI,
refs: {
currentSelectedItemRef: {
get: () => currentSelectedItem
},
currentTopicIdRef: {
get: () => currentTopicId
},
},
uiHelper: uiHelperFunctions,
mainRendererFunctions: {
updateCurrentItemConfig: (newConfig) => {
if (currentSelectedItem.config) {
currentSelectedItem.config = newConfig;
} else {
Object.assign(currentSelectedItem, newConfig);
}
},
handleTopicDeletion: (remainingTopics) => {
if (window.chatManager) {
return window.chatManager.handleTopicDeletion(remainingTopics);
} else {
console.error('[TopicListManager] chatManager not available for handleTopicDeletion');
}
},
selectTopic: (topicId) => {
if (window.chatManager) {
return window.chatManager.selectTopic(topicId);
} else {
console.error('[TopicListManager] chatManager not available for selectTopic');
}
},
}
});
} else {
console.error('[RENDERER_INIT] topicListManager module not found!');
}
// Initialize ChatManager
if (window.chatManager) {
window.chatManager.init({
electronAPI: chatAPI,
uiHelper: uiHelperFunctions,
modules: {
messageRenderer: window.messageRenderer,
itemListManager: window.itemListManager,
topicListManager: window.topicListManager,
groupRenderer: window.GroupRenderer,
},
refs: {
currentSelectedItemRef: {
get: () => currentSelectedItem,
set: (val) => {
currentSelectedItem = val;
window.currentSelectedItem = val;
}
},
currentTopicIdRef: {
get: () => currentTopicId,
set: (val) => {
currentTopicId = val;
window.currentTopicId = val;
}
},
currentChatHistoryRef: { get: () => currentChatHistory, set: (val) => currentChatHistory = val },
attachedFilesRef: { get: () => attachedFiles, set: (val) => attachedFiles = val },
globalSettingsRef: { get: () => globalSettings },
},
elements: {
chatMessagesDiv: chatMessagesDiv,
currentChatNameH3: currentChatNameH3,
currentItemActionBtn: currentItemActionBtn,
clearCurrentChatBtn: clearCurrentChatBtn,
messageInput: messageInput,
sendMessageBtn: sendMessageBtn,
attachFileBtn: attachFileBtn,
},
mainRendererFunctions: {
displaySettingsForItem: () => window.settingsManager.displaySettingsForItem(),
updateAttachmentPreview: () => uiHelperFunctions.updateAttachmentPreview(attachedFiles, attachmentPreviewArea),
// This is no longer needed as chatManager will call messageRenderer's summarizer
}
});
} else {
console.error('[RENDERER_INIT] chatManager module not found!');
}
// Initialize Settings Manager
if (window.settingsManager) {
window.settingsManager.init({
electronAPI: chatAPI,
uiHelper: uiHelperFunctions,
refs: {
currentSelectedItemRef: {
get: () => currentSelectedItem,
set: (val) => {
currentSelectedItem = val;
window.currentSelectedItem = val;
}
},
currentTopicIdRef: {
get: () => currentTopicId,
set: (val) => {
currentTopicId = val;
window.currentTopicId = val;
}
},