File size: 36,559 Bytes
8ede856 | 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 | import { ref, reactive, type Ref } from 'vue';
import axios from 'axios';
import { useToast } from '@/utils/toast';
// 工具调用信息
export interface ToolCall {
id: string;
name: string;
args: Record<string, any>;
ts: number; // 开始时间戳
result?: string; // 工具调用结果
finished_ts?: number; // 完成时间戳
}
// Token 使用统计
export interface TokenUsage {
input_other: number;
input_cached: number;
output: number;
}
// Agent 统计信息
export interface AgentStats {
token_usage: TokenUsage;
start_time: number;
end_time: number;
time_to_first_token: number;
}
// 文件信息结构
export interface FileInfo {
url?: string; // blob URL (可选,点击时才加载)
filename: string;
attachment_id?: string; // 用于按需下载
}
// 消息部分的类型定义
export interface MessagePart {
type: 'plain' | 'image' | 'record' | 'file' | 'video' | 'reply' | 'tool_call';
text?: string; // for plain
attachment_id?: string; // for image, record, file, video
filename?: string; // for file (filename from backend)
message_id?: number; // for reply (PlatformSessionHistoryMessage.id)
tool_calls?: ToolCall[]; // for tool_call
// embedded fields - 加载后填充
embedded_url?: string; // blob URL for image, record
embedded_file?: FileInfo; // for file (保留 attachment_id 用于按需下载)
selected_text?: string; // for reply - 被引用消息的内容
}
// 引用信息 (用于发送消息时)
export interface ReplyInfo {
messageId: number;
selectedText?: string; // 选中的文本内容(可选)
}
// 简化的消息内容结构
export interface MessageContent {
type: string; // 'user' | 'bot'
message: MessagePart[]; // 消息部分列表 (保持顺序)
reasoning?: string; // reasoning content (for bot)
isLoading?: boolean; // loading state
agentStats?: AgentStats; // agent 统计信息 (for bot)
}
export interface Message {
id?: number;
content: MessageContent;
created_at?: string;
}
export type ChatTransportMode = 'sse' | 'websocket';
type StreamChunk = {
type?: string;
t?: string;
data?: any;
chain_type?: string;
streaming?: boolean;
session_id?: string;
message_id?: string;
code?: string;
ct?: string;
[key: string]: any;
};
type WsStreamContext = {
handleChunk: (payload: StreamChunk) => Promise<void>;
finish: (err?: unknown) => void;
};
const STREAMING_STORAGE_KEY = 'enableStreaming';
const TRANSPORT_MODE_STORAGE_KEY = 'chatTransportMode';
export function useMessages(
currSessionId: Ref<string>,
getMediaFile: (filename: string) => Promise<string>,
updateSessionTitle: (sessionId: string, title: string) => void,
onSessionsUpdate: () => void
) {
const messages = ref<Message[]>([]);
const isStreaming = ref(false);
const isConvRunning = ref(false);
const isToastedRunningInfo = ref(false);
const activeStreamCount = ref(0);
const enableStreaming = ref(true);
const transportMode = ref<ChatTransportMode>('sse');
const attachmentCache = new Map<string, string>(); // attachment_id -> blob URL
const currentRequestController = ref<AbortController | null>(null);
const currentReader = ref<ReadableStreamDefaultReader<Uint8Array> | null>(null);
const currentRunningSessionId = ref('');
const currentWsMessageId = ref('');
const currentBoundSessionId = ref('');
const userStopRequested = ref(false);
const currentWebSocket = ref<WebSocket | null>(null);
const webSocketConnectPromise = ref<Promise<WebSocket> | null>(null);
const wsContexts = new Map<string, WsStreamContext>();
// 当前会话的项目信息
const currentSessionProject = ref<{ project_id: string; title: string; emoji: string } | null>(null);
// 从 localStorage 读取配置
const savedStreamingState = localStorage.getItem(STREAMING_STORAGE_KEY);
if (savedStreamingState !== null) {
enableStreaming.value = JSON.parse(savedStreamingState);
}
const savedTransportMode = localStorage.getItem(TRANSPORT_MODE_STORAGE_KEY);
if (savedTransportMode === 'sse' || savedTransportMode === 'websocket') {
transportMode.value = savedTransportMode;
}
function toggleStreaming() {
enableStreaming.value = !enableStreaming.value;
localStorage.setItem(STREAMING_STORAGE_KEY, JSON.stringify(enableStreaming.value));
}
function setTransportMode(mode: ChatTransportMode) {
transportMode.value = mode;
localStorage.setItem(TRANSPORT_MODE_STORAGE_KEY, mode);
if (mode === 'websocket') {
if (currSessionId.value) {
void bindSessionToWebSocket(currSessionId.value).catch((err) => {
console.error('建立 WebSocket 连接失败:', err);
});
}
} else {
closeChatWebSocket();
}
}
function generateMessageId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
}
function buildWebSocketUrl(): string {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('Missing authentication token');
}
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = new URL('/api/unified_chat/ws', window.location.href);
wsUrl.protocol = protocol;
wsUrl.searchParams.set('token', token);
return wsUrl.toString();
}
function closeChatWebSocket() {
if (currentWebSocket.value) {
try {
currentWebSocket.value.close();
} catch {
// ignore websocket close errors
}
currentWebSocket.value = null;
}
webSocketConnectPromise.value = null;
currentBoundSessionId.value = '';
}
async function bindSessionToWebSocket(sessionId: string) {
if (!sessionId || transportMode.value !== 'websocket') {
return;
}
const ws = await ensureChatWebSocket();
if (ws.readyState !== WebSocket.OPEN) {
return;
}
if (currentBoundSessionId.value === sessionId) {
return;
}
ws.send(JSON.stringify({
ct: 'chat',
t: 'bind',
session_id: sessionId
}));
currentBoundSessionId.value = sessionId;
}
async function handlePassiveWebSocketChunk(payload: StreamChunk) {
if (!payload.type) {
return;
}
if (payload.type === 'plain') {
const chainType = payload.chain_type || 'normal';
if (chainType === 'reasoning') {
messages.value.push({
content: {
type: 'bot',
message: [],
reasoning: String(payload.data || '')
}
});
return;
}
messages.value.push({
content: {
type: 'bot',
message: [{
type: 'plain',
text: String(payload.data || '')
}]
}
});
return;
}
if (payload.type === 'image') {
const img = String(payload.data || '').replace('[IMAGE]', '');
const imageUrl = await getMediaFile(img);
messages.value.push({
content: {
type: 'bot',
message: [{ type: 'image', embedded_url: imageUrl }]
}
});
return;
}
if (payload.type === 'record') {
const audio = String(payload.data || '').replace('[RECORD]', '');
const audioUrl = await getMediaFile(audio);
messages.value.push({
content: {
type: 'bot',
message: [{ type: 'record', embedded_url: audioUrl }]
}
});
return;
}
if (payload.type === 'file') {
const fileData = String(payload.data || '').replace('[FILE]', '');
const [filename, originalName] = fileData.includes('|')
? fileData.split('|', 2)
: [fileData, fileData];
const fileUrl = await getMediaFile(filename);
messages.value.push({
content: {
type: 'bot',
message: [{
type: 'file',
embedded_file: { url: fileUrl, filename: originalName }
}]
}
});
}
}
async function dispatchWebSocketMessage(event: MessageEvent) {
let payload: StreamChunk;
try {
payload = JSON.parse(event.data);
} catch (err) {
console.warn('WebSocket JSON parse failed:', err);
return;
}
if (payload.ct && payload.ct !== 'chat') {
return;
}
if (payload.type === 'session_bound') {
if (typeof payload.session_id === 'string') {
currentBoundSessionId.value = payload.session_id;
}
return;
}
if (payload.t === 'error') {
const targetMessageId = payload.message_id || currentWsMessageId.value;
if (!targetMessageId) {
console.warn('WebSocket chat error:', payload);
return;
}
const ctx = wsContexts.get(targetMessageId);
if (!ctx) {
console.warn('WebSocket chat error (no ctx):', payload);
return;
}
if (userStopRequested.value || payload.code === 'INTERRUPTED') {
ctx.finish();
} else {
ctx.finish(new Error(payload.data || 'WebSocket chat error'));
}
return;
}
const targetMessageId = payload.message_id || currentWsMessageId.value;
if (!targetMessageId) {
return;
}
const ctx = wsContexts.get(targetMessageId);
if (!ctx) {
await handlePassiveWebSocketChunk(payload);
return;
}
try {
await ctx.handleChunk(payload);
} catch (err) {
ctx.finish(err);
return;
}
if (payload.type === 'end') {
ctx.finish();
}
}
function ensureChatWebSocket(): Promise<WebSocket> {
if (currentWebSocket.value?.readyState === WebSocket.OPEN) {
return Promise.resolve(currentWebSocket.value);
}
if (webSocketConnectPromise.value) {
return webSocketConnectPromise.value;
}
const connectPromise = new Promise<WebSocket>((resolve, reject) => {
let settled = false;
let ws: WebSocket;
try {
ws = new WebSocket(buildWebSocketUrl());
} catch (err) {
reject(err);
return;
}
const timeoutId = window.setTimeout(() => {
if (settled) {
return;
}
settled = true;
webSocketConnectPromise.value = null;
try {
ws.close();
} catch {
// ignore close errors
}
reject(new Error('WebSocket connection timeout'));
}, 5000);
ws.onopen = () => {
if (settled) {
return;
}
settled = true;
window.clearTimeout(timeoutId);
currentWebSocket.value = ws;
resolve(ws);
};
ws.onerror = () => {
if (settled) {
return;
}
settled = true;
window.clearTimeout(timeoutId);
webSocketConnectPromise.value = null;
reject(new Error('WebSocket connection failed'));
};
ws.onmessage = (event) => {
void dispatchWebSocketMessage(event);
};
ws.onclose = () => {
currentWebSocket.value = null;
webSocketConnectPromise.value = null;
const pending = Array.from(wsContexts.values());
for (const ctx of pending) {
if (userStopRequested.value) {
ctx.finish();
} else {
ctx.finish(new Error('WebSocket closed'));
}
}
};
});
webSocketConnectPromise.value = connectPromise;
return connectPromise;
}
function createStreamChunkProcessor() {
let inStreaming = false;
let messageObj: MessageContent | null = null;
return async (chunkJson: StreamChunk) => {
if (!chunkJson || typeof chunkJson !== 'object') {
return;
}
if (chunkJson.type === 'session_id') {
return;
}
if (!chunkJson.type) {
return;
}
const lastMsg = messages.value[messages.value.length - 1];
if (lastMsg?.content?.isLoading) {
messages.value.pop();
}
if (chunkJson.type === 'error') {
console.error('Error received:', chunkJson.data);
return;
}
if (chunkJson.type === 'image') {
const img = String(chunkJson.data || '').replace('[IMAGE]', '');
const imageUrl = await getMediaFile(img);
const botResp: MessageContent = {
type: 'bot',
message: [{
type: 'image',
embedded_url: imageUrl
}]
};
messages.value.push({ content: botResp });
} else if (chunkJson.type === 'record') {
const audio = String(chunkJson.data || '').replace('[RECORD]', '');
const audioUrl = await getMediaFile(audio);
const botResp: MessageContent = {
type: 'bot',
message: [{
type: 'record',
embedded_url: audioUrl
}]
};
messages.value.push({ content: botResp });
} else if (chunkJson.type === 'file') {
const fileData = String(chunkJson.data || '').replace('[FILE]', '');
const [filename, originalName] = fileData.includes('|')
? fileData.split('|', 2)
: [fileData, fileData];
const fileUrl = await getMediaFile(filename);
const botResp: MessageContent = {
type: 'bot',
message: [{
type: 'file',
embedded_file: {
url: fileUrl,
filename: originalName
}
}]
};
messages.value.push({ content: botResp });
} else if (chunkJson.type === 'plain') {
const chainType = chunkJson.chain_type || 'normal';
if (chainType === 'tool_call') {
let toolCallData: any;
try {
toolCallData = JSON.parse(String(chunkJson.data || '{}'));
} catch {
return;
}
const toolCall: ToolCall = {
id: toolCallData.id,
name: toolCallData.name,
args: toolCallData.args,
ts: toolCallData.ts
};
if (!inStreaming) {
messageObj = reactive<MessageContent>({
type: 'bot',
message: [{
type: 'tool_call',
tool_calls: [toolCall]
}]
});
messages.value.push({ content: messageObj });
inStreaming = true;
} else {
const lastPart = messageObj!.message[messageObj!.message.length - 1];
if (lastPart?.type === 'tool_call') {
const existingIndex = lastPart.tool_calls!.findIndex((tc: ToolCall) => tc.id === toolCall.id);
if (existingIndex === -1) {
lastPart.tool_calls!.push(toolCall);
}
} else {
messageObj!.message.push({
type: 'tool_call',
tool_calls: [toolCall]
});
}
}
} else if (chainType === 'tool_call_result') {
let resultData: any;
try {
resultData = JSON.parse(String(chunkJson.data || '{}'));
} catch {
return;
}
if (messageObj) {
for (const part of messageObj.message) {
if (part.type === 'tool_call' && part.tool_calls) {
const toolCall = part.tool_calls.find((tc: ToolCall) => tc.id === resultData.id);
if (toolCall) {
toolCall.result = resultData.result;
toolCall.finished_ts = resultData.ts;
break;
}
}
}
}
} else if (chainType === 'reasoning') {
if (!inStreaming) {
messageObj = reactive<MessageContent>({
type: 'bot',
message: [],
reasoning: String(chunkJson.data || '')
});
messages.value.push({ content: messageObj });
inStreaming = true;
} else {
messageObj!.reasoning = (messageObj!.reasoning || '') + String(chunkJson.data || '');
}
} else {
if (!inStreaming) {
messageObj = reactive<MessageContent>({
type: 'bot',
message: [{
type: 'plain',
text: String(chunkJson.data || '')
}]
});
messages.value.push({ content: messageObj });
inStreaming = true;
} else {
const lastPart = messageObj!.message[messageObj!.message.length - 1];
if (lastPart?.type === 'plain') {
lastPart.text = (lastPart.text || '') + String(chunkJson.data || '');
} else {
messageObj!.message.push({
type: 'plain',
text: String(chunkJson.data || '')
});
}
}
}
} else if (chunkJson.type === 'update_title') {
if (chunkJson.session_id) {
updateSessionTitle(chunkJson.session_id, chunkJson.data);
}
} else if (chunkJson.type === 'message_saved') {
const lastBotMsg = messages.value[messages.value.length - 1];
if (lastBotMsg && lastBotMsg.content?.type === 'bot') {
lastBotMsg.id = chunkJson.data?.id;
lastBotMsg.created_at = chunkJson.data?.created_at;
}
} else if (chunkJson.type === 'agent_stats') {
if (messageObj) {
messageObj.agentStats = chunkJson.data;
}
}
if (typeof chunkJson.streaming === 'boolean') {
if ((chunkJson.type === 'break' && chunkJson.streaming) || !chunkJson.streaming) {
inStreaming = false;
if (!chunkJson.streaming) {
isStreaming.value = false;
}
}
}
};
}
// 获取 attachment 文件并返回 blob URL
async function getAttachment(attachmentId: string): Promise<string> {
if (attachmentCache.has(attachmentId)) {
return attachmentCache.get(attachmentId)!;
}
try {
const response = await axios.get(`/api/chat/get_attachment?attachment_id=${attachmentId}`, {
responseType: 'blob'
});
const blobUrl = URL.createObjectURL(response.data);
attachmentCache.set(attachmentId, blobUrl);
return blobUrl;
} catch (err) {
console.error('Failed to get attachment:', attachmentId, err);
return '';
}
}
// 解析消息内容,填充 embedded 字段 (保持原始顺序)
async function parseMessageContent(content: any): Promise<void> {
const message = content.message;
// 如果 message 是字符串 (旧格式),转换为数组格式
if (typeof message === 'string') {
const parts: MessagePart[] = [];
let text = message;
// 处理旧格式的特殊标记
if (text.startsWith('[IMAGE]')) {
const img = text.replace('[IMAGE]', '');
const imageUrl = await getMediaFile(img);
parts.push({
type: 'image',
embedded_url: imageUrl
});
} else if (text.startsWith('[RECORD]')) {
const audio = text.replace('[RECORD]', '');
const audioUrl = await getMediaFile(audio);
parts.push({
type: 'record',
embedded_url: audioUrl
});
} else if (text) {
parts.push({
type: 'plain',
text: text
});
}
content.message = parts;
return;
}
// 如果 message 是数组 (新格式),遍历并填充 embedded 字段
if (Array.isArray(message)) {
for (const part of message as MessagePart[]) {
if (part.type === 'image' && part.attachment_id) {
part.embedded_url = await getAttachment(part.attachment_id);
} else if (part.type === 'record' && part.attachment_id) {
part.embedded_url = await getAttachment(part.attachment_id);
} else if (part.type === 'file' && part.attachment_id) {
// file 类型不预加载,保留 attachment_id 以便点击时下载
part.embedded_file = {
attachment_id: part.attachment_id,
filename: part.filename || 'file'
};
}
// plain, reply, tool_call, video 保持原样
}
}
// 处理 agent_stats (snake_case -> camelCase)
if (content.agent_stats) {
content.agentStats = content.agent_stats;
delete content.agent_stats;
}
}
async function getSessionMessages(sessionId: string) {
if (!sessionId) return;
try {
if (transportMode.value === 'websocket') {
try {
await bindSessionToWebSocket(sessionId);
} catch (err) {
console.error('进入会话时建立 WebSocket 连接失败:', err);
}
}
const response = await axios.get('/api/chat/get_session?session_id=' + sessionId);
isConvRunning.value = response.data.data.is_running || false;
let history = response.data.data.history;
// 保存项目信息(如果存在)
currentSessionProject.value = response.data.data.project || null;
if (isConvRunning.value) {
if (!isToastedRunningInfo.value) {
useToast().info('该会话正在运行中。', { timeout: 5000 });
isToastedRunningInfo.value = true;
}
// 如果会话还在运行,3秒后重新获取消息
setTimeout(() => {
getSessionMessages(currSessionId.value);
}, 3000);
}
// 处理历史消息
for (let i = 0; i < history.length; i++) {
let content = history[i].content;
await parseMessageContent(content);
}
messages.value = history;
} catch (err) {
console.error(err);
}
}
function buildBackendMessageParts(
prompt: string,
stagedFiles: { attachment_id: string; url: string; original_name: string; type: string }[],
replyTo: ReplyInfo | null
): MessagePart[] {
const parts: MessagePart[] = [];
if (replyTo) {
parts.push({
type: 'reply',
message_id: replyTo.messageId,
selected_text: replyTo.selectedText
});
}
if (prompt) {
parts.push({
type: 'plain',
text: prompt
});
}
for (const f of stagedFiles) {
const partType = f.type === 'image' ? 'image' :
f.type === 'record' ? 'record' : 'file';
parts.push({
type: partType as 'image' | 'record' | 'file',
attachment_id: f.attachment_id
});
}
return parts;
}
async function sendMessageViaSSE(
messageToSend: string | MessagePart[],
selectedProviderId: string,
selectedModelName: string
) {
const controller = new AbortController();
currentRequestController.value = controller;
const response = await fetch('/api/chat/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('token')
},
signal: controller.signal,
body: JSON.stringify({
message: messageToSend,
session_id: currSessionId.value,
selected_provider: selectedProviderId,
selected_model: selectedModelName,
enable_streaming: enableStreaming.value
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body!.getReader();
currentReader.value = reader;
const decoder = new TextDecoder();
const processChunk = createStreamChunkProcessor();
isStreaming.value = true;
while (true) {
try {
const { done, value } = await reader.read();
if (done) {
if (currSessionId.value) {
await getSessionMessages(currSessionId.value);
}
break;
}
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split('\n\n');
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim();
if (!line) continue;
let chunkJson: StreamChunk;
try {
chunkJson = JSON.parse(line.replace('data: ', ''));
} catch (parseError) {
console.warn('JSON解析失败:', line, parseError);
continue;
}
await processChunk(chunkJson);
}
} catch (readError) {
if (!userStopRequested.value) {
console.error('SSE读取错误:', readError);
}
break;
}
}
}
async function sendMessageViaWebSocket(
messageParts: MessagePart[],
selectedProviderId: string,
selectedModelName: string
) {
await bindSessionToWebSocket(currSessionId.value);
const ws = await ensureChatWebSocket();
const messageId = generateMessageId();
currentWsMessageId.value = messageId;
const processChunk = createStreamChunkProcessor();
isStreaming.value = true;
await new Promise<void>((resolve, reject) => {
let finished = false;
const finish = (err?: unknown) => {
if (finished) {
return;
}
finished = true;
wsContexts.delete(messageId);
if (err) {
reject(err);
} else {
resolve();
}
};
wsContexts.set(messageId, {
handleChunk: processChunk,
finish
});
try {
ws.send(JSON.stringify({
ct: 'chat',
t: 'send',
message_id: messageId,
session_id: currSessionId.value,
message: messageParts,
selected_provider: selectedProviderId,
selected_model: selectedModelName,
enable_streaming: enableStreaming.value
}));
} catch (err) {
finish(err);
}
});
if (currSessionId.value) {
await getSessionMessages(currSessionId.value);
}
}
async function sendMessage(
prompt: string,
stagedFiles: { attachment_id: string; url: string; original_name: string; type: string }[],
audioName: string,
selectedProviderId: string,
selectedModelName: string,
replyTo: ReplyInfo | null = null
) {
const userMessageParts: MessagePart[] = [];
if (replyTo) {
userMessageParts.push({
type: 'reply',
message_id: replyTo.messageId,
selected_text: replyTo.selectedText
});
}
if (prompt) {
userMessageParts.push({
type: 'plain',
text: prompt
});
}
for (const f of stagedFiles) {
const partType = f.type === 'image' ? 'image' :
f.type === 'record' ? 'record' : 'file';
const embeddedUrl = await getAttachment(f.attachment_id);
userMessageParts.push({
type: partType as 'image' | 'record' | 'file',
attachment_id: f.attachment_id,
filename: f.original_name,
embedded_url: partType !== 'file' ? embeddedUrl : undefined,
embedded_file: partType === 'file' ? {
attachment_id: f.attachment_id,
filename: f.original_name
} : undefined
});
}
if (audioName) {
userMessageParts.push({
type: 'record',
embedded_url: audioName
});
}
const userMessage: MessageContent = {
type: 'user',
message: userMessageParts
};
messages.value.push({ content: userMessage });
const loadingMessage = reactive<MessageContent>({
type: 'bot',
message: [],
reasoning: '',
isLoading: true
});
messages.value.push({ content: loadingMessage });
try {
activeStreamCount.value++;
if (activeStreamCount.value === 1) {
isConvRunning.value = true;
}
userStopRequested.value = false;
currentRunningSessionId.value = currSessionId.value;
const backendMessageParts = buildBackendMessageParts(prompt, stagedFiles, replyTo);
const hasAttachmentOrReply = stagedFiles.length > 0 || !!replyTo;
if (transportMode.value === 'websocket') {
await sendMessageViaWebSocket(
backendMessageParts,
selectedProviderId,
selectedModelName
);
} else {
const messageToSend: string | MessagePart[] = hasAttachmentOrReply
? backendMessageParts
: prompt;
await sendMessageViaSSE(
messageToSend,
selectedProviderId,
selectedModelName
);
}
onSessionsUpdate();
} catch (err) {
if (!userStopRequested.value) {
console.error('发送消息失败:', err);
}
const lastMsg = messages.value[messages.value.length - 1];
if (lastMsg?.content?.isLoading) {
messages.value.pop();
}
} finally {
isStreaming.value = false;
currentReader.value = null;
currentRequestController.value = null;
currentRunningSessionId.value = '';
currentWsMessageId.value = '';
userStopRequested.value = false;
activeStreamCount.value--;
if (activeStreamCount.value === 0) {
isConvRunning.value = false;
}
}
}
async function stopMessage() {
const sessionId = currentRunningSessionId.value || currSessionId.value;
if (!sessionId) {
return;
}
userStopRequested.value = true;
try {
await axios.post('/api/chat/stop', {
session_id: sessionId
});
} catch (err) {
console.error('停止会话失败:', err);
}
if (transportMode.value === 'websocket' && currentWebSocket.value?.readyState === WebSocket.OPEN) {
try {
currentWebSocket.value.send(JSON.stringify({
ct: 'chat',
t: 'interrupt',
session_id: sessionId,
message_id: currentWsMessageId.value || undefined
}));
} catch (err) {
console.error('发送 websocket interrupt 失败:', err);
}
}
try {
await currentReader.value?.cancel();
} catch {
// ignore reader cancel failures
}
currentReader.value = null;
currentRequestController.value?.abort();
currentRequestController.value = null;
isStreaming.value = false;
}
function cleanupTransport() {
closeChatWebSocket();
}
return {
messages,
isStreaming,
isConvRunning,
enableStreaming,
transportMode,
currentSessionProject,
getSessionMessages,
sendMessage,
stopMessage,
toggleStreaming,
setTransportMode,
cleanupTransport,
getAttachment
};
}
|