Skip to content

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

:art: https://github.com/siyuan-note/siyuan/issues/18458

Vanessa0f0ac093d573
diff --git a/app/src/assets/scss/business/_ai_agent.scss b/app/src/assets/scss/business/_ai_agent.scss
index b2811744b6..9fa0a9f388 100644
--- a/app/src/assets/scss/business/_ai_agent.scss
+++ b/app/src/assets/scss/business/_ai_agent.scss
@@ -210,16 +210,19 @@
width: min(100%, 560px);
}
-.agent-chat__edit-textarea {
- display: block;
+.agent-chat__edit-editor {
+ background-color: transparent;
+ max-height: 40vh;
min-height: 96px;
width: 100%;
- resize: vertical;
- line-height: 1.5;
+}
+
+.agent-chat__edit-editor .protyle-wysiwyg {
+ min-height: 96px;
}
.agent-chat__msg--editing .agent-chat__msg-actions {
- margin-top: 8px;
+ margin-top: 4px;
opacity: 1;
}
@@ -245,7 +248,7 @@
width: 100%;
justify-content: flex-end;
opacity: 0;
- transition: var(--b3-transition);
+ transition: opacity .2s cubic-bezier(0, 0, .2, 1) 0ms;
}
.agent-chat__msg--ai:hover .agent-chat__msg-actions,
@@ -1045,14 +1048,18 @@
}
}
-// 迷你 protyle 输入框:复用 .protyle-wysiwyg,此处只约束尺寸(min/max-height、滚动)。
-.agent-chat__composer-host .protyle-wysiwyg {
+// 发送框和历史消息编辑器复用相同排版,尺寸和滚动按使用场景分别约束。
+.agent-chat__composer-host .protyle-wysiwyg,
+.agent-chat__edit-editor .protyle-wysiwyg {
outline: none;
- font-size: 14px;
+ font-size: var(--b3-font-size);
line-height: 1.6;
color: var(--b3-theme-on-background);
+ padding: 0;
+}
+
+.agent-chat__composer-host .protyle-wysiwyg {
min-height: 24px;
max-height: 120px;
overflow-y: auto;
- padding: 0;
}
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index a525412aac..0e4ffc80f4 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -3,7 +3,7 @@ import {Model} from "../../Model";
import type {App} from "../../../index";
import {AgentHttpError, fetchAgentSSE, IEditorContext, ISSEResult, IToolEffects} from "./agentSSE";
import {genUUID} from "../../../util/genID";
-import {mountComposer} from "./AgentComposer";
+import {mountComposer, type AgentComposerData} from "./AgentComposer";
import {disabledWYSIWYG} from "../../../protyle/util/disabledWYSIWYG";
import {getAllEditor} from "../../getAll";
import "./frontendActions";
@@ -22,8 +22,8 @@ import {showMessage} from "../../../dialog/message";
import * as dayjs from "dayjs";
import {sendNotification} from "../../../plugin/platformUtils";
import {
+ applyAgentUserEdit,
findAgentUserEntryIndex,
- filterAgentReferencesForContent,
hasAgentExecutedToolsAfter,
isAgentRegenerateStateCurrent
} from "./AgentHistory";
@@ -122,7 +122,8 @@ export class AgentChat extends Model {
private currentThinkingReasoning = "";
private currentThinkingReasoningContent = "";
private editingUserEntryID = "";
- private pendingEditDraft: { entryID: string; content: string } | null = null;
+ private editingComposer: ReturnType<typeof mountComposer> | null = null;
+ private pendingEditDraft: { entryID: string; data: AgentComposerData } | null = null;
// thinking step 只保留工具名列表(去重:arguments/result 仅在 assistant entry 存一份),
// 不再保存 text("已思考:Xs" 由 i18n 在渲染时从 duration 生成)。
private currentThinkingSteps: Array<{
@@ -486,7 +487,7 @@ export class AgentChat extends Model {
}
private showWelcome() {
- this.editingUserEntryID = "";
+ this.destroyEditingComposer();
const hasModel = this.modelOptions.length > 0;
this.messagesContainer.innerHTML = renderWelcomeHTML(hasModel);
if (!hasModel) {
@@ -1038,6 +1039,7 @@ export class AgentChat extends Model {
// 当前会话被其他实例删除时,清空到欢迎页。不调 saveSession(会话已不存在于磁盘)。
private handleCurrentSessionDeleted() {
+ this.destroyEditingComposer();
this.pendingEditDraft = null;
const deletedSessionID = this.sessionId;
this.removeMirrorPlaceholder();
@@ -1063,6 +1065,7 @@ export class AgentChat extends Model {
}
private async switchSession(id: string) {
+ this.destroyEditingComposer();
this.pendingEditDraft = null;
const previousSessionID = this.sessionId;
const hadActiveTurn = this.isStreaming || !!this.currentTurnID;
@@ -1276,7 +1279,7 @@ export class AgentChat extends Model {
}
private renderLoadedSession(session: AgentSession) {
- this.editingUserEntryID = "";
+ this.destroyEditingComposer();
for (let i = 0; i < session.entries.length; i++) {
const entry = session.entries[i];
const entryId = (entry as { id?: string }).id;
@@ -1395,6 +1398,7 @@ export class AgentChat extends Model {
}
private async createSession() {
+ this.destroyEditingComposer();
this.pendingEditDraft = null;
const previousSessionID = this.sessionId;
const hadActiveTurn = this.isStreaming || !!this.currentTurnID;
@@ -1584,6 +1588,12 @@ export class AgentChat extends Model {
showMessage(L.agentChatBusy || "This session is busy in another instance", 3000);
}
+ private destroyEditingComposer() {
+ this.editingComposer?.destroy();
+ this.editingComposer = null;
+ this.editingUserEntryID = "";
+ }
+
private restorePendingEditDraft() {
const draft = this.pendingEditDraft;
if (!draft) {
@@ -1592,7 +1602,7 @@ export class AgentChat extends Model {
const userEl = this.messagesContainer.querySelector(
'.agent-chat__msg--user[data-message-id="' + draft.entryID + '"]') as HTMLElement | null;
if (userEl) {
- this.beginEditUserMessage(draft.entryID, userEl, draft.content);
+ this.beginEditUserMessage(draft.entryID, userEl, draft.data);
}
}
@@ -2029,7 +2039,7 @@ export class AgentChat extends Model {
this.scrollToBottom(true);
}
- private beginEditUserMessage(entryID: string, el: HTMLElement, initialContent?: string) {
+ private beginEditUserMessage(entryID: string, el: HTMLElement, initialData?: AgentComposerData) {
if (this.editingUserEntryID || this.isStreaming || this.mirrorLocked) {
return;
}
@@ -2041,23 +2051,25 @@ export class AgentChat extends Model {
el.classList.add("agent-chat__msg--editing");
const body = el.querySelector(".agent-chat__body") as HTMLElement;
const actions = el.querySelector(".agent-chat__msg-actions") as HTMLElement;
- const textarea = document.createElement("textarea");
- textarea.className = "b3-text-field agent-chat__edit-textarea";
- textarea.value = initialContent ?? entry.content;
+ const editorHost = document.createElement("div");
+ editorHost.className = "agent-chat__edit-editor";
+ body.classList.remove("protyle-wysiwyg");
+ body.removeAttribute("contenteditable");
+ body.removeAttribute("data-readonly");
body.innerHTML = "";
- body.appendChild(textarea);
+ body.appendChild(editorHost);
actions.innerHTML = "";
const cancel = document.createElement("button");
- cancel.className = "b3-button b3-button--cancel";
+ cancel.className = "b3-button b3-button--small b3-button--cancel";
cancel.textContent = window.siyuan.languages.cancel;
const submit = document.createElement("button");
- submit.className = "b3-button b3-button--text";
+ submit.className = "b3-button b3-button--small b3-button--text";
submit.textContent = window.siyuan.languages.confirm;
actions.append(cancel, submit);
const restore = () => {
- this.editingUserEntryID = "";
+ this.destroyEditingComposer();
if (this.pendingEditDraft?.entryID === entryID) {
this.pendingEditDraft = null;
}
@@ -2066,28 +2078,29 @@ export class AgentChat extends Model {
this.renderUserMessage(replacement);
};
cancel.addEventListener("click", restore);
- submit.addEventListener("click", async () => {
- const content = textarea.value.trim();
- if (!content) {
- textarea.focus();
+ let editComposer: ReturnType<typeof mountComposer> | null = null;
+ const submitEdit = async () => {
+ const data = editComposer?.getSendData();
+ if (!data?.text) {
+ editComposer?.focus();
return;
}
- await this.regenerateResponse(entryID, content);
+ await this.regenerateResponse(entryID, data);
+ };
+ submit.addEventListener("click", () => {
+ void submitEdit();
});
- textarea.addEventListener("keydown", (event) => {
- if (event.isComposing) {
- return;
- }
- if (event.key === "Escape") {
- event.preventDefault();
- restore();
- } else if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
- event.preventDefault();
- submit.click();
- }
+ editComposer = mountComposer(editorHost, () => {
+ void submitEdit();
+ }, undefined, {
+ initialContent: initialData?.text ?? entry.content,
+ initialBlockHTML: initialData?.blockHTML ?? entry.blockHTML,
+ submitMode: "mod-enter",
+ onCancel: restore,
+ enableHistory: false,
});
- textarea.focus();
- textarea.setSelectionRange(textarea.value.length, textarea.value.length);
+ this.editingComposer = editComposer;
+ editComposer.focus(true);
}
private createAIMessagePlaceholder(): HTMLElement {
@@ -2518,11 +2531,15 @@ export class AgentChat extends Model {
});
}
- private async regenerateResponse(userEntryID?: string, editedContent?: string) {
+ private async regenerateResponse(userEntryID?: string, editedData?: AgentComposerData) {
if (this.isStreaming || this.mirrorLocked || this.modelOptions.length === 0) {
return;
}
+ if (editedData !== undefined && userEntryID) {
+ this.pendingEditDraft = {entryID: userEntryID, data: editedData};
+ }
if (!await this.prepareForNewTurn()) {
+ this.restorePendingEditDraft();
return;
}
const requestSessionID = this.sessionId;
@@ -2531,9 +2548,6 @@ export class AgentChat extends Model {
if (targetIndex < 0) {
return;
}
- if (editedContent !== undefined && userEntryID) {
- this.pendingEditDraft = {entryID: userEntryID, content: editedContent};
- }
if (!await this.confirmHistoryTruncation(targetIndex)) {
this.restorePendingEditDraft();
return;
@@ -2556,19 +2570,13 @@ export class AgentChat extends Model {
if (targetEntry.type !== "user") {
return;
}
- this.editingUserEntryID = "";
- this.pendingEditDraft = editedContent === undefined ? null : {
+ this.destroyEditingComposer();
+ this.pendingEditDraft = editedData === undefined ? null : {
entryID: targetEntry.id || "",
- content: editedContent,
+ data: editedData,
};
- if (editedContent !== undefined) {
- const contentChanged = editedContent !== targetEntry.content;
- targetEntry.content = editedContent;
- if (contentChanged) {
- targetEntry.blockHTML = undefined;
- }
- const references = filterAgentReferencesForContent(targetEntry.references || [], editedContent);
- targetEntry.references = references.length > 0 ? references : undefined;
+ if (editedData !== undefined) {
+ applyAgentUserEdit(targetEntry, editedData);
}
this.entries.splice(targetIndex + 1);
@@ -2581,7 +2589,7 @@ export class AgentChat extends Model {
sibling.remove();
sibling = next;
}
- if (editedContent !== undefined) {
+ if (editedData !== undefined) {
const replacement = this.createUserMessage(targetEntry.content, targetEntry.timestamp, targetEntry.id,
targetEntry.blockHTML);
targetEl.replaceWith(replacement);
@@ -2645,6 +2653,7 @@ export class AgentChat extends Model {
pluginActions,
lastUserEntry.id,
SessionStore.getRevision(this.sessionId),
+ editedData?.blockHTML,
);
}
diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.ts
index ebb90c0234..627a43b6fa 100644
--- a/app/src/layout/dock/agent/AgentComposer.ts
+++ b/app/src/layout/dock/agent/AgentComposer.ts
@@ -6,11 +6,18 @@ import {fetchPost} from "../../../util/fetch";
import {hintRef} from "../../../protyle/hint/extend";
import {genEmptyElement} from "../../../block/util";
import {blockRender} from "../../../protyle/render/blockRender";
+import {focusBlock} from "../../../protyle/util/selection";
+
+export interface AgentComposerData {
+ text: string;
+ blockHTML: string;
+ references: { id: string; title: string }[];
+}
interface ComposerHandle {
- focus: () => void;
+ focus: (toEnd?: boolean) => void;
destroy: () => void;
- getSendData: () => { text: string; blockHTML: string; references: { id: string; title: string }[] };
+ getSendData: () => AgentComposerData;
clear: () => void;
pushHistory: (text: string) => void;
getHistory: () => string[];
@@ -23,6 +30,14 @@ interface ComposerHandle {
type OnChangeCallback = () => void;
+interface ComposerOptions {
+ initialContent?: string;
+ initialBlockHTML?: string;
+ submitMode?: "enter" | "mod-enter";
+ onCancel?: () => void;
+ enableHistory?: boolean;
+}
+
const resetEmbedBlocks = (element: HTMLElement) => {
element.querySelectorAll<HTMLElement>('[data-type="NodeBlockQueryEmbed"]').forEach((embedElement) => {
embedElement.removeAttribute("data-render");
@@ -126,9 +141,12 @@ class ComposerHistory {
}
}
-export function mountComposer(host: HTMLElement, onSend: () => void, onChange?: OnChangeCallback): ComposerHandle {
+export function mountComposer(host: HTMLElement, onSend: () => void, onChange?: OnChangeCallback,
+ options: ComposerOptions = {}): ComposerHandle {
const history = new ComposerHistory();
const L = window.siyuan.languages;
+ const submitMode = options.submitMode || "enter";
+ const enableHistory = options.enableHistory !== false;
const app: App = window.siyuan.ws.app;
const protyle = new Protyle(app, host, {
@@ -170,11 +188,23 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
const p = protyle.protyle;
const wysiwyg = p.wysiwyg!;
- wysiwyg.element.innerHTML = "";
- const emptyElement = genEmptyElement(false, false);
- emptyElement.firstElementChild.classList.add("protyle-wysiwyg--empty");
- emptyElement.firstElementChild.setAttribute("placeholder", L.agentInputPlaceholder);
- wysiwyg.element.appendChild(emptyElement);
+ const setEmptyContent = () => {
+ wysiwyg.element.innerHTML = "";
+ const emptyElement = genEmptyElement(false, false);
+ emptyElement.firstElementChild.classList.add("protyle-wysiwyg--empty");
+ emptyElement.firstElementChild.setAttribute("placeholder", L.agentInputPlaceholder);
+ wysiwyg.element.appendChild(emptyElement);
+ };
+ if (options.initialBlockHTML) {
+ wysiwyg.element.innerHTML = options.initialBlockHTML;
+ resetEmbedBlocks(wysiwyg.element);
+ blockRender(p, wysiwyg.element);
+ } else if (options.initialContent) {
+ wysiwyg.element.innerHTML = p.lute.Md2BlockDOM(options.initialContent);
+ blockRender(p, wysiwyg.element);
+ } else {
+ setEmptyContent();
+ }
const updatePlaceholder = () => {
const isEmpty = (wysiwyg.element.textContent || "").replace(new RegExp(Constants.ZWSP, "g"), "").trim() === "";
@@ -208,16 +238,26 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
return;
}
- // Enter 发送(Shift+Enter 让 protyle 走软换行/分块)
- if (event.key === "Enter" && !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) {
+ // 底部输入框使用 Enter 发送,历史消息编辑使用 Ctrl/Cmd+Enter 确认。
+ const enterToSubmit = submitMode === "enter" && event.key === "Enter" &&
+ !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey;
+ const modEnterToSubmit = submitMode === "mod-enter" && event.key === "Enter" &&
+ (event.ctrlKey || event.metaKey);
+ if (enterToSubmit || modEnterToSubmit) {
event.preventDefault();
event.stopPropagation();
onSend();
return;
}
+ if (event.key === "Escape" && options.onCancel) {
+ event.preventDefault();
+ event.stopPropagation();
+ options.onCancel();
+ return;
+ }
// ↑ 翻历史:仅在空输入或已处于历史浏览时触发
- if (event.key === "ArrowUp" && !event.shiftKey) {
+ if (enableHistory && event.key === "ArrowUp" && !event.shiftKey) {
const isEmpty = (wysiwyg.element.textContent || "").replace(new RegExp(Constants.ZWSP, "g"), "").trim() === "";
if ((history.isBrowsing() || isEmpty) && history.has()) {
event.preventDefault();
@@ -229,7 +269,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
}
}
// ↓ 翻历史:仅浏览中触发
- if (event.key === "ArrowDown" && history.isBrowsing()) {
+ if (enableHistory && event.key === "ArrowDown" && history.isBrowsing()) {
event.preventDefault();
event.stopPropagation();
const target = history.navigateDown();
@@ -242,7 +282,8 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
}
// 用户开始新输入时退出历史浏览
- if (history.isBrowsing() && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
+ if (enableHistory && history.isBrowsing() && event.key.length === 1 &&
+ !event.ctrlKey && !event.metaKey && !event.altKey) {
history.resetCursor();
}
}, true);
@@ -258,7 +299,11 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
};
return {
- focus: () => protyle.focus(),
+ focus: (toEnd = false) => {
+ if (!toEnd || !focusBlock(wysiwyg.element.lastElementChild, wysiwyg.element, false)) {
+ protyle.focus();
+ }
+ },
destroy: () => {
contentObserver.disconnect();
protyle.destroy();
@@ -274,11 +319,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
return {text: getMarkdown(), blockHTML: getBlockHTML(), references};
},
clear: () => {
- wysiwyg.element.innerHTML = "";
- const emptyElement = genEmptyElement(false, false);
- emptyElement.firstElementChild.classList.add("protyle-wysiwyg--empty");
- emptyElement.firstElementChild.setAttribute("placeholder", L.agentInputPlaceholder);
- wysiwyg.element.appendChild(emptyElement);
+ setEmptyContent();
p.undo.clear();
updatePlaceholder();
history.resetCursor();
diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.ts
index 1467afe451..fd0a7a38e5 100644
--- a/app/src/layout/dock/agent/AgentHistory.test.ts
+++ b/app/src/layout/dock/agent/AgentHistory.test.ts
@@ -1,8 +1,8 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
+ applyAgentUserEdit,
findAgentUserEntryIndex,
- filterAgentReferencesForContent,
hasAgentExecutedToolsAfter,
isAgentRegenerateStateCurrent
} from "./AgentHistory";
@@ -45,11 +45,30 @@ describe("AgentHistory", () => {
assert.equal(isAgentRegenerateStateCurrent("session-1", "session-1", 2, 2, false, true), false);
});
- it("drops block references removed from edited content", () => {
- const references = [
- {id: "block-1", title: "First block"},
- {id: "block-2", title: "Second block"},
- ];
- assert.deepEqual(filterAgentReferencesForContent(references, "Review First block"), [references[0]]);
+ it("updates rich user message data together", () => {
+ const entry = {
+ content: "Old content",
+ blockHTML: "<div>Old content</div>",
+ references: [{id: "block-1", title: "Old reference"}],
+ };
+ const references = [{id: "block-2", title: "New reference"}];
+ applyAgentUserEdit(entry, {
+ text: "| A | B |",
+ blockHTML: '<div data-type="NodeTable">table</div>',
+ references,
+ });
+ assert.deepEqual(entry, {
+ content: "| A | B |",
+ blockHTML: '<div data-type="NodeTable">table</div>',
+ references,
+ });
+ assert.notEqual(entry.references, references);
+
+ applyAgentUserEdit(entry, {
+ text: "No references",
+ blockHTML: "<div>No references</div>",
+ references: [],
+ });
+ assert.equal(entry.references, undefined);
});
});
diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.ts
index 6427eb859e..d63e23f2f7 100644
--- a/app/src/layout/dock/agent/AgentHistory.ts
+++ b/app/src/layout/dock/agent/AgentHistory.ts
@@ -7,6 +7,24 @@ export type AgentHistoryEntry = {
export type AgentHistoryReference = { id: string; title: string };
+export type AgentHistoryUserEntry = {
+ content: string;
+ blockHTML?: string;
+ references?: AgentHistoryReference[];
+};
+
+export type AgentHistoryEditData = {
+ text: string;
+ blockHTML: string;
+ references: AgentHistoryReference[];
+};
+
+export const applyAgentUserEdit = (entry: AgentHistoryUserEntry, data: AgentHistoryEditData) => {
+ entry.content = data.text;
+ entry.blockHTML = data.blockHTML;
+ entry.references = data.references.length > 0 ? data.references.slice() : undefined;
+};
+
export const findAgentUserEntryIndex = (entries: AgentHistoryEntry[], userEntryID?: string): number => {
for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i].type === "user" && (!userEntryID || entries[i].id === userEntryID)) {
@@ -35,7 +53,3 @@ export const isAgentRegenerateStateCurrent = (requestSessionID: string, currentS
return requestSessionID === currentSessionID && requestRevision === currentRevision &&
!isStreaming && !mirrorLocked;
};
-
-export const filterAgentReferencesForContent = (references: AgentHistoryReference[], content: string) => {
- return references.filter(reference => content.includes(reference.title));
-};
diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.ts
index f88ac6c1db..a47ecba829 100644
--- a/app/src/layout/dock/agent/agentSSE.ts
+++ b/app/src/layout/dock/agent/agentSSE.ts
@@ -102,6 +102,7 @@ export async function fetchAgentSSE(
pluginActions?: Array<{name: string; description: string}>,
userEntryID?: string,
contentRevision?: number,
+ blockHTML?: string,
): Promise<void> {
let errorReported = false;
const reportError = async (err: Error) => {
@@ -125,6 +126,7 @@ export async function fetchAgentSSE(
if (pluginActions && pluginActions.length > 0) { body.pluginActions = pluginActions; }
if (userEntryID) { body.userEntryID = userEntryID; }
if (typeof contentRevision === "number") { body.contentRevision = contentRevision; }
+ if (blockHTML !== undefined) { body.blockHTML = blockHTML; }
const response = await fetch("/api/ai/agent/chat", {
method: "POST",
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index f4d3964956..30caa8ef1b 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -443,7 +443,7 @@ type agentCheckpoint struct {
LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`
}
-func AgentChat(ctx context.Context, client *openai.Client, model string, contextLimit int, 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, streamIdleTimeout time.Duration) <-chan AgentEvent {
+func AgentChat(ctx context.Context, client *openai.Client, model string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, userBlockHTML *string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {
ch := make(chan AgentEvent, 256)
go func() {
@@ -555,6 +555,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, context
currentUserEntry.Content = userMessage
currentUserEntry.References = append([]Reference(nil), references...)
currentUserEntry.EditorContext = cloneEditorContext(editorCtx)
+ if userBlockHTML != nil {
+ currentUserEntry.BlockHTML = *userBlockHTML
+ }
}
messages = checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, pluginActions, compaction)
}
@@ -582,6 +585,10 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, context
userReferences := append([]Reference(nil), references...)
turn.UserReferences = &userReferences
turn.UserEditorContext = cloneEditorContext(editorCtx)
+ if userBlockHTML != nil {
+ blockHTML := *userBlockHTML
+ turn.UserBlockHTML = &blockHTML
+ }
}
select {
case <-ctx.Done():
diff --git a/kernel/agent/attachments_test.go b/kernel/agent/attachments_test.go
index 71d04d3fbd..f68e6ed4a0 100644
--- a/kernel/agent/attachments_test.go
+++ b/kernel/agent/attachments_test.go
@@ -327,7 +327,7 @@ func TestAgentChatSendsToolAttachmentToCurrentModel(t *testing.T) {
events := AgentChat(
context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1,
- "look at the image", "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
+ "look at the image", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
)
doneSeen := false
for event := range events {
diff --git a/kernel/agent/compaction_test.go b/kernel/agent/compaction_test.go
index 6c38603c57..d95eaf5781 100644
--- a/kernel/agent/compaction_test.go
+++ b/kernel/agent/compaction_test.go
@@ -279,7 +279,7 @@ func TestAgentChatCompactsBeforeSendingOversizedContext(t *testing.T) {
events := AgentChat(
context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,
- "user-2", 1, "start the current task", "English", nil, EditorContext{}, nil, false,
+ "user-2", 1, "start the current task", nil, "English", nil, EditorContext{}, nil, false,
time.Second, 0, "", time.Second, time.Second,
)
doneSeen := false
@@ -314,10 +314,11 @@ func TestAgentChatCompactsBeforeSendingOversizedContext(t *testing.T) {
func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {
setupCompactionAgentTest(t)
const (
- originalTarget = "ORIGINAL_TARGET_PROMPT_DO_NOT_SEND"
- editedTarget = "EDITED_TARGET_PROMPT_MUST_SEND"
- staleAnswer = "STALE_REGENERATED_ANSWER_DO_NOT_SEND"
- futureTurn = "FUTURE_TURN_DO_NOT_SEND"
+ originalTarget = "ORIGINAL_TARGET_PROMPT_DO_NOT_SEND"
+ editedTarget = "EDITED_TARGET_PROMPT_MUST_SEND"
+ editedBlockHTML = `<div data-node-id="edited">EDITED_TARGET_PROMPT_MUST_SEND</div>`
+ staleAnswer = "STALE_REGENERATED_ANSWER_DO_NOT_SEND"
+ futureTurn = "FUTURE_TURN_DO_NOT_SEND"
)
entries := []SessionEntry{
{ID: "user-1", Type: "user", Content: "complete the old task"},
@@ -373,7 +374,7 @@ func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {
events := AgentChat(
context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,
- "user-2", 1, editedTarget, "English", nil, EditorContext{}, nil, true,
+ "user-2", 1, editedTarget, stringPointer(editedBlockHTML), "English", nil, EditorContext{}, nil, true,
time.Second, 0, "", time.Second, time.Second,
)
for event := range events {
@@ -400,6 +401,9 @@ func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {
if runtime.ActiveTurn == nil {
t.Fatal("regenerate runtime turn was not persisted")
}
+ if runtime.ActiveTurn.UserBlockHTML == nil || *runtime.ActiveTurn.UserBlockHTML != editedBlockHTML {
+ t.Fatalf("regenerate runtime lost edited block HTML: %#v", runtime.ActiveTurn)
+ }
deltaJSON, err := json.Marshal(runtime.ActiveTurn.Delta)
if err != nil {
t.Fatal(err)
@@ -468,7 +472,7 @@ func TestAgentChatRetriesOverflowAfterProactiveCompaction(t *testing.T) {
events := AgentChat(
context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,
- "user-3", 1, "current task", "English", nil, EditorContext{}, nil, false,
+ "user-3", 1, "current task", nil, "English", nil, EditorContext{}, nil, false,
time.Second, 0, "", time.Second, time.Second,
)
doneSeen := false
diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.go
index b2283209fb..bd5c33891f 100644
--- a/kernel/agent/runtime.go
+++ b/kernel/agent/runtime.go
@@ -46,6 +46,7 @@ type agentRuntimeTurn struct {
UserEntryID string `json:"userEntryID"`
TargetUserEntryID string `json:"targetUserEntryID,omitempty"`
UserContent string `json:"userContent,omitempty"`
+ UserBlockHTML *string `json:"userBlockHTML,omitempty"`
UserReferences *[]Reference `json:"userReferences,omitempty"`
UserEditorContext *EditorContext `json:"userEditorContext,omitempty"`
BaseRevision int64 `json:"baseRevision"`
@@ -347,6 +348,13 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeT
if turn.Mode == "regenerate" && turn.UserContent != "" {
entry, _ := entries[anchor].(map[string]any)
entry["content"] = turn.UserContent
+ if turn.UserBlockHTML != nil {
+ if *turn.UserBlockHTML != "" {
+ entry["blockHTML"] = *turn.UserBlockHTML
+ } else {
+ delete(entry, "blockHTML")
+ }
+ }
if turn.UserReferences != nil {
if len(*turn.UserReferences) > 0 {
entry["references"] = *turn.UserReferences
diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.go
index 2d62c23210..9ad171fd8d 100644
--- a/kernel/agent/session_test.go
+++ b/kernel/agent/session_test.go
@@ -39,6 +39,10 @@ func marshalSession(t *testing.T, value any) []byte {
return data
}
+func stringPointer(value string) *string {
+ return &value
+}
+
func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
useTestDataDir(t)
base := map[string]any{
@@ -291,6 +295,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
useTestDataDir(t)
+ const editedBlockHTML = `<div data-node-id="edited">edited prompt</div>`
base := map[string]any{
"id": testSessionID,
"title": "base",
@@ -301,6 +306,7 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
"id": "user-1", "type": "user", "content": "original prompt",
"references": []any{map[string]any{"id": "block-1", "title": "First block"}},
"editorContext": map[string]any{"activeDocID": "old-doc"},
+ "blockHTML": `<div data-node-id="original">original prompt</div>`,
},
map[string]any{"id": "assistant-1", "type": "assistant", "content": "old answer"},
map[string]any{"id": "user-2", "type": "user", "content": "later prompt"},
@@ -325,6 +331,7 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
}},
}
emptyReferences := []Reference{}
+ turn.UserBlockHTML = stringPointer(editedBlockHTML)
turn.UserReferences = &emptyReferences
turn.UserEditorContext = &EditorContext{ActiveDocID: "new-doc"}
if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
@@ -347,6 +354,9 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
if _, ok := entries[0].(map[string]any)["references"]; ok {
t.Fatalf("references removed by the edit were restored: %#v", entries[0])
}
+ if blockHTML := entries[0].(map[string]any)["blockHTML"]; blockHTML != editedBlockHTML {
+ t.Fatalf("regenerated runtime lost edited block HTML: %#v", entries[0])
+ }
editorContext := entries[0].(map[string]any)["editorContext"].(*EditorContext)
if editorContext.ActiveDocID != "new-doc" {
t.Fatalf("regenerated editor context was not restored: %#v", entries[0])
@@ -360,6 +370,9 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
if len(committedEntries) != 2 || committedEntries[0].(map[string]any)["content"] != "edited prompt" {
t.Fatalf("committed regenerate turn lost edited content: %#v", committedEntries)
}
+ if blockHTML := committedEntries[0].(map[string]any)["blockHTML"]; blockHTML != editedBlockHTML {
+ t.Fatalf("committed regenerate turn lost edited block HTML: %#v", committedEntries[0])
+ }
committedEditorContext := committedEntries[0].(map[string]any)["editorContext"].(*EditorContext)
if committedEditorContext.ActiveDocID != "new-doc" {
t.Fatalf("committed regenerate turn lost editor context: %#v", committedEntries[0])
@@ -369,6 +382,9 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
t.Fatal(err)
}
persistedEntries := persisted["entries"].([]any)
+ if blockHTML := persistedEntries[0].(map[string]any)["blockHTML"]; blockHTML != editedBlockHTML {
+ t.Fatalf("persisted regenerate turn lost edited block HTML: %#v", persistedEntries[0])
+ }
persistedEditorContext := persistedEntries[0].(map[string]any)["editorContext"].(map[string]any)
if persistedEditorContext["activeDocID"] != "new-doc" {
t.Fatalf("persisted regenerate turn lost editor context: %#v", persistedEntries[0])
@@ -642,20 +658,25 @@ func TestApplyRuntimePreservesUIOrderAndReplacesAssistant(t *testing.T) {
}
func TestApplyRegenerateRuntimeReplacesUserContent(t *testing.T) {
+ const editedBlockHTML = `<div data-node-id="edited">edited prompt</div>`
session := map[string]any{
"entries": []any{
- map[string]any{"id": "user-1", "type": "user", "content": "original prompt"},
+ map[string]any{
+ "id": "user-1", "type": "user", "content": "original prompt",
+ "blockHTML": `<div data-node-id="original">original prompt</div>`,
+ },
map[string]any{"id": "assistant-1", "type": "assistant", "content": "old answer"},
map[string]any{"id": "user-2", "type": "user", "content": "later prompt"},
map[string]any{"id": "assistant-2", "type": "assistant", "content": "later answer"},
},
}
turn := &agentRuntimeTurn{
- TurnID: "20260715120007-abcdefg",
- Mode: "regenerate",
- UserEntryID: "user-1",
- UserContent: "edited prompt",
- UpdatedAt: 1,
+ TurnID: "20260715120007-abcdefg",
+ Mode: "regenerate",
+ UserEntryID: "user-1",
+ UserContent: "edited prompt",
+ UserBlockHTML: stringPointer(editedBlockHTML),
+ UpdatedAt: 1,
Delta: []AgentMessage{{
Role: "assistant",
Content: "new answer",
@@ -671,11 +692,66 @@ func TestApplyRegenerateRuntimeReplacesUserContent(t *testing.T) {
if content := entries[0].(map[string]any)["content"]; content != "edited prompt" {
t.Fatalf("edited user content was not restored: %v", content)
}
+ if blockHTML := entries[0].(map[string]any)["blockHTML"]; blockHTML != editedBlockHTML {
+ t.Fatalf("edited user block HTML was not restored: %v", blockHTML)
+ }
if content := entries[1].(map[string]any)["content"]; content != "new answer" {
t.Fatalf("regenerated assistant content was not restored: %v", content)
}
}
+func TestApplyRegenerateRuntimePreservesUneditedUserBlockHTML(t *testing.T) {
+ const originalBlockHTML = `<div data-node-id="original">original prompt</div>`
+ session := map[string]any{
+ "entries": []any{
+ map[string]any{
+ "id": "user-1", "type": "user", "content": "original prompt",
+ "blockHTML": originalBlockHTML,
+ },
+ },
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120010-abcdefg",
+ Mode: "regenerate",
+ UserEntryID: "user-1",
+ UserContent: "original prompt",
+ UpdatedAt: 1,
+ }
+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {
+ t.Fatal(err)
+ }
+ entry := session["entries"].([]any)[0].(map[string]any)
+ if blockHTML := entry["blockHTML"]; blockHTML != originalBlockHTML {
+ t.Fatalf("regenerate without an edit changed user block HTML: %#v", entry)
+ }
+}
+
+func TestApplyRegenerateRuntimeClearsEditedUserBlockHTML(t *testing.T) {
+ session := map[string]any{
+ "entries": []any{
+ map[string]any{
+ "id": "user-1", "type": "user", "content": "original prompt",
+ "blockHTML": `<div data-node-id="original">original prompt</div>`,
+ },
+ },
+ }
+ turn := &agentRuntimeTurn{
+ TurnID: "20260715120011-abcdefg",
+ Mode: "regenerate",
+ UserEntryID: "user-1",
+ UserContent: "edited prompt",
+ UserBlockHTML: stringPointer(""),
+ UpdatedAt: 1,
+ }
+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {
+ t.Fatal(err)
+ }
+ entry := session["entries"].([]any)[0].(map[string]any)
+ if _, ok := entry["blockHTML"]; ok {
+ t.Fatalf("empty edited block HTML was not cleared: %#v", entry)
+ }
+}
+
func TestApplyRuntimeDistinguishesPendingAndExecutingTools(t *testing.T) {
session := map[string]any{
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.go
index 2666ad9f50..ee26d6fc62 100644
--- a/kernel/agent/stream_timeout_test.go
+++ b/kernel/agent/stream_timeout_test.go
@@ -210,7 +210,7 @@ func TestAgentChatPartialStreamTimeoutSavesInterruptedWithoutRetry(t *testing.T)
}))
defer server.Close()
- events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1, "hello", "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
+ events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1, "hello", nil, "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
contentSeen := false
errorSeen := false
for event := range events {
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index ae0b8373a8..55fce93bb8 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -39,6 +39,7 @@ type agentChatReq struct {
UserEntryID string `json:"userEntryID"`
ContentRevision *int64 `json:"contentRevision"`
Message string `json:"message"`
+ BlockHTML *string `json:"blockHTML"`
Language string `json:"language"`
References []agent.Reference `json:"references"`
EditorContext agent.EditorContext `json:"editorContext"`
@@ -135,7 +136,7 @@ func agentChat(c *gin.Context) {
contentRevision = *req.ContentRevision
}
contextLimit := agent.ResolveModelContextLimit(selectedModel.Name, selectedModel.ContextLength)
- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
+ eventCh := agent.AgentChat(ctx, client, selectedModel.Name, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.BlockHTML, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
defer cancel()
streamClosed := false
defer func() {