AgentPanelBodyAgent.vue
44.1 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
<template>
<div class="agent-panel-body">
<!-- 消息列表 -->
<div class="messages-container" ref="messagesContainerRef">
<div class="messages-list">
<div
v-for="(message, index) in messages"
:key="message.id || index"
class="chat-item"
>
<!-- 用户问题 -->
<div v-if="message.role === 'user'" class="user-question">
<div
v-if="message.attachedFiles && message.attachedFiles.length > 0"
class="user-attached-files"
>
<CodexUserAttachedFileCard
v-for="(af, ai) in message.attachedFiles"
:key="`${af.id}-${ai}`"
:id="af.id"
:name="af.name || `file-${af.id}`"
:file-path="af.filePath"
:type="af.type"
/>
</div>
<div class="message-body-question">{{ message.content }}</div>
<div class="message-actions-user">
<button
class="action-btn"
:title="t('chat.copy')"
@click="handleCopy(message.content)"
>
<img src="/fuzhi.svg" alt="复制" class="icon-svg" />
</button>
</div>
</div>
<!-- AI回答 -->
<div v-else-if="message.role === 'assistant'" class="ai-answer">
<!-- AI思考状态 -->
<div v-if="message.status === 'pending'" class="ai-thinking">
<div class="thinking-dots">
<span></span>
<span></span>
<span></span>
</div>
<span class="thinking-text">{{
t("agent.thinking") || "AI正在思考中..."
}}</span>
</div>
<!-- 打字机效果显示回答内容 -->
<div
v-else-if="message.status === 'streaming' && message.isStreaming"
class="message-body-answer typewriter"
>
<!-- 使用增强版 MarkdownPreview 渲染(支持完整 Markdown + KaTeX) -->
<MarkdownPreview
:content="getTypingDisplayContent(message)"
:is-streaming="true"
model="external"
/>
</div>
<!-- 错误状态 -->
<div
v-else-if="message.status === 'error'"
class="message-body-answer error-message"
>
<el-icon><WarningFilled /></el-icon>
<span>{{ message.error || message.content }}</span>
<el-icon
class="retry-icon"
@click="handleRetry(message)"
:title="t('chat.retrySend')"
>
<RefreshRight />
</el-icon>
</div>
<!-- 待审批状态 -->
<div
v-else-if="message.pendingApproval"
class="message-body-answer approval-pending"
>
<div class="approval-content">
<div class="approval-header">
<el-icon><Warning /></el-icon>
<span>需要审批</span>
</div>
<div class="approval-body">
<div v-if="message.pendingApproval.type === 'command'">
<p><strong>命令:</strong> {{ message.pendingApproval.command }}</p>
<p v-if="message.pendingApproval.description">{{ message.pendingApproval.description }}</p>
</div>
<div v-else-if="message.pendingApproval.type === 'patch'">
<p><strong>文件:</strong> {{ message.pendingApproval.filePath }}</p>
<p v-if="message.pendingApproval.changes">
<strong>变更:</strong>
<pre>{{ message.pendingApproval.changes }}</pre>
</p>
</div>
</div>
<div class="approval-actions">
<el-button
size="small"
type="success"
@click="handleApprove(message, 'approved')"
>
批准
</el-button>
<el-button
size="small"
type="danger"
@click="handleApprove(message, 'denied')"
>
拒绝
</el-button>
</div>
</div>
</div>
<!-- 正常显示回答内容 -->
<div v-else class="message-body-answer">
<!-- 使用增强版 MarkdownPreview 渲染(支持完整 Markdown + KaTeX) -->
<MarkdownPreview
:content="message.content"
:is-streaming="false"
model="external"
/>
<div
class="message-actions-answer"
v-if="
message.content &&
!['pending', 'streaming', 'error'].includes(message.status || '')
"
>
<button
class="action-btn"
:class="{ disabled: !isMessageCompleted(message) }"
:title="t('chat.generateDocument')"
@click="handleSaveAndEdit(message)"
>
<img src="/bianji.svg" alt="生成文档并编辑" class="icon-svg" />
</button>
<button
class="action-btn"
:title="t('chat.copy')"
@click="handleCopyMessage(message)"
>
<img src="/fuzhi.svg" alt="复制" class="icon-svg" />
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 流式状态提示 -->
<div v-if="streamingError" class="websocket-error">
<el-icon><CircleCloseFilled /></el-icon>
<span>{{ t("agent.connectionError", { error: streamingError }) }}</span>
</div>
<div v-else-if="streamingAnswer" class="websocket-success">
<el-icon><SuccessFilled /></el-icon>
<span>{{ t("agent.streamingConnected") }}</span>
</div>
<!-- 聊天输入框 -->
<div class="chat-container">
<AgentChat
ref="agentChatRef"
:loading="sendingMessage"
@send="handleSend"
@stop="handleStop"
@file-upload="handleFileUpload"
@knowledge-reference="handleKnowledgeReference"
@select-model="handleSelectModel"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import {
WarningFilled,
RefreshRight,
CircleCloseFilled,
SuccessFilled,
Warning,
Document,
} from "@element-plus/icons-vue";
import AgentChat from "./AgentChatAgent.vue";
import CodexUserAttachedFileCard from "./CodexUserAttachedFileCard.vue";
import MarkdownPreview from "@/components/Workspace/MarkdownPreview.vue";
import {
apiCreateDraftFromDeepSearch,
apiSaveDraftToKnowledge,
} from "@/api/drafts";
import {
getFiles,
createFolder,
getFileContent,
} from "@/api/files";
import { useCodexStore } from "@/stores/codex";
import { useAppStore } from "@/stores/app";
import { useRouter } from "vue-router";
import { ElLoading } from "element-plus";
import type { AttachedFilePayload } from "./agentAttachedPayload";
import {
parseRefFileIdsList,
resolveFileEntryId,
buildAttachedFilesPayload,
ensureAttachedPayloadCoversTurnFileIds,
} from "./agentAttachedPayload";
// import "https://cdn.jsdelivr.net/npm/katex@0.16.25/dist/katex.min.js";
const { t } = useI18n();
const codexStore = useCodexStore();
const router = useRouter();
// 引用
const messagesContainerRef = ref<HTMLElement | null>(null);
const agentChatRef = ref<InstanceType<typeof AgentChat> | null>(null);
// 响应式数据
const shouldAutoScroll = ref(true);
const userScrolled = ref(false);
const isTypingActive = ref(false); // 标记当前是否有打字机效果在进行
// 打字机效果:为每个 typing 状态的 answer 维护显示内容
const typingDisplayContent = ref<Map<string, string>>(new Map());
// 打字机效果:追踪打字机动画帧
const typingAnimationFrames = ref<Map<string, number>>(new Map());
// 计算属性
const messages = computed(() => codexStore.messages);
const currentSession = computed(() => codexStore.currentSession);
const sendingMessage = computed(() =>
codexStore.aiThinking ||
codexStore.aiTyping ||
false
);
const streamingAnswer = computed(() => codexStore.streaming || codexStore.aiTyping || false);
const streamingError = computed(() => codexStore.streamingError);
// 获取打字机显示内容
const getTypingDisplayContent = (message: any): string => {
const messageId = message.id;
if (!messageId) return message.content || "";
// 如果还没有初始化打字机内容,返回空字符串并启动打字机效果
if (!typingDisplayContent.value.has(messageId)) {
typingDisplayContent.value.set(messageId, "");
startTypingEffect(messageId, message.content || "");
return "";
}
return typingDisplayContent.value.get(messageId) || "";
};
// 监听消息变化
watch(
messages,
(newMessages, oldMessages) => {
console.log("消息列表变化:", newMessages.length, "条消息");
if (newMessages.length > (oldMessages ? oldMessages.length : 0)) {
nextTick(() => {
scrollToBottom();
});
}
// 检查是否有打字机效果正在进行
let hasTyping = false;
newMessages.forEach((message: any) => {
const messageId = message.id;
if (message.status === "streaming" && message.isStreaming && message.content) {
hasTyping = true;
// 更新打字机目标内容
if (messageId) {
updateTypingTarget(messageId, message.content);
}
} else if (message.status === "completed") {
// 完成时,清理打字机状态并强制滚动到底部
if (messageId) {
stopTypingEffect(messageId);
}
// 使用 setTimeout 确保 DOM 更新完成后再滚动
setTimeout(() => {
forceScrollToBottom();
}, 50);
}
});
// 更新打字机活跃状态
isTypingActive.value = hasTyping;
// 历史回放:loadTurns 会一次性灌入 messages,且每条 user message 可能带 attachedFiles
// 这里仅在“从空到有”的首次加载时恢复绿条(上一轮附件)
if (
agentChatRef.value &&
(!oldMessages || oldMessages.length === 0) &&
newMessages.length > 0
) {
const lastUserWithFiles = [...newMessages]
.reverse()
.find(
(m: any) =>
m?.role === "user" &&
Array.isArray(m?.attachedFiles) &&
m.attachedFiles.length > 0,
);
if (lastUserWithFiles) {
(agentChatRef.value as any).setLastRoundAttachments?.(
lastUserWithFiles.attachedFiles,
);
}
}
},
{ deep: true },
);
// 方法
const handleSend = async (msg: any) => {
// 不再在这里拦截,sendMessage 会处理会话创建
// if (!currentSession.value) {
// console.warn("没有当前会话");
// return;
// }
try {
const content = typeof msg === "string" ? msg : msg.question;
const knowledgeReferences = msg.knowledgeReferences || [];
const localFiles = msg.files || [];
// 处理知识库引用 - 收集当前引用的文件 ID
let newContextFileIds: number[] = [];
const uploadedMeta: { id: number; name: string }[] = [];
// 1. 如果有本地拖拽的文件,先上传到根目录
if (localFiles.length > 0) {
try {
const { uploadBatchFiles } = await import("@/api/files");
const uploadResult = await uploadBatchFiles(localFiles, -1);
if (uploadResult) {
const apiData = uploadResult.data;
const uploadedItems = Array.isArray(apiData)
? apiData
: apiData?.files || apiData?.items || [];
uploadedItems.forEach((file: any) => {
const fileId = file.id || file.fileId;
const nm =
file.name ||
file.fileName ||
file.itemName ||
(fileId ? `file-${fileId}` : "");
if (fileId) {
const nid = Number(fileId);
newContextFileIds.push(nid);
uploadedMeta.push({ id: nid, name: nm || `file-${nid}` });
}
});
ElMessage.success(t("KnowledgeBase.uploadToRootJoinChatSuccess") || "文件已保存至知识库根目录并加入对话");
}
} catch (uploadError) {
console.error("Agent 模式拖拽文件上传失败:", uploadError);
ElMessage.error(t("KnowledgeBase.uploadFailed") || "文件上传失败,请稍后重试");
}
}
// 2. 处理已有的知识库引用(与 buildAttachedFilesPayload 使用相同的 id 解析)
if (knowledgeReferences.length > 0) {
knowledgeReferences.forEach((ref: any) => {
if (ref.type === "files" && ref.files && ref.files.length > 0) {
const refIdList = parseRefFileIdsList(ref);
ref.files.forEach((file: any, idx: number) => {
const id = resolveFileEntryId(file, idx, refIdList);
if (id !== undefined) {
newContextFileIds.push(id);
}
});
}
});
}
const turnFileIds = [...new Set(newContextFileIds)];
let attachedPayload = buildAttachedFilesPayload(
knowledgeReferences,
uploadedMeta,
);
attachedPayload = ensureAttachedPayloadCoversTurnFileIds(
attachedPayload,
turnFileIds,
knowledgeReferences,
uploadedMeta,
);
// 发送文本消息
if (content.trim()) {
resetAutoScrollState();
nextTick(scrollToBottom);
console.log("[AgentPanelBodyAgent] send turn", {
turnFileIds,
attachedPayload,
knowledgeRefsCount: knowledgeReferences.length,
});
const result = await codexStore.sendMessage(
content.trim(),
currentSession.value ? currentSession.value.sessionId : undefined,
turnFileIds,
attachedPayload.length > 0 ? attachedPayload : undefined,
);
if (!result.success) {
console.error("发送消息失败:", result.error);
ElMessage.error(result.error || "发送消息失败");
} else if (agentChatRef.value) {
// 发送成功后:编辑态引用仅用于发送前展示,清空后改用绿条提示“上一轮附件”
(agentChatRef.value as any).clearEditingAttachments?.();
// 仅当本轮有附件时才覆盖绿条;纯文字发送不清空上一轮绿条
if (attachedPayload.length > 0) {
(agentChatRef.value as any).setLastRoundAttachments(attachedPayload);
}
}
}
} catch (error) {
console.error("发送消息失败:", error);
ElMessage.error("发送消息失败");
}
};
watch(
() => currentSession.value?.sessionId,
(sid, prev) => {
if (!agentChatRef.value) return;
if (sid && prev && sid === prev) return;
// 切换/新建会话时清空:避免上一会话绿条串到下一会话
(agentChatRef.value as any).clearEditingAttachments?.();
(agentChatRef.value as any).clearLastRoundAttachments?.();
},
);
const handleStop = () => {
codexStore.stopStreaming();
ElMessage.info(t("chat.stopStreaming") || "已中止当前生成");
};
const handleFileUpload = async (file: File) => {
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
if (file.size > MAX_FILE_SIZE) {
ElMessage.error(`${file.name}: ${t("KnowledgeBase.fileSizeExceeded") || "文件大小不能超过 100MB"}`);
return;
}
const loading = ElLoading.service({
lock: true,
text: t("KnowledgeBase.uploading") || "正在上传...",
background: "rgba(0, 0, 0, 0.1)",
});
try {
const { uploadBatchFiles, listenBatchProgress } = await import("@/api/files");
// 这里的 -1 表示强制保存到知识库根目录
const uploadResult = await uploadBatchFiles([file], -1);
if (uploadResult && uploadResult.data) {
// 兼容 Axios 响应结构和后端返回的业务数据结构
const responsePayload = uploadResult.data;
const apiData = responsePayload.data || responsePayload;
const uploadedItems = Array.isArray(apiData)
? apiData
: apiData?.files || apiData?.items || [];
const uploadId = uploadResult.uploadId || (uploadResult as any).data?.uploadId;
if (uploadedItems.length > 0) {
const uploadedFile = { ...uploadedItems[0] };
// 兼容不同的字段名
const fileId = uploadedFile.id || uploadedFile.fileId || uploadedFile.itemId;
const fileName = uploadedFile.name || uploadedFile.fileName || uploadedFile.itemName;
// 确保 uploadedFile 对象上有必要的属性
if (!uploadedFile.name && fileName) uploadedFile.name = fileName;
if (!uploadedFile.id && fileId) uploadedFile.id = fileId;
// 初始状态设为解析中
uploadedFile.knowledgeStatus = "processing";
// 成功通知:已保存至知识库根目录
ElMessage.success(t("KnowledgeBase.uploadToRootJoinChatSuccess") || "文件已保存至知识库根目录并加入对话");
// 将上传成功的素材加入到当前对话引用中(初始为解析中状态)
if (agentChatRef.value) {
agentChatRef.value.addFileReferences(
[uploadedFile],
[String(fileId)],
"drag"
);
}
// 如果有 uploadId,开始监听解析进度
if (uploadId) {
console.log("开始监听文件解析进度:", uploadId);
listenBatchProgress(
uploadId,
(progress) => {
// 进度回调:实时更新每个文件的状态
if (progress.fileProgresses && agentChatRef.value) {
const refs = (agentChatRef.value as any).knowledgeReferences;
if (refs) {
Object.entries(progress.fileProgresses).forEach(([uid, fProgress]: [string, any]) => {
const isDone = fProgress.status === 'COMPLETED' || fProgress.percentage >= 100;
refs.forEach((ref: any) => {
if (ref.type === 'files' && ref.files) {
ref.files.forEach((f: any) => {
if (String(f.id) === String(uid) || f.name === uid) {
f.knowledgeStatus = isDone ? 'completed' : 'processing';
}
});
}
});
});
}
}
},
() => {
// 完成回调:确保所有相关文件状态设为完成,并刷新全局列表
console.log("文件解析完成:", fileId);
if (agentChatRef.value) {
const refs = (agentChatRef.value as any).knowledgeReferences;
if (refs) {
refs.forEach((ref: any) => {
if (ref.type === 'files' && ref.files) {
ref.files.forEach((f: any) => {
if (String(f.id) === String(fileId)) {
f.knowledgeStatus = 'completed';
}
});
}
});
}
}
// 刷新全局文件列表/树
appStore.triggerRefreshFileHierarchy(-1);
},
(error) => {
console.error("解析监听出错:", error);
}
);
}
} else {
console.warn("上传成功但未返回文件列表:", responsePayload);
// 如果后端只返回了成功码但没返回具体列表,尝试降级提示
if (responsePayload.code === 200 || responsePayload.status === 'success') {
ElMessage.success(t("KnowledgeBase.uploadToRootSuccess") || "文件已保存至知识库根目录");
}
}
}
} catch (error) {
console.error("Agent 模式对话框上传文件失败:", error);
ElMessage.error(t("KnowledgeBase.uploadFailed") || "文件上传失败,请重试");
} finally {
loading.close();
}
};
const handleKnowledgeReference = (doc: any) => {
console.log("知识库引用:", doc);
};
const handleSelectModel = (model: any) => {
console.log("选择模型:", model);
};
const handleRetry = async (message: any) => {
if (!currentSession.value) {
console.warn("无法重试:缺少会话");
return;
}
// 找到对应的用户消息
const messageIndex = messages.value.findIndex((m: any) => m.id === message.id);
if (messageIndex <= 0) {
ElMessage.warning("无法找到原始问题");
return;
}
const userMessage = messages.value[messageIndex - 1];
if (!userMessage || userMessage.role !== "user") {
ElMessage.warning("无法找到原始问题");
return;
}
try {
console.log("重试发送消息:", userMessage.content);
// 更新消息状态为等待中
message.status = "pending";
message.error = null;
resetAutoScrollState();
nextTick(scrollToBottom);
const attached = (userMessage as any).attachedFiles as
| Array<{ id: number }>
| undefined;
const retryFileIds =
Array.isArray(attached) && attached.length > 0
? attached.map((f) => Number(f.id)).filter((n) => !Number.isNaN(n))
: null;
const retryAttached = (userMessage as any).attachedFiles as
| AttachedFilePayload[]
| undefined;
const result = await codexStore.sendMessage(
userMessage.content,
currentSession.value.sessionId,
retryFileIds,
retryAttached && retryAttached.length > 0 ? retryAttached : undefined,
);
if (!result.success) {
console.error("重试发送失败:", result.error);
message.status = "error";
message.error = result.error || "发送失败,请重试";
}
} catch (error: any) {
console.error("重试发送过程中出错:", error);
message.status = "error";
message.error = error.message || "发送失败,请重试";
}
};
const scrollToBottom = () => {
if (!shouldAutoScroll.value) {
console.log("用户手动滚动过,跳过自动滚动到底部");
return;
}
nextTick(() => {
const container = messagesContainerRef.value;
if (container) {
container.scrollTop = container.scrollHeight;
}
});
};
// 强制滚动到底部(用于打字机效果结束时)
const forceScrollToBottom = () => {
const container = messagesContainerRef.value;
if (container) {
// 使用 requestAnimationFrame 确保在 DOM 更新后执行
requestAnimationFrame(() => {
if (container) {
container.scrollTop = container.scrollHeight;
// 滚动后恢复自动滚动状态
shouldAutoScroll.value = true;
userScrolled.value = false;
console.log("打字机效果结束,强制滚动到底部并恢复自动滚动");
}
});
}
};
// 打字机目标内容映射
const typingTargetContent = ref<Map<string, string>>(new Map());
// 打字机配置
const TYPING_CONFIG = {
charsPerFrame: 3, // 每帧显示的字符数(值越大速度越快)
minCharsPerFrame: 2, // 最小每帧字符数
maxCharsPerFrame: 10, // 最大每帧字符数
};
// 启动打字机效果
const startTypingEffect = (answerId: string, targetContent: string) => {
// 如果已经有动画在运行,不重复启动
if (typingAnimationFrames.value.has(answerId)) {
return;
}
// 设置目标内容
typingTargetContent.value.set(answerId, targetContent);
const charsPerFrame = TYPING_CONFIG.charsPerFrame;
const typeNextChars = () => {
const currentContent = typingDisplayContent.value.get(answerId) || "";
const targetContent = typingTargetContent.value.get(answerId) || "";
// 如果目标内容大于当前显示内容,继续打字
if (targetContent.length > currentContent.length) {
// 计算下一次应该显示到的位置
const nextIndex = Math.min(
currentContent.length + charsPerFrame,
targetContent.length,
);
// 更新显示内容
const nextContent = targetContent.substring(0, nextIndex);
typingDisplayContent.value.set(answerId, nextContent);
// 打字机效果时,只在允许自动滚动的情况下滚动
if (shouldAutoScroll.value) {
nextTick(() => {
const container = messagesContainerRef.value;
if (container) {
container.scrollTop = container.scrollHeight;
}
});
}
// 继续动画
const frameId = requestAnimationFrame(typeNextChars);
typingAnimationFrames.value.set(answerId, frameId);
} else {
// 当前已经追上目标,暂停动画但不清理(等待新数据)
typingAnimationFrames.value.delete(answerId);
// 追上目标后,如果允许自动滚动,确保滚动到底部
if (shouldAutoScroll.value) {
nextTick(() => {
const container = messagesContainerRef.value;
if (container) {
container.scrollTop = container.scrollHeight;
}
});
}
}
};
// 启动动画
const frameId = requestAnimationFrame(typeNextChars);
typingAnimationFrames.value.set(answerId, frameId);
};
// 更新打字机目标内容
const updateTypingTarget = (answerId: string, newTargetContent: string) => {
const oldTarget = typingTargetContent.value.get(answerId) || "";
// 如果内容有更新
if (newTargetContent !== oldTarget) {
typingTargetContent.value.set(answerId, newTargetContent);
// 如果当前没有动画在运行,重新启动
if (!typingAnimationFrames.value.has(answerId)) {
startTypingEffect(answerId, newTargetContent);
}
}
};
// 停止打字机效果
const stopTypingEffect = (answerId: string) => {
// 取消动画帧
const frameId = typingAnimationFrames.value.get(answerId);
if (frameId) {
cancelAnimationFrame(frameId);
typingAnimationFrames.value.delete(answerId);
}
// 清理状态
typingDisplayContent.value.delete(answerId);
typingTargetContent.value.delete(answerId);
};
// 节流变量
let scrollCheckTimeout: number | null = null;
const handleScroll = (event: Event) => {
const container = event.target as HTMLElement;
if (!container) return;
// 使用节流,避免频繁触发
if (scrollCheckTimeout) {
clearTimeout(scrollCheckTimeout);
}
scrollCheckTimeout = window.setTimeout(() => {
const scrollTop = container.scrollTop;
const scrollHeight = container.scrollHeight;
const clientHeight = container.clientHeight;
const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
// 判断是否在底部(容差 50px)
const isAtBottom = distanceFromBottom <= 50;
if (isAtBottom) {
// 用户滚动到底部,恢复自动滚动
if (!shouldAutoScroll.value) {
console.log("用户滚动到底部,恢复自动滚动");
shouldAutoScroll.value = true;
userScrolled.value = false;
}
} else {
// 用户手动滚动离开底部,停止自动滚动
// 但只有在打字机效果进行时才标记为用户滚动
if (shouldAutoScroll.value && isTypingActive.value) {
console.log("打字机效果中,用户手动滚动离开底部,停止自动滚动");
shouldAutoScroll.value = false;
userScrolled.value = true;
}
}
}, 100); // 100ms 节流
};
const resetAutoScrollState = () => {
shouldAutoScroll.value = true;
userScrolled.value = false;
console.log("重置自动滚动状态");
};
const isMessageCompleted = (message: any) => {
if (!message.status) return true;
return message.status === "completed";
};
const handleCopy = async (content: string) => {
try {
if (!content) {
ElMessage.warning(t("chat.noContentToCopy") || "没有可复制的内容");
return;
}
await navigator.clipboard.writeText(content);
ElMessage.success(t("chat.contentCopied") || "内容已复制到剪贴板");
} catch (error) {
try {
const textArea = document.createElement("textarea");
textArea.value = content;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
document.body.removeChild(textArea);
ElMessage.success(t("chat.contentCopied") || "内容已复制到剪贴板");
} catch (fallbackError) {
console.error("降级复制也失败:", fallbackError);
ElMessage.error(t("chat.copyFailed") || "复制失败,请手动复制");
}
}
};
const handleCopyMessage = async (message: any) => {
await handleCopy(message.content);
};
// 处理审批
const handleApprove = async (message: any, decision: string) => {
if (!message.pendingApproval) return;
try {
const approval = message.pendingApproval;
let result;
if (approval.type === "command") {
result = await codexStore.approveCommand(
approval.approvalId,
decision as any,
);
} else if (approval.type === "patch") {
result = await codexStore.approvePatch(
approval.approvalId,
decision as any,
approval.fileChangeId,
);
}
if (result && !result.success) {
ElMessage.error(result.error || "审批操作失败");
}
} catch (error: any) {
console.error("审批操作失败:", error);
ElMessage.error(error.message || "审批操作失败");
}
};
const handleSaveAndEdit = async (message: any) => {
try {
console.log("AgentPanelBodyAgent: 处理保存并编辑", { message });
if (!message.content) {
ElMessage.warning("没有可保存的内容");
return;
}
// 检查消息状态
if (message.status === "pending") {
ElMessage.warning("AI正在思考中,请等待回答完成后再保存");
return;
}
if (message.status === "streaming") {
ElMessage.warning("回答正在生成中,请等待完成后再保存");
return;
}
if (message.status === "error") {
ElMessage.warning("回答出现错误,无法保存");
return;
}
// 只有当状态为 completed 或者没有状态字段时才允许保存
if (message.status && message.status !== "completed") {
ElMessage.warning("回答尚未完成,请稍后再试");
return;
}
if (!currentSession.value) {
ElMessage.error("缺少会话信息,无法保存");
return;
}
try {
// 1. 获取文件名 (前20个字符)
// 尝试找到对应的问题
const messageIndex = messages.value.findIndex((m: any) => m.id === message.id);
let questionContent = "";
if (messageIndex > 0) {
const prevMessage = messages.value[messageIndex - 1];
if (prevMessage && prevMessage.role === "user") {
questionContent = prevMessage.content;
}
}
let title = questionContent || message.content;
title = title.replace(/\n/g, " ").substring(0, 20).trim();
if (!title) title = "未命名文档";
// 2. 检查并创建“草稿”目录
let draftFolderId: number | undefined;
const rootFilesRes = await getFiles();
if (
rootFilesRes.status === 200 &&
rootFilesRes.data
) {
const items = Array.isArray(rootFilesRes.data) ? rootFilesRes.data : (rootFilesRes.data.items || []);
const draftFolder = items.find(
(item: any) =>
(item.type === "folder" || item.isFolder) && item.name === "草稿",
);
if (draftFolder) {
draftFolderId = draftFolder.id;
}
}
if (!draftFolderId) {
const createFolderRes = await createFolder({ name: "草稿" });
if (createFolderRes.status === 200 && createFolderRes.data) {
draftFolderId = createFolderRes.data.id;
}
}
// 3. 调用保存API创建草稿
const response = await apiCreateDraftFromDeepSearch({
title,
content: message.content
});
console.log("创建草稿响应:", response);
if (response.status === 200 && response.data) {
const draftInfo = response.data;
const draftContent = draftInfo.content || "";
// 4. 将草稿保存到“草稿”目录
const saveRes = await apiSaveDraftToKnowledge(draftInfo.id, {
parentId: draftFolderId,
fileName: title + ".md",
});
console.log("保存到知识库响应:", saveRes);
if (saveRes.status === 200 && saveRes.data) {
const fileInfo = saveRes.data;
// 5. 添加到对话框引用
if (agentChatRef.value) {
agentChatRef.value.addFileReferences(
[
{
id: fileInfo.id || fileInfo.fileId,
name: fileInfo.name || fileInfo.fileName,
type: "md",
},
],
[(fileInfo.id || fileInfo.fileId).toString()],
);
}
// 6. 跳转到工作台编辑器
await openInWorkspace({
id: fileInfo.id,
title: fileInfo.name || fileInfo.fileName,
isDraft: false,
preloadContent: draftContent, // 传递预抓取的内容
});
// 7. 触发全局事件和状态信号,刷新文件列表
window.dispatchEvent(
new CustomEvent("refresh-file-hierarchy", {
detail: { folderId: draftFolderId },
}),
);
const appStore = useAppStore();
appStore.triggerRefreshFileHierarchy(draftFolderId);
ElMessage.success("已保存到草稿目录并添加到对话中");
} else {
throw new Error("保存到目录失败");
}
} else {
throw new Error((response as any)?.data?.message || "创建草稿失败");
}
} catch (apiError: any) {
console.error("API调用失败:", apiError);
if (!apiError.response && apiError.request) {
ElMessage.error("网络请求失败,请检查网络连接");
} else if (!apiError.response && !apiError.request) {
ElMessage.error(apiError.message || "保存失败");
}
}
} catch (error) {
console.error("保存并编辑失败:", error);
ElMessage.error("操作失败,请重试");
}
};
// 在工作台编辑器中打开文件
const openInWorkspace = async (fileInfo: any) => {
// 显示加载状态
const loading = ElLoading.service({
lock: true,
text: "正在准备文档...",
background: "rgba(0, 0, 0, 0.7)",
});
try {
console.log("准备在工作台中打开文件:", fileInfo);
// 先下载文件内容,确保文件可以正常访问
let fileContent = fileInfo.preloadContent || "";
try {
if (!fileContent) {
console.log("开始下载文件内容,fileId:", fileInfo.id);
// 统一使用常规文件 API
const contentResponse = await getFileContent(fileInfo.id);
fileContent = contentResponse.data;
console.log("文件内容下载成功,内容长度:", fileContent.length);
} else {
console.log("使用预传递的文件内容,内容长度:", fileContent.length);
}
} catch (downloadError) {
console.error("下载文件内容失败:", downloadError);
// 如果下载失败,仍然尝试跳转,让工作台组件自己处理
ElMessage.warning("文件内容预加载失败,将尝试在编辑器中重新加载");
}
// 构建跳转参数,包含文件内容
const params: any = {
fileId: fileInfo.id,
fileName: fileInfo.title || fileInfo.name,
fileType: "md", // 默认为 markdown
isChatAnswer: fileInfo.isDraft === false ? "false" : "true", // 明确标记是否为智能体回答文件(草稿)
};
// 如果成功获取到内容,也传递过去(可选)
if (fileContent) {
params.preloadContent = encodeURIComponent(fileContent);
}
// 跳转到工作台页面,并传递文件参数
await performRouterNavigation(params);
} catch (error) {
console.error("打开工作台编辑器失败:", error);
ElMessage.error("打开编辑器失败,请重试");
} finally {
loading.close();
}
};
// 执行路由跳转的辅助方法
const performRouterNavigation = async (params: any) => {
try {
console.log("开始执行路由跳转,参数:", params);
// 首先尝试使用路由名称跳转
try {
await router.push({
name: "Workspace",
query: params,
});
console.log("使用路由名称跳转成功");
return;
} catch (nameError) {
console.warn("路由名称跳转失败:", nameError);
}
// 如果路由名称失败,尝试使用路径跳转
try {
await router.push({
path: "/app/workspace",
query: params,
});
console.log("使用路径跳转成功");
return;
} catch (pathError) {
console.warn("路径跳转失败:", pathError);
}
// 尝试其他可能的路径
const possiblePaths = ["/workspace", "/Workspace", "/app/Workspace"];
for (const path of possiblePaths) {
try {
await router.push({
path: path,
query: params,
});
console.log(`使用路径 ${path} 跳转成功`);
return;
} catch (error) {
console.warn(`路径 ${path} 跳转失败:`, error);
}
}
// 如果所有Vue Router方式都失败,显示错误信息
console.error("所有路由跳转方式都失败");
ElMessage.error("无法跳转到工作台,请手动导航到工作台页面");
// 可选:提供手动跳转的提示
const queryString = new URLSearchParams(params).toString();
const targetUrl = `#/app/workspace?${queryString}`;
console.log("如需手动跳转,请访问:", targetUrl);
} catch (error) {
console.error("路由跳转过程中发生错误:", error);
ElMessage.error("跳转失败,请重试");
}
};
// 生命周期
onMounted(() => {
console.log("AgentPanelBody mounted");
nextTick(() => {
const container = messagesContainerRef.value;
if (container) {
container.addEventListener("scroll", handleScroll);
}
});
});
onUnmounted(() => {
const container = messagesContainerRef.value;
if (container) {
container.removeEventListener("scroll", handleScroll);
}
// 清理滚动检查定时器
if (scrollCheckTimeout) {
clearTimeout(scrollCheckTimeout);
scrollCheckTimeout = null;
}
// 清理所有打字机动画
typingAnimationFrames.value.forEach((frameId) => {
cancelAnimationFrame(frameId);
});
typingAnimationFrames.value.clear();
typingDisplayContent.value.clear();
typingTargetContent.value.clear();
});
// 暴露方法给父组件
defineExpose({
agentChatRef,
});
</script>
<style scoped>
.agent-panel-body {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
overflow: hidden;
}
.messages-container {
flex: 1;
overflow-y: auto;
padding: 16px 10px 16px 10px;
display: flex;
flex-direction: column;
gap: 16px;
min-height: 0;
}
.chat-container {
flex-shrink: 0;
}
.messages-list {
display: flex;
flex-direction: column;
gap: 16px;
}
.user-question {
display: flex;
flex-direction: column;
align-items: flex-end;
margin-bottom: 26px;
}
.user-attached-files {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 8px;
max-width: 100%;
margin-bottom: 8px;
}
.ai-answer {
display: flex;
flex-direction: column;
align-items: flex-start;
margin-bottom: 10px;
}
.message-body-question {
padding: 8px 12px 8px 12px;
border-radius: 8px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
max-width: 100%;
word-wrap: break-word;
font-size: 14px;
background: var(--user-question-bg);
color: var(--user-question-text);
}
.message-body-answer {
/* padding: 0px 0 8px 4px; */
border-radius: 8px;
line-height: 1.5;
/* white-space: pre-wrap; */
word-break: break-word;
max-width: 100%;
word-wrap: break-word;
font-size: 14px;
display: flex;
flex-direction: column;
align-items: flex-start;
background: var(--ai-answer-bg);
color: var(--ai-answer-text);
}
/* Markdown 内容容器样式 */
.markdown-content {
width: 100%;
padding: 8px 12px;
line-height: 1.6;
word-wrap: break-word;
overflow-wrap: break-word;
}
.message-actions-answer {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 12px;
gap: 4px;
}
.action-btn {
background: none;
border: none;
cursor: pointer;
padding: 6px;
border-radius: 4px;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
&:hover {
background: rgba(0, 0, 0, 0.05);
}
&.disabled {
opacity: 0.3;
cursor: not-allowed;
filter: grayscale(100%);
&:hover {
background: none;
}
}
}
.icon-svg {
width: 16px !important;
height: 16px !important;
object-fit: contain;
flex-shrink: 0;
}
.action-btn:hover .icon-svg {
/* 移除 hover 变化效果 */
}
/* AI思考状态样式 */
.ai-thinking {
display: flex;
align-items: center;
gap: 12px;
padding: 16px;
background: var(--ai-answer-bg);
border: 1px solid transparent;
border-radius: 8px;
color: var(--ai-answer-text);
min-height: 60px;
transition: all 0.3s ease;
}
.thinking-dots {
display: flex;
gap: 4px;
align-items: center;
}
.thinking-dots span {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-primary, #2871f6);
animation: thinking 1.4s infinite ease-in-out;
display: inline-block;
}
.thinking-dots span:nth-child(1) {
animation-delay: -0.32s;
}
.thinking-dots span:nth-child(2) {
animation-delay: -0.16s;
}
.thinking-text {
font-size: 14px;
color: var(--color-text-secondary, #999);
font-weight: 500;
}
@keyframes thinking {
0%,
80%,
100% {
transform: scale(0.8);
opacity: 0.5;
}
40% {
transform: scale(1);
opacity: 1;
}
}
/* 错误消息样式 */
.error-message {
background: rgba(244, 67, 54, 0.1) !important;
border: 1px solid #eaa8a3 !important;
color: #f44336 !important;
display: flex;
flex-direction: row;
align-items: center;
padding: 4px 2px 4px 12px;
border-radius: 4px;
gap: 8px;
}
.retry-icon {
cursor: pointer;
transition: all 0.2s ease;
}
.retry-icon:hover {
color: #d32f2f;
transform: rotate(180deg);
}
/* 流式状态提示 */
.websocket-error {
display: flex;
align-items: center;
gap: 8px;
background: rgba(244, 67, 54, 0.1);
border: 1px solid #eaa8a3 !important;
color: #f44336;
padding: 8px 12px;
border-radius: 4px;
margin: 8px 16px;
font-size: 12px;
}
.websocket-success {
display: flex;
align-items: center;
gap: 8px;
background: rgba(76, 175, 80, 0.1);
border: 1px solid #4caf50;
color: #4caf50;
padding: 8px 12px;
border-radius: 4px;
margin: 8px 16px;
font-size: 12px;
}
/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
width: 6px;
}
.messages-container::-webkit-scrollbar-track {
background: transparent;
}
.messages-container::-webkit-scrollbar-thumb {
background: var(--color-border);
border-radius: 3px;
}
.messages-container::-webkit-scrollbar-thumb:hover {
background: var(--color-secondary);
}
/* 打字机效果样式 */
.typewriter {
position: relative;
}
/* 打字机效果内容样式 */
.typewriter-content {
white-space: normal !important;
word-wrap: break-word;
}
/* 审批待处理状态 */
.approval-pending {
background: rgba(255, 193, 7, 0.1) !important;
border: 1px solid #ffc107 !important;
padding: 12px;
border-radius: 8px;
}
.approval-content {
display: flex;
flex-direction: column;
gap: 12px;
}
.approval-header {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: #ff9800;
}
.approval-body {
padding: 8px 0;
font-size: 13px;
}
.approval-body pre {
background: rgba(0, 0, 0, 0.05);
padding: 8px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 4px;
}
.approval-actions {
display: flex;
gap: 8px;
justify-content: flex-end;
}
.message-actions-user {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 4px;
gap: 4px;
}
</style>