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 turn rendering order https://github.com/siyuan-note/siyuan/issues/18576
Daniel776f16da18d8
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 5cdcc71eec..c1d4454cff 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -20,6 +20,7 @@ import * as dayjs from "dayjs";import {sendNotification} from "../../../plugin/platformUtils";import {applyAgentUserEdit,+ buildAgentPresentationEntries,findAgentUserEntryIndex,hasAgentExecutedToolsAfter,hasAgentModelSpecificContext,@@ -77,6 +78,7 @@ type SessionEntry =steps: Array<{reasoning: string;reasoningContent: string;+ roundID?: string;toolNames?: string[];content?: string}>;@@ -86,6 +88,7 @@ type SessionEntry =type: "assistant";content?: string;reasoningContent?: string;+ roundID?: string;toolCalls?: Array<{id?: string;name: string;@@ -123,6 +126,7 @@ export class AgentChat extends Model {private currentAssistantEntryId = "";private currentThinkingEntryId = "";private currentTurnID = "";+ private currentRoundID = "";private recoveryCommitTurnIDs = new Map<string, string>();private pendingRecoverySessionIDs = new Set<string>();private recoveryInFlightSessionIDs = new Set<string>();@@ -142,7 +146,13 @@ export class AgentChat extends Model {private requestStartTime = 0;private tokenDisplayEl: HTMLElement;private defaultTitle = "";- private currentToolCalls: Array<{ name: string; arguments: Record<string, unknown>; result?: string }> = [];+ private currentToolCalls: Array<{+ id?: string;+ name: string;+ roundID?: string;+ arguments: Record<string, unknown>;+ result?: string+ }> = [];private toolCallStartedAt = new Map<string, number>();private abortController: AbortController | null = null;private currentThinkingText = "";@@ -156,6 +166,7 @@ export class AgentChat extends Model {private currentThinkingSteps: Array<{reasoning: string;reasoningContent: string;+ roundID?: string;toolNames?: string[];content?: string}> = [];@@ -674,6 +685,7 @@ export class AgentChat extends Model {this.requestStartTime = Date.now();this.currentThinkingDuration = 0;this.currentTurnID = "";+ this.currentRoundID = "";await fetchAgentSSE(text, window.siyuan.config.appearance.lang, [],(event: ISSEResult) => {if (this.sessionId !== requestSessionId) {@@ -1063,6 +1075,7 @@ export class AgentChat extends Model {this.currentContent = "";this.fullContent = "";this.currentToolCalls = [];+ this.currentRoundID = "";this.pendingConfirms = [];this.currentThinkingSteps = [];this.currentThinkingEntryId = "";@@ -1214,6 +1227,7 @@ export class AgentChat extends Model {this.entries = [];this.sessionId = SessionStore.newSessionId();this.currentTurnID = "";+ this.currentRoundID = "";this.sessionCreatedAt = Date.now();this.sessionTitle = this.defaultTitle;this.pendingSessionTitle = null;@@ -1259,6 +1273,7 @@ export class AgentChat extends Model {}this.sessionId = session.id;this.currentTurnID = "";+ this.currentRoundID = "";if (session.recoveryTurnID) {this.recoveryCommitTurnIDs.set(session.id, session.recoveryTurnID);} else {@@ -1389,19 +1404,29 @@ export class AgentChat extends Model {// 持久化前精简 toolCalls:question 工具的完整 questions 参数已由独立的 question entry 存储,// assistant entry 的 toolCalls 里只需保留工具名和结果(供 LLM 上下文恢复),避免重复存储。private slimToolCallsForPersistence(toolCalls: Array<{+ id?: string;name: string;+ roundID?: string;arguments: Record<string, unknown>;result?: string- }>): Array<{ name: string; arguments: Record<string, unknown>; result?: string }> {+ }>): Array<{+ id?: string;+ name: string;+ arguments: Record<string, unknown>;+ result?: string+ }> {return toolCalls.map(tc => {+ let args = tc.arguments;if (tc.name === "question" && tc.arguments && tc.arguments.questions) {- const slim = {...tc};- const slimArgs = {...tc.arguments};- delete slimArgs.questions;- slim.arguments = slimArgs;- return slim;- }- return tc;+ args = {...tc.arguments};+ delete args.questions;+ }+ return {+ id: tc.id,+ name: tc.name,+ arguments: args,+ result: tc.result,+ };});}@@ -1450,8 +1475,9 @@ export class AgentChat extends Model {private renderLoadedSession(session: AgentSession) {this.destroyEditingComposer();- for (let i = 0; i < session.entries.length; i++) {- const entry = session.entries[i];+ const displayEntries = buildAgentPresentationEntries(session.entries || []) as SessionEntry[];+ for (let i = 0; i < displayEntries.length; i++) {+ const entry = displayEntries[i];const entryId = (entry as { id?: string }).id;switch (entry.type) {case "user":@@ -1466,6 +1492,7 @@ export class AgentChat extends Model {steps: Array<{reasoning: string;reasoningContent?: string;+ roundID?: string;toolNames?: string[];toolCalls?: Array<{ name: string; result?: string }>;text?: string;@@ -1476,6 +1503,7 @@ export class AgentChat extends Model {const normSteps = rawEntry.steps.map(s => ({reasoning: s.reasoning || "",reasoningContent: s.reasoningContent || "",+ roundID: s.roundID,toolNames: (s.toolNames && s.toolNames.length > 0)? s.toolNames: (s.toolCalls ? s.toolCalls.map(t => t.name) : undefined),@@ -1589,6 +1617,7 @@ export class AgentChat extends Model {}this.sessionId = SessionStore.newSessionId();this.currentTurnID = "";+ this.currentRoundID = "";this.sessionCreatedAt = Date.now();if (this.composer) {this.composer.clearHistory();@@ -1678,6 +1707,7 @@ export class AgentChat extends Model {this.setStreaming(true);this.clearThinking();this.hasInterveningCard = false;+ this.currentRoundID = "";this.composer.clear();const userEntryId = SessionStore.newSessionId();@@ -1711,6 +1741,7 @@ export class AgentChat extends Model {this.requestStartTime = Date.now();this.currentThinkingDuration = 0;this.currentTurnID = "";+ this.currentRoundID = "";this.abortController = new AbortController();const requestSessionId = this.sessionId;@@ -1975,10 +2006,15 @@ export class AgentChat extends Model {this.appendToken(event.token);break;case "thinking":- this.appendThinking(event.reasoning);+ this.appendThinking(event.reasoning, event.roundID || "");break;case "tool_call":- this.currentToolCalls.push({name: event.name, arguments: event.arguments});+ this.currentToolCalls.push({+ id: event.callID,+ name: event.name,+ roundID: event.roundID || this.currentRoundID || undefined,+ arguments: event.arguments,+ });this.appendToolCall(event.name);break;case "confirm":@@ -1990,7 +2026,8 @@ export class AgentChat extends Model {break;case "tool_result":{- const toolCall = this.currentToolCalls.find((item) => item.name === event.name && item.result === undefined);+ const toolCall = this.currentToolCalls.find((item) =>+ item.result === undefined && (event.callID ? item.id === event.callID : item.name === event.name));if (toolCall) {toolCall.result = event.result;}@@ -2451,7 +2488,7 @@ export class AgentChat extends Model {this.hasInterveningCard = true;}- private appendThinking(reasoning: string) {+ private appendThinking(reasoning: string, roundID: string) {const L = window.siyuan.languages;if (this.currentThinkingText) {// step 不保存 text(渲染时由 duration 经 i18n 生成)。@@ -2463,6 +2500,7 @@ export class AgentChat extends Model {this.currentThinkingSteps.push({reasoning: this.currentThinkingReasoning,reasoningContent: this.currentThinkingReasoningContent,+ roundID: this.currentRoundID || undefined,toolNames: toolNames.length > 0 ? toolNames : undefined,});this.lastStepToolCount = this.currentToolCalls.length;@@ -2470,6 +2508,7 @@ export class AgentChat extends Model {this.currentThinkingText = "";this.currentThinkingReasoning = reasoning;this.currentThinkingReasoningContent = "";+ this.currentRoundID = roundID;const text = L.agentThinking || "Thinking";this.currentThinkingText = text;@@ -2557,6 +2596,7 @@ export class AgentChat extends Model {this.entries.push({id: SessionStore.newSessionId(),type: "assistant",+ roundID: this.currentToolCalls[0].roundID,toolCalls: this.slimToolCallsForPersistence(this.currentToolCalls)});this.currentToolCalls = [];@@ -2788,6 +2828,7 @@ export class AgentChat extends Model {this.currentContent = "";this.fullContent = "";this.currentToolCalls = [];+ this.currentRoundID = "";this.lastStepToolCount = 0;this.renderedToolNames = {};this.hasInterveningCard = false;@@ -2804,6 +2845,7 @@ export class AgentChat extends Model {this.requestStartTime = Date.now();this.currentThinkingDuration = 0;this.currentTurnID = "";+ this.currentRoundID = "";const lastUserEntry = targetEntry;const lastUserText = lastUserEntry.content;const editorContext = this.captureEditorContext();@@ -2916,6 +2958,7 @@ export class AgentChat extends Model {id: this.currentAssistantEntryId || undefined,type: "assistant",content: this.currentContent,+ roundID: this.currentRoundID || undefined,toolCalls: this.currentToolCalls.length > 0 ? this.slimToolCallsForPersistence(this.currentToolCalls) : undefined,timestamp: ts,});@@ -2923,6 +2966,7 @@ export class AgentChat extends Model {this.entries.push({id: SessionStore.newSessionId(),type: "assistant",+ roundID: this.currentToolCalls[0].roundID,toolCalls: this.slimToolCallsForPersistence(this.currentToolCalls)});}@@ -2932,6 +2976,7 @@ export class AgentChat extends Model {this.currentContent = "";this.fullContent = "";this.currentToolCalls = [];+ this.currentRoundID = "";this.lastStepToolCount = 0;this.renderedToolNames = {};if (this.requestStartTime) {@@ -2993,6 +3038,7 @@ export class AgentChat extends Model {this.currentThinkingSteps.push({reasoning: this.currentThinkingReasoning,reasoningContent: this.currentThinkingReasoningContent,+ roundID: this.currentRoundID || undefined,toolNames: toolNames.length > 0 ? toolNames : undefined,content: this.currentThinkingStepContent || undefined,});@@ -3172,6 +3218,7 @@ export class AgentChat extends Model {id: this.currentAssistantEntryId || undefined,type: "assistant",content: this.currentContent,+ roundID: this.currentRoundID || undefined,toolCalls: this.currentToolCalls.length > 0 ? this.slimToolCallsForPersistence(this.currentToolCalls) : undefined,timestamp: ts,});@@ -3182,6 +3229,7 @@ export class AgentChat extends Model {this.currentContent = "";this.fullContent = "";this.currentToolCalls = [];+ this.currentRoundID = "";this.lastStepToolCount = 0;this.renderedToolNames = {};if (this.requestStartTime) {diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.tsindex a6b8d924a2..8771ad59e1 100644--- a/app/src/layout/dock/agent/AgentHistory.test.ts+++ b/app/src/layout/dock/agent/AgentHistory.test.ts@@ -2,6 +2,7 @@ import {describe, it} from "node:test";import * as assert from "node:assert/strict";import {applyAgentUserEdit,+ buildAgentPresentationEntries,findAgentUserEntryIndex,hasAgentExecutedToolsAfter,hasAgentModelSpecificContext,@@ -88,4 +89,172 @@ describe("AgentHistory", () => {});assert.equal(entry.references, undefined);});++ it("renders tool-call protocol messages inside thinking and keeps one final answer", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "create backlink"},+ {id: "snapshot-1", type: "snapshot"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{reasoningContent: "read blocks", toolNames: ["block", "block"]}],+ },+ {id: "assistant-0", type: "assistant", toolCalls: [{name: "block"}, {name: "block"}]},+ {+ id: "thinking-2",+ type: "thinking",+ steps: [+ {reasoningContent: "append", content: "Both blocks are documents", toolNames: ["block"]},+ {reasoningContent: "retry", content: "parentID is required", toolNames: ["block"]},+ ],+ },+ {+ id: "assistant-1",+ type: "assistant",+ content: "Both blocks are documents",+ toolCalls: [{name: "block"}],+ },+ {+ id: "assistant-2",+ type: "assistant",+ content: "parentID is required",+ toolCalls: [{name: "block"}],+ },+ {id: "assistant-3", type: "assistant", content: "Done"},+ ]);+ 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), [+ "Both blocks are documents",+ "parentID is required",+ ]);+ });++ it("uses round IDs to restore authoritative process content", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{roundID: "round-1", reasoningContent: "partial", toolNames: ["old"]}],+ },+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "authoritative content",+ reasoningContent: "authoritative reasoning",+ toolCalls: [{name: "block"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);+ 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);+ });++ it("synthesizes a thinking card when recovery has no UI process entries", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "working",+ reasoningContent: "reasoning",+ toolCalls: [{name: "block"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);+ assert.deepEqual(display.map(entry => entry.type), ["user", "thinking", "assistant", "assistant"]);+ assert.deepEqual(display[1].steps, [{+ reasoning: "processing",+ reasoningContent: "reasoning",+ roundID: "round-1",+ toolNames: ["block"],+ content: "working",+ }]);+ assert.equal(display[2].content, undefined);+ assert.equal(display[3].content, "Done");+ });++ it("falls back to legacy step matching and restores final reasoning", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{content: "working", reasoningContent: "legacy reasoning", toolNames: ["block"]}],+ },+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "working",+ reasoningContent: "authoritative reasoning",+ toolCalls: [{name: "block"}],+ },+ {+ id: "assistant-2",+ type: "assistant",+ roundID: "round-2",+ content: "Done",+ reasoningContent: "final reasoning",+ },+ ]);+ 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"],+ });+ assert.deepEqual(display[3].steps, [{+ reasoning: "processing",+ reasoningContent: "final reasoning",+ roundID: "round-2",+ toolNames: undefined,+ content: undefined,+ }]);+ assert.equal(display[2].content, undefined);+ assert.equal(display[4].content, "Done");+ });++ it("inserts a recovered middle round before the next known thinking step", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [+ {roundID: "round-0", reasoningContent: "first"},+ {roundID: "round-2", reasoningContent: "third"},+ ],+ },+ {id: "assistant-0", type: "assistant", roundID: "round-0", toolCalls: [{name: "block"}]},+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ content: "recovered middle",+ toolCalls: [{name: "block"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", toolCalls: [{name: "block"}]},+ {id: "assistant-3", type: "assistant", roundID: "round-3", content: "Done"},+ ]);+ assert.deepEqual(display.find(entry => entry.id === "thinking-1")?.steps?.map(step => step.roundID), [+ "round-0",+ "round-1",+ "round-2",+ ]);+ assert.equal(display.filter(entry => entry.type === "thinking").length, 1);+ assert.equal(display.find(entry => entry.roundID === "round-1")?.content, undefined);+ });});diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.tsindex f80780d9b7..95eff93e94 100644--- a/app/src/layout/dock/agent/AgentHistory.ts+++ b/app/src/layout/dock/agent/AgentHistory.ts@@ -2,9 +2,26 @@ export type AgentHistoryEntry = {id?: string;type: string;status?: string;+ content?: string;reasoningContent?: string;- steps?: Array<{ reasoningContent?: string }>;- toolCalls?: Array<{ result?: string; state?: string }>;+ roundID?: string;+ duration?: number;+ steps?: AgentHistoryThinkingStep[];+ toolCalls?: Array<{+ name?: string;+ result?: string;+ state?: string;+ [key: string]: unknown+ }>;+ [key: string]: unknown;+};++export type AgentHistoryThinkingStep = {+ reasoning?: string;+ reasoningContent?: string;+ roundID?: string;+ toolNames?: string[];+ content?: string;};export type AgentHistoryReference = { id: string; title: string };@@ -58,6 +75,151 @@ export const hasAgentModelSpecificContext = (entries: AgentHistoryEntry[]): bool});};+const sameToolNames = (left: string[] | undefined, right: string[]): boolean => {+ if (!left || left.length !== right.length) {+ return false;+ }+ 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;+ }+ if (entry.reasoningContent?.trim()) {+ step.reasoningContent = entry.reasoningContent;+ }+ const toolNames = entry.toolCalls?.map(call => call.name || "").filter(Boolean) || [];+ if (toolNames.length > 0) {+ step.toolNames = toolNames;+ }+ if (entry.roundID) {+ step.roundID = entry.roundID;+ }+};++const buildRecoveredThinkingStep = (entry: AgentHistoryEntry, includeContent: boolean): AgentHistoryThinkingStep => ({+ reasoning: "processing",+ reasoningContent: entry.reasoningContent || "",+ roundID: entry.roundID,+ toolNames: entry.toolCalls?.map(call => call.name || "").filter(Boolean),+ content: includeContent ? entry.content : undefined,+});++const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistoryEntry[] => {+ const prepared: AgentHistoryEntry[] = entries.map(entry => ({+ ...entry,+ steps: entry.steps?.map(step => ({+ ...step,+ toolNames: step.toolNames?.slice(),+ })),+ toolCalls: entry.toolCalls?.map(call => ({...call})),+ }));+ const thinkingSteps = prepared.flatMap(entry => entry.type === "thinking" ? (entry.steps || []) : []);+ const matchedSteps = new Set<AgentHistoryThinkingStep>();+ const recovered: Array<{ entry: AgentHistoryEntry; step: AgentHistoryThinkingStep }> = [];++ for (const entry of prepared) {+ if (entry.type !== "assistant") {+ continue;+ }+ const isProcess = !!entry.toolCalls?.length;+ const toolNames = entry.toolCalls?.map(call => call.name || "").filter(Boolean) || [];+ let step: AgentHistoryThinkingStep | undefined;+ if (entry.roundID) {+ step = thinkingSteps.find(item => item.roundID === entry.roundID && !matchedSteps.has(item));+ }+ if (!step && (isProcess || entry.reasoningContent?.trim())) {+ step = thinkingSteps.find(item => !item.roundID && !matchedSteps.has(item) && (+ (isProcess && !!entry.content?.trim() && item.content === entry.content) ||+ sameToolNames(item.toolNames, toolNames) ||+ (!!entry.reasoningContent?.trim() && item.reasoningContent === entry.reasoningContent)+ ));+ }+ if (step) {+ enrichThinkingStep(step, entry, isProcess);+ matchedSteps.add(step);+ } else if (isProcess || entry.reasoningContent?.trim()) {+ recovered.push({entry, step: buildRecoveredThinkingStep(entry, isProcess)});+ }+ if (isProcess) {+ // 带工具调用的 assistant 是模型协议过程,不单独渲染为回答气泡。+ entry.content = undefined;+ }+ }++ if (recovered.length === 0) {+ return prepared;+ }++ const roundOrder = new Map<string, number>();+ let order = 0;+ for (const entry of prepared) {+ if (entry.type === "assistant" && entry.roundID && !roundOrder.has(entry.roundID)) {+ roundOrder.set(entry.roundID, order++);+ }+ }+ const synthetic: Array<{ entry: AgentHistoryEntry; step: AgentHistoryThinkingStep }> = [];+ for (const item of recovered) {+ const itemOrder = item.entry.roundID ? roundOrder.get(item.entry.roundID) : undefined;+ let nextEntry: AgentHistoryEntry | undefined;+ let nextStep: AgentHistoryThinkingStep | undefined;+ let nextOrder = Number.MAX_SAFE_INTEGER;+ if (itemOrder !== undefined) {+ for (const entry of prepared) {+ if (entry.type !== "thinking") {+ continue;+ }+ for (const step of entry.steps || []) {+ const stepOrder = step.roundID ? roundOrder.get(step.roundID) : undefined;+ if (stepOrder !== undefined && stepOrder > itemOrder && stepOrder < nextOrder) {+ nextEntry = entry;+ nextStep = step;+ nextOrder = stepOrder;+ }+ }+ }+ }+ if (nextEntry && nextStep) {+ const nextIndex = nextEntry.steps?.indexOf(nextStep) ?? -1;+ nextEntry.steps?.splice(Math.max(nextIndex, 0), 0, item.step);+ } else {+ synthetic.push(item);+ }+ }+ if (synthetic.length > 0) {+ const firstUnmatched = prepared.indexOf(synthetic[0].entry);+ prepared.splice(firstUnmatched, 0, {+ type: "thinking",+ steps: synthetic.map(item => item.step),+ });+ }+ return prepared;+};++// 将持久化协议消息投影为 UI 条目:同一用户轮次中的工具调用消息归入思考卡片,+// 只有不带工具调用的 assistant 作为最终回答展示。+export const buildAgentPresentationEntries = (entries: AgentHistoryEntry[]): AgentHistoryEntry[] => {+ const result: AgentHistoryEntry[] = [];+ let turnEntries: AgentHistoryEntry[] = [];+ const flushTurn = () => {+ if (turnEntries.length > 0) {+ result.push(...prepareAgentTurnPresentation(turnEntries));+ turnEntries = [];+ }+ };+ for (const entry of entries) {+ if (entry.type === "user") {+ flushTurn();+ result.push({...entry});+ } else {+ turnEntries.push(entry);+ }+ }+ flushTurn();+ return result;+};+export const isAgentRegenerateStateCurrent = (requestSessionID: string, currentSessionID: string,requestRevision: number, currentRevision: number,isStreaming: boolean, mirrorLocked: boolean): boolean => {diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.tsindex e327beac3e..50c6209309 100644--- a/app/src/layout/dock/agent/SessionStore.ts+++ b/app/src/layout/dock/agent/SessionStore.ts@@ -66,17 +66,19 @@ export interface AgentSession {selectedBlockIDs?: string[];visibleBlockIDs?: string[];};- // thinking step:新格式只含 reasoning/reasoningContent/toolNames/content;+ // thinking step:新格式只含 reasoning/reasoningContent/roundID/toolNames/content;// text/toolCalls 仅为读取老数据而保留为可选(渲染时归一化)。steps?: Array<{reasoning: string;reasoningContent: string;+ roundID?: string;toolNames?: string[];content?: string;text?: string;toolCalls?: Array<{name: string; result?: string}>}>;reasoningContent?: string;+ roundID?: string;toolCalls?: Array<{id?: string;name: string;diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.tsindex 07db88605c..a33477e1ef 100644--- a/app/src/layout/dock/agent/agentSSE.ts+++ b/app/src/layout/dock/agent/agentSSE.ts@@ -14,9 +14,12 @@ export type ISSEResult = {} | {type: "thinking";reasoning: string;+ roundID?: string;} | {type: "tool_call";name: string;+ callID?: string;+ roundID?: string;arguments: Record<string, unknown>;} | {type: "confirm";@@ -27,6 +30,8 @@ export type ISSEResult = {} | {type: "tool_result";name: string;+ callID?: string;+ roundID?: string;result: string;} | {type: "error";@@ -261,11 +266,17 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResulcase "content":return {type: "content", token: data.token as string};case "thinking":- return {type: "thinking", reasoning: data.reasoning as string};+ return {+ type: "thinking",+ reasoning: data.reasoning as string,+ roundID: data.roundID as string || undefined,+ };case "tool_call":return {type: "tool_call",name: data.name as string,+ callID: data.callID as string || undefined,+ roundID: data.roundID as string || undefined,arguments: (data.arguments || {}) as Record<string, unknown>,};case "confirm":@@ -284,6 +295,8 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResulreturn {type: "tool_result",name: data.name as string,+ callID: data.callID as string || undefined,+ roundID: data.roundID as string || undefined,result: data.result as string,};case "error":diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 256967628a..7cd94d3c82 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -303,6 +303,8 @@ type AgentEvent struct {Type stringToken stringName string+ RoundID string+ ToolCallID stringArguments map[string]anyResult stringReasoning string@@ -328,6 +330,7 @@ type AgentMessage struct {Role string `json:"role"`Content string `json:"content"`ReasoningContent string `json:"reasoningContent,omitempty"`+ RoundID string `json:"roundID,omitempty"`References []Reference `json:"references,omitempty"`EditorContext *EditorContext `json:"editorContext,omitempty"`ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`@@ -418,6 +421,7 @@ type SessionEntry struct {CompletionTok int `json:"completionTokens,omitempty"`Timestamp int64 `json:"timestamp,omitempty"`ReasoningCont string `json:"reasoningContent,omitempty"`+ RoundID string `json:"roundID,omitempty"`Name string `json:"name,omitempty"`Args map[string]any `json:"args,omitempty"`ConfirmID string `json:"confirmID,omitempty"`@@ -428,12 +432,14 @@ type SessionEntry struct {SnapshotID string `json:"snapshotID,omitempty"`}-// SessionEntryStep 描述一次思考步骤。工具调用只保留名字列表,+// SessionEntryStep 描述一次思考步骤。工具调用只保留名字列表,过程正文保存在 Content,// arguments/result 仅在所属 assistant entry 的 ToolCalls 中存储,避免重复。type SessionEntryStep struct {Reasoning string `json:"reasoning"`ReasoningContent string `json:"reasoningContent,omitempty"`ToolNames []string `json:"toolNames,omitempty"`+ Content string `json:"content,omitempty"`+ RoundID string `json:"roundID,omitempty"`}type agentCheckpoint struct {@@ -774,10 +780,11 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitdefault:}+ roundID := fmt.Sprintf("%s_%d", turn.TurnID, modelRound)if modelRound == 0 {- sendEvent(ch, AgentEvent{Type: "thinking", Reasoning: "analyzing"})+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "thinking", Reasoning: "analyzing", RoundID: roundID})} else {- sendEvent(ch, AgentEvent{Type: "thinking", Reasoning: "processing"})+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "thinking", Reasoning: "processing", RoundID: roundID})}modelRound++@@ -868,8 +875,14 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitlogging.LogErrorf("agent stream error: %s", recvErr.Error())content := contentBuilder.String()if content != "" || reasoningBuilder.String() != "" {- checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content})+ checkpointMsgs = append(checkpointMsgs, AgentMessage{+ Role: "assistant",+ Content: content,+ ReasoningContent: reasoningBuilder.String(),+ RoundID: roundID,+ })turn.DraftContent = ""+ turn.DraftRoundID = ""}finalized := saveTurn("interrupted")stream.Close()@@ -883,6 +896,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitselect {case <-ctx.Done():turn.DraftContent = contentBuilder.String()+ turn.DraftRoundID = roundIDsaveTurn("interrupted")stream.Close()roundCancel()@@ -921,6 +935,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit}if contentBuilder.Len() > 0 && time.Since(lastDraftCheckpoint) >= time.Second {turn.DraftContent = contentBuilder.String()+ turn.DraftRoundID = roundIDsaveTurn("running")lastDraftCheckpoint = time.Now()}@@ -941,6 +956,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitstream.Close()roundCancel()turn.DraftContent = ""+ turn.DraftRoundID = ""if len(aggregatedToolCalls) > 0 {filtered := make([]openai.ToolCall, 0, len(aggregatedToolCalls))@@ -963,6 +979,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitRole: "assistant",Content: contentBuilder.String(),ReasoningContent: reasoningBuilder.String(),+ RoundID: roundID,}parsedArgs := make([]map[string]any, len(aggregatedToolCalls))var roundAttachments []AgentAttachment@@ -983,7 +1000,13 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitfor j := start; j < len(aggregatedToolCalls); j++ {checkpointMsgs[assistantIdx].ToolCalls[j].Result = resultcheckpointMsgs[assistantIdx].ToolCalls[j].State = "skipped"- sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: result})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: aggregatedToolCalls[j].Function.Name,+ RoundID: roundID,+ ToolCallID: aggregatedToolCalls[j].ID,+ Result: result,+ })}}// 在展示确认框前记录模型提出的整批调用。此时都尚未执行,崩溃恢复可以明确区分@@ -1000,9 +1023,11 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit}sendEvent(ch, AgentEvent{- Type: "tool_call",- Name: tc.Function.Name,- Arguments: args,+ Type: "tool_call",+ Name: tc.Function.Name,+ RoundID: roundID,+ ToolCallID: tc.ID,+ Arguments: args,})_, _, toolInputErr := validateToolCallInput(ctx, tc.Function.Name, args)@@ -1040,7 +1065,13 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitContent: wrapToolOutput(cancelMsg),ToolCallID: tc.ID,})- sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: cancelMsg})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: tc.Function.Name,+ RoundID: roundID,+ ToolCallID: tc.ID,+ Result: cancelMsg,+ })for j := i + 1; j < len(aggregatedToolCalls); j++ {checkpointMsgs[assistantIdx].ToolCalls[j].Result = cancelMsg@@ -1050,7 +1081,13 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitContent: wrapToolOutput(cancelMsg),ToolCallID: aggregatedToolCalls[j].ID,})- sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: cancelMsg})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: aggregatedToolCalls[j].Function.Name,+ RoundID: roundID,+ ToolCallID: aggregatedToolCalls[j].ID,+ Result: cancelMsg,+ })}if !saveTurn("interrupted") {return@@ -1063,13 +1100,25 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit}timedOut = truerejectionMsg = "Confirmation timed out, operation skipped automatically"- sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: rejectionMsg})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: tc.Function.Name,+ RoundID: roundID,+ ToolCallID: tc.ID,+ Result: rejectionMsg,+ })}if timedOut || !result.approved {if rejectionMsg == "" {rejectionMsg = "User rejected this operation"- sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: rejectionMsg})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: tc.Function.Name,+ RoundID: roundID,+ ToolCallID: tc.ID,+ Result: rejectionMsg,+ })}messages = append(messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleTool,@@ -1090,7 +1139,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit})}// 确认卡片会结束当前思考状态,工具执行前重新通知前端显示“思考中”。- sendEvent(ch, AgentEvent{Type: "thinking", Reasoning: "processing"})+ sendCriticalEvent(ctx, ch, AgentEvent{+ Type: "thinking", Reasoning: "processing", RoundID: roundID,+ })}select {case <-ctx.Done():@@ -1124,9 +1175,21 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitif !saveTurn("interrupted") {return}- sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: abortMsg})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: tc.Function.Name,+ RoundID: roundID,+ ToolCallID: tc.ID,+ Result: abortMsg,+ })for j := i + 1; j < len(aggregatedToolCalls); j++ {- sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: abortMsg})+ sendEvent(ch, AgentEvent{+ Type: "tool_result",+ Name: aggregatedToolCalls[j].Function.Name,+ RoundID: roundID,+ ToolCallID: aggregatedToolCalls[j].ID,+ Result: abortMsg,+ })}sendCriticalEvent(ctx, ch, AgentEvent{Type: "error",@@ -1188,9 +1251,11 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitresultStr = wrapToolOutput(resultStr)sendEvent(ch, AgentEvent{- Type: "tool_result",- Name: tc.Function.Name,- Result: resultStr,+ Type: "tool_result",+ Name: tc.Function.Name,+ RoundID: roundID,+ ToolCallID: tc.ID,+ Result: resultStr,})messages = append(messages, openai.ChatCompletionMessage{@@ -1273,6 +1338,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitRole: "assistant",Content: content,ReasoningContent: reasoningBuilder.String(),+ RoundID: roundID,})}if content == "" {@@ -1812,6 +1878,7 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {Role: "assistant",Content: e.Content,ReasoningContent: e.ReasoningCont,+ RoundID: e.RoundID,EntryID: e.ID,}if len(e.ToolCalls) > 0 {@@ -1973,6 +2040,7 @@ func agentMessagesToEntries(msgs []AgentMessage) []SessionEntry {Type: "assistant",Content: m.Content,ReasoningCont: m.ReasoningContent,+ RoundID: m.RoundID,ToolCalls: m.ToolCalls,}entries = append(entries, e)diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.goindex c3ae997f2c..40f8cc57bb 100644--- a/kernel/agent/prompt_test.go+++ b/kernel/agent/prompt_test.go@@ -149,6 +149,7 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {Type: "assistant",Content: "Let me search for that.",ReasoningCont: "I need to use the search tool.",+ RoundID: "round-1",ToolCalls: []AgentToolCall{{ID: "call-original",Name: "search",@@ -160,7 +161,8 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {}}checkpoint := entriesToAgentMessages(entries)- if len(checkpoint) != 1 || checkpoint[0].ReasoningContent != entries[0].ReasoningCont {+ if len(checkpoint) != 1 || checkpoint[0].ReasoningContent != entries[0].ReasoningCont ||+ checkpoint[0].RoundID != entries[0].RoundID {t.Fatalf("assistant reasoning was not restored into checkpoint: %#v", checkpoint)}if len(checkpoint[0].ToolCalls) != 1 || checkpoint[0].ToolCalls[0].ID != "call-original" ||@@ -184,6 +186,7 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {roundTripped := agentMessagesToEntries(checkpoint)if len(roundTripped) != 1 || roundTripped[0].ReasoningCont != entries[0].ReasoningCont ||+ roundTripped[0].RoundID != entries[0].RoundID ||len(roundTripped[0].ToolCalls) != 1 || roundTripped[0].ToolCalls[0].ID != "call-original" ||roundTripped[0].ToolCalls[0].ArgumentsJSON != argumentsJSON {t.Fatalf("assistant context changed during checkpoint round trip: %#v", roundTripped)diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.goindex 344e9a10ab..d1879513d7 100644--- a/kernel/agent/runtime.go+++ b/kernel/agent/runtime.go@@ -160,6 +160,7 @@ type agentRuntimeTurn struct {State string `json:"state"`Delta []AgentMessage `json:"delta,omitempty"`DraftContent string `json:"draftContent,omitempty"`+ DraftRoundID string `json:"draftRoundID,omitempty"`SnapshotIDs []string `json:"snapshotIDs,omitempty"`PromptTokens int `json:"promptTokens,omitempty"`CompletionTokens int `json:"completionTokens,omitempty"`@@ -492,6 +493,9 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeTif message.ReasoningContent != "" {entry["reasoningContent"] = message.ReasoningContent}+ if message.RoundID != "" {+ entry["roundID"] = message.RoundID+ }if len(message.ToolCalls) > 0 {calls := make([]map[string]any, 0, len(message.ToolCalls))for _, call := range message.ToolCalls {@@ -525,31 +529,31 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeTauthoritative = append(authoritative, entry)}if turn.DraftContent != "" {- authoritative = append(authoritative, map[string]any{+ draft := map[string]any{"id": fmt.Sprintf("runtime_draft_%s", turn.TurnID),"type": "assistant","content": turn.DraftContent,"timestamp": turn.UpdatedAt,- })+ }+ if turn.DraftRoundID != "" {+ draft["roundID"] = turn.DraftRoundID+ }+ authoritative = append(authoritative, draft)}// regenerate 在启动前已经把旧回答截断到目标 user,因此 user 之后的 UI 条目都属于当前 turn。+ // assistant 是模型协议消息,数量与前端展示占位并非一一对应。保留 UI 条目后按运行时顺序追加+ // 权威 assistant,避免按占位序号替换造成思考卡片与中间回复错位。merged := append([]any(nil), entries[:anchor+1]...)- authoritativeIndex := 0for _, raw := range entries[anchor+1:] {entry, _ := raw.(map[string]any)typeName, _ := entry["type"].(string)switch typeName {- case "assistant":- if authoritativeIndex < len(authoritative) {- merged = append(merged, authoritative[authoritativeIndex])- authoritativeIndex++- }case "thinking", "confirm", "question", "snapshot", "rollback":merged = append(merged, raw)}}- merged = append(merged, authoritative[authoritativeIndex:]...)+ merged = append(merged, authoritative...)existingSnapshots := map[string]bool{}for _, raw := range merged {diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.goindex d7106c37a3..fff80e59a0 100644--- a/kernel/agent/session_test.go+++ b/kernel/agent/session_test.go@@ -731,7 +731,7 @@ func TestGetSessionRejectsIncompatibleRuntimeMetadata(t *testing.T) {}}-func TestApplyRuntimePreservesUIOrderAndReplacesAssistant(t *testing.T) {+func TestApplyRuntimePreservesUIOrderAndAppendsAuthoritativeAssistants(t *testing.T) {session := map[string]any{"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"},@@ -755,7 +755,7 @@ func TestApplyRuntimePreservesUIOrderAndReplacesAssistant(t *testing.T) {t.Fatal(err)}entries := session["entries"].([]any)- wantTypes := []string{"user", "thinking", "assistant", "confirm", "assistant", "rollback"}+ wantTypes := []string{"user", "thinking", "confirm", "rollback", "assistant", "assistant"}if len(entries) != len(wantTypes) {t.Fatalf("unexpected merged entry count: %#v", entries)}@@ -765,12 +765,59 @@ func TestApplyRuntimePreservesUIOrderAndReplacesAssistant(t *testing.T) {t.Fatalf("entry %d type: got=%v, want=%s", i, entry["type"], wantType)}}- if entries[2].(map[string]any)["content"] != "server one" ||- entries[4].(map[string]any)["content"] != "server two" {+ if entries[4].(map[string]any)["content"] != "server one" ||+ entries[5].(map[string]any)["content"] != "server two" {t.Fatalf("client assistant content was not replaced: %#v", entries)}}+func TestApplyRuntimeDoesNotDependOnAssistantPlaceholderCount(t *testing.T) {+ session := map[string]any{+ "entries": []any{+ map[string]any{"id": "user-1", "type": "user", "content": "hello"},+ map[string]any{"id": "snapshot-1", "type": "snapshot"},+ map[string]any{"id": "thinking-1", "type": "thinking"},+ map[string]any{"id": "client-assistant-1", "type": "assistant"},+ map[string]any{"id": "thinking-2", "type": "thinking"},+ map[string]any{"id": "client-assistant-2", "type": "assistant", "content": "client final"},+ },+ }+ turn := &agentRuntimeTurn{+ TurnID: "20260806190742-abcdefg",+ UserEntryID: "user-1",+ UpdatedAt: 1,+ Delta: []AgentMessage{+ {Role: "assistant", RoundID: "round-0", ToolCalls: []AgentToolCall{{Name: "block"}}},+ {Role: "assistant", RoundID: "round-1", Content: "first", ToolCalls: []AgentToolCall{{Name: "block"}}},+ {Role: "assistant", RoundID: "round-2", Content: "retry", ToolCalls: []AgentToolCall{{Name: "block"}}},+ {Role: "assistant", RoundID: "round-3", Content: "done"},+ },+ }+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {+ t.Fatal(err)+ }+ entries := session["entries"].([]any)+ wantTypes := []string{"user", "snapshot", "thinking", "thinking", "assistant", "assistant", "assistant", "assistant"}+ if len(entries) != len(wantTypes) {+ t.Fatalf("unexpected merged entry count: %#v", entries)+ }+ for i, wantType := range wantTypes {+ entry := entries[i].(map[string]any)+ if entry["type"] != wantType {+ t.Fatalf("entry %d type: got=%v, want=%s", i, entry["type"], wantType)+ }+ }+ for i, roundID := range []string{"round-0", "round-1", "round-2", "round-3"} {+ entry := entries[i+4].(map[string]any)+ if entry["roundID"] != roundID {+ t.Fatalf("authoritative assistant %d round: got=%v, want=%s", i, entry["roundID"], roundID)+ }+ if entry["id"] == "client-assistant-1" || entry["id"] == "client-assistant-2" {+ t.Fatalf("client assistant placeholder was retained: %#v", entry)+ }+ }+}+func TestApplyRegenerateRuntimeReplacesUserContent(t *testing.T) {const editedBlockHTML = `<div data-node-id="edited">edited prompt</div>`session := map[string]any{diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 6f983cdb67..2cda999f64 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -671,7 +671,10 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {case "content":return writeSSEEvent(c, "content", map[string]string{"token": event.Token})case "thinking":- return writeSSEEvent(c, "thinking", map[string]string{"reasoning": event.Reasoning})+ return writeSSEEvent(c, "thinking", map[string]string{+ "reasoning": event.Reasoning,+ "roundID": event.RoundID,+ })case "reasoning":return writeSSEEvent(c, "reasoning", map[string]string{"token": event.Token})case "confirm":@@ -688,12 +691,16 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {case "tool_call":return writeSSEEvent(c, "tool_call", map[string]any{"name": event.Name,+ "callID": event.ToolCallID,+ "roundID": event.RoundID,"arguments": event.Arguments,})case "tool_result":return writeSSEEvent(c, "tool_result", map[string]string{- "name": event.Name,- "result": event.Result,+ "name": event.Name,+ "callID": event.ToolCallID,+ "roundID": event.RoundID,+ "result": event.Result,})case "error":return writeSSEEvent(c, "error", map[string]string{"message": event.Error})