Skip to content

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

:art: Improve AI agent session checkpoint safety https://github.com/siyuan-note/siyuan/issues/17797

Daniel669f0858c1ea
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 926445cb28..9958e6f286 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -52,7 +52,7 @@ type SessionEntry =
| (EntryBase & {
type: "assistant";
content?: string;
- toolCalls?: Array<{ name: string; arguments: Record<string, unknown>; result?: string }>;
+ toolCalls?: Array<{ name: string; arguments: Record<string, unknown>; result?: string; state?: string }>;
timestamp?: number
})
| (EntryBase & { type: "confirm"; name: string; args: Record<string, unknown>; confirmID: string; status?: string })
@@ -72,12 +72,17 @@ export class AgentChat extends Model {
private sessionPanel: AgentSessionPanel;
private sessionId = "";
private sessionTitle = "";
+ private pendingSessionTitle: string | null = null;
private entries: SessionEntry[] = [];
private hasTitled = false;
private isStreaming = false;
private currentAIElement: HTMLElement | null = null;
private currentAssistantEntryId = "";
private currentThinkingEntryId = "";
+ private currentTurnID = "";
+ private recoveryCommitTurnIDs = new Map<string, string>();
+ private pendingRecoverySessionIDs = new Set<string>();
+ private recoveryInFlightSessionIDs = new Set<string>();
private lute: Lute;
private currentContent = "";
private fullContent = "";
@@ -311,11 +316,17 @@ export class AgentChat extends Model {
onSwitch: (id) => this.switchSession(id),
onDelete: (id) => this.deleteSession(id),
onRename: async (id, title) => {
- await SessionStore.rename(id, title);
if (id === this.sessionId) {
this.sessionTitle = title;
this.titleElement.textContent = title;
+ // 当前轮次开始前后都依赖同一个内容修订号。流式中只更新本地标题,
+ // 由终止提交一并落盘,避免元数据保存抢先递增修订号。
+ if (this.isStreaming || this.currentTurnID) {
+ this.pendingSessionTitle = title;
+ return;
+ }
}
+ await SessionStore.rename(id, title);
},
}
);
@@ -471,7 +482,7 @@ export class AgentChat extends Model {
const examples = this.messagesContainer.querySelectorAll(".agent-welcome__example");
examples.forEach((example) => {
const ex = example as HTMLElement;
- ex.addEventListener("click", () => {
+ ex.addEventListener("click", async () => {
const text = ex.getAttribute("data-text") || "";
if (text && this.composer) {
this.messagesContainer.innerHTML = "";
@@ -481,27 +492,44 @@ export class AgentChat extends Model {
this.rebuildNavMarkers();
this.tryGenerateTitle();
this.setStreaming(true);
+ try {
+ await this.saveSession();
+ } catch (e) {
+ this.rollbackUserEntry(userEntryId);
+ this.setStreaming(false);
+ await this.reloadFromDisk();
+ return;
+ }
this.abortController = new AbortController();
const requestSessionId = this.sessionId;
this.requestStartTime = Date.now();
this.currentThinkingDuration = 0;
- fetchAgentSSE(text, window.siyuan.config.appearance.lang, [],
+ this.currentTurnID = "";
+ await fetchAgentSSE(text, window.siyuan.config.appearance.lang, [],
(event: ISSEResult) => {
if (this.sessionId !== requestSessionId) {
return;
}
- this.handleSSEEvent(event);
+ return this.handleSSEEvent(event);
},
(err: Error) => {
if (this.sessionId !== requestSessionId) {
return;
}
- this.handleConfigError(err, userEntryId);
+ if (err instanceof AgentHttpError && err.status === 409) {
+ return this.handleConflictReject();
+ }
+ return this.handleConfigError(err, userEntryId);
},
this.abortController.signal,
this.sessionId,
this.getSelectedModel(),
- this.selectedReasoningEffort);
+ this.selectedReasoningEffort,
+ undefined,
+ undefined,
+ undefined,
+ userEntryId,
+ SessionStore.getRevision(this.sessionId));
}
});
});
@@ -692,20 +720,25 @@ export class AgentChat extends Model {
this.sessionId = SessionStore.newSessionId();
this.sessionCreatedAt = Date.now();
this.sessionTitle = this.defaultTitle;
+ this.pendingSessionTitle = null;
this.entries = [];
this.showWelcome();
this.scrollToBottom(true);
}
- private async saveSession() {
+ private async saveSession(commitTurnID?: string): Promise<AgentSession | null> {
if (this.entries.length === 0) {
- return;
+ return null;
}
+ const sessionID = this.sessionId;
+ const recoveryTurnID = this.recoveryCommitTurnIDs.get(sessionID);
+ const turnID = commitTurnID || recoveryTurnID;
+ const pendingTitle = this.pendingSessionTitle;
const session: AgentSession = {
- id: this.sessionId,
+ id: sessionID,
title: this.sessionTitle,
titled: this.hasTitled,
- entries: this.entries.slice(),
+ entries: JSON.parse(JSON.stringify(this.entries.concat(this.pendingConfirms))) as AgentSession["entries"],
contextTokens: this.contextTokens,
contextTokenBreakdown: this.contextTokenBreakdown,
contextCachedTokens: this.contextCachedTokens,
@@ -715,22 +748,38 @@ export class AgentChat extends Model {
messageHistory: this.composer?.getHistory() || [],
model: this.getSelectedModel(),
};
- await SessionStore.save(session);
+ if (turnID) {
+ session.commitTurnID = turnID;
+ }
+ const result = await SessionStore.save(session);
+ if (turnID && this.recoveryCommitTurnIDs.get(sessionID) === turnID) {
+ this.recoveryCommitTurnIDs.delete(sessionID);
+ }
+ if (turnID) {
+ this.pendingRecoverySessionIDs.delete(sessionID);
+ }
+ if (this.sessionId !== sessionID) {
+ return result.session ?? null;
+ }
+ if (pendingTitle !== null && pendingTitle === session.title && this.pendingSessionTitle === pendingTitle) {
+ this.pendingSessionTitle = null;
+ }
+ if (turnID && this.currentTurnID === turnID) {
+ this.currentTurnID = "";
+ }
+ if (this.pendingSessionTitle !== null && !this.isStreaming && !this.currentTurnID) {
+ await this.saveSession();
+ }
+ return result.session ?? null;
}
- // 处理 ws 推送的跨实例会话变更通知。核心时序控制:
- // - streamStart:其他实例开始流式,本实例(若看同一会话且非自身流式中)进入占位锁定。
- // - streamEnd:其他实例流式结束,本实例从磁盘拉取整条会话重绘(唯一重绘触发点)。
- // - update:会话列表元数据刷新,不重绘当前视图(回避流式中途半截 saveSession 数据的时序问题)。
- // - delete:当前会话被删除则清空视图。
// 处理 ws 推送的跨实例会话变更通知。核心时序控制:
// - streamStart:其他实例开始流式。立即从磁盘拉取一次(发起者发消息时已把 user 消息落盘),
// 让本轮用户新消息尽快可见,然后进入占位锁定显示"AI 回复生成中"。
- // - update:发起者 saveSession 落盘后广播(含流式结束写完整 AI 回复的那次)。每次都重绘,
- // 保证镜像端始终显示发起者已落盘的最新内容。流式中途的 saveSession 只写已完成的历史
- // (正在生成的回复在 finishResponse 才入 entries),不会读到半截数据。
- // - streamEnd:后端 eventCh 关闭(流结束)。此时发起者前端可能尚未 saveSession 落盘,
- // 故只解除占位锁定、不重绘;完整内容由随后的 update 广播驱动重绘。
+ // - update:会话保存或未提交运行时进入可恢复状态。每次都读取后端权威视图;流式中途的保存
+ // 只包含已完成历史和交互卡片,不会把半截 assistant 文本当成最终结果。
+ // - streamEnd:后端 eventCh 关闭(流结束),只解除占位锁定;已提交内容由 saveSession 的 update
+ // 同步,未提交内容由后端紧随其后的恢复 update 同步。
// - delete:当前会话被删除则清空视图。
private onWsMessage(data: IWebSocketData) {
if (!data || data.cmd !== "agentSessionChanged") {
@@ -763,7 +812,11 @@ export class AgentChat extends Model {
this.removeMirrorPlaceholder();
break;
case "update":
- void this.reloadFromDisk();
+ void this.reloadFromDisk().then(() => {
+ if (this.pendingRecoverySessionIDs.has(payload.sessionID)) {
+ void this.recoverInterruptedTurn(payload.sessionID, this.currentTurnID);
+ }
+ });
break;
case "delete":
this.mirrorLocked = false;
@@ -798,7 +851,7 @@ export class AgentChat extends Model {
}
// 镜像端从磁盘拉取整条会话权威数据重绘。仅 entries 变化时清空重绘,避免无谓跳变。
- private async reloadFromDisk() {
+ private async reloadFromDisk(forceRender = false) {
const targetSessionId = this.sessionId;
const session = await SessionStore.load(targetSessionId);
// await 期间用户可能已切换会话,丢弃过期结果。
@@ -809,13 +862,32 @@ export class AgentChat extends Model {
return;
}
const newEntries = this.buildEntriesFromSession(session);
- if (this.entriesEqual(newEntries, this.entries)) {
+ if (!forceRender && this.entriesEqual(newEntries, this.entries)) {
// 内容未变,仅更新元数据(标题等)。
this.updateMetaFromSession(session);
return;
}
const atBottom = this.isScrolledToBottom();
const savedScroll = this.messagesContainer.scrollTop;
+ if (forceRender) {
+ this.currentAIElement = null;
+ this.observeStickTarget(null);
+ this.currentAssistantEntryId = "";
+ this.currentContent = "";
+ this.fullContent = "";
+ this.currentToolCalls = [];
+ this.pendingConfirms = [];
+ this.currentThinkingSteps = [];
+ this.currentThinkingEntryId = "";
+ this.currentThinkingStepContent = "";
+ this.currentThinkingText = "";
+ this.currentThinkingReasoning = "";
+ this.currentThinkingReasoningContent = "";
+ this.currentThinkingDuration = 0;
+ this.lastStepToolCount = 0;
+ this.renderedToolNames = {};
+ this.hasInterveningCard = false;
+ }
this.entries = newEntries;
this.updateMetaFromSession(session);
this.messagesContainer.innerHTML = "";
@@ -834,15 +906,94 @@ export class AgentChat extends Model {
}
}
+ private async recoverInterruptedTurn(sessionID: string, turnID = "") {
+ this.pendingRecoverySessionIDs.add(sessionID);
+ if (this.recoveryInFlightSessionIDs.has(sessionID)) {
+ return;
+ }
+ this.recoveryInFlightSessionIDs.add(sessionID);
+ const retryDelays = [100, 200, 400, 800, 1600, 3200];
+ try {
+ for (const delay of retryDelays) {
+ await new Promise((resolve) => window.setTimeout(resolve, delay));
+ if (this.sessionId !== sessionID || this.isStreaming) {
+ return;
+ }
+ let session: AgentSession | null;
+ try {
+ session = await SessionStore.load(sessionID);
+ } catch (e) {
+ console.error("recover interrupted agent turn failed:", e);
+ continue;
+ }
+ if (!session?.recoveryTurnID) {
+ if (session && !session.agentRunning) {
+ this.pendingRecoverySessionIDs.delete(sessionID);
+ if (!turnID || this.currentTurnID === turnID) {
+ this.currentTurnID = "";
+ }
+ return;
+ }
+ continue;
+ }
+ if (turnID && session.recoveryTurnID !== turnID) {
+ continue;
+ }
+ try {
+ await this.reloadFromDisk(true);
+ if (this.sessionId !== sessionID) {
+ return;
+ }
+ if (this.recoveryCommitTurnIDs.get(sessionID) !== session.recoveryTurnID) {
+ continue;
+ }
+ this.currentTurnID = "";
+ await this.saveSession();
+ this.pendingRecoverySessionIDs.delete(sessionID);
+ return;
+ } catch (e) {
+ console.error("commit recovered agent turn failed:", e);
+ }
+ }
+ } finally {
+ this.recoveryInFlightSessionIDs.delete(sessionID);
+ }
+ }
+
+ private async prepareForNewTurn(): Promise<boolean> {
+ const sessionID = this.sessionId;
+ if (this.pendingRecoverySessionIDs.has(sessionID) && !this.recoveryCommitTurnIDs.has(sessionID)) {
+ void this.recoverInterruptedTurn(sessionID, this.currentTurnID);
+ const L = window.siyuan.languages;
+ showMessage(L.agentChatBusy || "This session is busy in another instance", 3000);
+ return false;
+ }
+ if (!this.recoveryCommitTurnIDs.has(sessionID)) {
+ return true;
+ }
+ try {
+ await this.saveSession();
+ return this.sessionId === sessionID;
+ } catch (e) {
+ await this.reloadFromDisk(true);
+ return false;
+ }
+ }
+
// 从 session 更新标题/时间戳/token 计数/model 等元数据,不动 entries 与 DOM。
private updateMetaFromSession(session: AgentSession) {
- this.sessionTitle = session.title || this.defaultTitle;
+ this.sessionTitle = this.pendingSessionTitle || session.title || this.defaultTitle;
this.hasTitled = session.titled !== false;
this.sessionCreatedAt = session.createdAt || this.sessionCreatedAt;
this.contextTokens = session.contextTokens ?? 0;
this.contextTokenBreakdown = session.contextTokenBreakdown ?? {};
this.contextCachedTokens = session.contextCachedTokens ?? 0;
this.contextLimit = session.contextLimit ?? 0;
+ if (session.recoveryTurnID) {
+ this.recoveryCommitTurnIDs.set(session.id, session.recoveryTurnID);
+ } else {
+ this.recoveryCommitTurnIDs.delete(session.id);
+ }
if (session.model) {
this.applySessionModelIfValid(session.model);
}
@@ -868,11 +1019,16 @@ export class AgentChat extends Model {
// 当前会话被其他实例删除时,清空到欢迎页。不调 saveSession(会话已不存在于磁盘)。
private handleCurrentSessionDeleted() {
+ const deletedSessionID = this.sessionId;
this.removeMirrorPlaceholder();
this.entries = [];
this.sessionId = SessionStore.newSessionId();
+ this.currentTurnID = "";
this.sessionCreatedAt = Date.now();
this.sessionTitle = this.defaultTitle;
+ this.pendingSessionTitle = null;
+ this.pendingRecoverySessionIDs.delete(deletedSessionID);
+ this.recoveryCommitTurnIDs.delete(deletedSessionID);
this.hasTitled = false;
this.currentAIElement = null;
this.currentContent = "";
@@ -887,23 +1043,41 @@ export class AgentChat extends Model {
}
private async switchSession(id: string) {
+ const previousSessionID = this.sessionId;
+ const hadActiveTurn = this.isStreaming || !!this.currentTurnID;
+ if (hadActiveTurn) {
+ this.pendingRecoverySessionIDs.add(previousSessionID);
+ if (this.abortController) {
+ this.abortController.abort();
+ this.abortController = null;
+ }
+ }
this.setStreaming(false);
this.mirrorLocked = false;
this.removeMirrorPlaceholder();
this.finishActiveThinking();
this.flushThinkingStep();
- await this.saveSession();
+ if (!hadActiveTurn && !this.pendingRecoverySessionIDs.has(this.sessionId)) {
+ await this.saveSession();
+ }
const session = await SessionStore.load(id);
if (!session) {
return;
}
this.sessionId = session.id;
+ this.currentTurnID = "";
+ if (session.recoveryTurnID) {
+ this.recoveryCommitTurnIDs.set(session.id, session.recoveryTurnID);
+ } else {
+ this.recoveryCommitTurnIDs.delete(session.id);
+ }
if (this.composer) {
this.composer.clearHistory();
this.composer.restoreHistory(session.messageHistory || []);
}
this.sessionCreatedAt = session.createdAt || Date.now();
this.sessionTitle = session.title;
+ this.pendingSessionTitle = null;
this.titleElement.textContent = session.title || this.defaultTitle;
this.entries = this.buildEntriesFromSession(session);
this.hasTitled = session.titled !== false;
@@ -933,6 +1107,9 @@ export class AgentChat extends Model {
this.scrollToBottom(true);
}
this.messagesContainer.classList.remove("agent-chat__messages--switching");
+ if (this.pendingRecoverySessionIDs.has(session.id)) {
+ void this.recoverInterruptedTurn(session.id);
+ }
}, {once: true});
}
@@ -1195,6 +1372,11 @@ export class AgentChat extends Model {
}
private async createSession() {
+ const previousSessionID = this.sessionId;
+ const hadActiveTurn = this.isStreaming || !!this.currentTurnID;
+ if (hadActiveTurn) {
+ this.pendingRecoverySessionIDs.add(previousSessionID);
+ }
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
@@ -1204,13 +1386,17 @@ export class AgentChat extends Model {
this.removeMirrorPlaceholder();
this.finishActiveThinking();
this.flushThinkingStep();
- await this.saveSession();
+ if (!hadActiveTurn && !this.pendingRecoverySessionIDs.has(this.sessionId)) {
+ await this.saveSession();
+ }
this.sessionId = SessionStore.newSessionId();
+ this.currentTurnID = "";
this.sessionCreatedAt = Date.now();
if (this.composer) {
this.composer.clearHistory();
}
this.sessionTitle = this.defaultTitle;
+ this.pendingSessionTitle = null;
this.entries = [];
this.hasTitled = false;
this.currentAIElement = null;
@@ -1246,6 +1432,12 @@ export class AgentChat extends Model {
}
private async deleteSession(id: string) {
+ if (id === this.sessionId && (this.isStreaming || !!this.currentTurnID ||
+ this.pendingRecoverySessionIDs.has(id))) {
+ const L = window.siyuan.languages;
+ showMessage(L.agentChatBusy || "This session is busy in another instance", 3000);
+ return;
+ }
this.scrollBottomBySession.delete(id);
const wasCurrent = id === this.sessionId;
if (wasCurrent) {
@@ -1263,6 +1455,8 @@ export class AgentChat extends Model {
} else {
await SessionStore.remove(id);
}
+ this.pendingRecoverySessionIDs.delete(id);
+ this.recoveryCommitTurnIDs.delete(id);
}
private async sendMessage() {
@@ -1279,6 +1473,9 @@ export class AgentChat extends Model {
if (!text || this.isStreaming || this.modelOptions.length === 0) {
return;
}
+ if (!await this.prepareForNewTurn()) {
+ return;
+ }
this.setStreaming(true);
this.clearThinking();
@@ -1296,10 +1493,18 @@ export class AgentChat extends Model {
if (this.composer) {
this.composer.pushHistory(text);
}
- await this.saveSession();
+ try {
+ await this.saveSession();
+ } catch (e) {
+ this.rollbackUserEntry(userEntryId);
+ this.setStreaming(false);
+ await this.reloadFromDisk();
+ return;
+ }
this.requestStartTime = Date.now();
this.currentThinkingDuration = 0;
+ this.currentTurnID = "";
this.abortController = new AbortController();
const requestSessionId = this.sessionId;
@@ -1318,9 +1523,9 @@ export class AgentChat extends Model {
if (this.sessionId !== requestSessionId) {
return;
}
- // 409:该会话正在其他实例对话中(实例级互斥)。回滚刚追加的 user 消息,不进入流式。
+ // 409:该会话正在其他实例对话中(实例级互斥)。重载磁盘权威状态,不进入流式。
if (err instanceof AgentHttpError && err.status === 409) {
- this.handleConflictReject(userEntryId);
+ this.handleConflictReject();
return;
}
return this.handleConfigError(err, userEntryId);
@@ -1332,26 +1537,17 @@ export class AgentChat extends Model {
undefined,
editorContext,
pluginActions,
+ userEntryId,
+ SessionStore.getRevision(this.sessionId),
);
}
- // 实例级互斥被拒(409):回滚 sendMessage 已追加的 user 消息与磁盘保存,恢复到发送前状态。
- private async handleConflictReject(userEntryId: string) {
+ // 实例级互斥被拒(409)说明另一实例已在本轮保存之后抢先启动。此时磁盘可能已有对方的新消息,
+ // 不能再用本地快照回滚;直接重载权威会话,避免覆盖另一实例的数据。
+ private async handleConflictReject() {
this.requestStartTime = 0;
this.setStreaming(false);
- // 回滚 entries 里的 user entry。
- const idx = this.entries.findIndex(e => e.id === userEntryId);
- if (idx >= 0) {
- this.entries.splice(idx, 1);
- }
- // 回滚 DOM 上的 user 消息元素。
- const userEl = this.messagesContainer.querySelector('.agent-chat__msg--user[data-message-id="' + userEntryId + '"]');
- if (userEl) {
- userEl.remove();
- }
- this.rebuildNavMarkers();
- // 恢复磁盘到发送前状态(entries 已不含该 user 消息)。
- await this.saveSession();
+ await this.reloadFromDisk(true);
const L = window.siyuan.languages;
showMessage(L.agentChatBusy || "This session is busy in another instance", 3000);
}
@@ -1529,6 +1725,9 @@ export class AgentChat extends Model {
private async handleSSEEvent(event: ISSEResult) {
try {
switch (event.type) {
+ case "turn":
+ this.currentTurnID = event.turnID;
+ break;
case "content":
this.appendToken(event.token);
break;
@@ -1548,6 +1747,7 @@ export class AgentChat extends Model {
this.appendToolResult(event.name, event.result);
break;
case "done":
+ this.currentTurnID = event.turnID || this.currentTurnID;
this.flushTokenUpdate();
await this.finishResponse();
break;
@@ -1556,14 +1756,19 @@ export class AgentChat extends Model {
break;
case "error":
this.flushTokenUpdate();
- // 中断时同样需把已收到的纯文本 body 富渲染(与正常结束的 finalizeStreamingBody 一致)。
- if (this.currentContent) {
- this.finalizeStreamingBody(this.currentContent, Date.now());
- }
this.requestStartTime = 0;
- this.appendError(event.message);
- this.setStreaming(false);
- await this.saveSession();
+ if (this.currentTurnID) {
+ // 服务端 error 是终止事件:此前已完成运行时检查点和所有工具结果发送,
+ // 因此可复用正常收尾,把部分回复与工具调用写入 entries 后提交该 turn。
+ await this.finishResponse(false);
+ this.appendError(event.message);
+ } else {
+ // turn 建立前的错误没有可提交的运行时,直接恢复磁盘权威状态。
+ await this.handleError(new Error(event.message));
+ }
+ break;
+ case "interrupted":
+ await this.handleError(new Error(event.message));
break;
case "retry":
this.appendRetry(event.attempt, event.maxRetries);
@@ -1586,29 +1791,51 @@ export class AgentChat extends Model {
}
} catch (e) {
console.error("agent SSE event handler error:", e, event);
- this.flushTokenUpdate();
- if (this.currentContent) {
- this.finalizeStreamingBody(this.currentContent, Date.now());
+ if (this.abortController) {
+ this.abortController.abort();
+ this.abortController = null;
}
+ this.flushTokenUpdate();
this.requestStartTime = 0;
this.setStreaming(false);
+ const sessionID = this.sessionId;
+ const turnID = this.currentTurnID;
+ try {
+ await this.reloadFromDisk(true);
+ } catch (reloadError) {
+ console.error("reload agent session after event failure failed:", reloadError);
+ }
+ if (this.sessionId === sessionID) {
+ this.appendError((e as Error).message);
+ if (turnID) {
+ void this.recoverInterruptedTurn(sessionID, turnID);
+ }
+ }
}
}
private async handleError(err: Error) {
this.flushTokenUpdate();
- if (this.currentContent) {
- this.finalizeStreamingBody(this.currentContent, Date.now());
- }
this.requestStartTime = 0;
- this.appendError(err.message);
this.setStreaming(false);
- await this.saveSession();
+ const sessionID = this.sessionId;
+ const turnID = this.currentTurnID;
+ try {
+ await this.reloadFromDisk(true);
+ } catch (reloadError) {
+ console.error("reload agent session after stream failure failed:", reloadError);
+ }
+ if (this.sessionId === sessionID) {
+ this.appendError(err.message);
+ // 网络断流不等于服务端 turn 已终止,不能提交并清除 runtime。待后端释放运行实例后
+ // 再合并 runtime,避免重复执行结果未知的外部调用。turn 事件也可能在断流前尚未来得及送达。
+ void this.recoverInterruptedTurn(sessionID, turnID);
+ }
}
// 统一处理 fetchAgentSSE 的 onError:若为"未配置模型/提供商"则渲染可操作错误卡,
// 否则回退到普通错误卡。userEntryId 用于在"未配置"时回滚刚追加的 user 消息(避免留下空对话)。
- private async handleConfigError(err: Error, userEntryId?: string) {
+ private async handleConfigError(err: Error, userEntryId?: string, restoreSession = false) {
this.flushTokenUpdate();
if (this.currentContent) {
this.finalizeStreamingBody(this.currentContent, Date.now());
@@ -1617,17 +1844,31 @@ export class AgentChat extends Model {
const configMsg = window.siyuan.languages._kernel[193] || "";
const isConfigError = !!configMsg && err.message === configMsg;
if (isConfigError) {
- if (userEntryId) {
- this.rollbackUserEntry(userEntryId);
+ if (restoreSession) {
+ // 重新生成在 Agent 建立 runtime 前只截断了前端视图;配置错误时应恢复原回答,
+ // 不能把这个临时截断状态保存到 session.json。
+ await this.reloadFromDisk(true);
+ } else {
+ if (userEntryId) {
+ this.rollbackUserEntry(userEntryId);
+ }
+ if (this.entries.length === 0) {
+ await SessionStore.remove(this.sessionId);
+ this.sessionTitle = this.defaultTitle;
+ this.pendingSessionTitle = null;
+ this.hasTitled = false;
+ this.titleElement.textContent = this.defaultTitle;
+ void this.sessionPanel?.refresh();
+ } else {
+ await this.saveSession();
+ }
}
await this.appendConfigurableError(configMsg);
} else {
- this.appendError(err.message);
+ await this.handleError(err);
+ return;
}
this.setStreaming(false);
- if (!isConfigError) {
- await this.saveSession();
- }
}
// 回滚刚追加的 user entry 与 DOM 元素(用于"未配置"错误时避免留下空对话)。
@@ -2031,6 +2272,9 @@ export class AgentChat extends Model {
if (this.isStreaming || this.modelOptions.length === 0) {
return;
}
+ if (!await this.prepareForNewTurn()) {
+ return;
+ }
// Pop all entries after the last user entry
while (this.entries.length > 0 && this.entries[this.entries.length - 1].type !== "user") {
this.entries.pop();
@@ -2064,6 +2308,7 @@ export class AgentChat extends Model {
this.removeMirrorPlaceholder();
this.requestStartTime = Date.now();
this.currentThinkingDuration = 0;
+ this.currentTurnID = "";
const lastUserEntry = this.entries[this.entries.length - 1];
const lastUserText = lastUserEntry.type === "user" ? lastUserEntry.content : "";
this.abortController = new AbortController();
@@ -2084,19 +2329,19 @@ export class AgentChat extends Model {
}
// 409:该会话正在其他实例对话中(实例级互斥),不进入流式。
if (err instanceof AgentHttpError && err.status === 409) {
- this.requestStartTime = 0;
- this.setStreaming(false);
- const L = window.siyuan.languages;
- showMessage(L.agentChatBusy || "This session is busy in another instance", 3000);
- return;
+ return this.handleConflictReject();
}
- return this.handleConfigError(err);
+ return this.handleConfigError(err, undefined, true);
},
this.abortController.signal,
this.sessionId,
this.getSelectedModel(),
this.selectedReasoningEffort,
true,
+ undefined,
+ undefined,
+ lastUserEntry.id,
+ SessionStore.getRevision(this.sessionId),
);
}
@@ -2120,7 +2365,7 @@ export class AgentChat extends Model {
}
}
- private async finishResponse() {
+ private async finishResponse(notify = true) {
// 思考结束前先记录最后一张未完成的思考卡片,折叠后用于定位滚动锚点。
const activeThinkCard = this.messagesContainer.querySelector(
".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)"
@@ -2194,10 +2439,33 @@ export class AgentChat extends Model {
this.requestStartTime = 0;
}
this.updateTokenDisplay();
+ const sessionID = this.sessionId;
+ const canonicalSession = await this.saveSession(this.currentTurnID);
+ if (this.sessionId === sessionID) {
+ // 提交时后端会用 runtime 重建本轮 assistant/tool 结果。直接采用提交响应中的权威会话,
+ // 避免下一轮普通保存又用前端流式快照覆盖,也避免额外 GET 的失败/乱序窗口。
+ if (canonicalSession) {
+ const atBottom = this.isScrolledToBottom();
+ const savedScroll = this.messagesContainer.scrollTop;
+ this.entries = this.buildEntriesFromSession(canonicalSession);
+ this.updateMetaFromSession(canonicalSession);
+ this.messagesContainer.innerHTML = "";
+ this.renderLoadedSession(canonicalSession);
+ if (atBottom) {
+ this.scrollToBottom(true);
+ } else {
+ this.messagesContainer.scrollTop = savedScroll;
+ }
+ } else {
+ await this.reloadFromDisk(true);
+ }
+ }
this.setStreaming(false);
- await this.saveSession();
+ if (this.pendingSessionTitle !== null && this.sessionId === sessionID) {
+ await this.saveSession();
+ }
this.rebuildNavMarkers();
- if (savedContent && (!document.hasFocus() || document.hidden)) {
+ if (notify && savedContent && (!document.hasFocus() || document.hidden)) {
const L = window.siyuan.languages;
sendNotification({title: L.agentNotifyDone, timeoutType: "default"});
}
@@ -2247,6 +2515,7 @@ export class AgentChat extends Model {
return;
}
this.hasTitled = true;
+ const requestSessionID = this.sessionId;
const userEntry = this.entries.find((e): e is { type: "user"; content: string } => e.type === "user");
const userMsg = userEntry?.content?.slice(0, 500) || "";
fetch("/api/ai/agent/title", {
@@ -2258,17 +2527,22 @@ export class AgentChat extends Model {
language: window.siyuan.config.appearance.lang
}),
}).then((resp) => resp.json()).then((data) => {
- if (data.code === 0 && data.data && data.data !== this.sessionTitle) {
+ if (this.sessionId === requestSessionID && data.code === 0 && data.data && data.data !== this.sessionTitle) {
this.sessionTitle = data.data;
+ this.pendingSessionTitle = data.data;
this.titleElement.textContent = data.data;
- this.saveSession();
+ // 流式结束时的统一提交会包含最新标题;流式中单独保存会改变内容修订号,
+ // 使尚未创建的 runtime turn 被误判为旧请求。
+ if (!this.isStreaming && !this.currentTurnID) {
+ void this.saveSession();
+ }
}
}).catch((e) => {
console.error("agent title request error:", e);
});
}
- private async appendError(message: string) {
+ private appendError(message: string) {
this.finishActiveThinking();
this.clearThinking();
if (this.currentAIElement && !this.currentContent) {
@@ -2281,7 +2555,6 @@ export class AgentChat extends Model {
this.messagesContainer.appendChild(el);
this.scrollToBottom(true);
this.flushThinkingStep();
- await this.saveSession();
}
private appendRetry(attempt: number, maxRetries: number) {
@@ -2412,7 +2685,18 @@ export class AgentChat extends Model {
}
this.updateTokenDisplay();
this.setStreaming(false);
- await this.saveSession();
+ const sessionID = this.sessionId;
+ const turnID = this.currentTurnID;
+ // abort 只中断前端连接;外部工具可能仍在返回途中。不能在这里直接保存并清除 runtime,
+ // 等后端写完 interrupted 检查点后再恢复并提交。turn 事件可能尚未到达,因此空 ID 也要轮询。
+ try {
+ await this.reloadFromDisk(true);
+ } catch (e) {
+ console.error("reload agent session after stop failed:", e);
+ }
+ if (this.sessionId === sessionID) {
+ void this.recoverInterruptedTurn(sessionID, turnID);
+ }
this.rebuildNavMarkers();
}
@@ -2441,54 +2725,64 @@ export class AgentChat extends Model {
'<button class="b3-button b3-button--text agent-chat__confirm-always ariaLabel" data-position="n" aria-label="' + (L.agentConfirmAlwaysDesc || "Session Allow") + '">' + (L.agentConfirmAlways || "Session Allow") + "</button>" +
"</div>" +
"</div>";
+ const sessionID = this.sessionId;
+ const confirmEntryId = SessionStore.newSessionId();
+ const confirmEntry: SessionEntry = {
+ id: confirmEntryId,
+ type: "confirm",
+ name,
+ args,
+ confirmID,
+ status: "pending",
+ };
+ el.setAttribute("data-message-id", confirmEntryId);
+ this.pendingConfirms.push(confirmEntry);
+ const submitConfirm = async (approved: boolean, always: boolean, doneText: string) => {
+ const buttons = Array.from(el.querySelectorAll("button")) as HTMLButtonElement[];
+ buttons.forEach((button) => button.disabled = true);
+ const accepted = await this.postConfirm(confirmID, approved, always, sessionID, confirmEntryId);
+ if (!accepted) {
+ buttons.forEach((button) => button.disabled = false);
+ showMessage(window.siyuan.languages._kernel[28], 3000);
+ return;
+ }
+ el.classList.add("agent-chat__msg--confirmed");
+ const actions = el.querySelector(".agent-chat__confirm-actions") as HTMLElement;
+ if (actions) {
+ actions.innerHTML = '<span class="agent-chat__confirm-done">' + doneText + "</span>";
+ }
+ };
const approveBtn = el.querySelector(".agent-chat__confirm-approve");
if (approveBtn) {
approveBtn.addEventListener("click", (e) => {
e.stopPropagation();
- el.classList.add("agent-chat__msg--confirmed");
- const btns = el.querySelector(".agent-chat__confirm-actions") as HTMLElement;
- if (btns) {
- btns.innerHTML = '<span class="agent-chat__confirm-done">' + (L.agentConfirmApprove || "Approved") + "</span>";
- }
- this.postConfirm(confirmID, true);
+ void submitConfirm(true, false, L.agentConfirmApprove || "Approved");
});
}
const rejectBtn = el.querySelector(".agent-chat__confirm-reject");
if (rejectBtn) {
rejectBtn.addEventListener("click", (e) => {
e.stopPropagation();
- el.classList.add("agent-chat__msg--confirmed");
- const btns = el.querySelector(".agent-chat__confirm-actions") as HTMLElement;
- if (btns) {
- btns.innerHTML = '<span class="agent-chat__confirm-done">' + (L.agentConfirmReject || "Rejected") + "</span>";
- }
- this.postConfirm(confirmID, false);
+ void submitConfirm(false, false, L.agentConfirmReject || "Rejected");
});
}
const alwaysBtn = el.querySelector(".agent-chat__confirm-always");
if (alwaysBtn) {
alwaysBtn.addEventListener("click", (e) => {
e.stopPropagation();
- el.classList.add("agent-chat__msg--confirmed");
- const btns = el.querySelector(".agent-chat__confirm-actions") as HTMLElement;
- if (btns) {
- btns.innerHTML = '<span class="agent-chat__confirm-done">' + (L.agentConfirmAlways || "Session Allow") + "</span>";
- }
- this.postConfirm(confirmID, true, true);
+ void submitConfirm(true, true, L.agentConfirmAlways || "Session Allow");
});
}
this.insertBeforeAI(el);
this.scrollToBottom(true);
this.hasInterveningCard = true;
- const confirmEntryId = SessionStore.newSessionId();
- el.setAttribute("data-message-id", confirmEntryId);
- this.pendingConfirms.push({id: confirmEntryId, type: "confirm", name, args, confirmID, status: "pending"});
if (!document.hasFocus() || document.hidden) {
sendNotification({title: L.agentNotifyConfirm, body: "", timeoutType: "default"});
}
}
- private async postConfirm(confirmID: string, approved: boolean, always?: boolean) {
+ private async postConfirm(confirmID: string, approved: boolean, always: boolean,
+ sessionID: string, confirmEntryID: string): Promise<boolean> {
const body: Record<string, unknown> = {confirmID: confirmID, approved: approved};
if (always) {
body.always = true;
@@ -2499,19 +2793,29 @@ export class AgentChat extends Model {
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
});
- if (!resp.ok) {
+ const result = await resp.json() as {code?: number};
+ if (!resp.ok || result?.code !== 0) {
console.error("agent confirm request failed:", resp.status);
+ return false;
}
} catch (e) {
console.error("agent confirm request error:", e);
+ return false;
}
- const entry = this.entries.find(e => e.type === "confirm" && e.confirmID === confirmID) as {
- status?: string
- } | undefined;
+ if (this.sessionId !== sessionID) {
+ return true;
+ }
+ const entry = (this.entries.find(e => e.id === confirmEntryID) ||
+ this.pendingConfirms.find(e => e.id === confirmEntryID)) as {status?: string} | undefined;
if (entry) {
entry.status = always ? "always" : (approved ? "approved" : "rejected");
}
- await this.saveSession();
+ try {
+ await this.saveSession();
+ } catch (e) {
+ console.error("save agent confirmation state failed:", e);
+ }
+ return true;
}
private async handleFrontendToolCall(callID: string, args: Record<string, unknown>) {
diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.ts
index f3f0a8fbc1..46e8a0c9ee 100644
--- a/app/src/layout/dock/agent/SessionStore.ts
+++ b/app/src/layout/dock/agent/SessionStore.ts
@@ -2,9 +2,32 @@ import {fetchSyncPost} from "../../../util/fetch";
import {Constants} from "../../../constants";
const API = "/api/ai/agent";
+const sessionRevisions = new Map<string, number>();
+const sessionRuntimeRevisions = new Map<string, number>();
+const sessionSaveQueues = new Map<string, Promise<SessionSaveResult>>();
+
+interface SessionSaveResult {
+ revision: number;
+ session?: AgentSession;
+}
+
+async function waitForPendingSave(id: string) {
+ const pending = sessionSaveQueues.get(id);
+ if (pending) {
+ try {
+ await pending;
+ } catch (e) {
+ // 后续读取或删除以服务端当前状态为准。
+ }
+ }
+}
// 标识发起者 app,后端 saveSession/removeSession 据此排除自身、向其他实例广播会话变更。
-const APP_HEADER = {"X-SiYuan-App-ID": Constants.SIYUAN_APPID};
+const APP_HEADER = {
+ "Content-Type": "application/json",
+ "X-SiYuan-App-ID": Constants.SIYUAN_APPID,
+ "X-SiYuan-Agent-Checkpoint": "2",
+};
export interface SessionIndexItem {
id: string;
@@ -41,15 +64,15 @@ export interface AgentSession {
toolCalls?: Array<{name: string; result?: string}>
}>;
reasoningContent?: string;
- toolCalls?: Array<{name: string; arguments?: Record<string, unknown>; result?: string}>;
+ toolCalls?: Array<{name: string; arguments?: Record<string, unknown>; result?: string; state?: string}>;
duration?: number;
- confirmName?: string;
- confirmArgs?: Record<string, unknown>;
+ timestamp?: number;
+ name?: string;
+ args?: Record<string, unknown>;
confirmID?: string;
- confirmStatus?: string;
+ status?: string;
questionID?: string;
questions?: Array<Record<string, unknown>>;
- questionStatus?: string;
answers?: string[];
snapshotID?: string;
}>;
@@ -64,6 +87,14 @@ export interface AgentSession {
messageHistory?: string[];
createdAt: number;
updatedAt: number;
+ revision?: number;
+ expectedRevision?: number;
+ commitTurnID?: string;
+ lastCommittedTurnID?: string;
+ recoveryTurnID?: string;
+ recoveryState?: string;
+ recoveryRevision?: number;
+ agentRunning?: boolean;
}
function newSessionId(): string {
@@ -87,17 +118,69 @@ export const SessionStore = {
},
async load(id: string): Promise<AgentSession | null> {
- const resp = await fetchSyncPost(API + "/getSession", {id}) as {code: number, data: AgentSession};
- return (resp && resp.code === 0) ? resp.data : null;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ await waitForPendingSave(id);
+ const resp = await fetchSyncPost(API + "/getSession", {id}) as {code: number, data: AgentSession};
+ if (!resp || resp.code !== 0) {
+ return null;
+ }
+ const revision = resp.data.revision ?? 0;
+ const runtimeRevision = resp.data.recoveryRevision ?? 0;
+ const knownRevision = sessionRevisions.get(id) ?? 0;
+ const knownRuntimeRevision = sessionRuntimeRevisions.get(id) ?? 0;
+ if (revision < knownRevision ||
+ (revision === knownRevision && runtimeRevision < knownRuntimeRevision)) {
+ continue;
+ }
+ sessionRevisions.set(id, revision);
+ sessionRuntimeRevisions.set(id, runtimeRevision);
+ return resp.data;
+ }
+ // 连续写入期间若三次读取都落后于本地已知版本,则不返回旧数据覆盖界面。
+ return null;
},
- async save(session: AgentSession): Promise<void> {
- session.updatedAt = Date.now();
- await fetchSyncPost(API + "/saveSession", session, APP_HEADER);
+ async save(session: AgentSession): Promise<SessionSaveResult> {
+ const snapshot = JSON.parse(JSON.stringify(session)) as AgentSession;
+ snapshot.updatedAt = Date.now();
+ const baseRevision = snapshot.expectedRevision ?? sessionRevisions.get(snapshot.id) ?? snapshot.revision ?? 0;
+ const previous = sessionSaveQueues.get(snapshot.id);
+ const persist = async (expectedRevision: number) => {
+ snapshot.expectedRevision = expectedRevision;
+ const resp = await fetchSyncPost(API + "/saveSession", snapshot, APP_HEADER) as {
+ code: number;
+ msg?: string;
+ data?: {revision?: number; session?: AgentSession};
+ };
+ if (!resp || resp.code !== 0) {
+ throw new Error(resp?.msg || "Failed to save agent session");
+ }
+ const revision = resp.data?.revision ?? expectedRevision;
+ sessionRevisions.set(snapshot.id, revision);
+ if (snapshot.commitTurnID || snapshot.recoveryTurnID) {
+ sessionRuntimeRevisions.set(snapshot.id, 0);
+ }
+ return {revision, session: resp.data?.session};
+ };
+ const save = previous ? previous.then((result) => persist(result.revision)) : persist(baseRevision);
+ sessionSaveQueues.set(snapshot.id, save);
+ try {
+ return await save;
+ } finally {
+ if (sessionSaveQueues.get(snapshot.id) === save) {
+ sessionSaveQueues.delete(snapshot.id);
+ }
+ }
},
async remove(id: string): Promise<void> {
- await fetchSyncPost(API + "/removeSession", {id}, APP_HEADER);
+ await waitForPendingSave(id);
+ const resp = await fetchSyncPost(API + "/removeSession", {id}, APP_HEADER) as {code: number; msg?: string};
+ if (!resp || resp.code !== 0) {
+ throw new Error(resp?.msg || "Failed to remove agent session");
+ }
+ sessionRevisions.delete(id);
+ sessionRuntimeRevisions.delete(id);
},
async rename(id: string, newTitle: string): Promise<void> {
@@ -107,5 +190,9 @@ export const SessionStore = {
await this.save(session);
},
+ getRevision(id: string): number {
+ return sessionRevisions.get(id) ?? 0;
+ },
+
newSessionId,
};
diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.ts
index e53d712de4..5fa3383c1a 100644
--- a/app/src/layout/dock/agent/agentSSE.ts
+++ b/app/src/layout/dock/agent/agentSSE.ts
@@ -1,4 +1,7 @@
export type ISSEResult = {
+ type: "turn";
+ turnID: string;
+} | {
type: "content";
token: string;
} | {
@@ -20,8 +23,12 @@ export type ISSEResult = {
} | {
type: "error";
message: string;
+} | {
+ type: "interrupted";
+ message: string;
} | {
type: "done";
+ turnID: string;
} | {
type: "usage";
promptTokens: number;
@@ -77,7 +84,7 @@ export async function fetchAgentSSE(
language: string,
references: Array<{id: string; title: string}>,
onEvent: (event: ISSEResult) => void | Promise<void>,
- onError: (err: Error) => void,
+ onError: (err: Error) => void | Promise<void>,
signal?: AbortSignal,
sessionID?: string,
model?: string,
@@ -85,7 +92,21 @@ export async function fetchAgentSSE(
regenerate?: boolean,
editorContext?: IEditorContext,
pluginActions?: Array<{name: string; description: string}>,
+ userEntryID?: string,
+ contentRevision?: number,
): Promise<void> {
+ let errorReported = false;
+ const reportError = async (err: Error) => {
+ if (errorReported) {
+ return;
+ }
+ errorReported = true;
+ try {
+ await onError(err);
+ } catch (handlerErr) {
+ console.error("agent SSE error handler failed:", handlerErr);
+ }
+ };
try {
const body: Record<string, unknown> = {message: message, language: language, references: references};
if (sessionID) { body.sessionID = sessionID; }
@@ -94,6 +115,8 @@ export async function fetchAgentSSE(
if (regenerate) { body.regenerate = regenerate; }
if (editorContext) { body.editorContext = editorContext; }
if (pluginActions && pluginActions.length > 0) { body.pluginActions = pluginActions; }
+ if (userEntryID) { body.userEntryID = userEntryID; }
+ if (typeof contentRevision === "number") { body.contentRevision = contentRevision; }
const response = await fetch("/api/ai/agent/chat", {
method: "POST",
@@ -118,7 +141,7 @@ export async function fetchAgentSSE(
}
msg = window.siyuan.languages.agentChatBusy || msg;
}
- onError(new AgentHttpError(msg, response.status));
+ await reportError(new AgentHttpError(msg, response.status));
return;
}
@@ -130,22 +153,23 @@ export async function fetchAgentSSE(
const text = await response.text();
const data = text ? JSON.parse(text) : null;
const errMsg = (data && (data.msg || data.message)) || window.siyuan.languages._kernel[28];
- onError(new AgentHttpError(errMsg, response.status));
+ await reportError(new AgentHttpError(errMsg, response.status));
} catch (e) {
- onError(new Error(window.siyuan.languages._kernel[28]));
+ await reportError(new Error(window.siyuan.languages._kernel[28]));
}
return;
}
const reader = response.body ? response.body.getReader() : null;
if (!reader) {
- onError(new Error(window.siyuan.languages._kernel[28]));
+ await reportError(new Error(window.siyuan.languages._kernel[28]));
return;
}
const decoder = new TextDecoder();
let buffer = "";
let currentEvent = "";
+ let terminalReceived = false;
while (true) {
const readResult = await reader.read();
@@ -164,15 +188,17 @@ export async function fetchAgentSSE(
} else if (line.indexOf("data:") === 0) {
const dataStr = line.slice(5).trim();
if (currentEvent && dataStr) {
+ let result: ISSEResult | null = null;
try {
- const data = JSON.parse(dataStr);
- const result = buildSSEResult(currentEvent, data);
- if (result) {
- await onEvent(result);
- }
+ result = buildSSEResult(currentEvent, JSON.parse(dataStr));
} catch (e) {
// skip malformed data
}
+ if (result) {
+ await onEvent(result);
+ terminalReceived = result.type === "done" || result.type === "error" ||
+ result.type === "interrupted" || terminalReceived;
+ }
}
currentEvent = "";
}
@@ -185,26 +211,31 @@ export async function fetchAgentSSE(
if (line.indexOf("data:") === 0 && currentEvent) {
const dataStr = line.slice(5).trim();
if (dataStr) {
+ let result: ISSEResult | null = null;
try {
- const data = JSON.parse(dataStr);
- const result = buildSSEResult(currentEvent, data);
- if (result) {
- await onEvent(result);
- }
+ result = buildSSEResult(currentEvent, JSON.parse(dataStr));
} catch (e) {
// skip malformed data
}
+ if (result) {
+ await onEvent(result);
+ terminalReceived = result.type === "done" || result.type === "error" ||
+ result.type === "interrupted" || terminalReceived;
+ }
}
}
}
+ if (!terminalReceived && !signal?.aborted) {
+ await reportError(new Error(window.siyuan.languages._kernel[28]));
+ }
} catch (err) {
const e = err as Error;
if (e.name !== "AbortError") {
const msg = e.message.toLowerCase();
if (msg.indexOf("timeout") !== -1 || msg.indexOf("deadline") !== -1) {
- onError(new Error(window.siyuan.languages._kernel[24]));
+ await reportError(new Error(window.siyuan.languages._kernel[24]));
} else {
- onError(new Error(window.siyuan.languages._kernel[28]));
+ await reportError(new Error(window.siyuan.languages._kernel[28]));
}
}
}
@@ -212,6 +243,8 @@ export async function fetchAgentSSE(
function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResult | null {
switch (event) {
+ case "turn":
+ return {type: "turn", turnID: data.turnID as string};
case "content":
return {type: "content", token: data.token as string};
case "thinking":
@@ -237,8 +270,10 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResul
};
case "error":
return {type: "error", message: data.message as string};
+ case "interrupted":
+ return {type: "interrupted", message: data.message as string};
case "done":
- return {type: "done"};
+ return {type: "done", turnID: data.turnID as string};
case "usage":
return {
type: "usage",
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 1c42d83066..2df3bd5ab3 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -21,7 +21,6 @@ import (
"errors"
"fmt"
"io"
- "maps"
"math/rand/v2"
"os"
@@ -31,11 +30,12 @@ import (
"time"
"github.com/88250/gulu"
+ "github.com/88250/lute/ast"
"github.com/siyuan-note/logging"
"github.com/sashabaranov/go-openai"
- "github.com/siyuan-note/filelock"
mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client"
+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"
kernelModel "github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -199,12 +199,21 @@ func buildDoomSignature(name, action string, args map[string]any) string {
var confirmChannelsMu sync.Mutex
var confirmChannels = make(map[string]chan confirmResult)
-func ConfirmSession(id string, approved bool, always bool) {
+func ConfirmSession(id string, approved bool, always bool) bool {
confirmChannelsMu.Lock()
ch, ok := confirmChannels[id]
- confirmChannelsMu.Unlock()
if ok {
- ch <- confirmResult{approved: approved, always: always}
+ delete(confirmChannels, id)
+ }
+ confirmChannelsMu.Unlock()
+ if !ok {
+ return false
+ }
+ select {
+ case ch <- confirmResult{approved: approved, always: always}:
+ return true
+ default:
+ return false
}
}
@@ -220,11 +229,14 @@ func AnswerQuestion(id string, answers []string) {
ch, ok := questionChannels[id]
questionChannelsMu.Unlock()
if ok {
- ch <- QuestionAnswer{Answers: answers}
+ select {
+ case ch <- QuestionAnswer{Answers: answers}:
+ default:
+ }
}
}
-// frontendCallResult carries the result of a frontend tool action back from the browser.
+// frontendCallResult 承载浏览器返回的前端工具执行结果。
type frontendCallResult struct {
result string
isError bool
@@ -233,14 +245,16 @@ type frontendCallResult struct {
var frontendCallChannelsMu sync.Mutex
var frontendCallChannels = make(map[string]chan frontendCallResult)
-// FrontendToolResult is called by the API handler when the browser POSTs the outcome of a
-// frontend tool action. It unblocks the agent goroutine waiting in handleFrontendTool.
+// FrontendToolResult 由 API 在浏览器回传前端工具结果时调用,用于解除 Agent 的等待。
func FrontendToolResult(callID string, result string, isError bool) {
frontendCallChannelsMu.Lock()
ch, ok := frontendCallChannels[callID]
frontendCallChannelsMu.Unlock()
if ok {
- ch <- frontendCallResult{result: result, isError: isError}
+ select {
+ case ch <- frontendCallResult{result: result, isError: isError}:
+ default:
+ }
}
}
@@ -286,12 +300,14 @@ type AgentEvent struct {
RetryAttempt int
RetryMax int
SnapshotID string
+ TurnID string
}
type AgentMessage struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`
+ EntryID string `json:"entryID,omitempty"`
}
type AgentToolCall struct {
@@ -299,6 +315,7 @@ type AgentToolCall struct {
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
Result string `json:"result,omitempty"`
+ State string `json:"state,omitempty"`
}
type Reference struct {
@@ -340,10 +357,13 @@ type SessionEntry struct {
CompletionTok int `json:"completionTokens,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
ReasoningCont string `json:"reasoningContent,omitempty"`
- ConfirmName string `json:"confirmName,omitempty"`
- ConfirmArgs map[string]any `json:"confirmArgs,omitempty"`
+ Name string `json:"name,omitempty"`
+ Args map[string]any `json:"args,omitempty"`
ConfirmID string `json:"confirmID,omitempty"`
- ConfirmStatus string `json:"confirmStatus,omitempty"`
+ Status string `json:"status,omitempty"`
+ QuestionID string `json:"questionID,omitempty"`
+ Questions []map[string]any `json:"questions,omitempty"`
+ Answers []string `json:"answers,omitempty"`
SnapshotID string `json:"snapshotID,omitempty"`
}
@@ -372,9 +392,11 @@ type agentCheckpoint struct {
ContextTokenBreakdown map[string]int `json:"contextTokenBreakdown,omitempty"`
ContextCachedTokens int `json:"contextCachedTokens,omitempty"`
ContextLimit int `json:"contextLimit,omitempty"`
+ Revision int64 `json:"revision,omitempty"`
+ LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`
}
-func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout time.Duration) <-chan AgentEvent {
+func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userEntryID string, contentRevision int64, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout time.Duration) <-chan AgentEvent {
ch := make(chan AgentEvent, 256)
go func() {
@@ -382,13 +404,17 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
defer func() {
if r := recover(); r != nil {
logging.LogErrorf("agent chat panic: %v\n%s", r, logging.ShortStack())
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: kernelModel.Conf.Language(28)})
}
}()
if kernelModel.Conf.AI.MCP != nil {
mcpclient.EnsureMCPConnected(kernelModel.Conf.AI.MCP.Servers)
}
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
// 变量(非敏感)在用户消息注入对话时解析,让 LLM 看到实际值;密钥不进上下文。
// 在此统一解析一次,后续 checkpoint 与消息重建均使用解析后的值,保证全链路一致。
@@ -399,20 +425,12 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
var checkpointMsgs []AgentMessage
var totalPrompt, totalCompletion, lastPromptTokens, lastCachedTokens int
contextLimit := GetModelContextLimit(model)
- startTime := time.Now().UnixMilli()
alwaysAllow := map[string]bool{}
var doomLoop doomLoopTracker
var compactCount int
var snapshotIDs []string
snapshotCreated := false // 整个 AgentChat 过程最多打一次自动快照,避免多轮工具调用时每轮都打
var roundsSinceCheckpoint int
- var pendingCheckpoints sync.WaitGroup // 跟踪挂起的中途异步 checkpoint,保证最终落盘前全部完成
- // finalCheckpoint 先等待所有挂起的中途异步 checkpoint 完成,再做最终的同步落盘,
- // 确保旧的异步数据不会在最终 checkpoint 之后写入而覆盖新数据。
- finalCheckpoint := func() {
- pendingCheckpoints.Wait()
- saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
- }
if sessionID != "" {
if cp := loadCheckpoint(sessionID); cp != nil {
@@ -424,30 +442,112 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
// 截断/重建逻辑(thinking/confirm/snapshot 不参与 LLM 上下文)。
loadedMsgs := entriesToAgentMessages(cp.Entries)
truncated := loadedMsgs
+ currentUserExists := false
if regenerate {
lastUserIdx := -1
for i := len(truncated) - 1; i >= 0; i-- {
- if truncated[i].Role == "user" {
+ if truncated[i].Role == "user" && (userEntryID == "" || truncated[i].EntryID == userEntryID) {
lastUserIdx = i
break
}
}
- if lastUserIdx >= 0 && truncated[lastUserIdx].Content == userMessage {
+ if lastUserIdx >= 0 {
truncated = truncated[:lastUserIdx]
+ } else if userEntryID != "" {
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: kernelModel.Conf.Language(28)})
+ return
+ }
+ } else {
+ for i := len(truncated) - 1; i >= 0; i-- {
+ if truncated[i].Role != "user" {
+ continue
+ }
+ currentUserExists = userEntryID != "" && truncated[i].EntryID == userEntryID
+ if userEntryID == "" && truncated[i].Content == userMessage {
+ currentUserExists = true
+ }
+ break
}
}
checkpointMsgs = truncated
- checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "user", Content: userMessage})
+ if regenerate || !currentUserExists {
+ checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "user", Content: userMessage, EntryID: userEntryID})
+ }
messages = checkpointMessagesToOpenAI(checkpointMsgs, language, references, editorCtx, pluginActions)
}
}
+ if runtime, err := loadRuntimeState(sessionID); err == nil && runtime != nil && runtime.AlwaysAllow {
+ alwaysAllow["*"] = true
+ }
}
if messages == nil {
- checkpointMsgs = []AgentMessage{{Role: "user", Content: userMessage}}
+ checkpointMsgs = []AgentMessage{{Role: "user", Content: userMessage, EntryID: userEntryID}}
messages = buildInitialMessages(userMessage, language, references, editorCtx, pluginActions)
}
+ turnBaseIndex := len(checkpointMsgs)
+ turn := &agentRuntimeTurn{
+ TurnID: ast.NewNodeID(),
+ Mode: "append",
+ UserEntryID: userEntryID,
+ BaseRevision: contentRevision,
+ State: "running",
+ UpdatedAt: time.Now().UnixMilli(),
+ }
+ if regenerate {
+ turn.Mode = "regenerate"
+ turn.TargetUserEntryID = userEntryID
+ }
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ if err := beginRuntimeTurn(sessionID, turn, alwaysAllow["*"]); err != nil {
+ logging.LogErrorf("begin agent runtime failed: %s", err)
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: kernelModel.Conf.Language(28)})
+ return
+ }
+ // turn 是恢复协议的身份锚点,且此时事件通道仍为空。直接写入缓冲区,确保请求刚被取消时
+ // API 的后台排空逻辑仍能记录 turnID 并在最终检查点落盘后通知前端恢复。
+ ch <- AgentEvent{Type: "turn", TurnID: turn.TurnID}
+ runtimeFinalized := false
+ saveTurn := func(state string) bool {
+ turn.State = state
+ deltaStart := turnBaseIndex
+ for i := len(checkpointMsgs) - 1; i >= 0; i-- {
+ message := checkpointMsgs[i]
+ if message.Role == "user" && ((userEntryID != "" && message.EntryID == userEntryID) ||
+ (userEntryID == "" && message.Content == userMessage)) {
+ deltaStart = i + 1
+ break
+ }
+ }
+ if deltaStart > len(checkpointMsgs) {
+ deltaStart = len(checkpointMsgs)
+ }
+ turn.Delta = append([]AgentMessage(nil), checkpointMsgs[deltaStart:]...)
+ turn.SnapshotIDs = append([]string(nil), snapshotIDs...)
+ turn.PromptTokens = totalPrompt
+ turn.CompletionTokens = totalCompletion
+ turn.LastPromptTokens = lastPromptTokens
+ turn.CachedTokens = lastCachedTokens
+ turn.ContextLimit = contextLimit
+ if err := saveRuntimeTurn(sessionID, turn, alwaysAllow["*"]); err != nil {
+ logging.LogErrorf("save agent runtime failed: %s", err)
+ return false
+ } else if state != "running" {
+ runtimeFinalized = true
+ }
+ return true
+ }
+ defer func() {
+ if !runtimeFinalized {
+ saveTurn("interrupted")
+ }
+ }()
+
temperature := kernelModel.Conf.AI.Agent.Temperature
if temperature < 0 || 2 < temperature {
temperature = 1.0
@@ -499,14 +599,17 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
continue
}
logging.LogErrorf("agent API request failed: %s", streamErr.Error())
+ if !saveTurn("interrupted") {
+ return
+ }
sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(streamErr)})
- finalCheckpoint()
return
}
var contentBuilder strings.Builder
var reasoningBuilder strings.Builder
var aggregatedToolCalls []openai.ToolCall
+ lastDraftCheckpoint := time.Now()
for {
resp, recvErr := stream.Recv()
@@ -515,19 +618,24 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
break
}
logging.LogErrorf("agent stream error: %s", recvErr.Error())
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(recvErr)})
content := contentBuilder.String()
if content != "" || reasoningBuilder.String() != "" {
checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content})
+ turn.DraftContent = ""
}
- finalCheckpoint()
+ finalized := saveTurn("interrupted")
stream.Close()
roundCancel()
+ if finalized {
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(recvErr)})
+ }
return
}
select {
case <-ctx.Done():
+ turn.DraftContent = contentBuilder.String()
+ saveTurn("interrupted")
stream.Close()
roundCancel()
return
@@ -563,6 +671,11 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
aggregatedToolCalls[idx].Function.Arguments += tcd.Function.Arguments
}
}
+ if contentBuilder.Len() > 0 && time.Since(lastDraftCheckpoint) >= time.Second {
+ turn.DraftContent = contentBuilder.String()
+ saveTurn("running")
+ lastDraftCheckpoint = time.Now()
+ }
if resp.Usage != nil {
totalPrompt += resp.Usage.PromptTokens
@@ -579,6 +692,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
stream.Close()
roundCancel()
+ turn.DraftContent = ""
if len(aggregatedToolCalls) > 0 {
filtered := make([]openai.ToolCall, 0, len(aggregatedToolCalls))
@@ -608,10 +722,23 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
ID: tc.ID,
Name: tc.Function.Name,
Arguments: args,
+ State: "pending",
})
}
checkpointMsgs = append(checkpointMsgs, checkpointMsg)
assistantIdx := len(checkpointMsgs) - 1
+ skipRemainingTools := func(start int, result string) {
+ for j := start; j < len(aggregatedToolCalls); j++ {
+ checkpointMsgs[assistantIdx].ToolCalls[j].Result = result
+ checkpointMsgs[assistantIdx].ToolCalls[j].State = "skipped"
+ sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: result})
+ }
+ }
+ // 在展示确认框前记录模型提出的整批调用。此时都尚未执行,崩溃恢复可以明确区分
+ // “未执行”和“执行结果未知”,不会把后续尚未开始的调用误判为可能已产生副作用。
+ if !saveTurn("running") {
+ return
+ }
for i, tc := range aggregatedToolCalls {
args := parsedArgs[i]
@@ -627,12 +754,12 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
})
if needsConfirm(tc.Function.Name, action, alwaysAllow) {
- confirmID := fmt.Sprintf("%s_%d", tc.ID, i)
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "confirm", Name: tc.Function.Name, Arguments: args, ConfirmID: confirmID})
+ confirmID := fmt.Sprintf("%s_%s_%d", turn.TurnID, tc.ID, i)
ch2 := make(chan confirmResult, 1)
confirmChannelsMu.Lock()
confirmChannels[confirmID] = ch2
confirmChannelsMu.Unlock()
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "confirm", Name: tc.Function.Name, Arguments: args, ConfirmID: confirmID})
var rejectionMsg string
var result confirmResult
timedOut := false
@@ -649,6 +776,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
cancelMsg := "Operation cancelled"
checkpointMsgs[assistantIdx].ToolCalls[i].Result = cancelMsg
+ checkpointMsgs[assistantIdx].ToolCalls[i].State = "skipped"
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: wrapToolOutput(cancelMsg),
@@ -658,6 +786,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
for j := i + 1; j < len(aggregatedToolCalls); j++ {
checkpointMsgs[assistantIdx].ToolCalls[j].Result = cancelMsg
+ checkpointMsgs[assistantIdx].ToolCalls[j].State = "skipped"
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: wrapToolOutput(cancelMsg),
@@ -665,7 +794,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
})
sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: cancelMsg})
}
- finalCheckpoint()
+ if !saveTurn("interrupted") {
+ return
+ }
return
case <-time.After(confirmTimeout):
confirmChannelsMu.Lock()
@@ -687,6 +818,10 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
ToolCallID: tc.ID,
})
checkpointMsgs[assistantIdx].ToolCalls[i].Result = rejectionMsg
+ checkpointMsgs[assistantIdx].ToolCalls[i].State = "skipped"
+ if !saveTurn("running") {
+ return
+ }
continue
}
@@ -694,35 +829,46 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
alwaysAllow["*"] = true
}
}
+ select {
+ case <-ctx.Done():
+ skipRemainingTools(i, "Operation cancelled")
+ saveTurn("interrupted")
+ return
+ default:
+ }
- if !snapshotCreated && action != "" && !safeActions[action] && tc.Function.Name != "frontend" && !(tc.Function.Name == "repo" && action == "create") {
+ if !snapshotCreated && needsLocalSnapshot(tc.Function.Name, action) {
id, err := kernelModel.IndexRepo("AI agent auto snapshot")
if err != nil {
logging.LogErrorf("agent auto snapshot failed: %s", err)
- sendCriticalEvent(ctx, ch, AgentEvent{
- Type: "error",
- Error: "auto snapshot failed, operation aborted: " + err.Error(),
- })
-
abortMsg := "Operation aborted due to snapshot failure"
checkpointMsgs[assistantIdx].ToolCalls[i].Result = abortMsg
+ checkpointMsgs[assistantIdx].ToolCalls[i].State = "skipped"
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: wrapToolOutput(abortMsg),
ToolCallID: tc.ID,
})
- sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: abortMsg})
-
for j := i + 1; j < len(aggregatedToolCalls); j++ {
checkpointMsgs[assistantIdx].ToolCalls[j].Result = abortMsg
+ checkpointMsgs[assistantIdx].ToolCalls[j].State = "skipped"
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: wrapToolOutput(abortMsg),
ToolCallID: aggregatedToolCalls[j].ID,
})
+ }
+ if !saveTurn("interrupted") {
+ return
+ }
+ sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: abortMsg})
+ for j := i + 1; j < len(aggregatedToolCalls); j++ {
sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: abortMsg})
}
- finalCheckpoint()
+ sendCriticalEvent(ctx, ch, AgentEvent{
+ Type: "error",
+ Error: "auto snapshot failed, operation aborted: " + err.Error(),
+ })
return
}
snapshotIDs = append(snapshotIDs, id)
@@ -730,6 +876,19 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
sendCriticalEvent(ctx, ch, AgentEvent{Type: "snapshot", SnapshotID: id})
}
+ // 工具执行前先持久化“即将执行”状态。若落盘失败则禁止执行,避免外部写操作已经发生,
+ // 但恢复层没有任何记录可用于阻止自动重试。
+ checkpointMsgs[assistantIdx].ToolCalls[i].State = "executing"
+ if !saveTurn("running") {
+ return
+ }
+ select {
+ case <-ctx.Done():
+ skipRemainingTools(i, "Operation cancelled")
+ saveTurn("interrupted")
+ return
+ default:
+ }
var resultStr string
isErr := false
if tc.Function.Name == "question" {
@@ -757,6 +916,10 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
ToolCallID: tc.ID,
})
checkpointMsgs[assistantIdx].ToolCalls[i].Result = resultStr
+ checkpointMsgs[assistantIdx].ToolCalls[i].State = "finished"
+ if !saveTurn("running") {
+ return
+ }
// 死循环检测:只有 question/frontend 之外的普通工具参与,
// 且仅当本次调用失败或无返回(即"卡住反复重试"的真死循环特征)时才累加计数。
@@ -788,16 +951,17 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
if doomLoop.count >= doomLoopStopThreshold {
errMsg := "Repetitive tool calls detected: '" + doomLoop.prevName + "' called " + fmt.Sprintf("%d", doomLoop.count) + " times with the same action. Operation terminated."
+ if !saveTurn("interrupted") {
+ return
+ }
sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: errMsg})
- finalCheckpoint()
return
}
roundsSinceCheckpoint++
if roundsSinceCheckpoint >= 3 {
- // 流式中途的兜底 checkpoint 改为异步写盘,避免随会话增长的全文件重写阻塞 agent 主循环。
- // 出错/取消/done 时的 checkpoint 仍为同步调用,确保最终状态可靠落盘。
- saveCheckpointAsync(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow, &pendingCheckpoints)
+ // 每三轮工具调用持久化一次当前 turn 增量,避免长任务仅依赖工具前后的检查点。
+ saveTurn("running")
roundsSinceCheckpoint = 0
}
continue
@@ -807,7 +971,6 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
if content != "" {
checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content})
}
- finalCheckpoint()
if content == "" {
content = " "
}
@@ -816,15 +979,22 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
Content: content,
ReasoningContent: reasoningBuilder.String(),
})
+ turn.TokenBreakdown = computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens)
+ if !saveTurn("finished") {
+ return
+ }
- sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens), CachedTokens: lastCachedTokens, ContextLimit: contextLimit})
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "done"})
+ sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: turn.TokenBreakdown, CachedTokens: lastCachedTokens, ContextLimit: contextLimit})
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "done", TurnID: turn.TurnID})
return
}
- sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens), CachedTokens: lastCachedTokens, ContextLimit: contextLimit})
- finalCheckpoint()
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "done"})
+ turn.TokenBreakdown = computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens)
+ if !saveTurn("finished") {
+ return
+ }
+ sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: turn.TokenBreakdown, CachedTokens: lastCachedTokens, ContextLimit: contextLimit})
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "done", TurnID: turn.TurnID})
}()
return ch
@@ -880,6 +1050,12 @@ func needsConfirm(toolName string, action string, alwaysAllow map[string]bool) b
if alwaysAllow["*"] {
return false
}
+ tool := tools.GetTool(toolName)
+ if tool != nil && tool.Source != "" && tool.Source != "native" {
+ // 外部 MCP 与插件工具不能复用原生工具的全局 action 白名单,否则 close/open 等同名动作
+ // 可能在外部服务中产生写入。仅工具明确声明只读时免确认,未知能力按写操作处理。
+ return !tool.ReadOnlyHint
+ }
if action == "" {
return false
}
@@ -898,12 +1074,22 @@ func needsConfirm(toolName string, action string, alwaysAllow map[string]bool) b
return true
}
+func needsLocalSnapshot(toolName, action string) bool {
+ if action == "" || safeActions[action] || toolName == "frontend" || (toolName == "repo" && action == "create") {
+ return false
+ }
+ tool := tools.GetTool(toolName)
+ // 仓库快照只能回滚思源原生写操作,不能回滚外部 MCP 服务或插件自己的数据。
+ return tool != nil && (tool.Source == "" || tool.Source == "native")
+}
+
func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent, timeout time.Duration) string {
args := parseToolArgs(argsJSON)
- questionID := fmt.Sprintf("%d", time.Now().UnixNano())
- if len(questionID) > 10 {
- questionID = questionID[:10]
- }
+ questionID := ast.NewNodeID()
+ ch2 := make(chan QuestionAnswer, 1)
+ questionChannelsMu.Lock()
+ questionChannels[questionID] = ch2
+ questionChannelsMu.Unlock()
sendCriticalEvent(ctx, ch, AgentEvent{
Type: "question",
@@ -911,11 +1097,6 @@ func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent,
Arguments: args,
})
- ch2 := make(chan QuestionAnswer, 1)
- questionChannelsMu.Lock()
- questionChannels[questionID] = ch2
- questionChannelsMu.Unlock()
-
var answer QuestionAnswer
select {
case answer = <-ch2:
@@ -942,16 +1123,14 @@ func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent,
return strings.Join(answer.Answers, ", ")
}
-// handleFrontendTool dispatches a frontend tool action to the browser via SSE and blocks until
-// the browser POSTs the result (or the context is cancelled / timeout fires). It mirrors
-// handleQuestion's structure exactly — the only difference is the channel registry and the
-// event type ("frontend_tool_call").
+// handleFrontendTool 通过 SSE 把前端工具操作发送到浏览器,并等待浏览器回传结果。
func handleFrontendTool(ctx context.Context, tc openai.ToolCall, ch chan<- AgentEvent, timeout time.Duration) string {
args := parseToolArgs(tc.Function.Arguments)
- callID := fmt.Sprintf("%d", time.Now().UnixNano())
- if len(callID) > 12 {
- callID = callID[:12]
- }
+ callID := ast.NewNodeID()
+ ch2 := make(chan frontendCallResult, 1)
+ frontendCallChannelsMu.Lock()
+ frontendCallChannels[callID] = ch2
+ frontendCallChannelsMu.Unlock()
sendCriticalEvent(ctx, ch, AgentEvent{
Type: "frontend_tool_call",
@@ -960,11 +1139,6 @@ func handleFrontendTool(ctx context.Context, tc openai.ToolCall, ch chan<- Agent
Arguments: args,
})
- ch2 := make(chan frontendCallResult, 1)
- frontendCallChannelsMu.Lock()
- frontendCallChannels[callID] = ch2
- frontendCallChannelsMu.Unlock()
-
var fr frontendCallResult
select {
case fr = <-ch2:
@@ -1190,9 +1364,9 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {
e := &entries[i]
switch e.Type {
case "user":
- msgs = append(msgs, AgentMessage{Role: "user", Content: e.Content})
+ msgs = append(msgs, AgentMessage{Role: "user", Content: e.Content, EntryID: e.ID})
case "assistant":
- m := AgentMessage{Role: "assistant", Content: e.Content}
+ m := AgentMessage{Role: "assistant", Content: e.Content, EntryID: e.ID}
if len(e.ToolCalls) > 0 {
m.ToolCalls = make([]AgentToolCall, len(e.ToolCalls))
for j := range e.ToolCalls {
@@ -1288,14 +1462,22 @@ func agentMessagesToEntries(msgs []AgentMessage) []SessionEntry {
m := &msgs[i]
switch m.Role {
case "user":
+ id := m.EntryID
+ if id == "" {
+ id = fmt.Sprintf("cp_%d", i)
+ }
entries = append(entries, SessionEntry{
- ID: fmt.Sprintf("cp_%d", i),
+ ID: id,
Type: "user",
Content: m.Content,
})
case "assistant":
+ id := m.EntryID
+ if id == "" {
+ id = fmt.Sprintf("cp_%d", i)
+ }
e := SessionEntry{
- ID: fmt.Sprintf("cp_%d", i),
+ ID: id,
Type: "assistant",
Content: m.Content,
ToolCalls: m.ToolCalls,
@@ -1306,113 +1488,6 @@ func agentMessagesToEntries(msgs []AgentMessage) []SessionEntry {
return entries
}
-// checkpointMu 串行化对 session.json 的 read-modify-write,避免同步与异步 checkpoint 并发写时丢数据。
-var checkpointMu sync.Mutex
-
-func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int, completionTokens int, startTime int64, snapshotIDs []string, alwaysAllow map[string]bool) {
- if sessionID == "" || !isValidSessionID(sessionID) {
- return
- }
- checkpointMu.Lock()
- defer checkpointMu.Unlock()
- writeCheckpointLocked(sessionID, messages, promptTokens, completionTokens, startTime, snapshotIDs, alwaysAllow)
-}
-
-// saveCheckpointAsync 在独立 goroutine 中执行写盘,不阻塞 agent 主循环(用于流式中途的兜底 checkpoint)。
-// messages 会被深拷贝,避免与主循环的 append 产生数据竞争;写盘仍经 checkpointMu 串行化。
-// wg 用于在最终落盘(saveCheckpoint)前等待所有挂起的中途 checkpoint 完成,避免旧数据覆盖新数据。
-func saveCheckpointAsync(sessionID string, messages []AgentMessage, promptTokens int, completionTokens int, startTime int64, snapshotIDs []string, alwaysAllow map[string]bool, wg *sync.WaitGroup) {
- if sessionID == "" || !isValidSessionID(sessionID) {
- return
- }
- // 深拷贝 messages:主循环会持续 append/替换 checkpointMsgs,异步读需隔离。
- snap := make([]AgentMessage, len(messages))
- copy(snap, messages)
- snapshotIDsCopy := append([]string(nil), snapshotIDs...)
- var alwaysAllowCopy map[string]bool
- if alwaysAllow != nil {
- alwaysAllowCopy = make(map[string]bool, len(alwaysAllow))
- maps.Copy(alwaysAllowCopy, alwaysAllow)
- }
- wg.Go(func() {
- checkpointMu.Lock()
- defer checkpointMu.Unlock()
- writeCheckpointLocked(sessionID, snap, promptTokens, completionTokens, startTime, snapshotIDsCopy, alwaysAllowCopy)
- })
-}
-
-func writeCheckpointLocked(sessionID string, messages []AgentMessage, promptTokens int, completionTokens int, startTime int64, snapshotIDs []string, alwaysAllow map[string]bool) {
- cp := agentCheckpoint{
- ID: sessionID,
- Title: "AI Agent",
- Entries: agentMessagesToEntries(messages),
- PromptTokens: promptTokens,
- CompletionTokens: completionTokens,
- TotalDuration: time.Now().UnixMilli() - startTime,
- CreatedAt: startTime,
- UpdatedAt: time.Now().UnixMilli(),
- Snapshots: snapshotIDs,
- AlwaysAllow: alwaysAllow["*"],
- }
-
- dir := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", sessionID)
- if err := os.MkdirAll(dir, 0755); err != nil {
- logging.LogErrorf("create session dir failed: %s", err)
- return
- }
-
- path := filepath.Join(dir, "session.json")
- existing, err := os.ReadFile(path)
- if err == nil {
- var old agentCheckpoint
- if gulu.JSON.UnmarshalJSON(existing, &old) == nil {
- if old.Titled {
- cp.Title = old.Title
- cp.Titled = true
- }
- }
- if old.CreatedAt > 0 {
- cp.CreatedAt = old.CreatedAt
- }
- if len(old.MessageHistory) > 0 {
- cp.MessageHistory = old.MessageHistory
- }
- // 后端中途 checkpoint 只能派生最小 entries(user/assistant/toolCalls)。
- // 若磁盘上已有前端写入的完整 entries(含 thinking/confirm/snapshot),
- // 优先保留它,避免后端兜底数据覆盖前端的富信息。
- if len(old.Entries) > 0 {
- cp.Entries = old.Entries
- }
- if len(old.Snapshots) > 0 {
- cp.Snapshots = old.Snapshots
- }
- // 回填前端写入的上下文 token 统计字段,避免后端 checkpoint 擦除它们(双写覆盖修复)。
- // 后端 saveCheckpoint 在流式中途/结束都会触发,但这些统计值是 stream 结束时才由前端写入的,
- // 所以后端只保留磁盘已有值,不自行计算。
- if old.ContextTokens > 0 {
- cp.ContextTokens = old.ContextTokens
- }
- if len(old.ContextTokenBreakdown) > 0 {
- cp.ContextTokenBreakdown = old.ContextTokenBreakdown
- }
- if old.ContextCachedTokens > 0 {
- cp.ContextCachedTokens = old.ContextCachedTokens
- }
- if old.ContextLimit > 0 {
- cp.ContextLimit = old.ContextLimit
- }
- }
-
- data, err := gulu.JSON.MarshalIndentJSON(cp, "", "\t")
- if err != nil {
- return
- }
- if err := filelock.WriteFile(path, data); err != nil {
- logging.LogErrorf("save checkpoint file failed: %s", err)
- }
- UpdateSessionIndex(sessionID, cp.Title, cp.CreatedAt, cp.UpdatedAt)
-}
-
func createStreamWithRetry(ctx context.Context, client *openai.Client, req openai.ChatCompletionRequest, maxRetries int, ch chan<- AgentEvent) (*openai.ChatCompletionStream, error) {
if maxRetries <= 0 {
maxRetries = 1
diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.go
new file mode 100644
index 0000000000..d3578d7c96
--- /dev/null
+++ b/kernel/agent/runtime.go
@@ -0,0 +1,440 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package agent
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/filelock"
+)
+
+const (
+ toolNotExecutedResult = "Tool was not executed because the turn was interrupted."
+ toolUnknownResult = "Tool execution was interrupted; the result is unknown. Do not retry automatically."
+)
+
+type agentRuntime struct {
+ SchemaVersion int `json:"schemaVersion"`
+ Revision int64 `json:"revision"`
+ SessionID string `json:"sessionID"`
+ AlwaysAllow bool `json:"alwaysAllow,omitempty"`
+ ActiveTurn *agentRuntimeTurn `json:"activeTurn,omitempty"`
+ Compaction *runtimeCompaction `json:"compaction,omitempty"`
+}
+
+type agentRuntimeTurn struct {
+ TurnID string `json:"turnID"`
+ Mode string `json:"mode"`
+ UserEntryID string `json:"userEntryID"`
+ TargetUserEntryID string `json:"targetUserEntryID,omitempty"`
+ BaseRevision int64 `json:"baseRevision"`
+ State string `json:"state"`
+ Delta []AgentMessage `json:"delta,omitempty"`
+ DraftContent string `json:"draftContent,omitempty"`
+ SnapshotIDs []string `json:"snapshotIDs,omitempty"`
+ PromptTokens int `json:"promptTokens,omitempty"`
+ CompletionTokens int `json:"completionTokens,omitempty"`
+ LastPromptTokens int `json:"lastPromptTokens,omitempty"`
+ CachedTokens int `json:"cachedTokens,omitempty"`
+ ContextLimit int `json:"contextLimit,omitempty"`
+ TokenBreakdown map[string]int `json:"tokenBreakdown,omitempty"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
+
+type runtimeCompaction struct {
+ Summary string `json:"summary"`
+ CoveredEntryCount int `json:"coveredEntryCount"`
+ CoveredDigest string `json:"coveredDigest"`
+}
+
+func runtimePath(sessionID string) string {
+ return filepath.Join(sessionsDir(), sessionID, "runtime.json")
+}
+
+func loadRuntimeLocked(sessionID string) (*agentRuntime, error) {
+ data, err := os.ReadFile(runtimePath(sessionID))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return &agentRuntime{SchemaVersion: 1, SessionID: sessionID}, nil
+ }
+ return nil, err
+ }
+ var runtime agentRuntime
+ if err := gulu.JSON.UnmarshalJSON(data, &runtime); err != nil {
+ return nil, err
+ }
+ if runtime.SchemaVersion > 1 {
+ return nil, fmt.Errorf("unsupported agent runtime schema version: %d", runtime.SchemaVersion)
+ }
+ if runtime.SessionID != "" && runtime.SessionID != sessionID {
+ return nil, fmt.Errorf("agent runtime session id mismatch")
+ }
+ if runtime.Revision < 0 {
+ return nil, fmt.Errorf("invalid agent runtime revision")
+ }
+ if runtime.ActiveTurn != nil {
+ if runtime.ActiveTurn.TurnID == "" {
+ return nil, fmt.Errorf("invalid agent runtime turn id")
+ }
+ switch runtime.ActiveTurn.State {
+ case "running", "finished", "interrupted":
+ default:
+ return nil, fmt.Errorf("invalid agent runtime turn state")
+ }
+ }
+ if runtime.SchemaVersion == 0 {
+ runtime.SchemaVersion = 1
+ }
+ if runtime.SessionID == "" {
+ runtime.SessionID = sessionID
+ }
+ return &runtime, nil
+}
+
+func writeRuntimeLocked(sessionID string, runtime *agentRuntime) error {
+ if runtime == nil {
+ return nil
+ }
+ // runtime 只能附着在已经存在的会话上,避免迟到的 checkpoint 复活已删除会话。
+ if _, err := os.Stat(filepath.Join(sessionsDir(), sessionID, "session.json")); err != nil {
+ return err
+ }
+ runtime.SchemaVersion = 1
+ runtime.SessionID = sessionID
+ runtime.Revision++
+ data, err := gulu.JSON.MarshalIndentJSON(runtime, "", "\t")
+ if err != nil {
+ return err
+ }
+ return filelock.WriteFile(runtimePath(sessionID), data)
+}
+
+func beginRuntimeTurn(sessionID string, turn *agentRuntimeTurn, alwaysAllow bool) error {
+ if sessionID == "" || turn == nil {
+ return nil
+ }
+ if !isValidSessionID(sessionID) {
+ return fmt.Errorf("invalid session id")
+ }
+ if turn.TurnID == "" || turn.State != "running" {
+ return fmt.Errorf("invalid agent runtime turn")
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil {
+ return err
+ }
+ if runtime.ActiveTurn != nil && runtime.ActiveTurn.TurnID != turn.TurnID {
+ committed, err := isTurnCommittedLocked(sessionID, runtime.ActiveTurn.TurnID)
+ if err != nil {
+ return err
+ }
+ if !committed {
+ return fmt.Errorf("agent session has an uncommitted turn")
+ }
+ runtime.ActiveTurn = nil
+ }
+ data, err := os.ReadFile(filepath.Join(sessionsDir(), sessionID, "session.json"))
+ if err != nil {
+ return err
+ }
+ var session map[string]any
+ if err := gulu.JSON.UnmarshalJSON(data, &session); err != nil {
+ return err
+ }
+ if turn.BaseRevision >= 0 && numberToInt64(session["revision"]) != turn.BaseRevision {
+ return ErrSessionConflict
+ }
+ if findRuntimeUserAnchor(session, turn.UserEntryID) < 0 {
+ return fmt.Errorf("agent runtime user entry not found")
+ }
+ runtime.AlwaysAllow = runtime.AlwaysAllow || alwaysAllow
+ runtime.ActiveTurn = turn
+ return writeRuntimeLocked(sessionID, runtime)
+}
+
+func isTurnCommittedLocked(sessionID, turnID string) (bool, error) {
+ data, err := os.ReadFile(filepath.Join(sessionsDir(), sessionID, "session.json"))
+ if err != nil {
+ return false, err
+ }
+ var meta sessionMeta
+ if err := gulu.JSON.UnmarshalJSON(data, &meta); err != nil {
+ return false, err
+ }
+ return meta.LastCommittedTurnID == turnID, nil
+}
+
+func saveRuntimeTurn(sessionID string, turn *agentRuntimeTurn, alwaysAllow bool) error {
+ if sessionID == "" || turn == nil {
+ return nil
+ }
+ if !isValidSessionID(sessionID) {
+ return fmt.Errorf("invalid session id")
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ committed, err := isTurnCommittedLocked(sessionID, turn.TurnID)
+ if err != nil {
+ return err
+ }
+ if committed {
+ return nil
+ }
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil {
+ return err
+ }
+ if runtime.ActiveTurn != nil && runtime.ActiveTurn.TurnID != turn.TurnID {
+ return fmt.Errorf("agent runtime turn changed")
+ }
+ runtime.AlwaysAllow = runtime.AlwaysAllow || alwaysAllow
+ turn.UpdatedAt = time.Now().UnixMilli()
+ runtime.ActiveTurn = turn
+ return writeRuntimeLocked(sessionID, runtime)
+}
+
+func loadRuntimeState(sessionID string) (*agentRuntime, error) {
+ if sessionID == "" || !isValidSessionID(sessionID) {
+ return nil, nil
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ return loadRuntimeLocked(sessionID)
+}
+
+func FinalizeOrphanedTurn(sessionID string) error {
+ if sessionID == "" || !isValidSessionID(sessionID) {
+ return nil
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil || runtime.ActiveTurn == nil || runtime.ActiveTurn.State != "running" {
+ return err
+ }
+ runtime.ActiveTurn.State = "interrupted"
+ runtime.ActiveTurn.UpdatedAt = time.Now().UnixMilli()
+ return writeRuntimeLocked(sessionID, runtime)
+}
+
+func HasUncommittedTurn(sessionID string) (bool, error) {
+ if sessionID == "" || !isValidSessionID(sessionID) {
+ return false, nil
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil || runtime.ActiveTurn == nil {
+ return false, err
+ }
+ committed, err := isTurnCommittedLocked(sessionID, runtime.ActiveTurn.TurnID)
+ if err != nil {
+ return false, err
+ }
+ return !committed, nil
+}
+
+func RecoverableTurnID(sessionID string) (string, error) {
+ if sessionID == "" || !isValidSessionID(sessionID) {
+ return "", nil
+ }
+ lock := sessionLock(sessionID)
+ lock.Lock()
+ defer lock.Unlock()
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil || runtime.ActiveTurn == nil || !isRuntimeTurnTerminal(runtime.ActiveTurn) {
+ return "", err
+ }
+ committed, err := isTurnCommittedLocked(sessionID, runtime.ActiveTurn.TurnID)
+ if err != nil || committed {
+ return "", err
+ }
+ return runtime.ActiveTurn.TurnID, nil
+}
+
+func markRuntimeCommittedLocked(sessionID, turnID string) error {
+ if turnID == "" {
+ return nil
+ }
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil {
+ return err
+ }
+ if runtime.ActiveTurn == nil || runtime.ActiveTurn.TurnID != turnID {
+ return nil
+ }
+ runtime.ActiveTurn = nil
+ return writeRuntimeLocked(sessionID, runtime)
+}
+
+func isRuntimeTurnTerminal(turn *agentRuntimeTurn) bool {
+ return turn != nil && (turn.State == "finished" || turn.State == "interrupted")
+}
+
+func findRuntimeUserAnchor(session map[string]any, userEntryID string) int {
+ entries, _ := session["entries"].([]any)
+ for i := len(entries) - 1; i >= 0; i-- {
+ entry, _ := entries[i].(map[string]any)
+ if entry["type"] != "user" {
+ continue
+ }
+ id, _ := entry["id"].(string)
+ if userEntryID == "" || id == userEntryID {
+ return i
+ }
+ }
+ return -1
+}
+
+func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeTurn) error {
+ if turn == nil {
+ return nil
+ }
+ entries, _ := session["entries"].([]any)
+ anchor := findRuntimeUserAnchor(session, turn.UserEntryID)
+ if anchor < 0 {
+ return fmt.Errorf("agent runtime user entry not found")
+ }
+
+ // 当前 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" {
+ continue
+ }
+ entry := map[string]any{
+ "id": fmt.Sprintf("runtime_%s_%d", turn.TurnID, i),
+ "type": "assistant",
+ "timestamp": turn.UpdatedAt,
+ }
+ if message.Content != "" {
+ entry["content"] = message.Content
+ }
+ if len(message.ToolCalls) > 0 {
+ calls := make([]map[string]any, 0, len(message.ToolCalls))
+ for _, call := range message.ToolCalls {
+ result := call.Result
+ if result == "" {
+ if call.State == "pending" {
+ result = toolNotExecutedResult
+ } else {
+ result = toolUnknownResult
+ }
+ }
+ calls = append(calls, map[string]any{
+ "name": call.Name,
+ "arguments": call.Arguments,
+ "result": result,
+ "state": call.State,
+ })
+ }
+ entry["toolCalls"] = calls
+ }
+ authoritative = append(authoritative, entry)
+ }
+ if turn.DraftContent != "" {
+ authoritative = append(authoritative, map[string]any{
+ "id": fmt.Sprintf("runtime_draft_%s", turn.TurnID),
+ "type": "assistant",
+ "content": turn.DraftContent,
+ "timestamp": turn.UpdatedAt,
+ })
+ }
+
+ // regenerate 在启动前已经把旧回答截断到目标 user,因此 user 之后的 UI 条目都属于当前 turn。
+ merged := append([]any(nil), entries[:anchor+1]...)
+ authoritativeIndex := 0
+ for _, 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:]...)
+
+ existingSnapshots := map[string]bool{}
+ for _, raw := range merged {
+ entry, _ := raw.(map[string]any)
+ if snapshotID, _ := entry["snapshotID"].(string); snapshotID != "" {
+ existingSnapshots[snapshotID] = true
+ }
+ }
+ for i, snapshotID := range turn.SnapshotIDs {
+ if existingSnapshots[snapshotID] {
+ continue
+ }
+ merged = append(merged, map[string]any{
+ "id": fmt.Sprintf("runtime_snapshot_%s_%d", turn.TurnID, i),
+ "type": "snapshot",
+ "snapshotID": snapshotID,
+ })
+ }
+ session["entries"] = merged
+ if turn.PromptTokens > 0 || turn.CompletionTokens > 0 || turn.LastPromptTokens > 0 {
+ session["promptTokens"] = turn.PromptTokens
+ session["completionTokens"] = turn.CompletionTokens
+ session["contextTokens"] = turn.LastPromptTokens
+ session["contextCachedTokens"] = turn.CachedTokens
+ session["contextLimit"] = turn.ContextLimit
+ if len(turn.TokenBreakdown) > 0 {
+ session["contextTokenBreakdown"] = turn.TokenBreakdown
+ }
+ }
+ return nil
+}
+
+// mergeRuntimeIntoSessionLocked 仅在 API 返回值中叠加未提交 turn,不直接改写 session.json。
+func mergeRuntimeIntoSessionLocked(sessionID string, session map[string]any) error {
+ runtime, err := loadRuntimeLocked(sessionID)
+ if err != nil {
+ return err
+ }
+ if runtime.ActiveTurn == nil {
+ return nil
+ }
+ turn := runtime.ActiveTurn
+ if committed, _ := session["lastCommittedTurnID"].(string); committed == turn.TurnID {
+ return nil
+ }
+
+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {
+ return err
+ }
+ session["recoveryTurnID"] = turn.TurnID
+ session["recoveryState"] = turn.State
+ session["recoveryRevision"] = runtime.Revision
+ return nil
+}
diff --git a/kernel/agent/session.go b/kernel/agent/session.go
index d8dd56ee50..f61408aac2 100644
--- a/kernel/agent/session.go
+++ b/kernel/agent/session.go
@@ -17,6 +17,8 @@
package agent
import (
+ "errors"
+ "fmt"
"maps"
"os"
"path/filepath"
@@ -60,10 +62,25 @@ type SessionListResult struct {
}
type sessionMeta struct {
- ID string `json:"id"`
- Title string `json:"title"`
- CreatedAt int64 `json:"createdAt"`
- UpdatedAt int64 `json:"updatedAt"`
+ ID string `json:"id"`
+ Title string `json:"title"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+ Revision int64 `json:"revision"`
+ ExpectedRevision *int64 `json:"expectedRevision,omitempty"`
+ CommitTurnID string `json:"commitTurnID,omitempty"`
+ RecoveryTurnID string `json:"recoveryTurnID,omitempty"`
+ LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`
+}
+
+var ErrSessionConflict = errors.New("agent session revision conflict")
+var ErrRuntimeNotFinalized = errors.New("agent runtime turn is not finalized")
+
+var sessionLocks sync.Map
+
+func sessionLock(id string) *sync.Mutex {
+ lock, _ := sessionLocks.LoadOrStore(id, &sync.Mutex{})
+ return lock.(*sync.Mutex)
}
func loadSessionIndex() map[string]*SessionIndexItem {
@@ -261,9 +278,17 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {
}
func GetSession(id string) (map[string]any, error) {
+ return GetSessionState(id, true)
+}
+
+func GetSessionState(id string, includeRuntime bool) (map[string]any, error) {
if id == "" || !isValidSessionID(id) {
- return nil, nil
+ return nil, fmt.Errorf("invalid session id")
}
+ lock := sessionLock(id)
+ lock.Lock()
+ defer lock.Unlock()
+
sessionPath := filepath.Join(sessionsDir(), id, "session.json")
data, err := os.ReadFile(sessionPath)
if err != nil {
@@ -273,72 +298,150 @@ func GetSession(id string) (map[string]any, error) {
if err := gulu.JSON.UnmarshalJSON(data, &session); err != nil {
return nil, err
}
+ if includeRuntime {
+ if err := mergeRuntimeIntoSessionLocked(id, session); err != nil {
+ return nil, err
+ }
+ }
return session, nil
}
-func SaveSession(data []byte) error {
+func SaveSession(data []byte) (int64, error) {
var meta sessionMeta
if err := gulu.JSON.UnmarshalJSON(data, &meta); err != nil || meta.ID == "" || !isValidSessionID(meta.ID) {
- return nil
+ return 0, fmt.Errorf("invalid session data")
}
+ lock := sessionLock(meta.ID)
+ lock.Lock()
+ defer lock.Unlock()
dir := filepath.Join(sessionsDir(), meta.ID)
- if err := os.MkdirAll(dir, 0755); err != nil {
- logging.LogErrorf("create session dir failed: %s", err)
- }
path := filepath.Join(dir, "session.json")
+ var newData map[string]any
+ if err := gulu.JSON.UnmarshalJSON(data, &newData); err != nil {
+ return 0, fmt.Errorf("decode session data failed: %w", err)
+ }
+ delete(newData, "expectedRevision")
+ delete(newData, "commitTurnID")
+ delete(newData, "recoveryTurnID")
+ delete(newData, "recoveryState")
+ delete(newData, "recoveryRevision")
+ delete(newData, "agentRunning")
+ delete(newData, "lastCommittedTurnID")
+ commitTurnID := meta.CommitTurnID
+ if commitTurnID == "" {
+ commitTurnID = meta.RecoveryTurnID
+ }
+
+ currentRevision := int64(0)
+ currentCommittedTurnID := ""
existing, err := os.ReadFile(path)
if err == nil && len(existing) > 0 {
var existingData map[string]any
- var newData map[string]any
- if gulu.JSON.UnmarshalJSON(existing, &existingData) == nil &&
- gulu.JSON.UnmarshalJSON(data, &newData) == nil {
+ if err := gulu.JSON.UnmarshalJSON(existing, &existingData); err != nil {
+ return 0, fmt.Errorf("decode existing session data failed: %w", err)
+ } else {
+ currentRevision = numberToInt64(existingData["revision"])
+ currentCommittedTurnID, _ = existingData["lastCommittedTurnID"].(string)
+ if commitTurnID != "" && currentCommittedTurnID == commitTurnID {
+ // 提交响应丢失后,客户端可能原样重试同一个 commitTurnID。此判断要先于修订号校验,
+ // 并且不能再用客户端快照覆盖已经由 runtime 生成的权威内容。
+ if err := markRuntimeCommittedLocked(meta.ID, commitTurnID); err != nil {
+ logging.LogWarnf("clean committed agent runtime failed: %s", err)
+ }
+ return currentRevision, nil
+ }
+ if meta.ExpectedRevision != nil && *meta.ExpectedRevision != currentRevision {
+ return currentRevision, ErrSessionConflict
+ }
for k, v := range existingData {
if _, ok := newData[k]; !ok {
- switch k {
- // messages 不再保留:以 entries 为唯一持久化数据源,
- // 前端下次保存时会用 entries 覆盖,老 messages 字段自然清除。
- case "createdAt", "titled", "messageHistory", "entries", "snapshots", "id", "alwaysAllow":
+ // messages 是已废弃的旧会话字段,不再带入新格式;其他未知字段原样保留,
+ // 避免前后端版本不一致时擦除较新版本写入的数据。
+ if k != "messages" && k != "expectedRevision" && k != "commitTurnID" &&
+ k != "recoveryTurnID" && k != "recoveryState" && k != "recoveryRevision" && k != "agentRunning" {
newData[k] = v
}
}
}
- merged, err := gulu.JSON.MarshalIndentJSON(newData, "", "\t")
- if err == nil {
- data = merged
- }
}
- } else {
- var newData map[string]any
- if gulu.JSON.UnmarshalJSON(data, &newData) == nil {
- indented, err := gulu.JSON.MarshalIndentJSON(newData, "", "\t")
- if err == nil {
- data = indented
+ } else if err != nil && !os.IsNotExist(err) {
+ return 0, fmt.Errorf("read session file failed: %w", err)
+ } else if meta.ExpectedRevision != nil && *meta.ExpectedRevision != 0 {
+ return 0, ErrSessionConflict
+ }
+ if commitTurnID != "" {
+ runtime, err := loadRuntimeLocked(meta.ID)
+ if err != nil {
+ return currentRevision, fmt.Errorf("read agent runtime failed: %w", err)
+ }
+ if runtime.ActiveTurn != nil {
+ if runtime.ActiveTurn.TurnID != commitTurnID {
+ return currentRevision, ErrSessionConflict
}
+ if !isRuntimeTurnTerminal(runtime.ActiveTurn) {
+ return currentRevision, ErrRuntimeNotFinalized
+ }
+ if err := applyRuntimeTurnToSessionLocked(newData, runtime.ActiveTurn); err != nil {
+ return currentRevision, err
+ }
+ } else if currentCommittedTurnID != commitTurnID {
+ return currentRevision, ErrSessionConflict
}
}
+ newRevision := currentRevision + 1
+ newData["revision"] = newRevision
+ if commitTurnID != "" {
+ newData["lastCommittedTurnID"] = commitTurnID
+ }
+ data, err = gulu.JSON.MarshalIndentJSON(newData, "", "\t")
+ if err != nil {
+ return currentRevision, fmt.Errorf("encode session data failed: %w", err)
+ }
+
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return currentRevision, fmt.Errorf("create session dir failed: %w", err)
+ }
if err := filelock.WriteFile(path, data); err != nil {
- logging.LogErrorf("save session file failed: %s", err)
+ return currentRevision, fmt.Errorf("save session file failed: %w", err)
+ }
+ if commitTurnID != "" {
+ if err := markRuntimeCommittedLocked(meta.ID, commitTurnID); err != nil {
+ logging.LogWarnf("commit agent runtime failed: %s", err)
+ }
}
- title := meta.Title
+ title, _ := newData["title"].(string)
if title == "" {
title = "AI Agent"
}
- UpdateSessionIndex(meta.ID, title, meta.CreatedAt, meta.UpdatedAt)
+ createdAt := meta.CreatedAt
+ if value := numberToInt64(newData["createdAt"]); value > 0 {
+ createdAt = value
+ }
+ updatedAt := meta.UpdatedAt
+ if value := numberToInt64(newData["updatedAt"]); value > 0 {
+ updatedAt = value
+ }
+ UpdateSessionIndex(meta.ID, title, createdAt, updatedAt)
- return nil
+ return newRevision, nil
}
func DeleteSession(id string) error {
if id == "" || !isValidSessionID(id) {
- return nil
+ return fmt.Errorf("invalid session id")
}
+ lock := sessionLock(id)
+ lock.Lock()
+ defer lock.Unlock()
dir := filepath.Join(sessionsDir(), id)
- _ = os.RemoveAll(dir)
+ if err := os.RemoveAll(dir); err != nil {
+ return err
+ }
indexMu.Lock()
index := loadSessionIndex()
@@ -350,3 +453,23 @@ func DeleteSession(id string) error {
return nil
}
+
+func numberToInt64(value any) int64 {
+ switch v := value.(type) {
+ case float64:
+ return int64(v)
+ case int64:
+ return v
+ case int:
+ return int64(v)
+ case jsonNumber:
+ parsed, _ := v.Int64()
+ return parsed
+ }
+ return 0
+}
+
+// jsonNumber 保持与 encoding/json.Number 相同的最小接口,避免会话存储依赖具体解码器实现。
+type jsonNumber interface {
+ Int64() (int64, error)
+}
diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.go
new file mode 100644
index 0000000000..c5716afa5b
--- /dev/null
+++ b/kernel/agent/session_test.go
@@ -0,0 +1,579 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package agent
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const testSessionID = "20260715120000-abcdefg"
+
+func useTestDataDir(t *testing.T) {
+ t.Helper()
+ original := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = original
+ sessionLocks.Delete(testSessionID)
+ })
+}
+
+func marshalSession(t *testing.T, value any) []byte {
+ t.Helper()
+ data, err := gulu.JSON.MarshalJSON(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
+
+func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
+ useTestDataDir(t)
+ base := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ "future": map[string]any{"enabled": true},
+ }
+ revision, err := SaveSession(marshalSession(t, base))
+ if err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+ path := filepath.Join(sessionsDir(), testSessionID, "session.json")
+ legacyData, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var legacy map[string]any
+ if err := gulu.JSON.UnmarshalJSON(legacyData, &legacy); err != nil {
+ t.Fatal(err)
+ }
+ legacy["expectedRevision"] = int64(1)
+ legacy["commitTurnID"] = "legacy-turn"
+ legacy["recoveryTurnID"] = "legacy-turn"
+ legacy["recoveryState"] = "interrupted"
+ legacy["recoveryRevision"] = int64(99)
+ legacy["agentRunning"] = true
+ if err := os.WriteFile(path, marshalSession(t, legacy), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ stale := map[string]any{
+ "id": testSessionID,
+ "title": "stale",
+ "createdAt": int64(1),
+ "updatedAt": int64(2),
+ "entries": base["entries"],
+ "expectedRevision": int64(0),
+ }
+ revision, err = SaveSession(marshalSession(t, stale))
+ if !errors.Is(err, ErrSessionConflict) || revision != 1 {
+ t.Fatalf("expected revision conflict: revision=%d, err=%v", revision, err)
+ }
+
+ update := map[string]any{
+ "id": testSessionID,
+ "title": "updated",
+ "createdAt": int64(1),
+ "updatedAt": int64(3),
+ "entries": base["entries"],
+ "expectedRevision": int64(1),
+ "lastCommittedTurnID": "forged-turn",
+ }
+ revision, err = SaveSession(marshalSession(t, update))
+ if err != nil || revision != 2 {
+ t.Fatalf("save updated session failed: revision=%d, err=%v", revision, err)
+ }
+ session, err := GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if session["title"] != "updated" || session["future"] == nil {
+ t.Fatalf("session data was overwritten unexpectedly: %#v", session)
+ }
+ for _, key := range []string{"expectedRevision", "commitTurnID", "recoveryTurnID", "recoveryState", "recoveryRevision", "agentRunning"} {
+ if _, ok := session[key]; ok {
+ t.Fatalf("transient field %q was restored from legacy data: %#v", key, session)
+ }
+ }
+ if _, ok := session["lastCommittedTurnID"]; ok {
+ t.Fatalf("server-controlled commit marker was accepted from client data: %#v", session)
+ }
+}
+
+func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
+ useTestDataDir(t)
+ base := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120001-abcdefg",
+ Mode: "append",
+ UserEntryID: "user-1",
+ BaseRevision: 1,
+ State: "running",
+ PromptTokens: 21,
+ CompletionTokens: 8,
+ LastPromptTokens: 13,
+ CachedTokens: 5,
+ ContextLimit: 128,
+ TokenBreakdown: map[string]int{"user": 3, "system": 10},
+ Delta: []AgentMessage{{
+ Role: "assistant",
+ Content: "server authoritative content",
+ ToolCalls: []AgentToolCall{{
+ ID: "call-1",
+ Name: "external_write",
+ Arguments: map[string]any{"action": "write"},
+ State: "executing",
+ }},
+ }},
+ }
+ if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ t.Fatal(err)
+ }
+ if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ t.Fatal(err)
+ }
+ uncommitted, err := HasUncommittedTurn(testSessionID)
+ if err != nil || !uncommitted {
+ t.Fatalf("active runtime turn was not detected: uncommitted=%v, err=%v", uncommitted, err)
+ }
+ canonical, err := GetSessionState(testSessionID, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if entries := canonical["entries"].([]any); len(entries) != 1 {
+ t.Fatalf("live runtime leaked into canonical session view: %#v", canonical)
+ }
+
+ raw, err := os.ReadFile(filepath.Join(sessionsDir(), testSessionID, "session.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var persisted map[string]any
+ if err := gulu.JSON.UnmarshalJSON(raw, &persisted); err != nil {
+ t.Fatal(err)
+ }
+ if entries := persisted["entries"].([]any); len(entries) != 1 {
+ t.Fatalf("runtime changed canonical history: %#v", entries)
+ }
+
+ recovered, err := GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ entries := recovered["entries"].([]any)
+ if len(entries) != 2 || recovered["recoveryTurnID"] != turn.TurnID {
+ t.Fatalf("runtime recovery was not overlaid correctly: %#v", recovered)
+ }
+ assistant := entries[1].(map[string]any)
+ toolCalls := assistant["toolCalls"].([]map[string]any)
+ toolCall := toolCalls[0]
+ if toolCall["result"] != toolUnknownResult {
+ t.Fatalf("executing external write must be restored with an explicit unknown result: %#v", toolCall)
+ }
+ if numberToInt64(recovered["promptTokens"]) != 21 || numberToInt64(recovered["completionTokens"]) != 8 ||
+ numberToInt64(recovered["contextTokens"]) != 13 || numberToInt64(recovered["contextCachedTokens"]) != 5 ||
+ numberToInt64(recovered["contextLimit"]) != 128 {
+ t.Fatalf("runtime token metadata was not restored: %#v", recovered)
+ }
+ wrongCommit := map[string]any{}
+ for key, value := range recovered {
+ wrongCommit[key] = value
+ }
+ wrongCommit["expectedRevision"] = int64(1)
+ wrongCommit["commitTurnID"] = "20260715120009-abcdefg"
+ if revision, err := SaveSession(marshalSession(t, wrongCommit)); !errors.Is(err, ErrSessionConflict) || revision != 1 {
+ t.Fatalf("mismatched runtime commit was accepted: revision=%d, err=%v", revision, err)
+ }
+
+ recovered["expectedRevision"] = int64(1)
+ if revision, err := SaveSession(marshalSession(t, recovered)); !errors.Is(err, ErrRuntimeNotFinalized) || revision != 1 {
+ t.Fatalf("running runtime turn was committed: revision=%d, err=%v", revision, err)
+ }
+ turn.State = "interrupted"
+ if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ t.Fatal(err)
+ }
+ recovered, err = GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ entries = recovered["entries"].([]any)
+ entries[1].(map[string]any)["content"] = "client truncated content"
+ recovered["expectedRevision"] = int64(1)
+ revision, err := SaveSession(marshalSession(t, recovered))
+ if err != nil || revision != 2 {
+ t.Fatalf("commit recovered session failed: revision=%d, err=%v", revision, err)
+ }
+ committed, err := GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := committed["recoveryTurnID"]; ok {
+ t.Fatalf("transient recovery metadata was persisted: %#v", committed)
+ }
+ if entries := committed["entries"].([]any); len(entries) != 2 {
+ t.Fatalf("recovered history was duplicated: %#v", entries)
+ } else if entries[1].(map[string]any)["content"] != "server authoritative content" {
+ t.Fatalf("client snapshot overwrote authoritative runtime content: %#v", entries[1])
+ }
+ repeatedCommit := map[string]any{}
+ for key, value := range committed {
+ repeatedCommit[key] = value
+ }
+ repeatedCommit["entries"].([]any)[1].(map[string]any)["content"] = "tampered repeated commit"
+ // 模拟提交已落盘但响应丢失:客户端会携带旧修订号原样重试。
+ repeatedCommit["expectedRevision"] = int64(1)
+ repeatedCommit["commitTurnID"] = turn.TurnID
+ if revision, err := SaveSession(marshalSession(t, repeatedCommit)); err != nil || revision != 2 {
+ t.Fatalf("repeated commit was not idempotent: revision=%d, err=%v", revision, err)
+ }
+ committed, err = GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if entries := committed["entries"].([]any); entries[1].(map[string]any)["content"] != "server authoritative content" {
+ t.Fatalf("repeated commit overwrote authoritative content: %#v", entries[1])
+ }
+ if uncommitted, err := HasUncommittedTurn(testSessionID); err != nil || uncommitted {
+ t.Fatalf("committed runtime turn remained active: uncommitted=%v, err=%v", uncommitted, err)
+ }
+ if err := saveRuntimeTurn(testSessionID, turn, false); err != nil {
+ t.Fatalf("late runtime save should be ignored after commit: %v", err)
+ }
+ committed, err = GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := committed["recoveryTurnID"]; ok {
+ t.Fatalf("late runtime save recreated a committed turn: %#v", committed)
+ }
+
+ if err := DeleteSession(testSessionID); err != nil {
+ t.Fatal(err)
+ }
+ if err := saveRuntimeTurn(testSessionID, turn, false); err == nil {
+ t.Fatal("late runtime save recreated a deleted session")
+ }
+ if _, err := os.Stat(filepath.Join(sessionsDir(), testSessionID)); !os.IsNotExist(err) {
+ t.Fatalf("deleted session directory was recreated: %v", err)
+ }
+}
+
+func TestRejectedNewSessionDoesNotCreateDirectory(t *testing.T) {
+ useTestDataDir(t)
+ const sessionID = "20260715120009-abcdefg"
+ t.Cleanup(func() { sessionLocks.Delete(sessionID) })
+ expectedRevision := int64(1)
+ session := map[string]any{
+ "id": sessionID,
+ "title": "stale",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{},
+ "expectedRevision": expectedRevision,
+ }
+ if _, err := SaveSession(marshalSession(t, session)); !errors.Is(err, ErrSessionConflict) {
+ t.Fatalf("expected revision conflict, got %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(sessionsDir(), sessionID)); !os.IsNotExist(err) {
+ t.Fatalf("rejected save created a session directory: %v", err)
+ }
+}
+
+func TestSaveSessionRejectsCorruptExistingData(t *testing.T) {
+ useTestDataDir(t)
+ dir := filepath.Join(sessionsDir(), testSessionID)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "session.json")
+ if err := os.WriteFile(path, []byte("{"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ data := map[string]any{
+ "id": testSessionID,
+ "title": "replacement",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{},
+ }
+ if _, err := SaveSession(marshalSession(t, data)); err == nil {
+ t.Fatal("corrupt existing session was overwritten")
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(raw) != "{" {
+ t.Fatalf("corrupt session changed unexpectedly: %q", raw)
+ }
+}
+
+func TestBeginRuntimeTurnRejectsStaleRevision(t *testing.T) {
+ useTestDataDir(t)
+ base := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120002-abcdefg",
+ Mode: "append",
+ UserEntryID: "user-1",
+ BaseRevision: 0,
+ State: "running",
+ }
+ if err := beginRuntimeTurn(testSessionID, turn, false); !errors.Is(err, ErrSessionConflict) {
+ t.Fatalf("expected stale runtime revision to be rejected: %v", err)
+ }
+ if _, err := os.Stat(runtimePath(testSessionID)); !os.IsNotExist(err) {
+ t.Fatalf("stale runtime turn was persisted: %v", err)
+ }
+}
+
+func TestFinalizeOrphanedTurnMakesRuntimeRecoverable(t *testing.T) {
+ useTestDataDir(t)
+ base := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120003-abcdefg",
+ Mode: "append",
+ UserEntryID: "user-1",
+ BaseRevision: 1,
+ State: "running",
+ DraftContent: "partial response",
+ }
+ if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ t.Fatal(err)
+ }
+ runtimeBefore, err := loadRuntimeState(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := FinalizeOrphanedTurn(testSessionID); err != nil {
+ t.Fatal(err)
+ }
+ runtimeAfter, err := loadRuntimeState(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if runtimeAfter.ActiveTurn == nil || runtimeAfter.ActiveTurn.State != "interrupted" {
+ t.Fatalf("orphaned runtime was not finalized: %#v", runtimeAfter.ActiveTurn)
+ }
+ if runtimeAfter.Revision <= runtimeBefore.Revision {
+ t.Fatalf("runtime revision did not advance: before=%d, after=%d", runtimeBefore.Revision, runtimeAfter.Revision)
+ }
+ if turnID, err := RecoverableTurnID(testSessionID); err != nil || turnID != turn.TurnID {
+ t.Fatalf("finalized runtime was not reported as recoverable: turnID=%q, err=%v", turnID, err)
+ }
+ recovered, err := GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if recovered["recoveryState"] != "interrupted" || numberToInt64(recovered["recoveryRevision"]) != runtimeAfter.Revision {
+ t.Fatalf("orphaned runtime recovery metadata is incomplete: %#v", recovered)
+ }
+ recovered["expectedRevision"] = int64(1)
+ if revision, err := SaveSession(marshalSession(t, recovered)); err != nil || revision != 2 {
+ t.Fatalf("commit finalized orphan failed: revision=%d, err=%v", revision, err)
+ }
+ if turnID, err := RecoverableTurnID(testSessionID); err != nil || turnID != "" {
+ t.Fatalf("committed runtime remained recoverable: turnID=%q, err=%v", turnID, err)
+ }
+}
+
+func TestRuntimeRejectsInvalidSessionID(t *testing.T) {
+ useTestDataDir(t)
+ turn := &agentRuntimeTurn{TurnID: "20260715120004-abcdefg", State: "running"}
+ if err := beginRuntimeTurn("..", turn, false); err == nil {
+ t.Fatal("invalid runtime session id was accepted")
+ }
+ if err := saveRuntimeTurn("..", turn, false); err == nil {
+ t.Fatal("invalid runtime checkpoint session id was accepted")
+ }
+}
+
+func TestGetSessionRejectsRuntimeWithoutUserAnchor(t *testing.T) {
+ useTestDataDir(t)
+ session := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ t.Fatal(err)
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120007-abcdefg",
+ UserEntryID: "missing-user",
+ BaseRevision: 1,
+ State: "running",
+ }
+ if err := beginRuntimeTurn(testSessionID, turn, false); err == nil {
+ t.Fatal("runtime without a user anchor was started")
+ }
+ turn.State = "interrupted"
+ runtime := &agentRuntime{
+ SchemaVersion: 1,
+ Revision: 1,
+ SessionID: testSessionID,
+ ActiveTurn: turn,
+ }
+ if err := os.WriteFile(runtimePath(testSessionID), marshalSession(t, runtime), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := GetSession(testSessionID); err == nil {
+ t.Fatal("runtime without a user anchor was silently ignored")
+ }
+}
+
+func TestGetSessionRejectsIncompatibleRuntimeMetadata(t *testing.T) {
+ tests := []struct {
+ name string
+ runtime map[string]any
+ }{
+ {
+ name: "future schema",
+ runtime: map[string]any{
+ "schemaVersion": 2,
+ "sessionID": testSessionID,
+ },
+ },
+ {
+ name: "different session",
+ runtime: map[string]any{
+ "schemaVersion": 1,
+ "sessionID": "20260715120008-abcdefg",
+ },
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ useTestDataDir(t)
+ session := map[string]any{
+ "id": testSessionID,
+ "title": "base",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(runtimePath(testSessionID), marshalSession(t, test.runtime), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := GetSession(testSessionID); err == nil {
+ t.Fatal("incompatible runtime metadata was accepted")
+ }
+ })
+ }
+}
+
+func TestApplyRuntimePreservesUIOrderAndReplacesAssistant(t *testing.T) {
+ session := map[string]any{
+ "entries": []any{
+ map[string]any{"id": "user-1", "type": "user", "content": "hello"},
+ map[string]any{"id": "thinking-1", "type": "thinking"},
+ map[string]any{"id": "client-assistant-1", "type": "assistant", "content": "client one"},
+ map[string]any{"id": "confirm-1", "type": "confirm"},
+ map[string]any{"id": "client-assistant-2", "type": "assistant", "content": "client two"},
+ map[string]any{"id": "rollback-1", "type": "rollback"},
+ },
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120005-abcdefg",
+ UserEntryID: "user-1",
+ UpdatedAt: 1,
+ Delta: []AgentMessage{
+ {Role: "assistant", Content: "server one"},
+ {Role: "assistant", Content: "server two"},
+ },
+ }
+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {
+ t.Fatal(err)
+ }
+ entries := session["entries"].([]any)
+ wantTypes := []string{"user", "thinking", "assistant", "confirm", "assistant", "rollback"}
+ 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)
+ }
+ }
+ if entries[2].(map[string]any)["content"] != "server one" ||
+ entries[4].(map[string]any)["content"] != "server two" {
+ t.Fatalf("client assistant content was not replaced: %#v", entries)
+ }
+}
+
+func TestApplyRuntimeDistinguishesPendingAndExecutingTools(t *testing.T) {
+ session := map[string]any{
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120006-abcdefg",
+ UserEntryID: "user-1",
+ Delta: []AgentMessage{{
+ Role: "assistant",
+ ToolCalls: []AgentToolCall{
+ {Name: "not_started", State: "pending"},
+ {Name: "possibly_started", State: "executing"},
+ },
+ }},
+ }
+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {
+ t.Fatal(err)
+ }
+ entries := session["entries"].([]any)
+ calls := entries[1].(map[string]any)["toolCalls"].([]map[string]any)
+ if calls[0]["result"] != toolNotExecutedResult {
+ t.Fatalf("pending tool result is ambiguous: %#v", calls[0])
+ }
+ if calls[1]["result"] != toolUnknownResult {
+ t.Fatalf("executing tool result was not protected against automatic retry: %#v", calls[1])
+ }
+}
diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.go
index 1b77898c48..37a66687a1 100644
--- a/kernel/agent/tools_test.go
+++ b/kernel/agent/tools_test.go
@@ -89,3 +89,57 @@ func TestConvertSchemaRootAnyOf(t *testing.T) {
t.Fatalf("expected 1 property, got %d", len(props))
}
}
+
+func TestNeedsConfirmScopesReadOnlyActionsByToolSource(t *testing.T) {
+ const externalWrite = "test_external_write"
+ const externalRead = "test_external_read"
+ const nativeWrite = "test_native_write"
+ tools.SetTool(externalWrite, &tools.Tool{Name: externalWrite, Source: "mcp"})
+ tools.SetTool(externalRead, &tools.Tool{Name: externalRead, Source: "mcp", ReadOnlyHint: true})
+ tools.SetTool(nativeWrite, &tools.Tool{Name: nativeWrite, Source: "native"})
+ t.Cleanup(func() {
+ tools.RemoveTool(externalWrite)
+ tools.RemoveTool(externalRead)
+ tools.RemoveTool(nativeWrite)
+ })
+
+ if !needsConfirm(externalWrite, "", nil) {
+ t.Fatal("external tool with unknown mutability must require confirmation")
+ }
+ if !needsConfirm(externalWrite, "close", nil) {
+ t.Fatal("native safe action name must not bypass external tool confirmation")
+ }
+ if needsConfirm(externalRead, "query", nil) {
+ t.Fatal("external tool explicitly declared read-only should not require confirmation")
+ }
+ if needsLocalSnapshot(externalWrite, "write") {
+ t.Fatal("external write cannot be rolled back by a local repository snapshot")
+ }
+ if !needsLocalSnapshot(nativeWrite, "write") {
+ t.Fatal("native write should create a local repository snapshot")
+ }
+}
+
+func TestConfirmSessionAcceptsResponseOnce(t *testing.T) {
+ const confirmID = "test-confirm"
+ ch := make(chan confirmResult, 1)
+ confirmChannelsMu.Lock()
+ confirmChannels[confirmID] = ch
+ confirmChannelsMu.Unlock()
+ t.Cleanup(func() {
+ confirmChannelsMu.Lock()
+ delete(confirmChannels, confirmID)
+ confirmChannelsMu.Unlock()
+ })
+
+ if !ConfirmSession(confirmID, true, false) {
+ t.Fatal("registered confirmation was rejected")
+ }
+ if ConfirmSession(confirmID, false, false) {
+ t.Fatal("duplicate confirmation was accepted")
+ }
+ result := <-ch
+ if !result.approved || result.always {
+ t.Fatalf("unexpected confirmation result: %#v", result)
+ }
+}
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index f6ada1ce8f..ed95897414 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -19,6 +19,7 @@ package api
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -35,6 +36,8 @@ import (
type agentChatReq struct {
SessionID string `json:"sessionID"`
+ UserEntryID string `json:"userEntryID"`
+ ContentRevision *int64 `json:"contentRevision"`
Message string `json:"message"`
Language string `json:"language"`
References []agent.Reference `json:"references"`
@@ -46,7 +49,10 @@ type agentChatReq struct {
}
type runningSession struct {
- eventCh <-chan agent.AgentEvent
+ app string
+ turnID string
+ committed bool
+ terminal bool
}
var sessionsMu sync.Mutex
@@ -104,28 +110,39 @@ func agentChat(c *gin.Context) {
app := c.GetHeader("X-SiYuan-App-ID")
- ctx, cancel := context.WithCancel(c.Request.Context())
- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, req.SessionID, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout)
-
// 实例级互斥:同一 session 同时只允许一个活跃流。
- // 检查+占用在同一把锁内(compare-and-set),失败时 cancel 释放刚启动的 goroutine 防泄漏。
+ // 检查和占用在同一把锁内完成,成功占用后才启动 Agent goroutine。
sessionsMu.Lock()
if _, ok := runningSessions[req.SessionID]; ok {
sessionsMu.Unlock()
- cancel()
ret := gulu.Ret.NewResult()
ret.Code = -1
ret.Msg = "session is busy in another instance"
c.JSON(http.StatusConflict, ret)
return
}
- runningSessions[req.SessionID] = &runningSession{eventCh: eventCh}
+ ctx, cancel := context.WithCancel(c.Request.Context())
+ running := &runningSession{app: app}
+ runningSessions[req.SessionID] = running
sessionsMu.Unlock()
+
+ contentRevision := int64(-1)
+ if req.ContentRevision != nil {
+ contentRevision = *req.ContentRevision
+ }
+ eventCh := agent.AgentChat(ctx, client, selectedModel.Name, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout)
defer cancel()
+ streamClosed := false
defer func() {
- sessionsMu.Lock()
- delete(runningSessions, req.SessionID)
- sessionsMu.Unlock()
+ if streamClosed {
+ return
+ }
+ go func() {
+ for event := range eventCh {
+ recordRunningEvent(req.SessionID, running, event)
+ }
+ finishRunningSession(req.SessionID, running)
+ }()
}()
c.Header("Content-Type", "text/event-stream")
@@ -153,32 +170,58 @@ func agentChat(c *gin.Context) {
select {
case event, ok := <-eventCh:
if !ok {
- // 流正常结束(done 已写入 SSE)。通知镜像端解除占位锁定;
- // 实际内容重绘由发起者前端随后的 saveSession 广播(update)驱动,确保读到落盘后的完整数据。
- broadcastAgentSessionChanged(app, req.SessionID, "streamEnd")
- sessionsMu.Lock()
- delete(runningSessions, req.SessionID)
- sessionsMu.Unlock()
+ streamClosed = true
+ finishRunningSession(req.SessionID, running)
return
}
+ recordRunningEvent(req.SessionID, running, event)
if err := writeSSE(c, event); err != nil {
- // 客户端断开导致写失败,同样通知镜像端解除锁定,避免占位条悬挂。
- broadcastAgentSessionChanged(app, req.SessionID, "streamEnd")
return
}
flusher.Flush()
case <-c.Request.Context().Done():
- broadcastAgentSessionChanged(app, req.SessionID, "streamEnd")
return
case <-deadline:
- broadcastAgentSessionChanged(app, req.SessionID, "streamEnd")
- writeSSEError(c, model.Conf.Language(24))
+ writeSSEInterrupted(c, model.Conf.Language(24))
flusher.Flush()
return
}
}
}
+func recordRunningEvent(sessionID string, running *runningSession, event agent.AgentEvent) {
+ sessionsMu.Lock()
+ defer sessionsMu.Unlock()
+ if runningSessions[sessionID] != running {
+ return
+ }
+ if event.Type == "turn" {
+ running.turnID = event.TurnID
+ }
+ if event.Type == "done" || event.Type == "error" {
+ running.terminal = true
+ }
+}
+
+func finishRunningSession(sessionID string, running *runningSession) {
+ sessionsMu.Lock()
+ current := runningSessions[sessionID]
+ if current != running {
+ sessionsMu.Unlock()
+ return
+ }
+ uncommitted := running.turnID != "" && !running.committed
+ delete(runningSessions, sessionID)
+ sessionsMu.Unlock()
+ broadcastAgentSessionChanged(running.app, sessionID, "streamEnd")
+ if uncommitted {
+ util.BroadcastByType("agentChat", "agentSessionChanged", 0, "", map[string]string{
+ "sessionID": sessionID,
+ "action": "update",
+ })
+ }
+}
+
type agentConfirmReq struct {
ConfirmID string `json:"confirmID"`
Approved bool `json:"approved"`
@@ -194,8 +237,13 @@ func agentChatConfirm(c *gin.Context) {
c.JSON(http.StatusOK, ret)
return
}
- agent.ConfirmSession(req.ConfirmID, req.Approved, req.Always)
ret := gulu.Ret.NewResult()
+ if !agent.ConfirmSession(req.ConfirmID, req.Approved, req.Always) {
+ ret.Code = -1
+ ret.Msg = "agent confirmation expired"
+ c.JSON(http.StatusConflict, ret)
+ return
+ }
c.JSON(http.StatusOK, ret)
}
@@ -313,7 +361,23 @@ func getSession(c *gin.Context) {
return
}
- session, err := agent.GetSession(req.ID)
+ sessionsMu.Lock()
+ _, running := runningSessions[req.ID]
+ if !running {
+ if err := agent.FinalizeOrphanedTurn(req.ID); err != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
+ }
+ session, err := agent.GetSessionState(req.ID, !running)
+ if err == nil && running {
+ session["agentRunning"] = true
+ }
+ sessionsMu.Unlock()
if err != nil {
ret := gulu.Ret.NewResult()
ret.Code = -1
@@ -341,7 +405,25 @@ func removeSession(c *gin.Context) {
return
}
- _ = agent.DeleteSession(req.ID)
+ sessionsMu.Lock()
+ _, running := runningSessions[req.ID]
+ if running {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "session is running"
+ c.JSON(http.StatusConflict, ret)
+ return
+ }
+ err := agent.DeleteSession(req.ID)
+ sessionsMu.Unlock()
+ if err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
// 通知其他实例:会话已删除,刷新列表;若为当前会话则清空视图。
broadcastAgentSessionChanged(c.GetHeader("X-SiYuan-App-ID"), req.ID, "delete")
ret := gulu.Ret.NewResult()
@@ -357,15 +439,151 @@ func saveSession(c *gin.Context) {
c.JSON(http.StatusOK, ret)
return
}
+ var meta sessionMeta
+ if gulu.JSON.UnmarshalJSON(body, &meta) != nil || meta.ID == "" {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "invalid session data"
+ c.JSON(http.StatusBadRequest, ret)
+ return
+ }
+ sessionsMu.Lock()
+ running := runningSessions[meta.ID]
+ if running != nil && running.app != c.GetHeader("X-SiYuan-App-ID") {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "session is running in another instance"
+ c.JSON(http.StatusConflict, ret)
+ return
+ }
+ commitTurnID := meta.CommitTurnID
+ if commitTurnID == "" {
+ commitTurnID = meta.RecoveryTurnID
+ }
+ if running != nil && commitTurnID == "" && c.GetHeader("X-SiYuan-Agent-Checkpoint") != "2" && running.terminal && running.turnID != "" {
+ var payload map[string]any
+ if err := gulu.JSON.UnmarshalJSON(body, &payload); err != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusBadRequest, ret)
+ return
+ }
+ payload["commitTurnID"] = running.turnID
+ body, err = gulu.JSON.MarshalJSON(payload)
+ if err != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
+ commitTurnID = running.turnID
+ }
+ if running == nil {
+ if runtimeErr := agent.FinalizeOrphanedTurn(meta.ID); runtimeErr != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = runtimeErr.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
+ // 旧前端没有 commitTurnID。流已真正结束后,从终止检查点补出提交标识;SaveSession 仍会
+ // 用 runtime 重建权威内容,因此不会信任旧前端可能不完整的流式快照。
+ if commitTurnID == "" && c.GetHeader("X-SiYuan-Agent-Checkpoint") != "2" {
+ recoverableTurnID, runtimeErr := agent.RecoverableTurnID(meta.ID)
+ if runtimeErr != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = runtimeErr.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
+ if recoverableTurnID != "" {
+ var payload map[string]any
+ if err := gulu.JSON.UnmarshalJSON(body, &payload); err != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusBadRequest, ret)
+ return
+ }
+ payload["commitTurnID"] = recoverableTurnID
+ body, err = gulu.JSON.MarshalJSON(payload)
+ if err != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
+ commitTurnID = recoverableTurnID
+ }
+ }
+ }
+ // 已占用会话但尚未收到本轮 turn 事件,通常表示 Agent 初始化失败。此时若磁盘上仍有旧的
+ // 未提交 turn,不能让无 commitTurnID 的普通保存绕过恢复协议并覆盖它。
+ if commitTurnID == "" && (running == nil || running.turnID == "") {
+ uncommitted, runtimeErr := agent.HasUncommittedTurn(meta.ID)
+ if runtimeErr != nil {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = runtimeErr.Error()
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
+ if uncommitted {
+ sessionsMu.Unlock()
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = "session has an uncommitted turn"
+ c.JSON(http.StatusConflict, ret)
+ return
+ }
+ }
- _ = agent.SaveSession(body)
+ revision, err := agent.SaveSession(body)
+ var canonicalSession map[string]any
+ if err == nil && running != nil {
+ if commitTurnID != "" && commitTurnID == running.turnID {
+ running.committed = true
+ }
+ }
+ if err == nil && commitTurnID != "" {
+ // 将提交后的权威会话随响应返回,前端无需再经历一次可能失败或乱序的 GET,下一轮保存也
+ // 不会把流式期间的局部快照重新覆盖到服务端。
+ canonicalSession, _ = agent.GetSessionState(meta.ID, false)
+ }
+ sessionsMu.Unlock()
+ if err != nil {
+ ret := gulu.Ret.NewResult()
+ ret.Code = -1
+ ret.Msg = err.Error()
+ if errors.Is(err, agent.ErrSessionConflict) || errors.Is(err, agent.ErrRuntimeNotFinalized) {
+ ret.Data = map[string]int64{"revision": revision}
+ c.JSON(http.StatusConflict, ret)
+ return
+ }
+ c.JSON(http.StatusInternalServerError, ret)
+ return
+ }
// 从 body 解出 sessionID 用于广播。update 仅触发其他实例刷新会话列表元数据,
// 不触发当前视图重绘(重绘由 streamEnd 负责),回避流式中途半截数据的时序问题。
- var meta sessionMeta
- if gulu.JSON.UnmarshalJSON(body, &meta) == nil && meta.ID != "" {
- broadcastAgentSessionChanged(c.GetHeader("X-SiYuan-App-ID"), meta.ID, "update")
- }
+ broadcastAgentSessionChanged(c.GetHeader("X-SiYuan-App-ID"), meta.ID, "update")
ret := gulu.Ret.NewResult()
+ data := map[string]any{"revision": revision}
+ if canonicalSession != nil {
+ data["session"] = canonicalSession
+ }
+ ret.Data = data
c.JSON(http.StatusOK, ret)
}
@@ -381,11 +599,15 @@ func broadcastAgentSessionChanged(app, sessionID, action string) {
// sessionMeta 用于从 saveSession 的 body 中解析出会话 ID,agent 包内也有同名字段,此处独立定义避免循环依赖。
type sessionMeta struct {
- ID string `json:"id"`
+ ID string `json:"id"`
+ CommitTurnID string `json:"commitTurnID"`
+ RecoveryTurnID string `json:"recoveryTurnID"`
}
func writeSSE(c *gin.Context, event agent.AgentEvent) error {
switch event.Type {
+ case "turn":
+ return writeSSEEvent(c, "turn", map[string]string{"turnID": event.TurnID})
case "content":
return writeSSEEvent(c, "content", map[string]string{"token": event.Token})
case "thinking":
@@ -420,7 +642,7 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {
"contextLimit": event.ContextLimit,
})
case "done":
- return writeSSEEvent(c, "done", map[string]any{})
+ return writeSSEEvent(c, "done", map[string]string{"turnID": event.TurnID})
case "retry":
return writeSSEEvent(c, "retry", map[string]any{
"attempt": event.RetryAttempt,
@@ -456,6 +678,10 @@ func writeSSEError(c *gin.Context, message string) error {
return writeSSEEvent(c, "error", map[string]string{"message": message})
}
+func writeSSEInterrupted(c *gin.Context, message string) error {
+ return writeSSEEvent(c, "interrupted", map[string]string{"message": message})
+}
+
func lsSkills(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.go
index 934229f498..bf9bdc7b96 100644
--- a/kernel/mcp/client/mcp.go
+++ b/kernel/mcp/client/mcp.go
@@ -154,12 +154,14 @@ func connectServers(servers []conf.MCPServer) []Connection {
desc = "[MCP:" + server.Name + "] " + desc
}
+ readOnlyHint := tool.Annotations != nil && tool.Annotations.ReadOnlyHint
tools.SetTool(name, &tools.Tool{
- Name: name,
- Description: desc,
- InputSchema: convertMCPSchema(tool.InputSchema),
- Source: "mcp",
- Handler: mcpToolHandler(server.Name, tool.Name, serverTimeout(server)),
+ Name: name,
+ Description: desc,
+ InputSchema: convertMCPSchema(tool.InputSchema),
+ Source: "mcp",
+ ReadOnlyHint: readOnlyHint,
+ Handler: mcpToolHandler(server.Name, tool.Name, serverTimeout(server)),
})
registered++
}
diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.go
index 19532e07cb..0dfbbb42f8 100644
--- a/kernel/mcp/tools/types.go
+++ b/kernel/mcp/tools/types.go
@@ -25,6 +25,8 @@ type Tool struct {
// Source 标记工具来源:"native"(SiYuan 内置)、"plugin"(插件注册)、"mcp"(外部 MCP 服务)。
// 用于 token 分类统计按来源拆分。空值按 "native" 处理(兼容旧调用方)。
Source string `json:"source,omitempty"`
+ // ReadOnlyHint 仅在外部工具明确声明只读时为 true;未声明时按可能写入处理并要求确认。
+ ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
Handler func(args map[string]any) (CallToolResult, error) `json:"-"`
}
diff --git a/kernel/plugin/api_mcp.go b/kernel/plugin/api_mcp.go
index b229184d15..45d87714d0 100644
--- a/kernel/plugin/api_mcp.go
+++ b/kernel/plugin/api_mcp.go
@@ -50,6 +50,7 @@ func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erro
var name string
var title string
var description string
+ var readOnlyHint bool
var inputSchema *tools.ToolSchema
var outputSchema *tools.ToolSchema
var handler goja.Callable
@@ -91,6 +92,13 @@ func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erro
return
}
}
+ if readOnlyValue := configObj.Get("readOnly"); !goja.IsUndefined(readOnlyValue) && !goja.IsNull(readOnlyValue) {
+ var ok bool
+ if readOnlyHint, ok = readOnlyValue.Export().(bool); !ok {
+ err = fmt.Errorf("config.readOnly must be a boolean")
+ return
+ }
+ }
}
} else {
err = fmt.Errorf("second argument must be a config object")
@@ -121,6 +129,7 @@ func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erro
InputSchema: *inputSchema,
OutputSchema: outputSchema,
Source: "plugin",
+ ReadOnlyHint: readOnlyHint,
Handler: func(args map[string]any) (tools.CallToolResult, error) {
return p.invokeMcpTool(handler, args)
},
@@ -132,6 +141,7 @@ func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erro
"name": fullToolName,
"title": title,
"description": description,
+ "readOnly": readOnlyHint,
"inputSchema": inputSchema,
"outputSchema": outputSchema,
}