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: Keep agent tool cards in turn order https://github.com/siyuan-note/siyuan/issues/18576
Daniel63609a5f6f63
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex c1d4454cff..b6947b5c47 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -80,6 +80,7 @@ type SessionEntry =reasoningContent: string;roundID?: string;toolNames?: string[];+ toolCallIDs?: string[];content?: string}>;duration?: number@@ -101,6 +102,7 @@ type SessionEntry =})| (EntryBase & { type: "confirm"; name: string; args: Record<string, unknown>; confirmID: string; effects?: IToolEffects; status?: string })| (EntryBase & { type: "question"; questionID: string; questions: Array<Record<string, unknown>>; status?: string; answers?: string[] })+ | (EntryBase & { type: "todo"; result: string; callID?: string; roundID?: string })| (EntryBase & { type: "snapshot"; snapshotID: string })| (EntryBase & { type: "rollback"; snapshotID: string });@@ -161,13 +163,14 @@ export class AgentChat extends Model {private editingUserEntryID = "";private editingComposer: ReturnType<typeof mountComposer> | null = null;private pendingEditDraft: { entryID: string; data: AgentComposerData } | null = null;- // thinking step 只保留工具名列表(去重:arguments/result 仅在 assistant entry 存一份),+ // thinking step 只保留工具名与调用 ID(去重:arguments/result 仅在 assistant entry 存一份),// 不再保存 text("已思考:Xs" 由 i18n 在渲染时从 duration 生成)。private currentThinkingSteps: Array<{reasoning: string;reasoningContent: string;roundID?: string;toolNames?: string[];+ toolCallIDs?: string[];content?: string}> = [];// 当前请求的思考耗时(秒)。持久化为 entry.duration,"已思考"文本不落盘。@@ -1337,6 +1340,23 @@ export class AgentChat extends Model {this.addCopyButton(el, content, timestamp);}+ private createTodoElement(result: string, entryId?: string) {+ const el = document.createElement("div");+ el.className = "agent-chat__msg agent-chat__msg--tool";+ if (entryId) {+ el.setAttribute("data-message-id", entryId);+ }+ el.innerHTML = renderTodoList(result);+ return el;+ }++ private appendPersistedTodo(result: string, entryId?: string) {+ if (!result) {+ return;+ }+ this.messagesContainer.appendChild(this.createTodoElement(result, entryId));+ }+private appendPersistedToolCalls(content: string, toolCalls: Array<{name: string;arguments: Record<string, unknown>;@@ -1346,12 +1366,9 @@ export class AgentChat extends Model {for (let i = 0; i < toolCalls.length; i++) {const tc = toolCalls[i];if (tc.result && tc.name === "todo_write") {- const rel = document.createElement("div");- rel.className = "agent-chat__msg agent-chat__msg--tool";// todo 卡片是 assistant entry 的附属展示,不单独持有 entryId// (entryId 属于后续的 AI 消息元素),避免多个 todo 共享同一 id。- rel.innerHTML = renderTodoList(tc.result);- this.messagesContainer.appendChild(rel);+ this.appendPersistedTodo(tc.result);hasRendered = true;}}@@ -1536,6 +1553,9 @@ export class AgentChat extends Model {}break;}+ case "todo":+ this.appendPersistedTodo((entry as { result: string }).result, entryId);+ break;case "confirm":this.appendPersistedConfirm(entry as unknown as {id?: string;@@ -2479,10 +2499,7 @@ export class AgentChat extends Model {return;}- const el = document.createElement("div");- el.className = "agent-chat__msg agent-chat__msg--tool";- el.setAttribute("data-message-id", SessionStore.newSessionId());- el.innerHTML = renderTodoList(result);+ const el = this.createTodoElement(result, SessionStore.newSessionId());this.insertBeforeAI(el);this.scrollToBottom(true);this.hasInterveningCard = true;@@ -2497,11 +2514,14 @@ export class AgentChat extends Model {const toolNames = this.currentToolCalls.slice(this.lastStepToolCount).map(function (t) {return t.name;});+ const toolCallIDs = this.currentToolCalls.slice(this.lastStepToolCount)+ .map(toolCall => toolCall.id || "").filter(Boolean);this.currentThinkingSteps.push({reasoning: this.currentThinkingReasoning,reasoningContent: this.currentThinkingReasoningContent,roundID: this.currentRoundID || undefined,toolNames: toolNames.length > 0 ? toolNames : undefined,+ toolCallIDs: toolCallIDs.length > 0 ? toolCallIDs : undefined,});this.lastStepToolCount = this.currentToolCalls.length;}@@ -3035,11 +3055,14 @@ export class AgentChat extends Model {const toolNames = this.currentToolCalls.slice(this.lastStepToolCount).map(function (t) {return t.name;});+ const toolCallIDs = this.currentToolCalls.slice(this.lastStepToolCount)+ .map(toolCall => toolCall.id || "").filter(Boolean);this.currentThinkingSteps.push({reasoning: this.currentThinkingReasoning,reasoningContent: this.currentThinkingReasoningContent,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;diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.tsindex 8771ad59e1..c0beb8080b 100644--- a/app/src/layout/dock/agent/AgentHistory.test.ts+++ b/app/src/layout/dock/agent/AgentHistory.test.ts@@ -257,4 +257,85 @@ describe("AgentHistory", () => {assert.equal(display.filter(entry => entry.type === "thinking").length, 1);assert.equal(display.find(entry => entry.roundID === "round-1")?.content, undefined);});++ it("keeps todo results after their corresponding thinking card", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{roundID: "round-1", toolNames: ["todo_write"], toolCallIDs: ["call-todo"]}],+ },+ {+ id: "thinking-2",+ type: "thinking",+ steps: [{roundID: "round-2", reasoningContent: "continue"}],+ },+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ toolCalls: [{id: "call-todo", name: "todo_write", result: "todo result"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);+ assert.deepEqual(display.map(entry => entry.type), [+ "user", "thinking", "todo", "thinking", "assistant", "assistant",+ ]);+ assert.equal(display[2].result, "todo result");+ assert.deepEqual(display.find(entry => entry.id === "assistant-1")?.toolCalls, []);+ });++ it("uses tool call IDs to preserve tools split by confirmations in one round", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{roundID: "round-1", toolNames: ["old-a"], toolCallIDs: ["call-a"]}],+ },+ {id: "confirm-1", type: "confirm"},+ {+ id: "thinking-2",+ type: "thinking",+ steps: [{roundID: "round-1", toolNames: ["old-b"], toolCallIDs: ["call-b"]}],+ },+ {id: "confirm-2", type: "confirm"},+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ toolCalls: [{id: "call-a", name: "write-a"}, {id: "call-b", name: "write-b"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);+ const thinkingEntries = display.filter(entry => entry.type === "thinking");+ assert.deepEqual(thinkingEntries.map(entry => entry.steps?.[0].toolNames), [["write-a"], ["write-b"]]);+ });++ it("preserves legacy tool subsets when confirmations split one round", () => {+ const display = buildAgentPresentationEntries([+ {id: "user-1", type: "user", content: "work"},+ {+ id: "thinking-1",+ type: "thinking",+ steps: [{roundID: "round-1", toolNames: ["write-a"]}],+ },+ {id: "confirm-1", type: "confirm"},+ {+ id: "thinking-2",+ type: "thinking",+ steps: [{roundID: "round-1", toolNames: ["write-b"]}],+ },+ {+ id: "assistant-1",+ type: "assistant",+ roundID: "round-1",+ toolCalls: [{name: "write-a"}, {name: "write-b"}],+ },+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},+ ]);+ const thinkingEntries = display.filter(entry => entry.type === "thinking");+ assert.deepEqual(thinkingEntries.map(entry => entry.steps?.[0].toolNames), [["write-a"], ["write-b"]]);+ });});diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.tsindex 95eff93e94..7746d7aa3b 100644--- a/app/src/layout/dock/agent/AgentHistory.ts+++ b/app/src/layout/dock/agent/AgentHistory.ts@@ -3,11 +3,14 @@ export type AgentHistoryEntry = {type: string;status?: string;content?: string;+ result?: string;+ callID?: string;reasoningContent?: string;roundID?: string;duration?: number;steps?: AgentHistoryThinkingStep[];toolCalls?: Array<{+ id?: string;name?: string;result?: string;state?: string;@@ -21,6 +24,7 @@ export type AgentHistoryThinkingStep = {reasoningContent?: string;roundID?: string;toolNames?: string[];+ toolCallIDs?: string[];content?: string;};@@ -89,22 +93,89 @@ const enrichThinkingStep = (step: AgentHistoryThinkingStep, entry: AgentHistoryEif (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 enrichThinkingStepTools = (step: AgentHistoryThinkingStep, relatedSteps: AgentHistoryThinkingStep[],+ entry: AgentHistoryEntry) => {+ const calls = entry.toolCalls || [];+ const toolNames = calls.map(call => call.name || "").filter(Boolean);+ if (toolNames.length === 0) {+ return;+ }++ const hasCallIDs = relatedSteps.some(item => item.toolCallIDs && item.toolCallIDs.length > 0);+ if (hasCallIDs) {+ const assignedCallIndexes = new Set<number>();+ for (const relatedStep of relatedSteps) {+ if (!relatedStep.toolCallIDs || relatedStep.toolCallIDs.length === 0) {+ continue;+ }+ const resolvedNames: string[] = [];+ for (const callID of relatedStep.toolCallIDs) {+ const callIndex = calls.findIndex((call, index) =>+ !assignedCallIndexes.has(index) && call.id === callID);+ if (callIndex >= 0 && calls[callIndex].name) {+ assignedCallIndexes.add(callIndex);+ resolvedNames.push(calls[callIndex].name!);+ }+ }+ if (resolvedNames.length > 0) {+ relatedStep.toolNames = resolvedNames;+ }+ }+ // 兼容一部分步骤尚未写入调用 ID 的过渡数据,先用已有名称认领对应调用。+ for (const relatedStep of relatedSteps) {+ if (relatedStep.toolCallIDs?.length || !relatedStep.toolNames?.length) {+ continue;+ }+ for (const name of relatedStep.toolNames) {+ const callIndex = calls.findIndex((call, index) =>+ !assignedCallIndexes.has(index) && call.name === name);+ if (callIndex >= 0) {+ assignedCallIndexes.add(callIndex);+ }+ }+ }+ const remainingCalls = calls.filter((call, index) => !assignedCallIndexes.has(index) && !!call.name);+ if (remainingCalls.length > 0) {+ step.toolNames = (step.toolNames || []).concat(remainingCalls.map(call => call.name!));+ const remainingIDs = remainingCalls.map(call => call.id || "").filter(Boolean);+ if (remainingIDs.length > 0) {+ step.toolCallIDs = (step.toolCallIDs || []).concat(remainingIDs);+ }+ }+ return;+ }++ // 一个模型轮次可能被确认卡片拆成多个思考步骤。老数据没有调用 ID 时保留已有子集,+ // 避免把整轮工具列表覆盖到第一个步骤后造成重复。+ if (relatedSteps.length > 1 && relatedSteps.some(item => item.toolNames && item.toolNames.length > 0)) {+ return;+ }+ step.toolNames = toolNames;+ const toolCallIDs = calls.map(call => call.id || "").filter(Boolean);+ if (toolCallIDs.length > 0) {+ step.toolCallIDs = toolCallIDs;+ }+};++const buildRecoveredThinkingStep = (entry: AgentHistoryEntry, includeContent: boolean): 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) {+ step.toolCallIDs = toolCallIDs;+ }+ return step;+};const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistoryEntry[] => {const prepared: AgentHistoryEntry[] = entries.map(entry => ({@@ -112,12 +183,18 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorsteps: entry.steps?.map(step => ({...step,toolNames: step.toolNames?.slice(),+ ...(step.toolCallIDs ? {toolCallIDs: step.toolCallIDs.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 }> = [];+ const todoInsertions: Array<{+ sourceEntry: AgentHistoryEntry;+ anchorStep?: AgentHistoryThinkingStep;+ todoEntry: AgentHistoryEntry+ }> = [];for (const entry of prepared) {if (entry.type !== "assistant") {@@ -126,8 +203,10 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistorconst isProcess = !!entry.toolCalls?.length;const toolNames = entry.toolCalls?.map(call => call.name || "").filter(Boolean) || [];let step: AgentHistoryThinkingStep | undefined;+ let relatedSteps: AgentHistoryThinkingStep[] = [];if (entry.roundID) {- step = thinkingSteps.find(item => item.roundID === entry.roundID && !matchedSteps.has(item));+ relatedSteps = thinkingSteps.filter(item => item.roundID === entry.roundID);+ step = relatedSteps.find(item => !matchedSteps.has(item));}if (!step && (isProcess || entry.reasoningContent?.trim())) {step = thinkingSteps.find(item => !item.roundID && !matchedSteps.has(item) && (@@ -136,63 +215,100 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor(!!entry.reasoningContent?.trim() && item.reasoningContent === entry.reasoningContent)));}+ let presentationStep = step;if (step) {enrichThinkingStep(step, entry, isProcess);+ enrichThinkingStepTools(step, relatedSteps.length > 0 ? relatedSteps : [step], entry);matchedSteps.add(step);} else if (isProcess || entry.reasoningContent?.trim()) {- recovered.push({entry, step: buildRecoveredThinkingStep(entry, isProcess)});+ presentationStep = buildRecoveredThinkingStep(entry, isProcess);+ recovered.push({entry, step: presentationStep});}if (isProcess) {// 带工具调用的 assistant 是模型协议过程,不单独渲染为回答气泡。entry.content = undefined;+ const remainingToolCalls: NonNullable<AgentHistoryEntry["toolCalls"]> = [];+ for (const call of entry.toolCalls || []) {+ if (call.name === "todo_write" && call.result?.trim()) {+ const callStep = call.id+ ? thinkingSteps.find(item => item.toolCallIDs?.includes(call.id!))+ : undefined;+ todoInsertions.push({+ sourceEntry: entry,+ anchorStep: callStep || presentationStep,+ todoEntry: {+ type: "todo",+ result: call.result,+ callID: call.id,+ roundID: entry.roundID,+ },+ });+ } else {+ remainingToolCalls.push(call);+ }+ }+ entry.toolCalls = remainingToolCalls;}}- 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++);+ if (recovered.length > 0) {+ 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;+ 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 (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),+ });}}- if (synthetic.length > 0) {- const firstUnmatched = prepared.indexOf(synthetic[0].entry);- prepared.splice(firstUnmatched, 0, {- type: "thinking",- steps: synthetic.map(item => item.step),- });++ const todoOffsets = new Map<AgentHistoryEntry, number>();+ for (const item of todoInsertions) {+ const anchorEntry = item.anchorStep+ ? prepared.find(entry => entry.type === "thinking" && entry.steps?.includes(item.anchorStep!))+ : undefined;+ if (anchorEntry) {+ const offset = todoOffsets.get(anchorEntry) || 0;+ prepared.splice(prepared.indexOf(anchorEntry) + 1 + offset, 0, item.todoEntry);+ todoOffsets.set(anchorEntry, offset + 1);+ } else {+ const sourceIndex = prepared.indexOf(item.sourceEntry);+ prepared.splice(sourceIndex >= 0 ? sourceIndex : prepared.length, 0, item.todoEntry);+ }}return prepared;};diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.tsindex 50c6209309..c7d1d235e9 100644--- a/app/src/layout/dock/agent/SessionStore.ts+++ b/app/src/layout/dock/agent/SessionStore.ts@@ -66,13 +66,14 @@ export interface AgentSession {selectedBlockIDs?: string[];visibleBlockIDs?: string[];};- // thinking step:新格式只含 reasoning/reasoningContent/roundID/toolNames/content;+ // thinking step:新格式只含 reasoning/reasoningContent/roundID/toolNames/toolCallIDs/content;// text/toolCalls 仅为读取老数据而保留为可选(渲染时归一化)。steps?: Array<{reasoning: string;reasoningContent: string;roundID?: string;toolNames?: string[];+ toolCallIDs?: string[];content?: string;text?: string;toolCalls?: Array<{name: string; result?: string}>diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 7cd94d3c82..d645a8583c 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -432,12 +432,13 @@ type SessionEntry struct {SnapshotID string `json:"snapshotID,omitempty"`}-// SessionEntryStep 描述一次思考步骤。工具调用只保留名字列表,过程正文保存在 Content,+// SessionEntryStep 描述一次思考步骤。工具调用只保留名字与调用 ID 列表,过程正文保存在 Content,// arguments/result 仅在所属 assistant entry 的 ToolCalls 中存储,避免重复。type SessionEntryStep struct {Reasoning string `json:"reasoning"`ReasoningContent string `json:"reasoningContent,omitempty"`ToolNames []string `json:"toolNames,omitempty"`+ ToolCallIDs []string `json:"toolCallIDs,omitempty"`Content string `json:"content,omitempty"`RoundID string `json:"roundID,omitempty"`}diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.goindex d1879513d7..941071b871 100644--- a/kernel/agent/runtime.go+++ b/kernel/agent/runtime.go@@ -476,7 +476,6 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeT}// 当前 turn 的 assistant 内容以 runtime 为权威;前端只补充 thinking/confirm/question 等 UI 条目。- // 用权威 assistant 逐个替换前端占位可尽量保留 UI 条目的相对位置;缺少占位时再追加到末尾。authoritative := make([]any, 0, len(turn.Delta)+1)for i, message := range turn.Delta {if message.Role != "assistant" {