An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve agent response round layout https://github.com/siyuan-note/siyuan/issues/18726
Daniel8636bf7a9ec7
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 895b9cbebb..59e7711d10 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -26,6 +26,7 @@ import {getAgentThinkingToolGroups,hasAgentExecutedToolsAfter,hasAgentModelSpecificContext,+ isAgentAssistantContentFinalInTurn,isAgentRegenerateStateCurrent} from "./AgentHistory";import {@@ -185,11 +186,9 @@ export class AgentChat extends Model {roundID?: string;toolNames?: string[];toolCallIDs?: string[];- content?: string}> = [];// 当前请求的思考耗时(秒)。持久化为 entry.duration,"已思考"文本不落盘。private currentThinkingDuration = 0;- private currentThinkingStepContent = "";private pendingConfirms: SessionEntry[] = [];private renderedToolNames: Record<string, boolean> = {};private hasInterveningCard = false;@@ -995,12 +994,14 @@ export class AgentChat extends Model {case "streamStart":// 标记处于其他实例流式中,reloadFromDisk 重绘后会据此保留占位条。this.mirrorLocked = true;+ this.updateRegenerateButtons();// 立即拉取一次:发起者发消息时已 saveSession 写入 user 消息,让本轮新消息尽快可见。void this.reloadFromDisk();break;case "streamEnd":// 流结束,解除占位锁定并移除占位条。不重绘——完整内容由随后的 update 广播驱动。this.mirrorLocked = false;+ this.updateRegenerateButtons();this.removeMirrorPlaceholder();this.restorePendingEditDraft();break;@@ -1077,7 +1078,6 @@ export class AgentChat extends Model {this.pendingConfirms = [];this.currentThinkingSteps = [];this.currentThinkingEntryId = "";- this.currentThinkingStepContent = "";this.currentThinkingText = "";this.currentThinkingReasoning = "";this.currentThinkingReasoningContent = "";@@ -1321,7 +1321,7 @@ export class AgentChat extends Model {}, {once: true});}- private appendPersistedAssistant(content: string, timestamp?: number, entryId?: string) {+ private appendPersistedAssistant(content: string, timestamp?: number, entryId?: string, showActions = true) {if (!content || !content.trim()) {return;}@@ -1333,7 +1333,9 @@ export class AgentChat extends Model {el.innerHTML = '<div class="agent-chat__body b3-typography">' + (this.lute.ProtylePreviewStr("", content) || escapeHtml(content)) + "</div>";this.messagesContainer.appendChild(el);postRender(el, this.app, this.host.onNavigate);- this.addCopyButton(el, content, timestamp);+ if (showActions) {+ this.addCopyButton(el, content, timestamp);+ }}private createTodoElement(result: string, entryId?: string) {@@ -1357,7 +1359,7 @@ export class AgentChat extends Model {name: string;arguments: Record<string, unknown>;result?: string- }>, timestamp?: number, entryId?: string) {+ }>, timestamp?: number, entryId?: string, showActions = true) {let hasRendered = false;for (let i = 0; i < toolCalls.length; i++) {const tc = toolCalls[i];@@ -1369,7 +1371,7 @@ export class AgentChat extends Model {}}if (content && content.trim()) {- this.appendPersistedAssistant(content, timestamp, entryId);+ this.appendPersistedAssistant(content, timestamp, entryId, showActions);hasRendered = true;}if (!hasRendered) {@@ -1542,10 +1544,11 @@ export class AgentChat extends Model {toolCalls?: Array<{ name: string; arguments: Record<string, unknown>; result?: string }>;timestamp?: number};+ const showActions = isAgentAssistantContentFinalInTurn(displayEntries, i);if (a.toolCalls && a.toolCalls.length > 0) {- this.appendPersistedToolCalls(a.content, a.toolCalls, a.timestamp, entryId);+ this.appendPersistedToolCalls(a.content, a.toolCalls, a.timestamp, entryId, showActions);} else {- this.appendPersistedAssistant(a.content, a.timestamp, entryId);+ this.appendPersistedAssistant(a.content, a.timestamp, entryId, showActions);}break;}@@ -1660,7 +1663,6 @@ export class AgentChat extends Model {}this.messagesContainer.innerHTML = "";this.currentThinkingSteps = [];- this.currentThinkingStepContent = "";this.pendingConfirms = [];this.rebuildNavMarkers();this.titleElement.textContent = this.defaultTitle;@@ -2356,37 +2358,11 @@ export class AgentChat extends Model {private rafId = 0;private appendToken(token: string) {- this.currentContent += token;- this.fullContent += token;-- const thinkBody = this.messagesContainer.querySelector(".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done) .agent-chat__thinking-body");- if (thinkBody) {- let chatEl = thinkBody.querySelector(".agent-chat__thinking-chat--streaming") as HTMLElement;- if (!chatEl) {- chatEl = document.createElement("div");- chatEl.className = "agent-chat__thinking-chat b3-typography agent-chat__thinking-chat--streaming";- thinkBody.appendChild(chatEl);- }- if (!this.pendingTokenUpdate) {- this.pendingTokenUpdate = true;- // 用 RAF 合并更新(与普通 AI 消息一致),减少重建频率。- // 流式期间用 textContent 写纯文本,富渲染推迟到完成时,避免每帧重解析整段 markdown。- this.rafId = requestAnimationFrame(() => {- this.pendingTokenUpdate = false;- chatEl.textContent = this.currentContent;- const body = chatEl.closest(".agent-chat__thinking-body") as HTMLElement | null;- if (body) {- body.scrollTop = body.scrollHeight;- }- this.scrollToBottom();- });- }- return;- }-if (!this.currentAIElement) {this.currentAIElement = this.createAIMessagePlaceholder();}+ this.currentContent += token;+ this.fullContent += token;if (!this.pendingTokenUpdate) {this.pendingTokenUpdate = true;@@ -2407,17 +2383,6 @@ export class AgentChat extends Model {if (this.pendingTokenUpdate) {this.pendingTokenUpdate = false;cancelAnimationFrame(this.rafId);- // 思考卡片流式:更新 chatEl 并滚到底部(与 appendToken 思考分支一致)。- // 与 appendToken 一致用 textContent,富渲染由 finishResponse 完成时统一处理。- const thinkChat = this.messagesContainer.querySelector(".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done) .agent-chat__thinking-chat--streaming") as HTMLElement;- if (thinkChat) {- thinkChat.textContent = this.currentContent;- const thinkBody = thinkChat.parentElement;- if (thinkBody) {- thinkBody.scrollTop = thinkBody.scrollHeight;- }- return;- }const bodyEl = this.currentAIElement?.querySelector(".agent-chat__body") as HTMLElement;if (bodyEl) {bodyEl.textContent = this.currentContent;@@ -2496,6 +2461,49 @@ export class AgentChat extends Model {this.hasInterveningCard = true;}+ private finishVisibleRound() {+ if (!this.currentContent.trim()) {+ return;+ }+ this.flushTokenUpdate();+ const content = this.currentContent;+ const timestamp = Date.now();+ const assistantEntryID = this.currentAssistantEntryId || SessionStore.newSessionId();+ const roundID = this.currentRoundID || this.currentToolCalls[0]?.roundID;++ // 新一轮思考开始前结束上一张思考卡片,使正文位于两轮思考之间,而不是回填进折叠区。+ this.currentThinkingText = "";+ this.finishActiveThinking();+ this.flushThinkingStep();+ if (this.currentAIElement) {+ this.finalizeStreamingBody(content, timestamp, false);+ } else {+ this.appendPersistedAssistant(content, timestamp, assistantEntryID, false);+ }+ this.entries.push({+ id: assistantEntryID,+ type: "assistant",+ content,+ roundID,+ toolCalls: this.currentToolCalls.length > 0+ ? this.slimToolCallsForPersistence(this.currentToolCalls)+ : undefined,+ timestamp,+ });++ this.currentAIElement = null;+ this.observeStickTarget(null);+ this.currentAssistantEntryId = "";+ this.currentContent = "";+ this.fullContent = "";+ this.currentToolCalls = [];+ this.currentRoundID = "";+ this.lastStepToolCount = 0;+ this.renderedToolNames = {};+ this.currentThinkingDuration = 0;+ this.requestStartTime = Date.now();+ }+private appendThinking(reasoning: string, roundID: string) {const L = window.siyuan.languages;if (this.currentThinkingText) {@@ -2516,6 +2524,7 @@ export class AgentChat extends Model {});this.lastStepToolCount = this.currentToolCalls.length;}+ this.finishVisibleRound();// 工具名只在当前思考步骤内去重,新步骤仍需显示同名工具调用。this.renderedToolNames = {};this.currentThinkingText = "";@@ -2545,29 +2554,6 @@ export class AgentChat extends Model {}}- if (reasoning === "processing" && this.currentAIElement) {- if (this.currentContent) {- const bodyEl = this.currentAIElement.querySelector(".agent-chat__body") as HTMLElement;- if (bodyEl) {- bodyEl.classList.remove("agent-chat__body--streaming");- }- this.attachStepContent(this.currentContent);- this.currentAIElement.remove();- } else {- this.currentAIElement.remove();- }- this.currentAIElement = null;- this.currentAssistantEntryId = "";- this.currentContent = "";- } else if (reasoning === "processing" && this.currentContent) {- this.attachStepContent(this.currentContent);- this.currentContent = "";- const streamingEl = this.messagesContainer.querySelector(".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done) .agent-chat__thinking-chat--streaming") as HTMLElement;- if (streamingEl) {- streamingEl.classList.remove("agent-chat__thinking-chat--streaming");- }- }-if (reasoning === "processing" && this.hasInterveningCard) {// 与 finishActiveThinking 对齐:先把本张思考卡片的耗时算出来,// 既用于 DOM 显示「已思考 Xs」,也用于落盘 entry.duration(重载后仍能显示正确耗时)。@@ -2585,10 +2571,6 @@ export class AgentChat extends Model {txtEl.textContent = doneText;}}- if (this.currentThinkingStepContent && this.currentThinkingSteps.length > 0) {- this.currentThinkingSteps[this.currentThinkingSteps.length - 1].content = this.currentThinkingStepContent;- this.currentThinkingStepContent = "";- }if (this.currentThinkingSteps.length > 0) {this.entries.push({id: this.currentThinkingEntryId || undefined,@@ -2735,7 +2717,7 @@ export class AgentChat extends Model {actions.appendChild(copyBtn);const regenBtn = document.createElement("span");- regenBtn.className = "block__icon block__icon--show ariaLabel";+ regenBtn.className = "block__icon block__icon--show ariaLabel agent-chat__regenerate";regenBtn.setAttribute("data-position", "north");regenBtn.setAttribute("aria-label", L.agentRegenerate);regenBtn.innerHTML = '<svg><use xlink:href="#iconRefresh"></use></svg>';@@ -2744,10 +2726,18 @@ export class AgentChat extends Model {this.regenerateResponse(this.findUserEntryIDBeforeElement(el));});actions.appendChild(regenBtn);+ regenBtn.classList.toggle("fn__none", this.isStreaming || this.mirrorLocked);el.appendChild(actions);}+ private updateRegenerateButtons() {+ const hidden = this.isStreaming || this.mirrorLocked;+ this.messagesContainer.querySelectorAll(".agent-chat__regenerate").forEach((element) => {+ element.classList.toggle("fn__none", hidden);+ });+ }+private findUserEntryIDBeforeElement(el: HTMLElement): string | undefined {let current: Element | null = el;while (current) {@@ -2845,7 +2835,6 @@ export class AgentChat extends Model {this.renderedToolNames = {};this.hasInterveningCard = false;this.currentThinkingSteps = [];- this.currentThinkingStepContent = "";this.currentThinkingText = "";this.currentThinkingReasoning = "";this.currentThinkingReasoningContent = "";@@ -2900,7 +2889,7 @@ export class AgentChat extends Model {// 流式结束时把 currentAIElement 的 body 从纯文本一次性转为富渲染(Lute + postRender)。// 由 finishResponse(正常结束)与 error 路径(中断)共用,保证流式期轻渲染后仍得到完整富文本。- private finalizeStreamingBody(content: string, ts: number) {+ private finalizeStreamingBody(content: string, ts: number, showActions = true) {if (!this.currentAIElement) {return;}@@ -2913,7 +2902,9 @@ export class AgentChat extends Model {// 富渲染只在此处执行一次,避免流式期间每帧 O(n²) 重建带来的卡顿。bodyEl.innerHTML = this.lute.ProtylePreviewStr("", content) || escapeHtml(content);postRender(bodyEl, this.app, this.host.onNavigate);- this.addCopyButton(this.currentAIElement, undefined, ts);+ if (showActions) {+ this.addCopyButton(this.currentAIElement, undefined, ts);+ }this.scrollToBottom(true);}}@@ -3032,16 +3023,6 @@ export class AgentChat extends Model {}}- // 把上一轮在思考卡片内显示过的 content 归属到刚 push 的最后一个 step,- // 并清空 currentThinkingStepContent。这样每个 step 的 content 都能正确归属到自己的轮次,- // 而不会被 flushThinkingStep 错挂到下一轮的 step(导致重载后 content 位置错位)。- private attachStepContent(content: string) {- if (content && this.currentThinkingSteps.length > 0) {- this.currentThinkingSteps[this.currentThinkingSteps.length - 1].content = content;- }- this.currentThinkingStepContent = "";- }-private flushThinkingStep() {if (this.currentThinkingText) {const toolNames = this.currentToolCalls.slice(this.lastStepToolCount).map(function (t) {@@ -3055,11 +3036,9 @@ export class AgentChat extends Model {roundID: this.currentRoundID || undefined,toolNames: toolNames.length > 0 ? toolNames : undefined,toolCallIDs: toolCallIDs.length > 0 ? toolCallIDs : undefined,- content: this.currentThinkingStepContent || undefined,});this.lastStepToolCount = this.currentToolCalls.length;this.currentThinkingText = "";- this.currentThinkingStepContent = "";}if (this.currentThinkingSteps.length > 0) {this.entries.push({@@ -3125,7 +3104,6 @@ export class AgentChat extends Model {private appendRetry(attempt: number, maxRetries: number) {this.finishActiveThinking();this.currentThinkingSteps = [];- this.currentThinkingStepContent = "";this.renderedToolNames = {};this.clearThinking();const el = document.createElement("div");@@ -3464,7 +3442,7 @@ export class AgentChat extends Model {const timestamp = Date.now();if (this.currentAIElement) {if (content.trim()) {- this.finalizeStreamingBody(content, timestamp);+ this.finalizeStreamingBody(content, timestamp, false);} else {this.currentAIElement.remove();}@@ -3475,6 +3453,7 @@ export class AgentChat extends Model {content,timestamp,this.currentAssistantEntryId || SessionStore.newSessionId(),+ false,);}this.currentAssistantEntryId = "";@@ -3936,6 +3915,7 @@ export class AgentChat extends Model {private setStreaming(streaming: boolean) {this.isStreaming = streaming;+ this.updateRegenerateButtons();this.host.onStatusChange?.(streaming ? "running" : "idle");this.sendBtn.classList.toggle("fn__none", streaming);this.stopBtn.classList.toggle("fn__none", !streaming);diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.tsindex ef112b8690..1070056f12 100644--- a/app/src/layout/dock/agent/AgentHistory.test.ts+++ b/app/src/layout/dock/agent/AgentHistory.test.ts@@ -8,6 +8,7 @@ import {getAgentThinkingToolGroups,hasAgentExecutedToolsAfter,hasAgentModelSpecificContext,+ isAgentAssistantContentFinalInTurn,isAgentRegenerateStateCurrent} from "./AgentHistory";@@ -26,6 +27,22 @@ describe("AgentHistory", () => {assert.equal(findAgentUserEntryIndex(entries, "missing"), -1);});+ it("shows regenerate only on the final assistant content in each user turn", () => {+ const turnEntries = [+ {type: "user", content: "First question"},+ {type: "assistant", content: "Intermediate result"},+ {type: "thinking"},+ {type: "assistant", content: "Final result"},+ {type: "assistant", toolCalls: [{}]},+ {type: "user", content: "Second question"},+ {type: "assistant", content: "Second result"},+ ];+ assert.equal(isAgentAssistantContentFinalInTurn(turnEntries, 1), false);+ assert.equal(isAgentAssistantContentFinalInTurn(turnEntries, 3), true);+ assert.equal(isAgentAssistantContentFinalInTurn(turnEntries, 4), false);+ assert.equal(isAgentAssistantContentFinalInTurn(turnEntries, 6), true);+ });+it("displays every positive thinking duration as at least one second", () => {assert.equal(getAgentThinkingDisplaySeconds(undefined), undefined);assert.equal(getAgentThinkingDisplaySeconds(0), undefined);@@ -102,7 +119,7 @@ describe("AgentHistory", () => {assert.equal(entry.references, undefined);});- it("renders tool-call protocol messages inside thinking and keeps one final answer", () => {+ it("keeps tool-call content outside thinking", () => {const display = buildAgentPresentationEntries([{id: "user-1", type: "user", content: "create backlink"},{id: "snapshot-1", type: "snapshot"},@@ -136,11 +153,15 @@ describe("AgentHistory", () => {]);const visibleAnswers = display.filter(entry =>entry.type === "assistant" && !!entry.content?.trim());- assert.deepEqual(visibleAnswers.map(entry => entry.content), ["Done"]);- assert.equal(display.filter(entry => entry.type === "thinking").length, 2);- assert.deepEqual(display.find(entry => entry.id === "thinking-2")?.steps?.map(step => step.content), [+ assert.deepEqual(visibleAnswers.map(entry => entry.content), ["Both blocks are documents","parentID is required",+ "Done",+ ]);+ assert.equal(display.filter(entry => entry.type === "thinking").length, 2);+ assert.deepEqual(display.find(entry => entry.id === "thinking-2")?.steps?.map(step => step.content), [+ undefined,+ undefined,]);});@@ -281,11 +302,10 @@ describe("AgentHistory", () => {const step = display.find(entry => entry.id === "thinking-1")?.steps?.[0];assert.deepEqual(step, {roundID: "round-1",- content: "authoritative content",reasoningContent: "authoritative reasoning",toolNames: ["block"],});- assert.equal(display.find(entry => entry.id === "assistant-1")?.content, undefined);+ assert.equal(display.find(entry => entry.id === "assistant-1")?.content, "authoritative content");});it("synthesizes a thinking card when recovery has no UI process entries", () => {@@ -307,12 +327,133 @@ describe("AgentHistory", () => {reasoningContent: "reasoning",roundID: "round-1",toolNames: ["block"],- content: "working",}]);- assert.equal(display[2].content, undefined);+ assert.equal(display[2].content, "working");assert.equal(display[3].content, "Done");});+ it("keeps content from multiple recovered tool rounds visible", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "Checking settings",+ reasoningContent: "reasoning one",+ toolCalls: [{name: "file"}],+ },+ {+ id: "assistant-2",+ type: "assistant",+ roundID: "round-2",+ reasoningContent: "reasoning two",+ toolCalls: [{name: "file"}],+ },+ {+ id: "assistant-3",+ type: "assistant",+ roundID: "round-3",+ content: "Checking plugin configuration",+ reasoningContent: "reasoning three",+ toolCalls: [{name: "file"}],+ },+ ]);++ assert.deepEqual(display.map(entry => entry.id || entry.type), [+ "user-1", "thinking", "assistant-1", "thinking", "assistant-2", "assistant-3",+ ]);+ assert.deepEqual(display.filter(entry => entry.type === "thinking")+ .map(entry => entry.steps?.map(step => step.roundID)), [["round-1"], ["round-2", "round-3"]]);+ assert.deepEqual(display.filter(entry => entry.type === "assistant" && entry.content?.trim())+ .map(entry => entry.content), ["Checking settings", "Checking plugin configuration"]);+ });++ it("keeps recovered thinking paired after an earlier question continuation", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "search"},+ {+ id: "thinking-old",+ type: "thinking",+ steps: [{roundID: "old-round", reasoningContent: "old reasoning"}],+ },+ {id: "question-1", type: "question", roundID: "old-round"},+ {+ id: "assistant-0",+ type: "assistant",+ roundID: "new-round-0",+ reasoningContent: "first reasoning",+ toolCalls: [{name: "search"}],+ },+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "new-round-1",+ content: "First update",+ reasoningContent: "second reasoning",+ toolCalls: [{name: "search"}],+ },+ {+ id: "assistant-2",+ type: "assistant",+ roundID: "new-round-2",+ reasoningContent: "third reasoning",+ toolCalls: [{name: "document"}],+ },+ {+ id: "assistant-3",+ type: "assistant",+ roundID: "new-round-3",+ content: "Second update",+ reasoningContent: "fourth reasoning",+ toolCalls: [{name: "document"}],+ },+ ]);++ assert.deepEqual(display.map(entry => entry.id || entry.type), [+ "user-1", "thinking-old", "question-1", "thinking", "assistant-0", "assistant-1",+ "thinking", "assistant-2", "assistant-3",+ ]);+ assert.deepEqual(display.filter(entry => entry.type === "thinking")+ .map(entry => entry.steps?.map(step => step.roundID)), [+ ["old-round"], ["new-round-0", "new-round-1"], ["new-round-2", "new-round-3"],+ ]);+ });++ it("places tool-round content before the next thinking card", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{roundID: "round-1", reasoningContent: "reasoning one", toolNames: ["file"]}],+ },+ {+ id: "thinking-2",+ type: "thinking",+ steps: [{roundID: "round-2", reasoningContent: "reasoning two", toolNames: ["file"]}],+ },+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "First progress update",+ toolCalls: [{name: "file"}],+ },+ {+ id: "assistant-2",+ type: "assistant",+ roundID: "round-2",+ content: "Second progress update",+ toolCalls: [{name: "file"}],+ },+ ]);++ assert.deepEqual(display.map(entry => entry.id), [+ "user-1", "thinking-1", "assistant-1", "thinking-2", "assistant-2",+ ]);+ });+it("falls back to legacy step matching and restores final reasoning", () => {const display = buildAgentPresentationEntries([{id: "user-1", type: "user", content: "work"},@@ -339,7 +480,6 @@ describe("AgentHistory", () => {]);assert.deepEqual(display.map(entry => entry.type), ["user", "thinking", "assistant", "thinking", "assistant"]);assert.deepEqual(display[1].steps?.[0], {- content: "working",reasoningContent: "authoritative reasoning",roundID: "round-1",toolNames: ["block"],@@ -349,9 +489,8 @@ describe("AgentHistory", () => {reasoningContent: "final reasoning",roundID: "round-2",toolNames: undefined,- content: undefined,}]);- assert.equal(display[2].content, undefined);+ assert.equal(display[2].content, "working");assert.equal(display[4].content, "Done");});@@ -383,7 +522,7 @@ describe("AgentHistory", () => {"round-2",]);assert.equal(display.filter(entry => entry.type === "thinking").length, 1);- assert.equal(display.find(entry => entry.roundID === "round-1")?.content, undefined);+ assert.equal(display.find(entry => entry.roundID === "round-1")?.content, "recovered middle");});it("keeps todo results after their corresponding thinking card", () => {diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.tsindex 8e4e0d854b..da32a0cdb2 100644--- a/app/src/layout/dock/agent/AgentHistory.ts+++ b/app/src/layout/dock/agent/AgentHistory.ts@@ -68,6 +68,24 @@ export const findAgentUserEntryIndex = (entries: AgentHistoryEntry[], userEntryIreturn -1;};+export const isAgentAssistantContentFinalInTurn = (+ entries: Array<{ type: string; content?: string }>, entryIndex: number+): boolean => {+ const entry = entries[entryIndex];+ if (entry?.type !== "assistant" || !entry.content?.trim()) {+ return false;+ }+ for (let i = entryIndex + 1; i < entries.length; i++) {+ if (entries[i].type === "user") {+ break;+ }+ if (entries[i].type === "assistant" && entries[i].content?.trim()) {+ return false;+ }+ }+ return true;+};+export const hasAgentExecutedToolsAfter = (entries: AgentHistoryEntry[], entryIndex: number): boolean => {return entries.slice(entryIndex + 1).some((entry) => {if (entry.type === "snapshot") {@@ -97,9 +115,10 @@ const sameToolNames = (left: string[] | undefined, right: string[]): boolean =>return left.every((name, index) => name === right[index]);};-const enrichThinkingStep = (step: AgentHistoryThinkingStep, entry: AgentHistoryEntry, includeContent: boolean) => {- if (includeContent && entry.content?.trim()) {- step.content = entry.content;+const enrichThinkingStep = (step: AgentHistoryThinkingStep, entry: AgentHistoryEntry) => {+ // assistant.content 是面向用户的权威正文;匹配成功后从兼容用的旧思考步骤中移除副本。+ if (entry.content?.trim()) {+ delete step.content;}if (entry.reasoningContent?.trim()) {step.reasoningContent = entry.reasoningContent;@@ -173,13 +192,12 @@ const enrichThinkingStepTools = (step: AgentHistoryThinkingStep, relatedSteps: A}};-const buildRecoveredThinkingStep = (entry: AgentHistoryEntry, includeContent: boolean): AgentHistoryThinkingStep => {+const buildRecoveredThinkingStep = (entry: AgentHistoryEntry): AgentHistoryThinkingStep => {const step: AgentHistoryThinkingStep = {reasoning: "processing",reasoningContent: entry.reasoningContent || "",roundID: entry.roundID,toolNames: entry.toolCalls?.map(call => call.name || "").filter(Boolean),- content: includeContent ? entry.content : undefined,};const toolCallIDs = entry.toolCalls?.map(call => call.id || "").filter(Boolean) || [];if (toolCallIDs.length > 0) {@@ -203,7 +221,7 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorconst recovered: Array<{ entry: AgentHistoryEntry; step: AgentHistoryThinkingStep }> = [];const questionEntries = prepared.filter(entry => entry.type === "question");const matchedQuestionEntries = new Set<AgentHistoryEntry>();- const questionContentInsertions: Array<{+ const processContentInsertions: Array<{sourceEntry: AgentHistoryEntry;anchorStep?: AgentHistoryThinkingStep;questionEntry?: AgentHistoryEntry@@ -221,8 +239,7 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorconst isProcess = !!entry.toolCalls?.length;const toolNames = entry.toolCalls?.map(call => call.name || "").filter(Boolean) || [];const questionCallCount = entry.toolCalls?.filter(call => call.name === "question").length || 0;- const hasQuestion = questionCallCount > 0;- const hasQuestionContent = hasQuestion && !!entry.content?.trim();+ const hasProcessContent = isProcess && !!entry.content?.trim();let questionEntry: AgentHistoryEntry | undefined;for (let i = 0; i < questionCallCount; i++) {let matchedQuestion: AgentHistoryEntry | undefined;@@ -255,28 +272,24 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor}let presentationStep = step;if (step) {- enrichThinkingStep(step, entry, isProcess && !hasQuestionContent);+ enrichThinkingStep(step, entry);enrichThinkingStepTools(step, relatedSteps.length > 0 ? relatedSteps : [step], entry);matchedSteps.add(step);} else if (isProcess || entry.reasoningContent?.trim()) {- presentationStep = buildRecoveredThinkingStep(entry, isProcess && !hasQuestionContent);+ presentationStep = buildRecoveredThinkingStep(entry);recovered.push({entry, step: presentationStep});}- if (hasQuestionContent) {+ if (hasProcessContent) {if (presentationStep) {- presentationStep.content = undefined;+ delete presentationStep.content;}- questionContentInsertions.push({+ processContentInsertions.push({sourceEntry: entry,anchorStep: presentationStep,questionEntry,});}if (isProcess) {- // 普通工具调用的 assistant 是模型协议过程,不单独渲染为回答气泡;question 的同轮正文用于引出提问。- if (!hasQuestionContent) {- entry.content = undefined;- }const remainingToolCalls: NonNullable<AgentHistoryEntry["toolCalls"]> = [];for (const call of entry.toolCalls || []) {if (call.name === "todo_write" && call.result?.trim()) {@@ -338,15 +351,31 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor}}if (synthetic.length > 0) {- const firstUnmatched = prepared.indexOf(synthetic[0].entry);- prepared.splice(firstUnmatched, 0, {- type: "thinking",- steps: synthetic.map(item => item.step),- });+ let pending: Array<{ entry: AgentHistoryEntry; step: AgentHistoryThinkingStep }> = [];+ const flushPending = () => {+ if (pending.length === 0) {+ return;+ }+ const firstUnmatched = prepared.indexOf(pending[0].entry);+ prepared.splice(firstUnmatched, 0, {+ type: "thinking",+ steps: pending.map(item => item.step),+ });+ pending = [];+ };+ for (const item of synthetic) {+ pending.push(item);+ // 实时界面会在模型输出正文后结束当前思考卡片,恢复时沿用同一边界保持思考与正文配套。+ if (item.entry.content?.trim()) {+ flushPending();+ }+ }+ flushPending();}}- for (const item of questionContentInsertions) {+ const contentOffsets = new Map<AgentHistoryEntry, number>();+ for (const item of processContentInsertions) {const anchorEntry = item.anchorStep? prepared.find(entry => entry.type === "thinking" && entry.steps?.includes(item.anchorStep!)): undefined;@@ -363,12 +392,23 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorif (sourceIndex < 0) {continue;}- prepared.splice(sourceIndex, 1);const questionIndex = item.questionEntry ? prepared.indexOf(item.questionEntry) : -1;+ if (questionIndex < 0 && anchorEntry) {+ const anchorIndex = prepared.indexOf(anchorEntry);+ const nextThinkingIndex = prepared.findIndex((entry, index) =>+ index > anchorIndex && entry.type === "thinking");+ if (sourceIndex > anchorIndex && (nextThinkingIndex < 0 || sourceIndex < nextThinkingIndex)) {+ contentOffsets.set(anchorEntry, (contentOffsets.get(anchorEntry) || 0) + 1);+ continue;+ }+ }+ prepared.splice(sourceIndex, 1);if (questionIndex >= 0) {- prepared.splice(questionIndex, 0, item.sourceEntry);+ prepared.splice(prepared.indexOf(item.questionEntry!), 0, item.sourceEntry);} else if (anchorEntry) {- prepared.splice(prepared.indexOf(anchorEntry) + 1, 0, item.sourceEntry);+ const offset = contentOffsets.get(anchorEntry) || 0;+ prepared.splice(prepared.indexOf(anchorEntry) + 1 + offset, 0, item.sourceEntry);+ contentOffsets.set(anchorEntry, offset + 1);} else {prepared.splice(Math.min(sourceIndex, prepared.length), 0, item.sourceEntry);}@@ -415,8 +455,8 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorreturn prepared;};-// 将持久化协议消息投影为 UI 条目:普通工具调用消息归入思考卡片,-// question 的同轮正文保留在提问卡片前,其余不带工具调用的 assistant 作为回答展示。+// 将持久化协议消息投影为 UI 条目:reasoningContent 与工具调用归入思考卡片,+// assistant.content 始终作为正文展示,question 的同轮正文放在提问卡片前。export const buildAgentPresentationEntries = (entries: AgentHistoryEntry[]): AgentHistoryEntry[] => {const result: AgentHistoryEntry[] = [];let turnEntries: AgentHistoryEntry[] = [];