266 lines
9.7 KiB
TypeScript
266 lines
9.7 KiB
TypeScript
/**
|
||
* features/chat/composables/useChatTurn.ts
|
||
* 用途:统一发起 Chat Turn(POST /api/chat/turns/stream),复用与 sendMessage 相同的 SSE 渲染链路。
|
||
* 依赖:chat-turn.types、useChat 的 shipping UI 同步、streamErrorMessage、auth headers。
|
||
* 逻辑:useChat 构造 startChatTurn 并导出;货代/请假等业务只构造 actionType + payload。
|
||
*/
|
||
import { type Ref } from 'vue';
|
||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
|
||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||
import type { ChatMessage, ChatRun } from '../types/chat.types';
|
||
import { applyShippingUiStateToMessage } from './useChat';
|
||
|
||
export interface CreateStartChatTurnOptions {
|
||
messages: Ref<ChatMessage[]>;
|
||
isThinking: Ref<boolean>;
|
||
conversationId: Ref<string | null>;
|
||
viewId: Ref<number>;
|
||
runs: Ref<ChatRun[]>;
|
||
activeRunId: Ref<number | null>;
|
||
activeStreamController: Ref<AbortController | null>;
|
||
streamErrorLabels: () => StreamErrorLabels;
|
||
formatStreamError: (message: unknown) => string;
|
||
}
|
||
|
||
/**
|
||
* 创建 startChatTurn 函数,供 useChat 与业务 handler 共用。
|
||
*/
|
||
export function createStartChatTurn(options: CreateStartChatTurnOptions) {
|
||
let runSeq = 0;
|
||
|
||
const normalizeStreamText = (text: string) => text.replace(/\\n/g, '\n');
|
||
|
||
const startChatTurn = async (turn: StartChatTurnOptions): Promise<boolean> => {
|
||
const displayText = String(turn.displayText || '').trim();
|
||
if (!displayText && !turn.silent) return false;
|
||
|
||
if (options.activeStreamController.value) {
|
||
options.activeStreamController.value.abort();
|
||
options.activeStreamController.value = null;
|
||
}
|
||
|
||
const controller = new AbortController();
|
||
options.activeStreamController.value = controller;
|
||
const runViewId = options.viewId.value;
|
||
const runMessages = options.messages.value;
|
||
const run: ChatRun = {
|
||
runId: ++runSeq,
|
||
agentId: turn.agentId,
|
||
viewId: runViewId,
|
||
query: displayText,
|
||
messages: runMessages,
|
||
conversationId: options.conversationId.value,
|
||
status: 'running',
|
||
createdAt: new Date().toISOString(),
|
||
abortController: controller,
|
||
};
|
||
options.runs.value.unshift(run);
|
||
if (options.runs.value.length > 30) {
|
||
options.runs.value = options.runs.value.slice(0, 30);
|
||
}
|
||
options.activeRunId.value = run.runId;
|
||
|
||
if (!turn.silent && displayText) {
|
||
runMessages.push({ role: 'user', content: displayText });
|
||
}
|
||
|
||
let botMsgIndex: number | null = null;
|
||
let hasTerminalEvent = false;
|
||
const ensureBotMessage = () => {
|
||
if (botMsgIndex === null) {
|
||
botMsgIndex = runMessages.push({
|
||
role: 'assistant',
|
||
content: '',
|
||
retriever_resources: [],
|
||
attribution_parts: [],
|
||
}) - 1;
|
||
}
|
||
return runMessages[botMsgIndex] || null;
|
||
};
|
||
|
||
options.isThinking.value = true;
|
||
|
||
const refs = turn.refs || {};
|
||
|
||
try {
|
||
const inputBody = {
|
||
type: turn.inputType,
|
||
display_text: displayText || turn.actionType,
|
||
action_type: turn.actionType,
|
||
payload: turn.payload || {},
|
||
};
|
||
const refsPayload = Object.keys(refs).length > 0 ? refs : undefined;
|
||
const hasFiles = Array.isArray(turn.files) && turn.files.length > 0;
|
||
|
||
let response: Response;
|
||
if (hasFiles) {
|
||
const form = new FormData();
|
||
form.append('agent_id', String(turn.agentId));
|
||
if (options.conversationId.value) {
|
||
form.append('conversation_id', options.conversationId.value);
|
||
}
|
||
form.append('input', JSON.stringify(inputBody));
|
||
if (refsPayload) {
|
||
form.append('context', JSON.stringify({ refs: refsPayload }));
|
||
}
|
||
turn.files!.forEach((file) => form.append('files', file));
|
||
response = await fetch('/api/chat/turns/stream', {
|
||
method: 'POST',
|
||
headers: { ...getAuthHeaders() },
|
||
signal: controller.signal,
|
||
body: form,
|
||
});
|
||
} else {
|
||
response = await fetch('/api/chat/turns/stream', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||
signal: controller.signal,
|
||
body: JSON.stringify({
|
||
agent_id: turn.agentId,
|
||
conversation_id: options.conversationId.value,
|
||
input: inputBody,
|
||
context: {
|
||
refs: refsPayload,
|
||
},
|
||
}),
|
||
});
|
||
}
|
||
|
||
if (!response.ok) {
|
||
const err = await response.json().catch(() => ({}));
|
||
const envelope = err as { error?: { message?: string }; message?: string };
|
||
throw new Error(envelope.error?.message || envelope.message || `Request failed with status ${response.status}`);
|
||
}
|
||
|
||
const reader = response.body?.getReader();
|
||
const decoder = new TextDecoder();
|
||
if (!reader) throw new Error('No reader');
|
||
|
||
let buffer = '';
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
|
||
buffer += decoder.decode(value, { stream: true });
|
||
buffer = buffer.replace(/\r\n/g, '\n');
|
||
const frames = buffer.split('\n\n');
|
||
buffer = frames.pop() || '';
|
||
|
||
for (const frame of frames) {
|
||
const dataLines = frame
|
||
.split('\n')
|
||
.map((line) => line.trim())
|
||
.filter((line) => line.startsWith('data:'));
|
||
if (dataLines.length === 0) continue;
|
||
|
||
const payload = dataLines.map((line) => line.replace(/^data:\s?/, '')).join('\n');
|
||
if (!payload) continue;
|
||
|
||
try {
|
||
const data = JSON.parse(payload) as Record<string, unknown>;
|
||
if (data?.conversation_id) {
|
||
const cid = String(data.conversation_id);
|
||
if (!run.conversationId) run.conversationId = cid;
|
||
if (options.messages.value === runMessages) options.conversationId.value = cid;
|
||
}
|
||
|
||
const eventName = String(data.event || '');
|
||
if (eventName === 'shipping_ui_state' || eventName === 'ui_state.updated') {
|
||
const botMsg = ensureBotMessage();
|
||
if (botMsg) applyShippingUiStateToMessage(botMsg, data);
|
||
|
||
} else if (
|
||
eventName === 'message'
|
||
|| eventName === 'agent_message'
|
||
|| eventName === 'message.delta'
|
||
) {
|
||
const chunk = String(data.answer || data.content || '');
|
||
if (chunk) {
|
||
const botMsg = ensureBotMessage();
|
||
if (botMsg) botMsg.content += normalizeStreamText(chunk);
|
||
}
|
||
} else if (
|
||
eventName === 'message_end'
|
||
|| eventName === 'message.completed'
|
||
|| eventName === 'run.completed'
|
||
) {
|
||
if (eventName === 'run.completed') {
|
||
hasTerminalEvent = true;
|
||
run.status = 'done';
|
||
}
|
||
if (eventName === 'message_end' || eventName === 'message.completed') {
|
||
hasTerminalEvent = true;
|
||
run.status = 'done';
|
||
const botMsg = ensureBotMessage();
|
||
if (botMsg) {
|
||
const answer = normalizeStreamText(String(data.answer || data.content || ''));
|
||
if (answer) botMsg.content = answer;
|
||
const messageType = String(data.type || data.message_type || '').trim();
|
||
if (messageType) botMsg.type = messageType as ChatMessage['type'];
|
||
if (data.payload) botMsg.payload = data.payload;
|
||
if (data.chat_log_id != null) botMsg.chat_log_id = Number(data.chat_log_id);
|
||
if (botMsg.payload && typeof botMsg.payload === 'object' && (botMsg.payload as { shipping_actions_used?: boolean }).shipping_actions_used) {
|
||
botMsg.shipping_actions_used = true;
|
||
botMsg.shipping_actions = undefined;
|
||
}
|
||
}
|
||
}
|
||
} else if (eventName === 'run.failed' || eventName === 'error') {
|
||
hasTerminalEvent = true;
|
||
run.status = 'error';
|
||
const botMsg = ensureBotMessage();
|
||
if (botMsg) {
|
||
applyStreamErrorToMessage(botMsg, options.formatStreamError(data.message), options.streamErrorLabels());
|
||
}
|
||
}
|
||
} catch {
|
||
// ignore malformed SSE frames
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!hasTerminalEvent) {
|
||
run.status = 'done';
|
||
}
|
||
return run.status === 'done';
|
||
} catch (error: unknown) {
|
||
if (!controller.signal.aborted) {
|
||
run.status = 'error';
|
||
const botMsg = ensureBotMessage();
|
||
if (botMsg) {
|
||
const message = error instanceof Error ? error.message : 'Network Issue';
|
||
applyStreamErrorToMessage(botMsg, message, options.streamErrorLabels());
|
||
}
|
||
}
|
||
} finally {
|
||
if (options.activeStreamController.value === controller) {
|
||
options.activeStreamController.value = null;
|
||
}
|
||
if (run.abortController === controller) {
|
||
delete run.abortController;
|
||
}
|
||
if (options.messages.value === runMessages) {
|
||
options.isThinking.value = false;
|
||
}
|
||
if (run.status === 'done' && botMsgIndex !== null) {
|
||
const botMsg = runMessages[botMsgIndex];
|
||
if (botMsg) {
|
||
await turn.hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||
}
|
||
}
|
||
return run.status === 'done';
|
||
}
|
||
};
|
||
|
||
return { startChatTurn };
|
||
}
|
||
|
||
/**
|
||
* useChatTurn 组合式入口;通常由 useChat 内部调用 createStartChatTurn。
|
||
*/
|
||
export function useChatTurn(options: CreateStartChatTurnOptions) {
|
||
const { startChatTurn } = createStartChatTurn(options);
|
||
return { startChatTurn };
|
||
}
|