Skip to content

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

:sparkles: Support editing and resending Agent prompts https://github.com/siyuan-note/siyuan/issues/18276

Daniel72e9755f1802
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 55dc0830f9..9560655393 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "تتضمن الرسائل اللاحقة استدعاءات أدوات تم تنفيذها. ستؤدي إعادة الإرسال إلى حذف المحادثة اللاحقة، لكنها لن تتراجع عن العمليات التي تم تنفيذها بالفعل. هل تريد المتابعة؟",
"boxDocEnabled": "تمكين مستندات دفتر الملاحظات ذات المستوى الأعلى",
"boxDocEnabledTip": "عند التمكين، يمكن أيضًا استخدام دفتر الملاحظات نفسه لتسجيل المحتوى",
"insertImage": "إدراج صورة",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index b0a03dafe1..9ef7a45e9d 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Spätere Nachrichten enthalten ausgeführte Werkzeugaufrufe. Durch erneutes Senden wird der nachfolgende Gesprächsverlauf gelöscht, bereits ausgeführte Vorgänge werden jedoch nicht rückgängig gemacht. Fortfahren?",
"boxDocEnabled": "Notebook-Dokumente auf oberster Ebene aktivieren",
"boxDocEnabledTip": "Wenn aktiviert, kann auch das Notizbuch selbst zum Erfassen von Inhalten verwendet werden",
"insertImage": "Bild einfügen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index e5a9caf542..14a6b0fff2 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Later messages include executed tool calls. Resending will delete the later conversation, but it will not undo operations that have already run. Continue?",
"boxDocEnabled": "Enable top-level notebook documents",
"boxDocEnabledTip": "When enabled, the notebook itself can also be used to record content",
"insertImage": "Insert image",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 85ddfdc2d2..e0e66ffaee 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Los mensajes posteriores incluyen llamadas a herramientas ya ejecutadas. Volver a enviar eliminará la conversación posterior, pero no deshará las operaciones que ya se hayan ejecutado. ¿Continuar?",
"boxDocEnabled": "Habilitar documentos de nivel superior del cuaderno",
"boxDocEnabledTip": "Al habilitarlo, el propio cuaderno también se puede utilizar para registrar contenido",
"insertImage": "Insertar imagen",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 8b572ddb58..4e8dda8873 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Les messages suivants comprennent des appels d’outils déjà exécutés. Le renvoi supprimera la suite de la conversation, mais n’annulera pas les opérations déjà exécutées. Continuer ?",
"boxDocEnabled": "Activer les documents de carnet de niveau supérieur",
"boxDocEnabledTip": "Lorsque cette option est activée, le carnet lui-même peut également servir à consigner du contenu",
"insertImage": "Insérer une image",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index db5c3fc98f..d5472aa148 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "ההודעות הבאות כוללות קריאות לכלים שכבר בוצעו. שליחה מחדש תמחק את המשך השיחה, אך לא תבטל פעולות שכבר בוצעו. להמשיך?",
"boxDocEnabled": "הפעלת מסמכי מחברת ברמה העליונה",
"boxDocEnabledTip": "כאשר האפשרות מופעלת, ניתן להשתמש גם במחברת עצמה לתיעוד תוכן",
"insertImage": "הוספת תמונה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 951b38170b..a4a7b37100 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "बाद के संदेशों में निष्पादित टूल कॉल शामिल हैं। दोबारा भेजने पर बाद की बातचीत हट जाएगी, लेकिन पहले से किए गए ऑपरेशन पूर्ववत नहीं होंगे। जारी रखें?",
"boxDocEnabled": "शीर्ष-स्तरीय नोटबुक दस्तावेज़ सक्षम करें",
"boxDocEnabledTip": "सक्षम होने पर नोटबुक का उपयोग भी सामग्री दर्ज करने के लिए किया जा सकता है",
"insertImage": "छवि डालें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index cb09e06a38..9a11009863 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Pesan berikutnya berisi pemanggilan alat yang telah dijalankan. Mengirim ulang akan menghapus percakapan setelahnya, tetapi tidak akan membatalkan operasi yang sudah dijalankan. Lanjutkan?",
"boxDocEnabled": "Aktifkan dokumen buku catatan tingkat teratas",
"boxDocEnabledTip": "Jika diaktifkan, buku catatan itu sendiri juga dapat digunakan untuk mencatat konten",
"insertImage": "Sisipkan gambar",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 98d9638887..ea204f1baa 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "I messaggi successivi includono chiamate a strumenti già eseguite. Il nuovo invio eliminerà la conversazione successiva, ma non annullerà le operazioni già eseguite. Continuare?",
"boxDocEnabled": "Abilita i documenti di primo livello del taccuino",
"boxDocEnabledTip": "Se abilitato, anche il taccuino stesso può essere usato per registrare contenuti",
"insertImage": "Inserisci immagine",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 88f9e06d48..262437d09e 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "後続のメッセージには実行済みのツール呼び出しが含まれています。再送信すると後続の会話は削除されますが、すでに実行された操作は元に戻りません。続行しますか?",
"boxDocEnabled": "最上位のノートブック文書を有効にする",
"boxDocEnabledTip": "有効にすると、ノートブック自体にも内容を記録できます",
"insertImage": "画像を挿入",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index bd2a4c16bd..392a06023e 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "이후 메시지에 이미 실행된 도구 호출이 포함되어 있습니다. 다시 보내면 이후 대화는 삭제되지만 이미 실행된 작업은 되돌려지지 않습니다. 계속하시겠습니까?",
"boxDocEnabled": "최상위 노트북 문서 활성화",
"boxDocEnabledTip": "활성화하면 노트북 자체에도 내용을 기록할 수 있습니다",
"insertImage": "이미지 삽입",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 6e14926d47..fa1de3cd2e 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Latere berichten bevatten uitgevoerde toolaanroepen. Opnieuw verzenden verwijdert het latere gesprek, maar maakt reeds uitgevoerde bewerkingen niet ongedaan. Doorgaan?",
"boxDocEnabled": "Notebookdocumenten op het hoogste niveau inschakelen",
"boxDocEnabledTip": "Indien ingeschakeld kan ook het notebook zelf worden gebruikt om inhoud vast te leggen",
"insertImage": "Afbeelding invoegen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 8843ed226f..1779c71977 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Późniejsze wiadomości zawierają wykonane wywołania narzędzi. Ponowne wysłanie usunie dalszą część rozmowy, ale nie cofnie już wykonanych operacji. Kontynuować?",
"boxDocEnabled": "Włącz dokumenty notatnika najwyższego poziomu",
"boxDocEnabledTip": "Po włączeniu sam notatnik może również służyć do zapisywania treści",
"insertImage": "Wstaw obraz",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index e56f272113..800fdbabfa 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "As mensagens posteriores incluem chamadas de ferramentas já executadas. Reenviar excluirá a conversa posterior, mas não desfará as operações já executadas. Continuar?",
"boxDocEnabled": "Habilitar documentos de nível superior do caderno",
"boxDocEnabledTip": "Quando ativado, o próprio caderno também pode ser usado para registrar conteúdo",
"insertImage": "Inserir imagem",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index a5dbb90f55..fa3a2e4ccb 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Последующие сообщения содержат уже выполненные вызовы инструментов. Повторная отправка удалит последующую переписку, но не отменит уже выполненные операции. Продолжить?",
"boxDocEnabled": "Включить документы блокнота верхнего уровня",
"boxDocEnabledTip": "Если включено, сам блокнот также можно использовать для записи содержимого",
"insertImage": "Вставить изображение",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 5d93c94785..7cdd88f27d 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Neskoršie správy obsahujú vykonané volania nástrojov. Opätovné odoslanie odstráni nasledujúcu konverzáciu, ale nezruší už vykonané operácie. Pokračovať?",
"boxDocEnabled": "Povoliť dokumenty zápisníka najvyššej úrovne",
"boxDocEnabledTip": "Po povolení možno na zaznamenávanie obsahu použiť aj samotný zápisník",
"insertImage": "Vložiť obrázok",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 68591b82f8..78bf0e3205 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "ข้อความหลังจากนี้มีการเรียกใช้เครื่องมือที่ดำเนินการแล้ว การส่งอีกครั้งจะลบการสนทนาหลังจากนี้ แต่จะไม่ย้อนกลับการดำเนินการที่เกิดขึ้นแล้ว ดำเนินการต่อหรือไม่?",
"boxDocEnabled": "เปิดใช้งานเอกสารสมุดบันทึกระดับบนสุด",
"boxDocEnabledTip": "เมื่อเปิดใช้งาน ตัวสมุดบันทึกเองก็สามารถใช้บันทึกเนื้อหาได้",
"insertImage": "แทรกรูปภาพ",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index b9eae0c0db..8aedd885b5 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Sonraki iletilerde yürütülmüş araç çağrıları bulunuyor. Yeniden gönderme sonraki konuşmayı silecek, ancak daha önce yürütülen işlemleri geri almayacaktır. Devam edilsin mi?",
"boxDocEnabled": "Üst düzey not defteri belgelerini etkinleştir",
"boxDocEnabledTip": "Etkinleştirildiğinde not defterinin kendisi de içerik kaydetmek için kullanılabilir",
"insertImage": "Görsel ekle",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 3be1651d62..f5d5d6dbac 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "Наступні повідомлення містять уже виконані виклики інструментів. Повторне надсилання видалить подальшу розмову, але не скасує вже виконані операції. Продовжити?",
"boxDocEnabled": "Увімкнути документи нотатника верхнього рівня",
"boxDocEnabledTip": "Якщо ввімкнено, сам нотатник також можна використовувати для запису вмісту",
"insertImage": "Вставити зображення",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 44540990e1..8a5b553eb8 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "后续消息包含已执行的工具调用。重新发送将删除后续对话,但不会撤销已经执行的操作。是否继续?",
"boxDocEnabled": "启用顶层笔记本文档",
"boxDocEnabledTip": "启用后笔记本本身也可用于记录内容",
"insertImage": "插入图片",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index b75bb2a2ef..c30b8f8183 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "agentEditHistoryWarning": "後續訊息包含已執行的工具呼叫。重新傳送將刪除後續對話,但不會撤銷已經執行的操作。是否繼續?",
"boxDocEnabled": "啟用頂層筆記本文檔",
"boxDocEnabledTip": "啟用後筆記本本身也可用於記錄內容",
"insertImage": "插入圖片",
diff --git a/app/src/assets/scss/business/_ai_agent.scss b/app/src/assets/scss/business/_ai_agent.scss
index 3b57583bab..b3c57d366c 100644
--- a/app/src/assets/scss/business/_ai_agent.scss
+++ b/app/src/assets/scss/business/_ai_agent.scss
@@ -206,6 +206,23 @@
box-sizing: border-box;
}
+.agent-chat__msg--editing .agent-chat__body {
+ width: min(100%, 560px);
+}
+
+.agent-chat__edit-textarea {
+ display: block;
+ min-height: 96px;
+ width: 100%;
+ resize: vertical;
+ line-height: 1.5;
+}
+
+.agent-chat__msg--editing .agent-chat__msg-actions {
+ margin-top: 8px;
+ opacity: 1;
+}
+
.agent-chat__msg-meta {
font-size: 13px;
color: var(--b3-theme-on-surface-light);
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 3f6570420a..5fe5a5a2da 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -20,6 +20,12 @@ import {confirmDialog} from "../../../dialog/confirmDialog";
import {showMessage} from "../../../dialog/message";
import * as dayjs from "dayjs";
import {sendNotification} from "../../../plugin/platformUtils";
+import {
+ findAgentUserEntryIndex,
+ filterAgentReferencesForContent,
+ hasAgentExecutedToolsAfter,
+ isAgentRegenerateStateCurrent
+} from "./AgentHistory";
import {
bindThinkingCardToggle,
createThinkingCardElement,
@@ -36,9 +42,10 @@ import {
const maxVisibleBlockIDs = 50;
type EntryBase = { id?: string };
+type AgentReference = { id: string; title: string };
type SessionEntry =
- | (EntryBase & { type: "user"; content: string; timestamp?: number })
+ | (EntryBase & { type: "user"; content: string; references?: AgentReference[]; timestamp?: number })
| (EntryBase & {
type: "thinking";
steps: Array<{
@@ -104,6 +111,8 @@ export class AgentChat extends Model {
private currentThinkingText = "";
private currentThinkingReasoning = "";
private currentThinkingReasoningContent = "";
+ private editingUserEntryID = "";
+ private pendingEditDraft: { entryID: string; content: string } | null = null;
// thinking step 只保留工具名列表(去重:arguments/result 仅在 assistant entry 存一份),
// 不再保存 text("已思考:Xs" 由 i18n 在渲染时从 duration 生成)。
private currentThinkingSteps: Array<{
@@ -467,6 +476,7 @@ export class AgentChat extends Model {
}
private showWelcome() {
+ this.editingUserEntryID = "";
const hasModel = this.modelOptions.length > 0;
this.messagesContainer.innerHTML = renderWelcomeHTML(hasModel);
if (!hasModel) {
@@ -810,12 +820,16 @@ export class AgentChat extends Model {
// 流结束,解除占位锁定并移除占位条。不重绘——完整内容由随后的 update 广播驱动。
this.mirrorLocked = false;
this.removeMirrorPlaceholder();
+ this.restorePendingEditDraft();
break;
case "update":
void this.reloadFromDisk().then(() => {
if (this.pendingRecoverySessionIDs.has(payload.sessionID)) {
void this.recoverInterruptedTurn(payload.sessionID, this.currentTurnID);
}
+ if (!this.mirrorLocked) {
+ this.restorePendingEditDraft();
+ }
});
break;
case "delete":
@@ -1019,6 +1033,7 @@ export class AgentChat extends Model {
// 当前会话被其他实例删除时,清空到欢迎页。不调 saveSession(会话已不存在于磁盘)。
private handleCurrentSessionDeleted() {
+ this.pendingEditDraft = null;
const deletedSessionID = this.sessionId;
this.removeMirrorPlaceholder();
this.entries = [];
@@ -1043,6 +1058,7 @@ export class AgentChat extends Model {
}
private async switchSession(id: string) {
+ this.pendingEditDraft = null;
const previousSessionID = this.sessionId;
const hadActiveTurn = this.isStreaming || !!this.currentTurnID;
if (hadActiveTurn) {
@@ -1255,6 +1271,7 @@ export class AgentChat extends Model {
}
private renderLoadedSession(session: AgentSession) {
+ this.editingUserEntryID = "";
for (let i = 0; i < session.entries.length; i++) {
const entry = session.entries[i];
const entryId = (entry as { id?: string }).id;
@@ -1374,6 +1391,7 @@ export class AgentChat extends Model {
}
private async createSession() {
+ this.pendingEditDraft = null;
const previousSessionID = this.sessionId;
const hadActiveTurn = this.isStreaming || !!this.currentTurnID;
if (hadActiveTurn) {
@@ -1469,9 +1487,7 @@ export class AgentChat extends Model {
const text = sendData.text;
const refs = sendData.references;
const editorContext = this.captureEditorContext();
- const pluginActions = listActions()
- .filter(a => a.name.startsWith("plugin__") && a.description)
- .map(a => ({name: a.name, description: a.description as string}));
+ const pluginActions = this.getPluginActions();
if (!text || this.isStreaming || this.modelOptions.length === 0) {
return;
}
@@ -1485,7 +1501,13 @@ export class AgentChat extends Model {
this.composer.clear();
const userEntryId = SessionStore.newSessionId();
- this.entries.push({id: userEntryId, type: "user", content: text, timestamp: Date.now()});
+ this.entries.push({
+ id: userEntryId,
+ type: "user",
+ content: text,
+ references: refs.length > 0 ? refs : undefined,
+ timestamp: Date.now(),
+ });
if (this.entries.length === 1) {
this.messagesContainer.innerHTML = "";
}
@@ -1550,10 +1572,23 @@ export class AgentChat extends Model {
this.requestStartTime = 0;
this.setStreaming(false);
await this.reloadFromDisk(true);
+ this.restorePendingEditDraft();
const L = window.siyuan.languages;
showMessage(L.agentChatBusy || "This session is busy in another instance", 3000);
}
+ private restorePendingEditDraft() {
+ const draft = this.pendingEditDraft;
+ if (!draft) {
+ return;
+ }
+ 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);
+ }
+ }
+
// Capture a read-only snapshot of the user's editor to inject into the system prompt.
// Strategy: scan ALL editors. Prefer one that (a) is visible and (b) has selected blocks;
// this directly targets "user selected blocks here" regardless of which window has focus.
@@ -1644,6 +1679,12 @@ export class AgentChat extends Model {
/// #endif
}
+ private getPluginActions() {
+ return listActions()
+ .filter(action => action.name.startsWith("plugin__") && action.description)
+ .map(action => ({name: action.name, description: action.description as string}));
+ }
+
private readEditorContext(editor: {
protyle: {
block?: { id?: string; rootID?: string };
@@ -1828,6 +1869,9 @@ export class AgentChat extends Model {
console.error("reload agent session after stream failure failed:", reloadError);
}
if (this.sessionId === sessionID) {
+ if (!turnID) {
+ this.restorePendingEditDraft();
+ }
this.appendError(err.message);
// 网络断流不等于服务端 turn 已终止,不能提交并清除 runtime。待后端释放运行实例后
// 再合并 runtime,避免重复执行结果未知的外部调用。turn 事件也可能在断流前尚未来得及送达。
@@ -1871,6 +1915,9 @@ export class AgentChat extends Model {
return;
}
this.setStreaming(false);
+ if (isConfigError && restoreSession) {
+ this.restorePendingEditDraft();
+ }
}
// 回滚刚追加的 user entry 与 DOM 元素(用于"未配置"错误时避免留下空对话)。
@@ -1904,7 +1951,7 @@ export class AgentChat extends Model {
this.flushThinkingStep();
}
- private appendUserMessage(text: string, timestamp?: number, entryId?: string) {
+ private createUserMessage(text: string, timestamp?: number, entryId?: string): HTMLElement {
const el = document.createElement("div");
el.className = "agent-chat__msg agent-chat__msg--user";
if (entryId) {
@@ -1915,10 +1962,11 @@ export class AgentChat extends Model {
if (timestamp) {
html += '<span class="agent-chat__msg-meta agent-chat__msg-time">' + this.formatMessageTime(timestamp) + "</span>";
}
- html += '<span class="block__icon block__icon--show ariaLabel" data-position="north" aria-label="' + window.siyuan.languages.copy + '"><svg><use xlink:href="#iconCopy"></use></svg></span>' +
+ html += '<span class="block__icon block__icon--show ariaLabel agent-chat__user-copy" data-position="north" aria-label="' + window.siyuan.languages.copy + '"><svg><use xlink:href="#iconCopy"></use></svg></span>' +
+ '<span class="block__icon block__icon--show ariaLabel agent-chat__user-edit" data-position="north" aria-label="' + window.siyuan.languages.edit + '"><svg><use xlink:href="#iconEdit"></use></svg></span>' +
"</div>";
el.innerHTML = html;
- el.querySelector(".block__icon")?.addEventListener("click", (e) => {
+ el.querySelector(".agent-chat__user-copy")?.addEventListener("click", (e) => {
e.stopPropagation();
navigator.clipboard.writeText(text).then(() => {
showMessage(window.siyuan.languages.copied, 2000);
@@ -1926,10 +1974,91 @@ export class AgentChat extends Model {
showMessage(window.siyuan.languages.copied, 2000);
});
});
+ const edit = (force = false) => {
+ const selection = window.getSelection();
+ const selectingMessageText = selection && !selection.isCollapsed && el.contains(selection.anchorNode);
+ if (!entryId || this.isStreaming || this.mirrorLocked || (!force && selectingMessageText)) {
+ return;
+ }
+ this.beginEditUserMessage(entryId, el);
+ };
+ el.querySelector(".agent-chat__user-edit")?.addEventListener("click", (e) => {
+ e.stopPropagation();
+ edit(true);
+ });
+ el.querySelector(".agent-chat__body")?.addEventListener("click", () => edit());
+ return el;
+ }
+
+ private appendUserMessage(text: string, timestamp?: number, entryId?: string) {
+ const el = this.createUserMessage(text, timestamp, entryId);
this.messagesContainer.appendChild(el);
this.scrollToBottom(true);
}
+ private beginEditUserMessage(entryID: string, el: HTMLElement, initialContent?: string) {
+ if (this.editingUserEntryID || this.isStreaming || this.mirrorLocked) {
+ return;
+ }
+ const entry = this.entries.find((item): item is EntryBase & {
+ type: "user";
+ content: string;
+ timestamp?: number
+ } => item.type === "user" && item.id === entryID);
+ if (!entry) {
+ return;
+ }
+ this.editingUserEntryID = entryID;
+ 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;
+ body.innerHTML = "";
+ body.appendChild(textarea);
+ actions.innerHTML = "";
+
+ const cancel = document.createElement("button");
+ cancel.className = "b3-button b3-button--cancel";
+ cancel.textContent = window.siyuan.languages.cancel;
+ const submit = document.createElement("button");
+ submit.className = "b3-button b3-button--text";
+ submit.textContent = window.siyuan.languages.confirm;
+ actions.append(cancel, submit);
+
+ const restore = () => {
+ this.editingUserEntryID = "";
+ if (this.pendingEditDraft?.entryID === entryID) {
+ this.pendingEditDraft = null;
+ }
+ el.replaceWith(this.createUserMessage(entry.content, entry.timestamp, entry.id));
+ };
+ cancel.addEventListener("click", restore);
+ submit.addEventListener("click", async () => {
+ const content = textarea.value.trim();
+ if (!content) {
+ textarea.focus();
+ return;
+ }
+ await this.regenerateResponse(entryID, content);
+ });
+ 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();
+ }
+ });
+ textarea.focus();
+ textarea.setSelectionRange(textarea.value.length, textarea.value.length);
+ }
+
private createAIMessagePlaceholder(): HTMLElement {
this.currentContent = "";
this.currentAssistantEntryId = SessionStore.newSessionId();
@@ -2265,31 +2394,97 @@ export class AgentChat extends Model {
regenBtn.innerHTML = '<svg><use xlink:href="#iconRefresh"></use></svg>';
regenBtn.addEventListener("click", (e: Event) => {
e.stopPropagation();
- this.regenerateResponse();
+ this.regenerateResponse(this.findUserEntryIDBeforeElement(el));
});
actions.appendChild(regenBtn);
el.appendChild(actions);
}
- private async regenerateResponse() {
- if (this.isStreaming || this.modelOptions.length === 0) {
+ private findUserEntryIDBeforeElement(el: HTMLElement): string | undefined {
+ let current: Element | null = el;
+ while (current) {
+ if (current.classList.contains("agent-chat__msg--user")) {
+ return (current as HTMLElement).dataset.messageId;
+ }
+ current = current.previousElementSibling;
+ }
+ return undefined;
+ }
+
+ private async confirmHistoryTruncation(entryIndex: number): Promise<boolean> {
+ if (!hasAgentExecutedToolsAfter(this.entries, entryIndex)) {
+ return true;
+ }
+ return new Promise((resolve) => {
+ confirmDialog(window.siyuan.languages.confirm,
+ window.siyuan.languages.agentEditHistoryWarning,
+ () => resolve(true), () => resolve(false));
+ });
+ }
+
+ private async regenerateResponse(userEntryID?: string, editedContent?: string) {
+ if (this.isStreaming || this.mirrorLocked || 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();
+ const requestSessionID = this.sessionId;
+ const requestRevision = SessionStore.getRevision(requestSessionID);
+ let targetIndex = findAgentUserEntryIndex(this.entries, userEntryID);
+ if (targetIndex < 0) {
+ return;
}
- // Remove all AI/tool/thinking/error DOM after last user message
- const all = this.messagesContainer.querySelectorAll(".agent-chat__msg");
- for (let i = all.length - 1; i >= 0; i--) {
- if (all[i].classList.contains("agent-chat__msg--user")) {
- break;
+ if (editedContent !== undefined && userEntryID) {
+ this.pendingEditDraft = {entryID: userEntryID, content: editedContent};
+ }
+ if (!await this.confirmHistoryTruncation(targetIndex)) {
+ this.restorePendingEditDraft();
+ return;
+ }
+ if (!isAgentRegenerateStateCurrent(requestSessionID, this.sessionId, requestRevision,
+ SessionStore.getRevision(requestSessionID), this.isStreaming, this.mirrorLocked)) {
+ if (this.sessionId === requestSessionID) {
+ this.restorePendingEditDraft();
+ } else {
+ this.pendingEditDraft = null;
+ }
+ return;
+ }
+ targetIndex = findAgentUserEntryIndex(this.entries, userEntryID);
+ if (targetIndex < 0) {
+ this.restorePendingEditDraft();
+ return;
+ }
+ const targetEntry = this.entries[targetIndex];
+ if (targetEntry.type !== "user") {
+ return;
+ }
+ this.editingUserEntryID = "";
+ this.pendingEditDraft = editedContent === undefined ? null : {
+ entryID: targetEntry.id || "",
+ content: editedContent,
+ };
+ if (editedContent !== undefined) {
+ targetEntry.content = editedContent;
+ const references = filterAgentReferencesForContent(targetEntry.references || [], editedContent);
+ targetEntry.references = references.length > 0 ? references : undefined;
+ }
+ this.entries.splice(targetIndex + 1);
+
+ const targetEl = this.messagesContainer.querySelector(
+ '.agent-chat__msg--user[data-message-id="' + targetEntry.id + '"]') as HTMLElement | null;
+ if (targetEl) {
+ let sibling = targetEl.nextElementSibling;
+ while (sibling) {
+ const next = sibling.nextElementSibling;
+ sibling.remove();
+ sibling = next;
+ }
+ if (editedContent !== undefined) {
+ targetEl.replaceWith(this.createUserMessage(targetEntry.content, targetEntry.timestamp, targetEntry.id));
}
- all[i].remove();
}
this.currentAIElement = null;
this.observeStickTarget(null);
@@ -2308,19 +2503,20 @@ export class AgentChat extends Model {
// Re-submit
this.setStreaming(true);
- this.mirrorLocked = false;
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 : "";
+ const lastUserEntry = targetEntry;
+ const lastUserText = lastUserEntry.content;
+ const editorContext = this.captureEditorContext();
+ const pluginActions = this.getPluginActions();
this.abortController = new AbortController();
const requestSessionId = this.sessionId;
await fetchAgentSSE(
lastUserText,
window.siyuan.config.appearance.lang,
- [],
+ lastUserEntry.references || [],
(event: ISSEResult) => {
if (this.sessionId !== requestSessionId) {
return;
@@ -2342,8 +2538,8 @@ export class AgentChat extends Model {
this.getSelectedModel(),
this.selectedReasoningEffort,
true,
- undefined,
- undefined,
+ editorContext,
+ pluginActions,
lastUserEntry.id,
SessionStore.getRevision(this.sessionId),
);
@@ -2445,6 +2641,7 @@ export class AgentChat extends Model {
this.updateTokenDisplay();
const sessionID = this.sessionId;
const canonicalSession = await this.saveSession(this.currentTurnID);
+ this.pendingEditDraft = null;
if (this.sessionId === sessionID) {
// 提交时后端会用 runtime 重建本轮 assistant/tool 结果。直接采用提交响应中的权威会话,
// 避免下一轮普通保存又用前端流式快照覆盖,也避免额外 GET 的失败/乱序窗口。
diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.ts
new file mode 100644
index 0000000000..1467afe451
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentHistory.test.ts
@@ -0,0 +1,55 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ findAgentUserEntryIndex,
+ filterAgentReferencesForContent,
+ hasAgentExecutedToolsAfter,
+ isAgentRegenerateStateCurrent
+} from "./AgentHistory";
+
+describe("AgentHistory", () => {
+ const entries = [
+ {id: "user-1", type: "user"},
+ {id: "assistant-1", type: "assistant"},
+ {id: "user-2", type: "user"},
+ {id: "assistant-2", type: "assistant"},
+ ];
+
+ it("finds the requested user entry or the latest user entry", () => {
+ assert.equal(findAgentUserEntryIndex(entries, "user-1"), 0);
+ assert.equal(findAgentUserEntryIndex(entries, "user-2"), 2);
+ assert.equal(findAgentUserEntryIndex(entries), 2);
+ assert.equal(findAgentUserEntryIndex(entries, "missing"), -1);
+ });
+
+ it("detects executed tools after the selected user entry", () => {
+ assert.equal(hasAgentExecutedToolsAfter([
+ {id: "user-1", type: "user"},
+ {id: "assistant-1", type: "assistant", toolCalls: [{result: "done"}]},
+ ], 0), true);
+ assert.equal(hasAgentExecutedToolsAfter([
+ {id: "user-1", type: "user"},
+ {id: "confirm-1", type: "confirm", status: "rejected"},
+ ], 0), false);
+ assert.equal(hasAgentExecutedToolsAfter([
+ {id: "user-1", type: "user"},
+ {id: "snapshot-1", type: "snapshot"},
+ ], 0), true);
+ });
+
+ it("rejects regenerate state changed while confirmation is open", () => {
+ assert.equal(isAgentRegenerateStateCurrent("session-1", "session-1", 2, 2, false, false), true);
+ assert.equal(isAgentRegenerateStateCurrent("session-1", "session-2", 2, 2, false, false), false);
+ assert.equal(isAgentRegenerateStateCurrent("session-1", "session-1", 2, 3, false, false), false);
+ assert.equal(isAgentRegenerateStateCurrent("session-1", "session-1", 2, 2, true, false), false);
+ 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]]);
+ });
+});
diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.ts
new file mode 100644
index 0000000000..6427eb859e
--- /dev/null
+++ b/app/src/layout/dock/agent/AgentHistory.ts
@@ -0,0 +1,41 @@
+export type AgentHistoryEntry = {
+ id?: string;
+ type: string;
+ status?: string;
+ toolCalls?: Array<{ result?: string; state?: string }>;
+};
+
+export type AgentHistoryReference = { id: string; title: string };
+
+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)) {
+ return i;
+ }
+ }
+ return -1;
+};
+
+export const hasAgentExecutedToolsAfter = (entries: AgentHistoryEntry[], entryIndex: number): boolean => {
+ return entries.slice(entryIndex + 1).some((entry) => {
+ if (entry.type === "snapshot") {
+ return true;
+ }
+ if (entry.type === "confirm") {
+ return entry.status === "approved" || entry.status === "always";
+ }
+ return entry.type === "assistant" && !!entry.toolCalls?.some((call) =>
+ call.state === "executing" || call.state === "completed" || call.result !== undefined);
+ });
+};
+
+export const isAgentRegenerateStateCurrent = (requestSessionID: string, currentSessionID: string,
+ requestRevision: number, currentRevision: number,
+ isStreaming: boolean, mirrorLocked: boolean): boolean => {
+ 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/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.ts
index 46e8a0c9ee..c6d5da4265 100644
--- a/app/src/layout/dock/agent/SessionStore.ts
+++ b/app/src/layout/dock/agent/SessionStore.ts
@@ -53,6 +53,7 @@ export interface AgentSession {
id?: string;
type: "user" | "thinking" | "assistant" | "confirm" | "question" | "snapshot" | "rollback";
content?: string;
+ references?: Array<{id: string; title: string}>;
// thinking step:新格式只含 reasoning/reasoningContent/toolNames/content;
// text/toolCalls 仅为读取老数据而保留为可选(渲染时归一化)。
steps?: Array<{
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 06e90049f9..65ebcfe1bd 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -359,6 +359,7 @@ type SessionEntry struct {
ID string `json:"id,omitempty"`
Type string `json:"type"` // user|thinking|assistant|confirm|snapshot|rollback
Content string `json:"content,omitempty"`
+ References []Reference `json:"references,omitempty"`
Steps []SessionEntryStep `json:"steps,omitempty"` // 仅 thinking
ToolCalls []AgentToolCall `json:"toolCalls,omitempty"` // 仅 assistant
Duration float64 `json:"duration,omitempty"` // 秒(thinking/assistant 均可能带)
@@ -425,6 +426,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
default:
}
+ rawUserMessage := userMessage
// 变量(非敏感)在用户消息注入对话时解析,让 LLM 看到实际值;密钥不进上下文。
// 在此统一解析一次,后续 checkpoint 与消息重建均使用解析后的值,保证全链路一致。
userMessage = kernelModel.Conf.Variables.Resolve(userMessage)
@@ -507,6 +509,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
if regenerate {
turn.Mode = "regenerate"
turn.TargetUserEntryID = userEntryID
+ turn.UserContent = rawUserMessage
+ userReferences := append([]Reference(nil), references...)
+ turn.UserReferences = &userReferences
}
select {
case <-ctx.Done():
diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.go
index d3578d7c96..54bcd7032f 100644
--- a/kernel/agent/runtime.go
+++ b/kernel/agent/runtime.go
@@ -45,6 +45,8 @@ type agentRuntimeTurn struct {
Mode string `json:"mode"`
UserEntryID string `json:"userEntryID"`
TargetUserEntryID string `json:"targetUserEntryID,omitempty"`
+ UserContent string `json:"userContent,omitempty"`
+ UserReferences *[]Reference `json:"userReferences,omitempty"`
BaseRevision int64 `json:"baseRevision"`
State string `json:"state"`
Delta []AgentMessage `json:"delta,omitempty"`
@@ -320,6 +322,17 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeT
if anchor < 0 {
return fmt.Errorf("agent runtime user entry not found")
}
+ if turn.Mode == "regenerate" && turn.UserContent != "" {
+ entry, _ := entries[anchor].(map[string]any)
+ entry["content"] = turn.UserContent
+ if turn.UserReferences != nil {
+ if len(*turn.UserReferences) > 0 {
+ entry["references"] = *turn.UserReferences
+ } else {
+ delete(entry, "references")
+ }
+ }
+ }
// 当前 turn 的 assistant 内容以 runtime 为权威;前端只补充 thinking/confirm/question 等 UI 条目。
// 用权威 assistant 逐个替换前端占位可尽量保留 UI 条目的相对位置;缺少占位时再追加到末尾。
diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.go
index 9fd46a0382..fbb4186a5d 100644
--- a/kernel/agent/session_test.go
+++ b/kernel/agent/session_test.go
@@ -289,6 +289,73 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
}
}
+func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(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": "original prompt",
+ "references": []any{map[string]any{"id": "block-1", "title": "First block"}},
+ },
+ 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"},
+ },
+ }
+ 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: "20260715120008-abcdefg",
+ Mode: "regenerate",
+ UserEntryID: "user-1",
+ UserContent: "edited prompt",
+ BaseRevision: 1,
+ State: "running",
+ UpdatedAt: 2,
+ Delta: []AgentMessage{{
+ Role: "assistant",
+ Content: "new answer",
+ }},
+ }
+ emptyReferences := []Reference{}
+ turn.UserReferences = &emptyReferences
+ if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {
+ t.Fatal(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)
+ if len(entries) != 2 || entries[0].(map[string]any)["content"] != "edited prompt" ||
+ entries[1].(map[string]any)["content"] != "new answer" {
+ t.Fatalf("regenerated runtime was not recovered consistently: %#v", entries)
+ }
+ if _, ok := entries[0].(map[string]any)["references"]; ok {
+ t.Fatalf("references removed by the edit were restored: %#v", entries[0])
+ }
+ recovered["expectedRevision"] = int64(1)
+ revision, canonical, err := SaveSessionState(marshalSession(t, recovered))
+ if err != nil || revision != 2 {
+ t.Fatalf("commit recovered regenerate turn failed: revision=%d, err=%v", revision, err)
+ }
+ committedEntries := canonical["entries"].([]any)
+ if len(committedEntries) != 2 || committedEntries[0].(map[string]any)["content"] != "edited prompt" {
+ t.Fatalf("committed regenerate turn lost edited content: %#v", committedEntries)
+ }
+}
+
func TestRejectedNewSessionDoesNotCreateDirectory(t *testing.T) {
useTestDataDir(t)
const sessionID = "20260715120009-abcdefg"
@@ -555,6 +622,41 @@ func TestApplyRuntimePreservesUIOrderAndReplacesAssistant(t *testing.T) {
}
}
+func TestApplyRegenerateRuntimeReplacesUserContent(t *testing.T) {
+ session := map[string]any{
+ "entries": []any{
+ map[string]any{"id": "user-1", "type": "user", "content": "original prompt"},
+ 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,
+ Delta: []AgentMessage{{
+ Role: "assistant",
+ Content: "new answer",
+ }},
+ }
+ if err := applyRuntimeTurnToSessionLocked(session, turn); err != nil {
+ t.Fatal(err)
+ }
+ entries := session["entries"].([]any)
+ if len(entries) != 2 {
+ t.Fatalf("regenerated history was not truncated: %#v", entries)
+ }
+ if content := entries[0].(map[string]any)["content"]; content != "edited prompt" {
+ t.Fatalf("edited user content was not restored: %v", content)
+ }
+ if content := entries[1].(map[string]any)["content"]; content != "new answer" {
+ t.Fatalf("regenerated assistant content was not restored: %v", content)
+ }
+}
+
func TestApplyRuntimeDistinguishesPendingAndExecutingTools(t *testing.T) {
session := map[string]any{
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},