| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447 |
- /**
- * 对象关系分析 · AI 研判流式状态机
- *
- * 为什么新写 hook 而不复用 `ai/store/chatStream.ts`:那个 store 是 defineStore **单例**,
- * `workspaceId / sessions / messages` 均为全局态,AI 数据分析页正在使用;
- * 抽屉里再驱动它会把两处消息流搅在一起。这里用独立组合式 hook 持状态,
- * 但**复用** `ai/api/sse` 的解析器与 `ai/utils/parseMessageContent` 的解析函数。
- *
- * 状态:idle → creating(建会话)→ streaming(首轮/追问)→ done
- * ↘ error(模型未配置 / 网络 / 超限 / 409 进行中)
- */
- import { computed, ref, type Ref } from 'vue';
- import * as insightApi from '../api';
- import type { InsightContextVO, InsightCreateParams, InsightMessageVO, InsightSessionVO } from '../types';
- import type { ContentBlock } from '@/ai/utils/scanner';
- import { isInsightPayload } from '@/ai/utils/scanner';
- import type { InsightPayload, ToolStep } from '@/ai/api/types';
- import { RESCAN_THROTTLE_MS } from '@/ai/utils/constants';
- import {
- normalizeToolPayloadText,
- parseThinkingFromMetadata,
- parseToolEvents,
- parseMessageBlocksIncremental,
- } from '@/ai/utils/parseMessageContent';
- /** 消息分页每页条数(与后端 message-page-size 默认值一致) */
- const MESSAGE_PAGE_SIZE = 20;
- /** 抽屉内的消息(含前端渲染态) */
- export interface InsightChatMessage extends InsightMessageVO {
- /** 仅存在于前端(未落库) */
- local?: boolean;
- /** 解析后的富内容块 */
- blocks?: ContentBlock[];
- /** 工具调用步骤(流式期间实时累积;历史消息点开「分析过程」时才拉) */
- toolSteps?: ToolStep[];
- /** 模型思考过程 */
- thinking?: string;
- thinkingActive?: boolean;
- /** 是否正在流式输出 */
- streaming?: boolean;
- /** 结构化产物(首轮 assistant 消息才有) */
- payload?: InsightPayload | null;
- /** trace 是否已按需拉取过 */
- traceLoaded?: boolean;
- }
- /** 本地临时消息 ID(负数,与后端雪花 ID 的字符串形态区分开) */
- let tempIdSeed = -1;
- function nextTempId() {
- return String(tempIdSeed--);
- }
- /** 从内容块里取出第一个合法的 insight 载荷(结构化产物的唯一来源) */
- function pickInsightPayload(blocks: ContentBlock[]): InsightPayload | null {
- for (const block of blocks) {
- if (block.kind === 'insight' && isInsightPayload(block.data)) return block.data as InsightPayload;
- }
- return null;
- }
- export function useInsightStream(caseId: Ref<string>) {
- /** 当前会话ID(字符串,禁止 Number 转换) */
- const sessionId = ref<string | null>(null);
- /** 当前会话(含上下文摘要) */
- const session = ref<InsightSessionVO | null>(null);
- /** 上下文摘要(ContextBar 用) */
- const context = ref<InsightContextVO | null>(null);
- /** 消息(按 seq 升序) */
- const messages = ref<InsightChatMessage[]>([]);
- const creating = ref(false);
- const streaming = ref(false);
- const loadingMessages = ref(false);
- const loadingMore = ref(false);
- const loadMoreFailed = ref(false);
- const error = ref('');
- /** 分页水位(page=1 是最新一页) */
- const page = ref(1);
- const pages = ref(1);
- const total = ref(0);
- let abortController: AbortController | null = null;
- let rescanTimer: ReturnType<typeof setTimeout> | null = null;
- /* ---------------------------------------------------------------- *
- * 派生状态
- * ---------------------------------------------------------------- */
- /** 首轮分析消息(报告区渲染它,不进追问对话流) */
- const reportMessage = computed<InsightChatMessage | null>(
- () => messages.value.find((m) => m.messageType === 'first_round') || null,
- );
- /** 追问对话(用户提问 + 模型回答) */
- const followupMessages = computed(() => messages.value.filter((m) => m.messageType !== 'first_round'));
- /**
- * 结构化产物。
- *
- * 流式过程中来自 `insight` 帧(先于 done 下发,卡片能提前渲染);
- * 刷新 / 打开历史会话时,由 hydrate 从正文的 ```insight 围栏解析得到
- * (列表接口刻意不下发 output_json,避免大字段进列表)。
- */
- const payload = computed<InsightPayload | null>(() => reportMessage.value?.payload ?? null);
- /* ---------------------------------------------------------------- *
- * 内部工具
- * ---------------------------------------------------------------- */
- function clearRescanTimer() {
- if (rescanTimer) {
- clearTimeout(rescanTimer);
- rescanTimer = null;
- }
- }
- /** 服务端消息 → 前端渲染态 */
- function hydrate(message: InsightMessageVO): InsightChatMessage {
- const blocks = parseMessageBlocksIncremental(undefined, message.content || '').blocks;
- return {
- ...message,
- blocks,
- toolSteps: [],
- thinking: parseThinkingFromMetadata(message.metadata),
- payload: pickInsightPayload(blocks),
- };
- }
- /** 拉第 N 页消息(ORDER BY seq DESC),reverse 后 unshift 到头部 */
- async function loadPage(target: number) {
- const id = sessionId.value;
- const cid = caseId.value;
- if (!id || !cid) return 0;
- const resp = await insightApi.listInsightMessages(id, cid, target, MESSAGE_PAGE_SIZE);
- const records = Array.isArray(resp?.records) ? resp.records : [];
- // 服务端给的是 seq 降序,前端列表要升序
- const ordered = [...records].reverse().map(hydrate);
- if (target === 1) {
- messages.value = ordered;
- } else {
- // 按 id 去重兜底:页码分页在消息持续追加时可能出现「同一条出现在两页」
- const seen = new Set(messages.value.map((m) => m.id));
- messages.value = [...ordered.filter((m) => !seen.has(m.id)), ...messages.value];
- }
- page.value = Number(resp?.current) || target;
- pages.value = Number(resp?.pages) || 1;
- total.value = Number(resp?.total) || 0;
- return ordered.length;
- }
- /** 上滑加载更早的消息(滚动位置补偿由列表组件负责) */
- async function loadMore() {
- if (loadingMore.value || loadingMessages.value) return 0;
- if (page.value >= pages.value) return 0;
- loadingMore.value = true;
- loadMoreFailed.value = false;
- try {
- return await loadPage(page.value + 1);
- } catch (e: any) {
- // 失败不回退 page、不重置列表,列表底部给「点击重试」
- loadMoreFailed.value = true;
- return 0;
- } finally {
- loadingMore.value = false;
- }
- }
- /** 按需拉取单条消息的执行明细(工具调用 + 思考过程) */
- async function ensureTrace(message: InsightChatMessage) {
- if (message.traceLoaded || message.local || !caseId.value) return;
- try {
- const trace = await insightApi.getInsightMessageTrace(message.id, caseId.value);
- message.toolSteps = parseToolEvents(trace?.toolEvents);
- const thinking = parseThinkingFromMetadata(trace?.metadata);
- if (thinking) message.thinking = thinking;
- message.traceLoaded = true;
- } catch {
- // 明细拉取失败不影响报告主体,保持原状即可
- message.traceLoaded = true;
- }
- }
- /**
- * 跑一轮流式。
- *
- * @param userText 追问内容;首轮传空串(服务端注入固定首轮指令)
- */
- async function runStream(userText: string) {
- const id = sessionId.value;
- const cid = caseId.value;
- if (!id || !cid) return;
- const firstRound = !userText;
- if (!firstRound) {
- messages.value = [
- ...messages.value,
- {
- id: nextTempId(),
- sessionId: id,
- seq: Number.MAX_SAFE_INTEGER - 1,
- role: 'user',
- content: userText,
- messageType: 'followup',
- local: true,
- createAt: new Date().toISOString(),
- } as InsightChatMessage,
- ];
- }
- const target: InsightChatMessage = {
- id: nextTempId(),
- sessionId: id,
- seq: Number.MAX_SAFE_INTEGER,
- role: 'assistant',
- content: '',
- messageType: firstRound ? 'first_round' : 'chat',
- local: true,
- streaming: true,
- blocks: [],
- toolSteps: [],
- createAt: new Date().toISOString(),
- };
- messages.value = [...messages.value, target];
- streaming.value = true;
- error.value = '';
- abortController = new AbortController();
- const rescan = () => {
- const res = parseMessageBlocksIncremental(target.blocks, target.content);
- target.blocks = res.blocks;
- // 围栏闭合后即可拿到结构化产物(不依赖 SSE 的 insight 帧)
- const fromBlocks = pickInsightPayload(res.blocks);
- if (fromBlocks) target.payload = fromBlocks;
- };
- const scheduleRescan = () => {
- if (rescanTimer) return;
- rescanTimer = setTimeout(() => {
- rescanTimer = null;
- rescan();
- }, RESCAN_THROTTLE_MS);
- };
- try {
- await insightApi.streamInsight(
- { sessionId: id, caseId: cid, message: firstRound ? undefined : userText },
- {
- onThinking: (data) => {
- if (data.phase === 'start') {
- if (target.thinking) target.thinking += '\n\n';
- target.thinkingActive = true;
- return;
- }
- if (data.phase === 'end') {
- target.thinkingActive = false;
- return;
- }
- const delta = data.data || '';
- if (!delta) return;
- target.thinking = (target.thinking || '') + delta;
- target.thinkingActive = true;
- },
- onToolCall: (data) => {
- target.toolSteps = [
- ...(target.toolSteps || []),
- { id: data.toolCallId, toolName: data.toolName, status: 'running' },
- ];
- },
- onToolInput: (data) => {
- const step = target.toolSteps?.find((s) => s.id === data.toolCallId);
- if (step) step.input = normalizeToolPayloadText(data.toolInput || '');
- },
- onToolResult: (data) => {
- const step = target.toolSteps?.find((s) => s.id === data.toolCallId);
- if (step) {
- step.result = normalizeToolPayloadText(data.toolResult || '');
- step.status = 'done';
- if (!step.toolName && data.toolName) step.toolName = data.toolName;
- }
- },
- onInsight: (data) => {
- if (isInsightPayload(data?.data)) target.payload = data.data as InsightPayload;
- },
- onToken: (data) => {
- target.content += data.data || '';
- scheduleRescan();
- },
- onError: (data) => {
- error.value = data.error || '请求失败';
- target.content = target.content || `⚠️ ${error.value}`;
- },
- onTransportError: (err) => {
- error.value = (err as Error)?.message || String(err);
- target.content = target.content || `⚠️ 网络异常:${error.value}`;
- },
- },
- abortController.signal,
- );
- } catch (err: any) {
- if (err?.name !== 'AbortError') {
- error.value = err?.message || '请求失败';
- target.content = target.content || `⚠️ ${error.value}`;
- } else {
- target.content = target.content || '(已停止生成)';
- }
- } finally {
- clearRescanTimer();
- rescan();
- target.streaming = false;
- target.thinkingActive = false;
- streaming.value = false;
- abortController = null;
- }
- }
- /* ---------------------------------------------------------------- *
- * 对外动作
- * ---------------------------------------------------------------- */
- /**
- * 新建会话并立刻开跑首轮分析(打开抽屉即分析,用户不用敲字)。
- *
- * @param buildParams 上下文组装函数(由 useInsightContext 提供)
- * @param topN 研判规模
- */
- async function start(buildParams: (caseId: string, topN: number) => InsightCreateParams, topN: number) {
- const cid = caseId.value;
- if (!cid || creating.value || streaming.value) return;
- creating.value = true;
- error.value = '';
- try {
- const created = await insightApi.createInsightSession(buildParams(cid, topN));
- sessionId.value = created.id;
- session.value = created;
- context.value = created.context || null;
- messages.value = [];
- page.value = 1;
- pages.value = 1;
- total.value = 0;
- await runStream('');
- } catch (e: any) {
- error.value = e?.message || '创建研判会话失败';
- throw e;
- } finally {
- creating.value = false;
- }
- }
- /** 打开历史会话 */
- async function openSession(id: string) {
- const cid = caseId.value;
- if (!cid) return;
- stop();
- loadingMessages.value = true;
- error.value = '';
- try {
- const detail = await insightApi.getInsightSession(id, cid);
- sessionId.value = detail.id;
- session.value = detail;
- context.value = detail.context || null;
- page.value = 1;
- pages.value = 1;
- await loadPage(1);
- } catch (e: any) {
- error.value = e?.message || '加载会话失败';
- } finally {
- loadingMessages.value = false;
- }
- }
- /** 追问(同一会话) */
- async function followup(text: string) {
- const content = (text || '').trim();
- if (!content || streaming.value || !sessionId.value) return;
- await runStream(content);
- }
- /** 中止当前流 */
- function stop() {
- clearRescanTimer();
- if (abortController) {
- abortController.abort();
- abortController = null;
- }
- streaming.value = false;
- const last = messages.value[messages.value.length - 1];
- if (last?.streaming) {
- last.streaming = false;
- last.thinkingActive = false;
- if (!last.content) last.content = '(已停止生成)';
- }
- }
- /** 重置(关闭抽屉 / 切换案件时调用,防泄漏) */
- function reset() {
- stop();
- sessionId.value = null;
- session.value = null;
- context.value = null;
- messages.value = [];
- page.value = 1;
- pages.value = 1;
- total.value = 0;
- loadingMore.value = false;
- loadMoreFailed.value = false;
- error.value = '';
- }
- /** 删除会话 */
- async function remove(id: string) {
- const cid = caseId.value;
- if (!cid) return;
- await insightApi.deleteInsightSession(id, cid);
- if (sessionId.value === id) reset();
- }
- return {
- // 状态
- sessionId,
- session,
- context,
- messages,
- reportMessage,
- followupMessages,
- payload,
- creating,
- streaming,
- loadingMessages,
- loadingMore,
- loadMoreFailed,
- error,
- page,
- pages,
- total,
- // 动作
- start,
- openSession,
- followup,
- stop,
- reset,
- remove,
- loadMore,
- ensureTrace,
- };
- }
|