Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Correct agent snapshot and tool presentation https://github.com/siyuan-note/siyuan/issues/18576

Daniel9c48737eba85
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index b6947b5c47..e0ed69b591 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -22,6 +22,7 @@ import {
applyAgentUserEdit,
buildAgentPresentationEntries,
findAgentUserEntryIndex,
+ getAgentThinkingToolGroups,
hasAgentExecutedToolsAfter,
hasAgentModelSpecificContext,
isAgentRegenerateStateCurrent
@@ -103,7 +104,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: "snapshot"; snapshotID: string; roundID?: string })
| (EntryBase & { type: "rollback"; snapshotID: string });
export class AgentChat extends Model {
@@ -2090,7 +2091,12 @@ export class AgentChat extends Model {
break;
case "snapshot": {
const snapshotEntryId = SessionStore.newSessionId();
- this.entries.push({id: snapshotEntryId, type: "snapshot", snapshotID: event.snapshotID});
+ this.entries.push({
+ id: snapshotEntryId,
+ type: "snapshot",
+ snapshotID: event.snapshotID,
+ roundID: event.roundID,
+ });
this.appendSnapshotInfo(event.snapshotID, snapshotEntryId);
}
break;
@@ -2525,6 +2531,8 @@ export class AgentChat extends Model {
});
this.lastStepToolCount = this.currentToolCalls.length;
}
+ // 工具名只在当前思考步骤内去重,新步骤仍需显示同名工具调用。
+ this.renderedToolNames = {};
this.currentThinkingText = "";
this.currentThinkingReasoning = reasoning;
this.currentThinkingReasoningContent = "";
@@ -2534,9 +2542,9 @@ export class AgentChat extends Model {
this.currentThinkingText = text;
let detailLines = "";
- if (reasoning === "processing" && this.currentToolCalls.length > 0) {
+ if (reasoning === "processing" && this.currentToolCalls.length > this.lastStepToolCount) {
const newTools: Array<{ name: string; running: boolean }> = [];
- for (let i = 0; i < this.currentToolCalls.length; i++) {
+ for (let i = this.lastStepToolCount; i < this.currentToolCalls.length; i++) {
const tc = this.currentToolCalls[i];
if (!this.renderedToolNames[tc.name]) {
this.renderedToolNames[tc.name] = true;
@@ -2608,8 +2616,7 @@ export class AgentChat extends Model {
this.currentThinkingSteps = [];
this.currentThinkingEntryId = "";
}
- // 卡片边界:一张思考卡片已落盘,重置工具名去重表,使下一张卡片独立显示本轮工具
- // (与重载路径 renderMergedThinkingCard 的单卡片局部去重 seenTools 对齐)。
+ // 卡片边界:一张思考卡片已落盘,下一张卡片独立显示工具。
this.renderedToolNames = {};
// Flush tool calls as assistant entry
if (this.currentToolCalls.length > 0) {
@@ -3170,20 +3177,8 @@ export class AgentChat extends Model {
});
});
});
- // 快照应在执行区域之前:有确认卡片时插到确认卡片前,否则查找活跃的思考卡片
- const confirmCards = this.messagesContainer.querySelectorAll(".agent-chat__msg--confirm");
- if (confirmCards.length > 0) {
- this.messagesContainer.insertBefore(el, confirmCards[confirmCards.length - 1]);
- } else {
- const activeThinking = this.messagesContainer.querySelector(
- ".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)"
- );
- if (activeThinking) {
- this.messagesContainer.insertBefore(el, activeThinking);
- } else {
- this.insertBeforeAI(el);
- }
- }
+ // 快照在工具执行前产生,应显示在触发写操作的思考和确认内容之后。
+ this.insertBeforeAI(el);
this.scrollToBottom(true);
this.hasInterveningCard = true;
}
@@ -3603,7 +3598,7 @@ export class AgentChat extends Model {
return;
}
let detail = "";
- const seenTools: Record<string, boolean> = {};
+ const toolGroups = getAgentThinkingToolGroups(steps);
for (let i = 0; i < steps.length; i++) {
const step = steps[i];
if (step.content) {
@@ -3614,19 +3609,9 @@ export class AgentChat extends Model {
}
// 工具行放在该步 reasoning 之后,对齐实时流式渲染中
// 「reasoning/content 先到、工具行在下一轮 thinking 时补到末尾」的实际呈现。
- const names = step.toolNames && step.toolNames.length > 0
- ? step.toolNames
- : undefined;
- if (names && names.length > 0) {
- const newTools = names.filter(n => !seenTools[n]);
- if (newTools.length > 0) {
- detail += "<div class=\"agent-chat__thinking-tools-line\"><span class=\"agent-chat__thinking-summary\">Tool calls:</span>";
- for (let j = 0; j < newTools.length; j++) {
- seenTools[newTools[j]] = true;
- detail += '<span class="agent-chat__thinking-tool">' + escapeHtml(newTools[j]) + "</span>";
- }
- detail += "</div>";
- }
+ const names = toolGroups[i];
+ if (names.length > 0) {
+ detail += renderToolsLineHTML(names.map(name => ({name})));
}
}
diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.ts
index c0beb8080b..864a2d0bbf 100644
--- a/app/src/layout/dock/agent/AgentHistory.test.ts
+++ b/app/src/layout/dock/agent/AgentHistory.test.ts
@@ -4,6 +4,7 @@ import {
applyAgentUserEdit,
buildAgentPresentationEntries,
findAgentUserEntryIndex,
+ getAgentThinkingToolGroups,
hasAgentExecutedToolsAfter,
hasAgentModelSpecificContext,
isAgentRegenerateStateCurrent
@@ -338,4 +339,56 @@ describe("AgentHistory", () => {
const thinkingEntries = display.filter(entry => entry.type === "thinking");
assert.deepEqual(thinkingEntries.map(entry => entry.steps?.[0].toolNames), [["write-a"], ["write-b"]]);
});
+
+ it("moves a legacy snapshot after the thinking that triggered it", () => {
+ const display = buildAgentPresentationEntries([
+ {id: "user-1", type: "user", content: "create a reference"},
+ {id: "snapshot-1", type: "snapshot"},
+ {
+ id: "thinking-1",
+ type: "thinking",
+ steps: [
+ {roundID: "round-0", toolNames: ["block", "block"]},
+ {roundID: "round-1", toolNames: ["block"]},
+ ],
+ },
+ {
+ id: "thinking-2",
+ type: "thinking",
+ steps: [{roundID: "round-2", reasoningContent: "done"}],
+ },
+ {
+ id: "assistant-0",
+ type: "assistant",
+ roundID: "round-0",
+ toolCalls: [{name: "block"}, {name: "block"}],
+ },
+ {id: "assistant-1", type: "assistant", roundID: "round-1", toolCalls: [{name: "block"}]},
+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},
+ ]);
+ assert.deepEqual(display.map(entry => entry.type), [
+ "user", "thinking", "snapshot", "thinking", "assistant", "assistant", "assistant",
+ ]);
+ assert.deepEqual(getAgentThinkingToolGroups(display[1].steps || []), [["block", "block"], ["block"]]);
+ });
+
+ it("places a round snapshot after the last matching thinking card", () => {
+ const display = buildAgentPresentationEntries([
+ {id: "user-1", type: "user", content: "write"},
+ {id: "thinking-1", type: "thinking", steps: [{roundID: "round-1", toolNames: ["write"]}]},
+ {id: "confirm-1", type: "confirm"},
+ {id: "snapshot-1", type: "snapshot", roundID: "round-1"},
+ {id: "thinking-2", type: "thinking", steps: [{roundID: "round-1"}]},
+ {
+ id: "assistant-1",
+ type: "assistant",
+ roundID: "round-1",
+ toolCalls: [{name: "write"}],
+ },
+ {id: "assistant-2", type: "assistant", roundID: "round-2", content: "Done"},
+ ]);
+ assert.deepEqual(display.map(entry => entry.type), [
+ "user", "thinking", "confirm", "thinking", "snapshot", "assistant", "assistant",
+ ]);
+ });
});
diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.ts
index 7746d7aa3b..c460868f53 100644
--- a/app/src/layout/dock/agent/AgentHistory.ts
+++ b/app/src/layout/dock/agent/AgentHistory.ts
@@ -28,6 +28,10 @@ export type AgentHistoryThinkingStep = {
content?: string;
};
+export const getAgentThinkingToolGroups = (steps: AgentHistoryThinkingStep[]): string[][] => {
+ return steps.map(step => (step.toolNames || []).filter(Boolean));
+};
+
export type AgentHistoryReference = { id: string; title: string };
export type AgentHistoryUserEntry = {
@@ -310,6 +314,30 @@ const prepareAgentTurnPresentation = (entries: AgentHistoryEntry[]): AgentHistor
prepared.splice(sourceIndex >= 0 ? sourceIndex : prepared.length, 0, item.todoEntry);
}
}
+
+ // snapshot 事件先于当前思考卡片落盘。按 roundID 将其移到对应思考卡片之后;
+ // 老数据没有 roundID 时,优先使用原位置之后的第一张思考卡片。
+ for (const snapshot of prepared.filter(entry => entry.type === "snapshot")) {
+ const snapshotIndex = prepared.indexOf(snapshot);
+ const thinkingEntries = prepared.filter(entry => entry.type === "thinking" && entry.steps?.length);
+ let anchorEntry: AgentHistoryEntry | undefined;
+ if (snapshot.roundID) {
+ for (let i = thinkingEntries.length - 1; i >= 0; i--) {
+ if (thinkingEntries[i].steps?.some(step => step.roundID === snapshot.roundID)) {
+ anchorEntry = thinkingEntries[i];
+ break;
+ }
+ }
+ }
+ if (!anchorEntry) {
+ anchorEntry = thinkingEntries.find(entry => prepared.indexOf(entry) > snapshotIndex) || thinkingEntries[0];
+ }
+ if (!anchorEntry) {
+ continue;
+ }
+ prepared.splice(snapshotIndex, 1);
+ prepared.splice(prepared.indexOf(anchorEntry) + 1, 0, snapshot);
+ }
return prepared;
};
diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.ts
index a33477e1ef..5c31aa0b2f 100644
--- a/app/src/layout/dock/agent/agentSSE.ts
+++ b/app/src/layout/dock/agent/agentSSE.ts
@@ -64,6 +64,7 @@ export type ISSEResult = {
} | {
type: "snapshot";
snapshotID: string;
+ roundID?: string;
} | {
type: "permission";
permissionMode: "confirm" | "allowSession";
@@ -330,7 +331,11 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResul
case "reasoning":
return {type: "reasoning", token: data.token as string};
case "snapshot":
- return {type: "snapshot", snapshotID: data.snapshotID as string};
+ return {
+ type: "snapshot",
+ snapshotID: data.snapshotID as string,
+ roundID: data.roundID as string || undefined,
+ };
case "frontend_tool_call":
return {
type: "frontend_tool_call",
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index d645a8583c..017691d7bc 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -73,6 +73,7 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their
## Formatting
- Inline formatting uses standard markdown: **bold**, *italic*, ~~strikethrough~~, ==mark==, and "code" (backticks).
+- Block references in markdown must use ((<blockID> "<anchor text>")); never use [[<blockID>]], which is not block-reference syntax.
- For text styling that markdown cannot express (color, background, font size), use SiYuan text marks.
The syntax requires a leading data-type="text" attribute — WITHOUT it the HTML is escaped and shown as literal text:
- Text color: <span data-type="text" style="color: #ff0000;">red text</span>
@@ -1200,7 +1201,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit
}
snapshotIDs = append(snapshotIDs, id)
snapshotCreated = true
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "snapshot", SnapshotID: id})
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "snapshot", RoundID: roundID, SnapshotID: id})
}
// 工具执行前先持久化“即将执行”状态。若落盘失败则禁止执行,避免外部写操作已经发生,
diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.go
index 40f8cc57bb..147220b86a 100644
--- a/kernel/agent/prompt_test.go
+++ b/kernel/agent/prompt_test.go
@@ -47,6 +47,15 @@ func TestTurnContextStaysInUserMessage(t *testing.T) {
}
}
+func TestSystemPromptDocumentsBlockReferenceSyntax(t *testing.T) {
+ if !strings.Contains(systemPrompt, `((<blockID> "<anchor text>"))`) {
+ t.Fatal("system prompt is missing the SiYuan block-reference syntax")
+ }
+ if !strings.Contains(systemPrompt, `never use [[<blockID>]]`) {
+ t.Fatal("system prompt does not reject bracketed block IDs")
+ }
+}
+
func TestSystemPromptSortsPluginActions(t *testing.T) {
actions := []PluginAction{
{Name: "plugin__z__run", Description: "Run Z"},
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 2cda999f64..b8d0c3f7a8 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -732,7 +732,10 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {
"arguments": event.Arguments,
})
case "snapshot":
- return writeSSEEvent(c, "snapshot", map[string]string{"snapshotID": event.SnapshotID})
+ return writeSSEEvent(c, "snapshot", map[string]string{
+ "snapshotID": event.SnapshotID,
+ "roundID": event.RoundID,
+ })
}
return nil
}
diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.go
index eff14c399c..2175da24fe 100644
--- a/kernel/mcp/tools/block.go
+++ b/kernel/mcp/tools/block.go
@@ -36,7 +36,7 @@ var BlockTool = &Tool{
"notebook": {Type: "string", Description: "Notebook ID that owns the target blocks; required for encrypted notebooks"},
"id": {Type: "string", Description: "Block ID"},
"ids": {Type: "string", Description: "Comma-separated block IDs (for batch_get, batch_kramdown)"},
- "data": {Type: "string", Description: "Content (markdown or dom)"},
+ "data": {Type: "string", Description: "Content (markdown or dom). Markdown block references use ((blockID \"anchor text\")); never [[blockID]]"},
"dataType": {Type: "string", Description: "Content type: markdown or dom", Enum: []string{"markdown", "dom"}},
"lockType": {Type: "boolean", Description: "Reject update when the parsed block type differs from the existing block type; defaults to false"},
"parentID": {Type: "string", Description: "Parent block ID"},