"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useI18n } from "@/i18n/i18n-context"; import { streamChat } from "@/services/llm-chat"; import { FILEMEM_DEFAULT_RUN_ID } from "@/lib/memory-storage-mode"; import { newId } from "@/lib/random-id"; import { devFlag } from "@/lib/dev-flags"; import { clampWikiEvidence, clampWikiRetrievalError, clampWikiRetrievalGroup, MAX_WIKI_ERRORS, MAX_WIKI_EVIDENCE, MAX_WIKI_GROUPS, MAX_WIKI_SOURCES, normalizeRequiredWikiMetadata, } from "@/lib/wiki-metadata-limits"; import { removeAt, removePair, truncateUpToAndIncluding, } from "@/lib/chat-message-ops"; import type { ChatMessage, ChatRequestBody, ChatRole } from "@/types/llm-chat"; import type { WikiEvidence, WikiRetrievalError, WikiRetrievalGroup, } from "@/types/llm-chat"; /** * Token deltas can arrive faster than React can profitably re-render * (especially on long answers — every keystroke previously diffed the full * messages array). We buffer per-message string appends and flush them on * the next animation frame so the UI updates at most ~60fps regardless of * SSE chunk frequency. The terminal `done` / `error` events flush * synchronously to avoid losing the tail. */ type StreamPatch = { content?: string; reasoning?: string }; /** Remove a curation state that never received a terminal server event. */ export function settlePendingMemorySave( messages: ChatMessage[], assistantId: string, ): ChatMessage[] { let changed = false; const settled = messages.map((message) => { if (message.id !== assistantId || message.memorySaveStatus !== "saving") { return message; } changed = true; const next = { ...message }; delete next.memorySaveStatus; delete next.memorySavePath; delete next.memorySaveCount; delete next.memorySaveError; return next; }); return changed ? settled : messages; } export interface UseQaChatOptions { dataScopeKey: string; activeInstance: string | null; providerId: string; model: string; systemPrompt: string; temperature?: number; rag?: ChatRequestBody["rag"]; /** 绑定的记忆库写 scope(完整四字段)。undefined ⇒ 该轮不开启记忆。 */ memory?: ChatRequestBody["memory"]; /** 当前 Memory store/scope 下选中的 Wiki。undefined ⇒ 该轮不开启 Wiki 检索。 */ wiki?: ChatRequestBody["wiki"]; /** * Invoked after each streaming turn settles (done / error / abort) with the * final message list. The chat homepage uses this to upsert the session * snapshot into localStorage without coupling persistence to the hook. */ onPersist?: (messages: ChatMessage[]) => void; } function normalizeMemoryForRequest( memory: ChatRequestBody["memory"], ): ChatRequestBody["memory"] { if (!memory) return undefined; const snapshot = { ...memory, scope: { appId: memory.scope.appId, tenantId: memory.scope.tenantId, agentId: memory.scope.agentId, runId: memory.scope.runId, }, }; if (snapshot.storageMode !== "filemem") return snapshot; return { ...snapshot, scope: { ...snapshot.scope, runId: FILEMEM_DEFAULT_RUN_ID }, retrievalMode: "local", }; } function snapshotWikiBinding( wiki: ChatRequestBody["wiki"], ): ChatRequestBody["wiki"] { if (!wiki) return undefined; return { memoryStoreName: wiki.memoryStoreName, scope: { appId: wiki.scope.appId, tenantId: wiki.scope.tenantId, agentId: wiki.scope.agentId, runId: wiki.scope.runId, }, topK: wiki.topK, }; } function memoryWikiIdentityMatches( memory: ChatRequestBody["memory"], wiki: ChatRequestBody["wiki"], ): boolean { if (!memory || !wiki) return false; return ( memory.memoryStoreName === wiki.memoryStoreName && memory.scope.appId === wiki.scope.appId && memory.scope.tenantId === wiki.scope.tenantId && memory.scope.agentId === wiki.scope.agentId && memory.scope.runId === wiki.scope.runId ); } function snapshotRequestBindings( rawMemory: ChatRequestBody["memory"], rawWiki: ChatRequestBody["wiki"], ) { const rawIdentityMatches = memoryWikiIdentityMatches(rawMemory, rawWiki); const normalizedMemory = normalizeMemoryForRequest(rawMemory); const rawMemorySnapshot = rawMemory ? { ...rawMemory, scope: { appId: rawMemory.scope.appId, tenantId: rawMemory.scope.tenantId, agentId: rawMemory.scope.agentId, runId: rawMemory.scope.runId, }, } : undefined; const wireMemory = rawMemory?.storageMode === "filemem" && rawWiki && !rawIdentityMatches ? rawMemorySnapshot : normalizedMemory; const wikiSnapshot = snapshotWikiBinding(rawWiki); const wireWiki = wikiSnapshot && normalizedMemory?.storageMode === "filemem" && rawIdentityMatches ? { ...wikiSnapshot, memoryStoreName: normalizedMemory.memoryStoreName, scope: { appId: normalizedMemory.scope.appId, tenantId: normalizedMemory.scope.tenantId, agentId: normalizedMemory.scope.agentId, runId: normalizedMemory.scope.runId, }, } : wikiSnapshot; return { normalizedMemory, wireMemory, wireWiki }; } function composeChatRequestBody( opts: Pick< UseQaChatOptions, | "activeInstance" | "providerId" | "model" | "systemPrompt" | "temperature" | "rag" >, historyToSend: Array<{ role: ChatRole; content: string }>, turnId: string, memory: ChatRequestBody["memory"], wiki: ChatRequestBody["wiki"], ): ChatRequestBody { const memoryWithTurn = memory ? { ...memory, turnId } : undefined; return { activeInstance: opts.activeInstance, providerId: opts.providerId, model: opts.model, messages: historyToSend, systemPrompt: opts.systemPrompt, temperature: opts.temperature, rag: opts.rag, ...(memoryWithTurn ? { memory: memoryWithTurn } : {}), ...(wiki ? { wiki } : {}), }; } /** * Compose the wire body sent to `/api/v1/llm/chat` for one turn. Pulled out * of `_runAssistantTurn` so it can be unit-tested without spinning up React * (the dashboard's vitest config runs in node env, so renderHook is not * available). The function MUST stay pure — no refs, no state, no closures * over hook-local mutables. */ export function buildChatRequestBody( opts: Pick< UseQaChatOptions, | "activeInstance" | "providerId" | "model" | "systemPrompt" | "temperature" | "rag" | "memory" | "wiki" >, historyToSend: Array<{ role: ChatRole; content: string }>, turnId: string, ): ChatRequestBody { const { wireMemory, wireWiki } = snapshotRequestBindings( opts.memory, opts.wiki, ); return composeChatRequestBody( opts, historyToSend, turnId, wireMemory, wireWiki, ); } type PrepareChatRequestOptions = Pick< UseQaChatOptions, | "dataScopeKey" | "activeInstance" | "providerId" | "model" | "systemPrompt" | "temperature" | "rag" | "memory" | "wiki" >; function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } function sanitizeStreamWikiEvidence(raw: unknown): WikiEvidence | null { if (!isRecord(raw)) return null; const value = raw; const wikiName = normalizeRequiredWikiMetadata(value.wikiName); const path = normalizeRequiredWikiMetadata(value.path); if ( typeof value.reference !== "string" || !/^W[1-6]$/.test(value.reference) || !wikiName || !path || typeof value.truncated !== "boolean" || !Number.isInteger(value.injectedChars) || (value.injectedChars as number) < 0 || (value.injectedChars as number) > 8_000 ) { return null; } return clampWikiEvidence({ reference: value.reference as `W${number}`, wikiName, path, ...(typeof value.title === "string" ? { title: value.title } : {}), ...(typeof value.type === "string" ? { type: value.type } : {}), ...(typeof value.description === "string" ? { description: value.description } : {}), ...(typeof value.score === "number" && Number.isFinite(value.score) ? { score: value.score } : {}), ...(Array.isArray(value.sources) ? { sources: value.sources .slice(0, MAX_WIKI_SOURCES) .filter((source): source is string => typeof source === "string"), } : {}), truncated: value.truncated, injectedChars: value.injectedChars as number, }); } function sanitizeStreamWikiError(raw: unknown): WikiRetrievalError | null { if (!isRecord(raw)) return null; const value = raw; const code = normalizeRequiredWikiMetadata(value.code); const message = normalizeRequiredWikiMetadata(value.message); if ( !code || !message || (value.stage !== "validate" && value.stage !== "search" && value.stage !== "read" && value.stage !== "budget") ) { return null; } return clampWikiRetrievalError({ code, message, ...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}), ...(typeof value.httpStatus === "number" && Number.isFinite(value.httpStatus) && Number.isInteger(value.httpStatus) ? { httpStatus: value.httpStatus } : {}), stage: value.stage, ...(typeof value.path === "string" ? { path: value.path } : {}), }); } function sanitizeStreamWikiGroup(raw: unknown): WikiRetrievalGroup | null { if (!isRecord(raw)) return null; const value = raw; const wikiName = normalizeRequiredWikiMetadata(value.wikiName); if (!wikiName || !Array.isArray(value.pages)) { return null; } return clampWikiRetrievalGroup({ wikiName, pages: value.pages .slice(0, MAX_WIKI_EVIDENCE) .map(sanitizeStreamWikiEvidence) .filter((page): page is WikiEvidence => page !== null), ...(Array.isArray(value.errors) ? { errors: value.errors .slice(0, MAX_WIKI_ERRORS) .map(sanitizeStreamWikiError) .filter((error): error is WikiRetrievalError => error !== null), } : {}), }); } function sanitizeWikiStartPatch(raw: unknown): Partial | null { if ( !isRecord(raw) || raw.type !== "wiki.start" || typeof raw.query !== "string" || !Number.isInteger(raw.wikiCount) || (raw.wikiCount as number) < 1 || (raw.wikiCount as number) > 10 ) { return null; } // Request validation enables exactly one scope-owned Wiki, so zero is not a // legal runtime count even though it would be harmless as display metadata. return { wikiQuery: raw.query, wikiCount: raw.wikiCount as number, wikiRetrievalDone: false, }; } function sanitizeWikiDonePatch( raw: unknown, wikiBinding: ChatRequestBody["wiki"], ): Partial | null { if ( !isRecord(raw) || raw.type !== "wiki.done" || typeof raw.query !== "string" || !Number.isInteger(raw.totalContextChars) || (raw.totalContextChars as number) < 0 || (raw.totalContextChars as number) > 24_000 || !Array.isArray(raw.pages) || !Array.isArray(raw.byWiki) ) { return null; } return { wikiQuery: raw.query, wikiRetrievalDone: true, wikiEvidence: raw.pages .slice(0, MAX_WIKI_EVIDENCE) .map(sanitizeStreamWikiEvidence) .filter((page): page is WikiEvidence => page !== null), wikiRetrievalGroups: raw.byWiki .slice(0, MAX_WIKI_GROUPS) .map(sanitizeStreamWikiGroup) .filter((group): group is WikiRetrievalGroup => group !== null), wikiTotalContextChars: raw.totalContextChars as number, ...(wikiBinding ? { wikiMemoryStoreName: wikiBinding.memoryStoreName, wikiScope: { appId: wikiBinding.scope.appId, tenantId: wikiBinding.scope.tenantId, agentId: wikiBinding.scope.agentId, runId: wikiBinding.scope.runId, }, } : {}), }; } /** Snapshot bindings immediately before opening the SSE. */ export async function prepareChatRequestBody( opts: PrepareChatRequestOptions, historyToSend: Array<{ role: ChatRole; content: string }>, turnId: string, _deps: { loadFileMemory?: unknown; searchFileMemory?: unknown; } = {}, ): Promise { const { wireMemory, wireWiki } = snapshotRequestBindings( opts.memory, opts.wiki, ); return composeChatRequestBody( opts, historyToSend, turnId, wireMemory, wireWiki, ); } export interface UseQaChatResult { messages: ChatMessage[]; isStreaming: boolean; error: string | null; send(userInput: string): Promise; /** Truncate to and including the given user message, then re-run the * assistant pipeline. Powers resend / regenerate / edit-and-resend. */ reissueTurn(anchorUserId: string): Promise; /** Remove a message by id. When the target is a user message and * `withNextAssistant` is true, the immediately-following assistant * message (if any) is removed too. Persists immediately. */ deleteMessage(id: string, opts?: { withNextAssistant?: boolean }): void; /** Rewrite the content of a user message in place. Returns the message * id on success so the caller can chain `reissueTurn(id)` for the * edit-and-resend flow, or null if the id wasn't a user message. */ editUserMessage(id: string, nextContent: string): string | null; stop(): void; clear(): void; /** Replace the entire message list, e.g. when switching sessions. */ setMessages(messages: ChatMessage[]): void; } /** * QA chat state machine. * * Responsibilities: * - Maintain the in-memory message list. * - Stream assistant replies (content + reasoning) via SSE. * - Expose an abort signal the UI can trigger from a stop button. * * Intentionally NOT handled here: * - Token-based history trimming (the server applies a simple tail cut). * - Persistence (sessions are transient; user can clear at any time). */ export function useQaChat(options: UseQaChatOptions): UseQaChatResult { const { t } = useI18n(); const tRef = useRef(t); tRef.current = t; const [messages, setMessages] = useState([]); const [isStreaming, setIsStreaming] = useState(false); const [error, setError] = useState(null); const abortRef = useRef(null); // Keep the freshest persist callback in a ref so the streaming closure in // `send` always calls the current handler, even if the caller memoizes it // lazily. const onPersistRef = useRef(options.onPersist); onPersistRef.current = options.onPersist; // Mirror the live message list and options into refs so `send` does not // need them in its useCallback deps. Without this, every token delta // (which calls setMessages) would rebuild `send`, invalidating any child // memo that depends on it. const messagesRef = useRef(messages); messagesRef.current = messages; const optionsRef = useRef(options); optionsRef.current = options; const isStreamingRef = useRef(isStreaming); isStreamingRef.current = isStreaming; // rAF-coalesced delta buffer: maps message id → pending appends. The // scheduled frame drains the buffer in a single setMessages pass. const pendingDeltasRef = useRef>(new Map()); const rafIdRef = useRef(null); const flushDeltas = useCallback(() => { rafIdRef.current = null; const pending = pendingDeltasRef.current; if (pending.size === 0) return; const snapshot = new Map(pending); pending.clear(); const nextMessages = messagesRef.current.map((m) => { const patch = snapshot.get(m.id); if (!patch) return m; return { ...m, ...(patch.content ? { content: m.content + patch.content } : null), ...(patch.reasoning ? { reasoning: (m.reasoning ?? "") + patch.reasoning } : null), }; }); messagesRef.current = nextMessages; setMessages(nextMessages); }, []); const scheduleFlush = useCallback(() => { if (rafIdRef.current !== null) return; if (typeof requestAnimationFrame === "undefined") { // SSR / test environments without rAF — flush synchronously so the // hook stays observable in jsdom-based tests. flushDeltas(); return; } rafIdRef.current = requestAnimationFrame(flushDeltas); }, [flushDeltas]); const cancelScheduledFlush = useCallback(() => { if ( rafIdRef.current !== null && typeof cancelAnimationFrame !== "undefined" ) { cancelAnimationFrame(rafIdRef.current); } rafIdRef.current = null; }, []); // Drop any pending frame when the hook unmounts so we never call // setMessages on an unmounted React tree. useEffect(() => { return cancelScheduledFlush; }, [cancelScheduledFlush]); const stop = useCallback(() => { abortRef.current?.abort(); }, []); const clear = useCallback(() => { abortRef.current?.abort(); // Sync the ref before triggering the async setMessages so a `send` that // happens to land in the same JS task — between this call and React's // next commit — sees an empty history instead of the previous session's // messages. The render-body assignment below catches the steady state; // this assignment closes the in-flight window. messagesRef.current = []; setMessages([]); setError(null); }, []); const replaceMessages = useCallback((next: ChatMessage[]) => { abortRef.current?.abort(); // Same race-window guard as in `clear` — see the comment there. messagesRef.current = next; setMessages(next); setError(null); }, []); /** * Internal: run one assistant turn against an already-prepared message * list. Shared between `send` (which prepends a fresh user+assistant * placeholder) and `reissueTurn` (which truncates and re-anchors on an * existing user message). * * Pre-conditions: * - `assistantId` matches a message in the current list (the placeholder) * - `historyToSend` is the exact wire payload, already trimmed * - the caller has already set isStreaming = true and abortRef */ const _runAssistantTurn = useCallback( async ( assistantId: string, historyToSend: Array<{ role: ChatRole; content: string }>, turnId: string, ) => { const opts = optionsRef.current; const wikiBinding = snapshotWikiBinding(opts.wiki); const controller = new AbortController(); abortRef.current = controller; // Per-turn one-shot latches for the reasoning timing stamps. Refs // (not state) because we observe them from inside the streaming loop // closure — re-rendering on every flip would defeat the rAF batching // that keeps token streaming at 60fps. const reasoningStartedRef = { current: false }; const reasoningCompletedRef = { current: false }; const updateAssistant = (patch: Partial) => { const nextMessages = messagesRef.current.map((m) => m.id === assistantId ? { ...m, ...patch } : m, ); messagesRef.current = nextMessages; setMessages(nextMessages); }; try { const body = await prepareChatRequestBody(opts, historyToSend, turnId); if (devFlag("logChatRequest")) { // Diagnostic surface for the cross-session bleed investigation. // Off by default; enable via // localStorage.setItem("tsagent.dev.logChatRequest","1") // in the browser devtools console. console.groupCollapsed("[chat] outgoing turn"); console.log("assistantId", assistantId); console.log("messages", historyToSend); console.log("rag.knowledgeBases", opts.rag?.knowledgeBases); console.groupEnd(); } for await (const event of streamChat(body, controller.signal)) { if (!isRecord(event)) continue; if (event.type === "query.rewritten") { updateAssistant({ retrievalQuery: event.query, retrievalQueryRewritten: event.query !== event.original, }); } else if (event.type === "query.fallback") { // Rewriter failed; record the failure so the UI can surface a // non-blocking warning chip while the pipeline continues with // the original query. updateAssistant({ retrievalQuery: event.original, retrievalQueryRewritten: false, queryRewriteFailed: true, queryRewriteError: event.reason, }); } else if (event.type === "retrieval.done") { updateAssistant({ retrievedChunks: event.chunks, retrievalGroups: event.byKnowledgeBase, }); } else if (event.type === "wiki.start") { const patch = sanitizeWikiStartPatch(event); if (patch) updateAssistant(patch); } else if (event.type === "wiki.done") { const patch = sanitizeWikiDonePatch(event, wikiBinding); if (patch) updateAssistant(patch); } else if (event.type === "memory.start") { // 把服务端真正发起的 SearchMemories query 落到当前 message 上: // - chunks 命中时,服务端复用 rewriter 重写后的 query; // - chunks 为空时,回退到原始用户输入。 // 渲染层把它放在「参考 N 条记忆」触发栏的副标题位置,便于 // 用户/调试者一眼看出「服务端到底拿什么去搜的记忆」。 updateAssistant({ memoryQuery: event.query }); } else if (event.type === "memory.done") { // 永远写一次,即便是空数组——零命中由 MemoryHitsBlock 内部 // 的 `length > 0` 守卫吞掉,不在 hook 这层做条件分支,避免 // 「想看为什么没召回」时 message 上没有信号可查。 updateAssistant({ memoryHits: event.hits }); } else if (event.type === "memory.files") { // 文件记忆模式专属:把 Chat BFF 返回的文件树与有界缓存统计 // 落到 assistant message 上,供气泡展示「本轮文件记忆」摘要。 updateAssistant({ memoryFiles: event.files, memoryFilesCache: event.cache, memoryFilesStoreName: event.memoryStoreName, memoryFilesWritable: event.writable, memoryFilesScope: event.scope, }); } else if (event.type === "memory.save.start") { updateAssistant({ memorySaveStatus: "saving", memorySavePath: undefined, memorySaveCount: undefined, memorySaveError: undefined, }); } else if (event.type === "memory.save.done") { updateAssistant({ memorySaveStatus: event.status, memorySavePath: event.path, memorySaveCount: event.count, memorySaveError: undefined, }); } else if (event.type === "memory.save.skipped") { updateAssistant({ memorySaveStatus: "error", memorySaveError: event.reason, }); // 写回失败不打断对话流,同时保留控制台诊断。 console.warn("[chat] memory.save.skipped:", event.reason); } else if (event.type === "reasoning.delta") { const buf = pendingDeltasRef.current.get(assistantId) ?? {}; buf.reasoning = (buf.reasoning ?? "") + event.delta; pendingDeltasRef.current.set(assistantId, buf); if (!reasoningStartedRef.current) { reasoningStartedRef.current = true; updateAssistant({ reasoningStartedAt: Date.now() }); } scheduleFlush(); } else if (event.type === "content.delta") { const buf = pendingDeltasRef.current.get(assistantId) ?? {}; buf.content = (buf.content ?? "") + event.delta; pendingDeltasRef.current.set(assistantId, buf); if (reasoningStartedRef.current && !reasoningCompletedRef.current) { reasoningCompletedRef.current = true; updateAssistant({ reasoningCompletedAt: Date.now() }); } scheduleFlush(); } else if (event.type === "error") { cancelScheduledFlush(); flushDeltas(); const patch: Partial = { status: "error", errorMessage: `${event.code}: ${event.message}`, }; if (reasoningStartedRef.current && !reasoningCompletedRef.current) { patch.reasoningCompletedAt = Date.now(); } updateAssistant(patch); setError(event.message); break; } else if (event.type === "done") { cancelScheduledFlush(); flushDeltas(); const patch: Partial = { status: "done" }; if (reasoningStartedRef.current && !reasoningCompletedRef.current) { patch.reasoningCompletedAt = Date.now(); } updateAssistant(patch); break; } } } catch (err) { // AbortError is expected when the user clicks "stop" or starts a new // turn; do not treat it as a hard failure. Either way drain buffered // deltas so any partial answer is preserved. cancelScheduledFlush(); flushDeltas(); const isAbort = err instanceof DOMException && err.name === "AbortError"; const closeReasoning = reasoningStartedRef.current && !reasoningCompletedRef.current ? { reasoningCompletedAt: Date.now() } : undefined; if (!isAbort) { const message = err instanceof Error ? err.message : String(err); updateAssistant({ status: "error", errorMessage: message, ...closeReasoning, }); setError(message); } else { updateAssistant({ status: "done", ...closeReasoning }); } } finally { cancelScheduledFlush(); flushDeltas(); const settledMessages = settlePendingMemorySave( messagesRef.current, assistantId, ); messagesRef.current = settledMessages; setMessages(settledMessages); setIsStreaming(false); abortRef.current = null; // Flush the latest snapshot to the persist handler. // Use messagesRef directly instead of a setMessages updater to avoid // calling side effects during React's render phase. const persist = onPersistRef.current; if (persist) { persist(settledMessages); } } }, [scheduleFlush, flushDeltas, cancelScheduledFlush], ); const send = useCallback( async (userInput: string) => { const trimmed = userInput.trim(); if (!trimmed || isStreamingRef.current) return; const opts = optionsRef.current; if (!opts.providerId || !opts.model) { setError(tRef.current("qa.form.selectModelFirst")); return; } setError(null); const turnId = newId("turn"); const userMsg: ChatMessage = { id: newId(), role: "user", content: trimmed, createdAt: Date.now(), status: "done", turnId, }; const assistantId = newId(); // Snapshot whether this turn is RAG-enabled. The pill uses this to pick // pre-stream labels (intent extraction → retrieval → thinking) instead // of a single generic "正在思考" that sits unchanged for several // seconds while the server runs the rewriter and KB queries. const usingRag = (opts.rag?.knowledgeBases?.length ?? 0) > 0 || Boolean(opts.wiki); const assistantMsg: ChatMessage = { id: assistantId, role: "assistant", content: "", reasoning: "", createdAt: Date.now(), status: "streaming", usingRag, }; // Capture the history to send BEFORE inserting the placeholder so we // don't include an empty assistant turn in the request payload. const historyToSend = [...messagesRef.current, userMsg].map((m) => ({ role: m.role, content: m.content, })); // Sync the ref alongside setMessages so a follow-up reissueTurn or a // racing read sees the new state immediately, not on the next commit. const nextMessages = [...messagesRef.current, userMsg, assistantMsg]; messagesRef.current = nextMessages; setMessages(nextMessages); setIsStreaming(true); await _runAssistantTurn(assistantId, historyToSend, turnId); }, [_runAssistantTurn], ); /** * Truncate to and including `anchorUserId`, then re-run the assistant * pipeline against that user message. Powers UI-level「重新发送」、 *「重新生成」、「编辑后保存」 — the editing path mutates the anchor's * content via `editUserMessage` first and then calls this. * * No-op if streaming is already in flight, the anchor is missing, or * the anchor isn't a user message. */ const reissueTurn = useCallback( async (anchorUserId: string) => { if (isStreamingRef.current) return; const opts = optionsRef.current; if (!opts.providerId || !opts.model) { setError(tRef.current("qa.form.selectModelFirst")); return; } const truncated = truncateUpToAndIncluding( messagesRef.current, anchorUserId, ); const anchor = truncated[truncated.length - 1]; if (!anchor || anchor.role !== "user") return; // 复用 anchor 用户消息原有的 turnId;老消息(Task 10 之前持久化的) // 没有 turnId 时退回新生成。把新生成的 turnId 回写到 anchor 上, // 这样后续再次 reissueTurn 仍能复用同一个值(避免每次重发都触发新写入)。 const turnId = anchor.turnId ?? newId("turn"); if (!anchor.turnId) { const idx = truncated.length - 1; truncated[idx] = { ...anchor, turnId }; } setError(null); const assistantId = newId(); const usingRag = (opts.rag?.knowledgeBases?.length ?? 0) > 0 || Boolean(opts.wiki); const assistantMsg: ChatMessage = { id: assistantId, role: "assistant", content: "", reasoning: "", createdAt: Date.now(), status: "streaming", usingRag, }; const historyToSend = truncated.map((m) => ({ role: m.role, content: m.content, })); const nextMessages = [...truncated, assistantMsg]; messagesRef.current = nextMessages; setMessages(nextMessages); setIsStreaming(true); await _runAssistantTurn(assistantId, historyToSend, turnId); }, [_runAssistantTurn], ); /** * Remove a single message by id. When `withNextAssistant` is true and the * target is a user message immediately followed by an assistant message, * remove that assistant too (the "paired delete" semantic from the spec). * * Persists immediately via the registered onPersist callback — pure * deletes don't trigger a streaming turn so we cannot rely on the * `finally` block in `_runAssistantTurn` to write to localStorage. */ const deleteMessage = useCallback( (id: string, opts?: { withNextAssistant?: boolean }) => { if (isStreamingRef.current) return; const list = messagesRef.current; const target = list.find((m) => m.id === id); if (!target) return; const next = target.role === "user" && opts?.withNextAssistant ? removePair(list, id) : removeAt(list, id); messagesRef.current = next; setMessages(next); onPersistRef.current?.(next); }, [], ); /** * Replace the textual content of a user message in place — used by the * inline edit affordance before it calls `reissueTurn` to rerun the * assistant pipeline against the new content. Returns the message id on * success so the caller can chain `reissueTurn(id)` without re-querying; * returns null when the id isn't a user message. */ const editUserMessage = useCallback((id: string, nextContent: string) => { const list = messagesRef.current; const idx = list.findIndex((m) => m.id === id); if (idx < 0 || list[idx].role !== "user") return null; const updated = list.slice(); updated[idx] = { ...list[idx], content: nextContent }; messagesRef.current = updated; setMessages(updated); // Do NOT persist here — the typical caller follows up with // reissueTurn, which will persist after the stream settles. return id; }, []); return { messages, isStreaming, error, send, reissueTurn, deleteMessage, editUserMessage, stop, clear, setMessages: replaceMessages, }; }