feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

@@ -8,6 +8,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
import { createStartChatTurn } from './useChatTurn';
export interface SendMessageLifecycleHooks {
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
@@ -300,9 +301,14 @@ export function useChat() {
activeRunId.value = runId;
};
/**
* 打开空白新会话视图:仅脱离当前流与视图绑定,不 abort 后台 SSE。
*
* 核心逻辑:与 loadConversationState 一致;旧 run 继续在 runs 中更新,并在侧栏显示为「生成中」。
*/
const createNewChatView = () => {
clearLikelyCompletedStreamTimer();
cancelActiveStream();
detachActiveStreamFromView();
viewId.value += 1;
messages.value = [];
conversationId.value = null;
@@ -310,6 +316,25 @@ export function useChat() {
activeRunId.value = null;
};
/**
* 用户显式点击「停止生成」时中止当前可见 run 的流式请求。
*
* 核心逻辑:优先 abort 活动视图绑定的 controller;若已 detach,则回退到 run 上保存的 controller。
*/
const stopActiveGeneration = () => {
clearLikelyCompletedStreamTimer();
const run = activeRunId.value != null
? runs.value.find((r) => r.runId === activeRunId.value)
: undefined;
const controller = activeStreamController.value ?? run?.abortController ?? null;
if (!controller) return;
controller.abort();
activeStreamController.value = null;
if (run && messages.value === run.messages) {
isThinking.value = false;
}
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
clearLikelyCompletedStreamTimer();
detachActiveStreamFromView();
@@ -388,6 +413,18 @@ export function useChat() {
generic: t('chat.streamError.generic'),
});
const { startChatTurn } = createStartChatTurn({
messages,
isThinking,
conversationId,
viewId,
runs,
activeRunId,
activeStreamController,
streamErrorLabels,
formatStreamError,
});
const sendMessage = async (
query: string,
agentId: number,
@@ -420,6 +457,7 @@ export function useChat() {
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
abortController: controller,
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
@@ -634,6 +672,9 @@ export function useChat() {
if (activeStreamController.value === controller) {
activeStreamController.value = null;
}
if (run.abortController === controller) {
delete run.abortController;
}
if (messages.value === runMessages) {
isThinking.value = false;
}
@@ -657,5 +698,7 @@ export function useChat() {
createNewChatView,
loadConversationState,
sendMessage,
startChatTurn,
stopActiveGeneration,
};
}
@@ -7,6 +7,11 @@ import { BusinessError } from '@/shared/api/client';
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
import { sortAgentsByCategory } from '@/shared/utils/agent-category.utils';
import {
agentHasErpKb,
type AgentRegistryFields,
} from '@/shared/utils/agent-registry.utils';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import type { ChatDeps } from './chat.deps';
import type { UseChatGuidesReturn } from './useChatGuides';
@@ -17,41 +22,9 @@ export type AgentSuggestedQuestionItem = {
const DEFAULT_KB = '企业知识库';
const ERP_KB = 'ERP知识库';
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
const isTrainingAgentName = (name: string) => TRAINING_AGENT_NAME_PATTERN.test(name);
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
};
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
人事规章: {
style: 'styled',
questions: [
{ question: '查询我有多少假期?', group: '考勤与休假' },
{ question: '如何进行请假?', group: '考勤与休假' },
{ question: '查公司法定节假日?', group: '考勤与休假' },
{ question: '新员工入职须知', group: '规章与日常' },
{ question: '怎么开具在职证明?', group: '规章与日常' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
],
},
通用入口: {
style: 'plain',
questions: [
{ question: '新员工入职须知', group: '' },
{ question: '查询我有多少假期?', group: '' },
{ question: '如何进行请假?', group: '' },
{ question: '查公司法定节假日?', group: '' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
],
},
};
const TRAINING_AGENT_DESCRIPTION = '我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const TRAINING_AGENT_DESCRIPTION =
'我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const TRAINING_AGENT_QUESTIONS: AgentSuggestedQuestionItem[] = [
{ question: '开始新人培训', group: '培训流程' },
@@ -87,8 +60,8 @@ export function useChatAgent(options: UseChatAgentOptions) {
const { deps, currentAgentId, chatGuides } = options;
const { t, msg, router } = deps;
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{
const currentAgent = ref<AgentRegistryFields | null>(null);
const userAgents = ref<Array<AgentRegistryFields & {
id: number;
name: string;
description: string;
@@ -108,8 +81,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
return kb;
};
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
const canSelectErpKnowledgeBase = computed(() => ERP_KB_ENABLED_AGENT_NAMES.has(currentAgentName.value));
const canSelectErpKnowledgeBase = computed(() => agentHasErpKb(currentAgent.value));
const availableKbOptions = computed(() => (
canSelectErpKnowledgeBase.value
? kbOptions
@@ -118,7 +90,6 @@ export function useChatAgent(options: UseChatAgentOptions) {
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
watch(canSelectErpKnowledgeBase, (allowed) => {
// 固资管理默认先走企业知识库,用户可手动切换到 ERP 知识库。
if (allowed) {
selectedKb.value = DEFAULT_KB;
return;
@@ -129,26 +100,28 @@ export function useChatAgent(options: UseChatAgentOptions) {
}, { immediate: true });
const agentDescription = computed(() => {
const welcome = String(currentAgent.value?.welcome_message || '').trim();
if (welcome) return welcome;
const text = String(currentAgent.value?.description || '').trim();
if (!text && isTrainingAgentName(currentAgentName.value)) return TRAINING_AGENT_DESCRIPTION;
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
if (!text && matchesTrainingAgent(currentAgent.value)) return TRAINING_AGENT_DESCRIPTION;
return text;
});
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
const style = String(currentAgent.value?.suggested_questions_style || '').trim().toLowerCase();
if (style === 'styled') return 'styled';
if (style === 'plain') return 'plain';
if (isTrainingAgentName(currentAgentName.value)) return 'styled';
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
if (matchesTrainingAgent(currentAgent.value)) return 'styled';
return 'plain';
});
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
const configured = normalizeAgentSuggestedQuestions(
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
currentAgent.value?.suggested_questions,
);
if (configured.length > 0) return configured;
if (isTrainingAgentName(currentAgentName.value)) return TRAINING_AGENT_QUESTIONS;
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
if (matchesTrainingAgent(currentAgent.value)) return TRAINING_AGENT_QUESTIONS;
return [];
});
const styledSuggestedQuestionSections = computed(() => {
@@ -191,7 +164,6 @@ export function useChatAgent(options: UseChatAgentOptions) {
? agents.filter((a: any) => (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
userAgents.value = sortAgentsByCategory(filtered);
// [STEP 1] 有可切换智能体时默认展开面板;避免切换 Agent 后列表「消失」
showAgentPanel.value = userAgents.value.length > 0;
} catch {
userAgents.value = [];
@@ -77,6 +77,32 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
});
const attachmentPolicy = computed(() => {
const fileUploadAllowed = currentAgent.value?.capabilities?.file_upload;
if (fileUploadAllowed === false) {
return {
anyEnabled: false,
enabled: {
image: { local: false, remote: false },
document: { local: false, remote: false },
audio: { local: false, remote: false },
video: { local: false, remote: false },
custom: { local: false, remote: false },
},
sizeLimitMb: {
image: null,
audio: null,
video: null,
document: null,
custom: null,
},
canLocal: false,
canRemote: false,
accept: '',
allowedExts: null,
totalLimit: null,
};
}
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
image: { local: false, remote: false },
@@ -9,7 +9,9 @@
*/
import { computed, type ComputedRef, type Ref } from 'vue';
import { getUserProfile } from '@/features/auth/api/user.api';
import { LEAVE_FEATURE_AGENT_NAMES, LEAVE_TYPES } from '../constants/leave';
import { canUseLeaveFeature as resolveLeaveFeatureEnabled } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { LEAVE_TYPES } from '../constants/leave';
import {
createLeaveAgentPickerApi,
createLeaveFlowApi,
@@ -30,7 +32,7 @@ import type { ChatDeps } from './chat.deps';
export interface UseChatLeaveOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgent: Ref<AgentRegistryFields | null>;
currentAgentId: ComputedRef<number>;
currentUser: Ref<Record<string, unknown> | null>;
currentUserDisplayName: ComputedRef<string>;
@@ -57,9 +59,7 @@ export function useChatLeave(options: UseChatLeaveOptions) {
loadHistory,
} = options;
const canUseLeaveFeature = computed(() =>
LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()),
);
const canUseLeaveFeature = computed(() => resolveLeaveFeatureEnabled(currentAgent.value));
const { newLocalMessageId, saveLocalMessageToBackend } = createLeaveLocalMessageApi({
conversationId,
@@ -115,6 +115,8 @@ export function useChatPage() {
createNewChatView,
loadConversationState,
sendMessage,
startChatTurn,
stopActiveGeneration,
} = useChat();
const shippingActionBusy = computed(() => hasActiveRunningChatRun(
isThinking.value,
@@ -284,6 +286,7 @@ export function useChatPage() {
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
startChatTurn,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
loadConversation: (id, opts) => loadConversation(id, opts),
createNewChatView,
@@ -538,6 +541,7 @@ export function useChatPage() {
shouldRenderMessage: markdown.shouldRenderMessage,
canSendMessage: sendApi.canSendMessage,
handleSend: sendApi.handleSend,
stopActiveGeneration,
pushLocalAssistantMessage,
copyToClipboard: sendApi.copyToClipboard,
regenerate: sendApi.regenerate,
@@ -13,14 +13,14 @@ import {
type ComputedRef,
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import { isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
createShippingDecisionHandlers,
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingParseReviewHandlers,
@@ -49,8 +49,8 @@ import {
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
import {
buildShortageDetailsMessage,
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
@@ -62,7 +62,7 @@ import { listChatMessages } from '../api/chat.api';
export interface UseChatShippingOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgent: Ref<AgentRegistryFields | null>;
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
@@ -90,6 +90,7 @@ export interface UseChatShippingOptions {
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
createNewChatView: () => void;
@@ -154,6 +155,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
startChatTurn,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
@@ -165,7 +167,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const isShippingNoticeAgent = computed(() => resolveShippingNoticeAgent(currentAgent.value));
const isShippingActionBusy = computed(() => {
if (shippingActionBusy.value) return true;
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
@@ -525,10 +527,23 @@ export function useChatShipping(options: UseChatShippingOptions) {
getActiveBatchTaskId,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
startChatTurn,
currentAgentId,
refreshShippingActions,
msg,
});
/**
@@ -573,10 +588,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
/**
* 在聊天流中输出确定性的缺口明细。
*
* 核心逻辑:追加一条本地用户意图消息和一条本地助手事实回复,不转发给 Dify,
* 避免大模型复述或重新计算预订单、料号与缺口数量。
* 在聊天流中输出确定性的缺口明细(Chat Turn SSE)。
*/
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
const task = await resolveShippingTaskForShortageQuery(taskNo);
@@ -584,8 +596,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return true;
}
await pushShippingLocalUserMessage(displayText || t('chat.shippingNoticeUi.queryShortageDetails'));
await pushShippingLocalAssistantMessage(buildShortageDetailsMessage(task, t));
const normalizedTaskNo = String(task.task_no || '').trim().toUpperCase();
const turn = buildShippingQueryShortageTurn(
normalizedTaskNo,
displayText || t('chat.shippingNoticeUi.queryShortageDetails'),
);
await startChatTurn({
agentId: currentAgentId.value,
inputType: 'action',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
});
return true;
};
@@ -599,36 +622,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
sendMessage,
});
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
currentAgentId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
loadHistory,
openShippingInventoryMappingFormForTask,
refreshShippingActions,
startChatTurn,
msg,
t,
});
@@ -660,6 +666,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
useShippingSuggestedPrompt,
} = createShippingUploadHandlers({
conversationId,
currentAgentId,
attachments,
input,
shippingAutoFlowRequested,
@@ -676,9 +683,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingInventorySelectionTaskId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
startChatTurn,
refreshShippingActions,
msg,
t,
@@ -686,10 +691,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
currentAgentId,
getActiveShippingTaskId,
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
messages,
newLocalMessageId,
saveLocalMessageToBackend,
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
@@ -697,6 +702,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
startChatTurn,
msg,
t,
});
@@ -723,8 +729,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
buildFileSpecsForSend,
loadHistory,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
startChatTurn,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
@@ -0,0 +1,264 @@
/**
* 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 };
}