Skip to content

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

:bug: Preserve AI reading position and copy complete replies https://github.com/siyuan-note/siyuan/issues/19701

Daniel5bbe942d4061
diff --git a/app/src/ai/editor.ts b/app/src/ai/editor.ts
index 836641ee3d..2b7c2778bd 100644
--- a/app/src/ai/editor.ts
+++ b/app/src/ai/editor.ts
@@ -18,7 +18,7 @@ import {confirmDialog} from "../dialog/confirmDialog";
import {escapeAriaLabel, escapeHtml} from "../util/escape";
import {isMobile} from "../util/functions";
import {Constants} from "../constants";
-import {bindThinkingCardToggle} from "./thinkingCard";
+import {bindThinkingCardToggle, updateThinkingBody} from "./thinkingCard";
import {BLOCK_SELECTION_MODE_CLASS} from "../protyle/wysiwyg/blockSelection";
import {normalizeHTMLAssetIFrameBlockDOM} from "../asset/html";
@@ -373,10 +373,11 @@ const renderTaskPreview = (task: IAIEditorTask, rich = false) => {
};
const renderTaskReasoning = (task: IAIEditorTask) => {
- task.thinkingReasoningElement.textContent = task.reasoningContent;
+ updateThinkingBody(task.thinkingBody, () => {
+ task.thinkingReasoningElement.textContent = task.reasoningContent;
+ });
task.thinkingLatestElement.textContent = task.reasoningContent.replace(/\s+/g, " ").trim();
task.thinkingLatestElement.scrollLeft = task.thinkingLatestElement.scrollWidth;
- task.thinkingBody.scrollTop = task.thinkingBody.scrollHeight;
};
const updateTaskThinkingText = (task: IAIEditorTask) => {
diff --git a/app/src/ai/thinkingCard.test.ts b/app/src/ai/thinkingCard.test.ts
index 8bf3b78009..daeef49fbd 100644
--- a/app/src/ai/thinkingCard.test.ts
+++ b/app/src/ai/thinkingCard.test.ts
@@ -1,6 +1,6 @@
import * as assert from "node:assert/strict";
-import {describe, it} from "node:test";
-import {bindThinkingCardToggle} from "./thinkingCard";
+import {describe, it, test} from "node:test";
+import {bindThinkingCardToggle, updateThinkingBody} from "./thinkingCard";
class FakeClassList {
private readonly values = new Set<string>();
@@ -116,3 +116,27 @@ describe("thinking card toggle", () => {
assert.equal(card.latest.classList.contains("fn__none"), true);
});
});
+
+test("streaming reasoning follows the bottom and preserves a user's reading position", () => {
+ const body = {clientHeight: 200, scrollHeight: 600, scrollTop: 400} as HTMLElement;
+ const append = () => Object.assign(body, {scrollHeight: body.scrollHeight + 100});
+ updateThinkingBody(body, append);
+ assert.equal(body.scrollTop, 700);
+
+ body.scrollTop = 100;
+ updateThinkingBody(body, append);
+ updateThinkingBody(body, append);
+ assert.equal(body.scrollTop, 100);
+
+ body.scrollTop = body.scrollHeight - body.clientHeight;
+ updateThinkingBody(body, append);
+ assert.equal(body.scrollTop, body.scrollHeight);
+});
+
+test("short and collapsed reasoning can continue following new content", () => {
+ for (const clientHeight of [0, 200]) {
+ const body = {clientHeight, scrollHeight: 100, scrollTop: 0} as HTMLElement;
+ updateThinkingBody(body, () => Object.assign(body, {scrollHeight: 300}));
+ assert.equal(body.scrollTop, 300);
+ }
+});
diff --git a/app/src/ai/thinkingCard.ts b/app/src/ai/thinkingCard.ts
index a8d55d9c58..af7bb969ba 100644
--- a/app/src/ai/thinkingCard.ts
+++ b/app/src/ai/thinkingCard.ts
@@ -1,3 +1,11 @@
+export const updateThinkingBody = (body: HTMLElement, update: () => void): void => {
+ const followBottom = body.clientHeight === 0 || body.scrollHeight - body.scrollTop - body.clientHeight <= 10;
+ update();
+ if (followBottom) {
+ body.scrollTop = body.scrollHeight;
+ }
+};
+
export const bindThinkingCardToggle = (el: HTMLElement, onLayoutChange?: () => void): void => {
const header = el.querySelector(".agent-chat__thinking-header") as HTMLElement;
const body = el.querySelector(".agent-chat__thinking-body") as HTMLElement;
diff --git a/app/src/assets/scss/business/_ai_agent.scss b/app/src/assets/scss/business/_ai_agent.scss
index 29b90c0ec0..52b84f0f23 100644
--- a/app/src/assets/scss/business/_ai_agent.scss
+++ b/app/src/assets/scss/business/_ai_agent.scss
@@ -517,6 +517,7 @@
.agent-chat__thinking-body--expanded {
max-height: 2000px;
+ overflow-y: auto;
padding: 8px 0;
border-top-color: var(--b3-border-color);
}
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.ts
index 7a43af2029..942288c90e 100644
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@ -24,6 +24,7 @@ import {
findAgentUserEntryIndex,
getAgentThinkingDisplaySeconds,
getAgentThinkingToolGroups,
+ getAgentTurnContent,
hasAgentExecutedToolsAfter,
hasAgentModelSpecificContext,
hasAgentThinkingStepDetails,
@@ -41,7 +42,7 @@ import {
renderToolsLineHTML,
renderWelcomeHTML
} from "./AgentMessageRenderer";
-import {bindThinkingCardToggle} from "../../../ai/thinkingCard";
+import {bindThinkingCardToggle, updateThinkingBody} from "../../../ai/thinkingCard";
import {getAgentReasoningEffort, getAgentReasoningEffortOptions, setAgentReasoningEffort} from "./AgentReasoning";
import {mountGroupedModelPicker, type IGroupedModelPicker} from "../../../config/tabs/ai/aiProviderUi";
import {AI_CONFIG_CHANGED_EVENT} from "../../../config/tabs/ai/aiRuntime";
@@ -453,6 +454,13 @@ export class AgentChat extends Model {
this.initPermissionMenu();
this.initReasoningEffortMenu();
this.scrollBottomBtn = panel.querySelector(".agent-chat__scroll-bottom") as HTMLElement;
+ this.messagesContainer.addEventListener("wheel", (event: WheelEvent) => {
+ if (event.deltaY < 0) {
+ this.programmaticScrollGeneration++;
+ this.programmaticScroll = false;
+ this.userScrolledUp = true;
+ }
+ }, {passive: true});
this.messagesContainer.addEventListener("scroll", () => {
const {scrollTop, scrollHeight, clientHeight} = this.messagesContainer;
// 仅在面板有效展开时记录滚动位置:dock 折叠过渡期间容器尺寸归零、浏览器把 scrollTop
@@ -3161,16 +3169,17 @@ export class AgentChat extends Model {
}
this.renderedToolNames[name] = true;
- const lastElement = body.lastElementChild as HTMLElement;
- if (lastElement?.classList.contains("agent-chat__thinking-tools-line")) {
- const toolElement = document.createElement("span");
- toolElement.className = "agent-chat__thinking-tool agent-chat__thinking-tool--running";
- toolElement.textContent = name;
- lastElement.appendChild(toolElement);
- } else {
- body.insertAdjacentHTML("beforeend", renderToolsLineHTML([{name, running: true}]));
- }
- body.scrollTop = body.scrollHeight;
+ updateThinkingBody(body, () => {
+ const lastElement = body.lastElementChild as HTMLElement;
+ if (lastElement?.classList.contains("agent-chat__thinking-tools-line")) {
+ const toolElement = document.createElement("span");
+ toolElement.className = "agent-chat__thinking-tool agent-chat__thinking-tool--running";
+ toolElement.textContent = name;
+ lastElement.appendChild(toolElement);
+ } else {
+ body.insertAdjacentHTML("beforeend", renderToolsLineHTML([{name, running: true}]));
+ }
+ });
this.scrollToBottom();
}
@@ -3215,7 +3224,7 @@ export class AgentChat extends Model {
const el = this.createTodoElement(result, SessionStore.newSessionId());
this.insertBeforeAI(el);
- this.scrollToBottom(true);
+ this.scrollToBottom();
this.hasInterveningCard = true;
}
@@ -3429,7 +3438,7 @@ export class AgentChat extends Model {
this.pendingReasoningUpdate = false;
cancelAnimationFrame(this.reasoningRafId);
this.reasoningRafId = 0;
- const thinking = this.pendingReasoningElement;
+ const thinking = this.pendingReasoningElement as HTMLElement | null;
this.pendingReasoningElement = null;
if (!thinking) {
return;
@@ -3437,17 +3446,14 @@ export class AgentChat extends Model {
const allReasoning = thinking.querySelectorAll(".agent-chat__thinking-reasoning-text");
const reasoningEl = allReasoning[allReasoning.length - 1] as HTMLElement;
if (reasoningEl) {
- reasoningEl.textContent = this.currentThinkingReasoningContent;
+ updateThinkingBody(thinking, () => {
+ reasoningEl.textContent = this.currentThinkingReasoningContent;
+ });
const latestElement = thinking.parentElement?.querySelector(".agent-chat__thinking-latest") as HTMLElement | null;
if (latestElement) {
latestElement.textContent = this.currentThinkingReasoningContent.replace(/\s+/g, " ").trim();
latestElement.scrollLeft = latestElement.scrollWidth;
}
- // 预览态固定高度,滚到底部让最新 reasoning 内容可见。
- const body = reasoningEl.closest(".agent-chat__thinking-body") as HTMLElement | null;
- if (body) {
- body.scrollTop = body.scrollHeight;
- }
}
}
@@ -3472,7 +3478,9 @@ export class AgentChat extends Model {
copyBtn.innerHTML = '<svg><use xlink:href="#iconCopy"></use></svg>';
copyBtn.addEventListener("click", (e: Event) => {
e.stopPropagation();
- void copyAgentText(content);
+ const userEntryID = this.findUserEntryIDBeforeElement(el);
+ const turnContent = userEntryID && getAgentTurnContent(buildAgentPresentationEntries(this.entries), userEntryID);
+ void copyAgentText(turnContent || content);
});
actions.appendChild(copyBtn);
@@ -3654,7 +3662,7 @@ export class AgentChat extends Model {
if (showActions) {
this.addCopyButton(this.currentAIElement, undefined, ts);
}
- this.scrollToBottom(!this.streamingMarkdownEnabled);
+ this.scrollToBottom();
}
}
@@ -3692,7 +3700,7 @@ export class AgentChat extends Model {
if (activeThinkCard?.isConnected) {
this.scrollToThinkingCardBelow(activeThinkCard);
} else {
- this.scrollToBottom(true);
+ this.scrollToBottom();
}
} else if (this.currentAIElement) {
// 场景二:普通流式元素,一次性完整渲染并补齐增强功能。
@@ -3865,7 +3873,7 @@ export class AgentChat extends Model {
}
this.currentAIElement = null;
this.renderError(message);
- this.scrollToBottom(true);
+ this.scrollToBottom();
this.flushThinkingStep();
}
@@ -3886,7 +3894,7 @@ export class AgentChat extends Model {
el.className = "agent-chat__msg agent-chat__msg--retry";
el.innerHTML = renderRetryCardHTML(attempt, maxRetries);
this.insertBeforeAI(el);
- this.scrollToBottom(true);
+ this.scrollToBottom();
this.hasInterveningCard = true;
}
@@ -3918,7 +3926,7 @@ export class AgentChat extends Model {
});
// 快照在工具执行前产生,应显示在触发写操作的思考和确认内容之后。
this.insertBeforeAI(el);
- this.scrollToBottom(true);
+ this.scrollToBottom();
this.hasInterveningCard = true;
}
@@ -4127,7 +4135,7 @@ export class AgentChat extends Model {
});
}
this.insertBeforeAI(el);
- this.scrollToBottom(true);
+ this.scrollToBottom();
this.hasInterveningCard = true;
if (notify) {
if (this.host.notify) {
@@ -4344,7 +4352,7 @@ export class AgentChat extends Model {
}
this.insertBeforeAI(el);
- this.scrollToBottom(true);
+ this.scrollToBottom();
this.hasInterveningCard = true;
}
@@ -4862,7 +4870,7 @@ export class AgentChat extends Model {
// 其下方留出空间承载即将/已开始流式的正文。delay 用于等待卡片折叠的 max-height 过渡(约 0.2s)完成。
private scrollToThinkingCardBelow(card: HTMLElement, delay = 220) {
const align = () => {
- if (!card.isConnected) {
+ if (!card.isConnected || this.userScrolledUp) {
return;
}
// 用 getBoundingClientRect 计算卡片底部相对滚动容器的偏移,
diff --git a/app/src/layout/dock/agent/AgentHistory.test.ts b/app/src/layout/dock/agent/AgentHistory.test.ts
index 450099ecff..a4eee71444 100644
--- a/app/src/layout/dock/agent/AgentHistory.test.ts
+++ b/app/src/layout/dock/agent/AgentHistory.test.ts
@@ -6,6 +6,7 @@ import {
findAgentUserEntryIndex,
getAgentThinkingDisplaySeconds,
getAgentThinkingToolGroups,
+ getAgentTurnContent,
hasAgentExecutedToolsAfter,
hasAgentModelSpecificContext,
hasAgentThinkingStepDetails,
@@ -54,6 +55,31 @@ describe("AgentHistory", () => {
assert.equal(getAgentThinkingDisplaySeconds(1.5), 2);
});
+ it("copies all assistant rounds within the selected user turn", () => {
+ const turnEntries = [
+ {id: "user-1", type: "user", content: "First question"},
+ {type: "assistant", content: "**First part**", toolCalls: [{name: "document"}]},
+ {type: "thinking", steps: [{reasoningContent: "Reasoning"}]},
+ {type: "assistant", toolCalls: [{result: "Tool output"}]},
+ {type: "assistant", content: "Last part"},
+ {id: "user-2", type: "user", content: "Second question"},
+ {type: "assistant", content: "Second answer"},
+ ];
+ assert.equal(getAgentTurnContent(turnEntries, "user-1"), "**First part**\n\nLast part");
+ assert.equal(getAgentTurnContent(turnEntries, "user-2"), "Second answer");
+ assert.equal(getAgentTurnContent(turnEntries, "missing"), "");
+ });
+
+ it("copies legacy thinking content once after presentation normalization", () => {
+ const turnEntries = buildAgentPresentationEntries([
+ {id: "user-1", type: "user", content: "Question"},
+ {type: "thinking", steps: [{content: "Intermediate answer", toolNames: ["document"]}]},
+ {type: "assistant", content: "Intermediate answer", toolCalls: [{name: "document"}]},
+ {type: "assistant", content: "Final answer"},
+ ]);
+ assert.equal(getAgentTurnContent(turnEntries, "user-1"), "Intermediate answer\n\nFinal answer");
+ });
+
it("recognizes only thinking steps with visible details", () => {
assert.equal(hasAgentThinkingStepDetails({reasoning: "processing", roundID: "round-1"}), false);
assert.equal(hasAgentThinkingStepDetails({reasoningContent: "reasoning"}), true);
diff --git a/app/src/layout/dock/agent/AgentHistory.ts b/app/src/layout/dock/agent/AgentHistory.ts
index 099562efb6..f0930b75ff 100644
--- a/app/src/layout/dock/agent/AgentHistory.ts
+++ b/app/src/layout/dock/agent/AgentHistory.ts
@@ -91,6 +91,21 @@ export const isAgentAssistantContentFinalInTurn = (
return true;
};
+export const getAgentTurnContent = (entries: AgentHistoryEntry[], userEntryID: string): string => {
+ const userIndex = entries.findIndex(entry => entry.type === "user" && entry.id === userEntryID);
+ if (userIndex < 0) {
+ return "";
+ }
+ const contents: string[] = [];
+ for (let i = userIndex + 1; i < entries.length && entries[i].type !== "user"; i++) {
+ const entry = entries[i];
+ if (entry.type === "assistant" && entry.content?.trim()) {
+ contents.push(entry.content);
+ }
+ }
+ return contents.join("\n\n");
+};
+
export const hasAgentExecutedToolsAfter = (entries: AgentHistoryEntry[], entryIndex: number): boolean => {
return entries.slice(entryIndex + 1).some((entry) => {
if (entry.type === "snapshot") {