Signed-off-by: Daniel <845765@qq.com>
This commit is contained in:
Daniel
2026-06-08 20:01:11 +08:00
parent 047445b8d9
commit 40e5c4b07f
5 changed files with 204 additions and 97 deletions
@@ -405,6 +405,30 @@
color: var(--b3-theme-on-surface);
}
.agent-chat__thinking-reasoning-text {
font-size: 13px;
color: var(--b3-theme-on-surface);
line-height: 1.5;
margin-bottom: 8px;
white-space: pre-wrap;
word-break: break-word;
}
.agent-chat__thinking-chat {
font-size: 13px;
color: var(--b3-theme-on-surface);
line-height: 1.5;
margin-bottom: 8px;
padding: 8px 10px;
background: var(--b3-theme-surface-light);
border: 1px solid var(--b3-border-color);
border-radius: var(--b3-border-radius-b);
}
.agent-chat__thinking-chat--streaming {
min-height: 20px;
}
.agent-chat__thinking-summary {
font-size: 12px;
color: var(--b3-theme-on-surface-light);
+173 -91
View File
@@ -51,7 +51,8 @@ export class AgentChat extends Model {
private currentThinkingText = "";
private currentThinkingReasoning = "";
private currentThinkingReasoningContent = "";
private currentThinkingSteps: Array<{reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string}> = [];
private currentThinkingSteps: Array<{reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string; content?: string}> = [];
private currentThinkingStepContent = "";
private modelSelect: HTMLSelectElement;
constructor(app: App, tab: Tab) {
@@ -178,7 +179,7 @@ export class AgentChat extends Model {
private bindEvents() {
this.sendBtn.addEventListener("click", (e: MouseEvent) => { e.stopPropagation(); this.sendMessage(); });
this.stopBtn.addEventListener("click", (e: MouseEvent) => { e.stopPropagation(); this.stopGeneration(); });
this.stopBtn.addEventListener("click", (e: MouseEvent) => { e.stopPropagation(); void this.stopGeneration(); });
this.newSessionBtn.addEventListener("click", (e: MouseEvent) => { e.stopPropagation(); this.createSession(); });
this.sessionMenuBtn.addEventListener("click", (e: MouseEvent) => {
e.stopPropagation();
@@ -210,7 +211,7 @@ export class AgentChat extends Model {
this.sessionId = session.id;
this.sessionCreatedAt = session.createdAt || Date.now();
this.sessionTitle = session.title;
this.entries = (session.entries && session.entries.length > 0) ? session.entries as any as SessionEntry[] : [];
this.entries = this.buildEntriesFromSession(session);
this.hasTitled = session.titled !== false;
this.sessionPromptTokens = session.promptTokens || 0;
this.sessionCompletionTokens = session.completionTokens || 0;
@@ -467,7 +468,7 @@ export class AgentChat extends Model {
}
this.sessionCreatedAt = session.createdAt || Date.now();
this.sessionTitle = session.title;
this.entries = (session.entries && session.entries.length > 0) ? session.entries as any as SessionEntry[] : [];
this.entries = this.buildEntriesFromSession(session);
this.hasTitled = session.titled !== false;
this.currentAIElement = null;
this.currentContent = "";
@@ -537,6 +538,28 @@ export class AgentChat extends Model {
}
}
private buildEntriesFromSession(session: AgentSession): SessionEntry[] {
if (session.messages && session.messages.length > 0) {
const entriesLen = session.entries ? session.entries.length : 0;
if (session.messages.length > entriesLen) {
const entries: SessionEntry[] = [];
for (let i = 0; i < session.messages.length; i++) {
const msg = session.messages[i];
if (msg.role === "user") {
entries.push({type: "user", content: msg.content});
} else if (msg.role === "assistant") {
entries.push({type: "assistant", content: msg.content});
}
}
return entries;
}
}
if (session.entries && session.entries.length > 0) {
return session.entries as any as SessionEntry[];
}
return [];
}
private async createSession() {
if (this.abortController) {
this.abortController.abort();
@@ -564,6 +587,7 @@ export class AgentChat extends Model {
}
this.messagesContainer.innerHTML = "";
this.currentThinkingSteps = [];
this.currentThinkingStepContent = "";
this.titleElement.textContent = this.defaultTitle;
if (this.composer) { this.composer.clear(); }
if (this.composer) { this.composer.focus(); }
@@ -607,7 +631,7 @@ export class AgentChat extends Model {
}
}
private sendMessage() {
private async sendMessage() {
if (!this.composer) { return; }
const sendData = this.composer.getSendData();
const text = sendData.text;
@@ -617,11 +641,13 @@ export class AgentChat extends Model {
}
this.setStreaming(true);
this.clearThinking();
this.composer.clear();
this.entries.push({type: "user", content: text});
this.appendUserMessage(text);
if (this.composer) { this.composer.pushHistory(text); }
await this.saveSession();
if (!this.hasTitled && this.entries.length === 1) {
this.hasTitled = true;
@@ -635,17 +661,17 @@ export class AgentChat extends Model {
this.abortController = new AbortController();
const requestSessionId = this.sessionId;
fetchAgentSSE(
await fetchAgentSSE(
apiMessages,
window.siyuan.config.appearance.lang,
refs,
(event: ISSEResult) => {
if (this.sessionId !== requestSessionId) { return; }
this.handleSSEEvent(event);
return this.handleSSEEvent(event);
},
(err: Error) => {
if (this.sessionId !== requestSessionId) { return; }
this.handleError(err);
return this.handleError(err);
},
this.abortController.signal,
this.sessionId,
@@ -653,7 +679,7 @@ export class AgentChat extends Model {
);
}
private handleSSEEvent(event: ISSEResult) {
private async handleSSEEvent(event: ISSEResult) {
try {
switch (event.type) {
case "content":
@@ -676,7 +702,7 @@ export class AgentChat extends Model {
break;
case "done":
this.flushTokenUpdate();
this.finishResponse();
await this.finishResponse();
break;
case "usage":
this.appendUsage(event.promptTokens, event.completionTokens);
@@ -684,6 +710,7 @@ export class AgentChat extends Model {
case "error":
this.appendError(event.message);
this.setStreaming(false);
await this.saveSession();
break;
case "retry":
this.appendRetry(event.attempt, event.maxRetries);
@@ -701,10 +728,11 @@ export class AgentChat extends Model {
}
}
private handleError(err: Error) {
private async handleError(err: Error) {
this.flushTokenUpdate();
this.appendError(err.message);
this.setStreaming(false);
await this.saveSession();
}
private appendUserMessage(text: string) {
@@ -729,11 +757,25 @@ export class AgentChat extends Model {
private rafId = 0;
private appendToken(token: string) {
this.currentContent += token;
this.fullContent += token;
const thinkBody = this.messagesContainer.querySelector(".agent-chat__msg--thinking .agent-chat__thinking-body");
if (thinkBody) {
let chatEl = thinkBody.querySelector(".agent-chat__thinking-chat--streaming") as HTMLElement;
if (!chatEl) {
chatEl = document.createElement("div");
chatEl.className = "agent-chat__thinking-chat agent-chat__thinking-chat--streaming";
thinkBody.appendChild(chatEl);
}
chatEl.innerHTML = this.lute.MarkdownStr("", this.currentContent) || this.escapeHtml(this.currentContent);
this.scrollToBottom();
return;
}
if (!this.currentAIElement) {
this.currentAIElement = this.createAIMessagePlaceholder();
}
this.currentContent += token;
this.fullContent += token;
this.scrollToBottom();
if (!this.pendingTokenUpdate) {
@@ -842,11 +884,20 @@ export class AgentChat extends Model {
if (this.currentContent) {
const bubble = this.currentAIElement.querySelector(".agent-chat__bubble") as HTMLElement;
if (bubble) { bubble.classList.remove("agent-chat__bubble--streaming"); }
this.currentThinkingStepContent = this.currentContent;
this.currentAIElement.remove();
} else {
this.currentAIElement.remove();
}
this.currentAIElement = null;
this.currentContent = "";
} else if (reasoning === "processing" && this.currentContent) {
this.currentThinkingStepContent = this.currentContent;
this.currentContent = "";
const streamingEl = this.messagesContainer.querySelector(".agent-chat__msg--thinking .agent-chat__thinking-chat--streaming") as HTMLElement;
if (streamingEl) {
streamingEl.classList.remove("agent-chat__thinking-chat--streaming");
}
}
const existingCard = this.messagesContainer.querySelector(".agent-chat__msg--thinking") as HTMLElement;
@@ -864,7 +915,7 @@ export class AgentChat extends Model {
existingCard.remove();
}
const bodyHTML = '<div class="agent-chat__thinking-body fn__none">' +
let bodyHTML = '<div class="agent-chat__thinking-body fn__none">' +
'<div class="agent-chat__thinking-round">' + this.escapeHtml(roundLabel) + "</div>" +
detailLines +
"</div>";
@@ -898,10 +949,34 @@ export class AgentChat extends Model {
}
private appendReasoning(token: string) {
const isNewRound = this.currentThinkingReasoningContent.length === 0;
this.currentThinkingReasoningContent += token;
const thinking = this.messagesContainer.querySelector(".agent-chat__msg--thinking:last-child .agent-chat__thinking-body");
if (!thinking) { return; }
thinking.innerHTML += token;
const thinkingElems = this.messagesContainer.querySelectorAll(".agent-chat__msg--thinking .agent-chat__thinking-body");
if (thinkingElems.length === 0) { return; }
const thinking = thinkingElems[thinkingElems.length - 1];
let reasoningEl: HTMLElement;
if (isNewRound) {
const roundDiv = document.createElement("div");
roundDiv.className = "agent-chat__thinking-round";
roundDiv.textContent = "Reasoning:";
thinking.appendChild(roundDiv);
reasoningEl = document.createElement("div");
reasoningEl.className = "agent-chat__thinking-reasoning-text";
thinking.appendChild(reasoningEl);
} else {
const allReasoning = thinking.querySelectorAll(".agent-chat__thinking-reasoning-text");
reasoningEl = allReasoning[allReasoning.length - 1] as HTMLElement;
if (!reasoningEl) {
const roundDiv = document.createElement("div");
roundDiv.className = "agent-chat__thinking-round";
roundDiv.textContent = "Reasoning:";
thinking.appendChild(roundDiv);
reasoningEl = document.createElement("div");
reasoningEl.className = "agent-chat__thinking-reasoning-text";
thinking.appendChild(reasoningEl);
}
}
reasoningEl.textContent += token;
}
private addCopyButton(el: HTMLElement, contentOverride?: string) {
@@ -936,7 +1011,7 @@ export class AgentChat extends Model {
el.appendChild(actions);
}
private regenerateResponse() {
private async regenerateResponse() {
if (this.isStreaming) {
return;
}
@@ -955,6 +1030,7 @@ export class AgentChat extends Model {
this.fullContent = "";
this.currentToolCalls = [];
this.currentThinkingSteps = [];
this.currentThinkingStepContent = "";
this.currentThinkingText = "";
this.currentThinkingReasoning = "";
this.currentThinkingReasoningContent = "";
@@ -964,17 +1040,17 @@ export class AgentChat extends Model {
const apiMessages = this.entries.filter((e) => e.type === "user" || e.type === "assistant").map((e) => ({role: e.type === "user" ? "user" as const : "assistant" as const, content: (e as {content: string}).content}));
this.abortController = new AbortController();
const requestSessionId = this.sessionId;
fetchAgentSSE(
await fetchAgentSSE(
apiMessages,
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.handleError(err);
return this.handleError(err);
},
this.abortController.signal,
this.sessionId,
@@ -982,64 +1058,42 @@ export class AgentChat extends Model {
);
}
private finishResponse() {
private async finishResponse() {
this.finishActiveThinking();
if (!this.currentAIElement) {
if (this.currentToolCalls.length === 0) {
this.setStreaming(false);
return;
const savedContent = this.currentContent;
const savedFullContent = this.fullContent;
if (!this.currentAIElement && savedContent) {
const thinkBody = this.messagesContainer.querySelector(".agent-chat__msg--thinking .agent-chat__thinking-body");
if (thinkBody) {
const streamingEl = thinkBody.querySelector(".agent-chat__thinking-chat--streaming") as HTMLElement;
if (streamingEl) { streamingEl.remove(); }
}
this.flushThinkingStep();
this.entries.push({type: "assistant", content: "", toolCalls: this.currentToolCalls.slice()});
this.currentToolCalls = [];
if (this.requestStartTime) {
this.sessionTotalDuration += Date.now() - this.requestStartTime;
this.requestStartTime = 0;
}
this.updateTokenDisplay();
this.setStreaming(false);
this.saveSession();
return;
const el = document.createElement("div");
el.className = "agent-chat__msg agent-chat__msg--ai";
el.innerHTML = '<div class="agent-chat__bubble">' + (this.lute.MarkdownStr("", savedContent) || this.escapeHtml(savedContent)) + "</div>";
this.messagesContainer.appendChild(el);
this.currentAIElement = el;
this.currentContent = savedContent;
this.fullContent = savedFullContent;
this.addCopyButton(el);
}
this.flushTokenUpdate();
if (!this.currentContent) {
this.currentAIElement.remove();
this.currentAIElement = null;
this.currentContent = "";
this.fullContent = "";
if (this.currentToolCalls.length > 0) {
this.flushThinkingStep();
this.entries.push({type: "assistant", content: "", toolCalls: this.currentToolCalls.slice()});
}
this.currentToolCalls = [];
if (this.requestStartTime) {
this.sessionTotalDuration += Date.now() - this.requestStartTime;
this.requestStartTime = 0;
}
this.updateTokenDisplay();
this.setStreaming(false);
this.saveSession();
return;
}
const bubble = this.currentAIElement.querySelector(".agent-chat__bubble") as HTMLElement;
if (bubble) {
bubble.classList.remove("agent-chat__bubble--streaming");
}
this.addCopyButton(this.currentAIElement);
this.flushThinkingStep();
this.entries.push({type: "assistant", content: this.currentContent || " ", toolCalls: this.currentToolCalls.length > 0 ? this.currentToolCalls.slice() : undefined});
if (this.currentContent) {
this.entries.push({type: "assistant", content: this.currentContent, toolCalls: this.currentToolCalls.length > 0 ? this.currentToolCalls.slice() : undefined});
} else if (this.currentToolCalls.length > 0) {
this.entries.push({type: "assistant", content: "", toolCalls: this.currentToolCalls.slice()});
}
this.currentAIElement = null;
this.currentContent = "";
this.fullContent = "";
this.currentToolCalls = [];
if (this.requestStartTime) {
this.sessionTotalDuration += Date.now() - this.requestStartTime;
this.requestStartTime = 0;
}
this.updateTokenDisplay();
this.setStreaming(false);
this.saveSession();
this.requestStartTime = 0;
}
this.updateTokenDisplay();
this.setStreaming(false);
await this.saveSession();
}
private flushThinkingStep() {
@@ -1050,8 +1104,10 @@ export class AgentChat extends Model {
text: this.currentThinkingText,
toolCalls: tc,
reasoningContent: this.currentThinkingReasoningContent,
content: this.currentThinkingStepContent,
});
this.currentThinkingText = "";
this.currentThinkingStepContent = "";
}
if (this.currentThinkingSteps.length > 0) {
this.entries.push({
@@ -1080,7 +1136,7 @@ export class AgentChat extends Model {
});
}
private appendError(message: string) {
private async appendError(message: string) {
this.finishActiveThinking();
this.clearThinking();
if (this.currentAIElement && !this.currentContent) {
@@ -1093,12 +1149,13 @@ export class AgentChat extends Model {
this.messagesContainer.appendChild(el);
this.scrollToBottom();
this.flushThinkingStep();
this.saveSession();
await this.saveSession();
}
private appendRetry(attempt: number, maxRetries: number) {
this.finishActiveThinking();
this.currentThinkingSteps = [];
this.currentThinkingStepContent = "";
this.clearThinking();
const el = document.createElement("div");
el.className = "agent-chat__msg agent-chat__msg--thinking";
@@ -1112,34 +1169,44 @@ export class AgentChat extends Model {
this.scrollToBottom();
}
private stopGeneration() {
private async stopGeneration() {
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
}
this.flushTokenUpdate();
if (this.currentAIElement) {
const bubble = this.currentAIElement.querySelector(".agent-chat__bubble") as HTMLElement;
if (bubble) {
bubble.classList.remove("agent-chat__bubble--streaming");
}
this.finishActiveThinking();
this.flushThinkingStep();
if (this.currentContent) {
this.entries.push({type: "assistant", content: this.currentContent || " ", toolCalls: this.currentToolCalls.length > 0 ? this.currentToolCalls.slice() : undefined});
this.finishActiveThinking();
const savedContent = this.currentContent;
const savedFullContent = this.fullContent;
if (!this.currentAIElement && savedContent) {
const thinkBody = this.messagesContainer.querySelector(".agent-chat__msg--thinking .agent-chat__thinking-body");
if (thinkBody) {
const streamingEl = thinkBody.querySelector(".agent-chat__thinking-chat--streaming") as HTMLElement;
if (streamingEl) { streamingEl.remove(); }
}
const el = document.createElement("div");
el.className = "agent-chat__msg agent-chat__msg--ai";
el.innerHTML = '<div class="agent-chat__bubble">' + (this.lute.MarkdownStr("", savedContent) || this.escapeHtml(savedContent)) + "</div>";
this.messagesContainer.appendChild(el);
this.currentAIElement = el;
this.currentContent = savedContent;
this.fullContent = savedFullContent;
}
this.flushThinkingStep();
if (this.currentContent) {
this.entries.push({type: "assistant", content: this.currentContent, toolCalls: this.currentToolCalls.length > 0 ? this.currentToolCalls.slice() : undefined});
}
this.currentAIElement = null;
this.currentContent = "";
this.fullContent = "";
this.currentToolCalls = [];
}
if (this.requestStartTime) {
this.sessionTotalDuration += Date.now() - this.requestStartTime;
this.requestStartTime = 0;
}
this.updateTokenDisplay();
this.setStreaming(false);
this.saveSession();
this.requestStartTime = 0;
}
this.updateTokenDisplay();
this.setStreaming(false);
await this.saveSession();
}
private insertBeforeAI(el: HTMLElement) {
@@ -1356,23 +1423,38 @@ export class AgentChat extends Model {
this.messagesContainer.appendChild(el);
}
private renderMergedThinkingCard(steps: Array<{reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string}>) {
private renderMergedThinkingCard(steps: Array<{reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string; content?: string}>) {
const L = window.siyuan.languages;
let detail = "";
for (let i = 0; i < steps.length; i++) {
const step = steps[i];
let roundLabel = "";
if (step.reasoning === "analyzing") {
roundLabel = "Step 1";
} else if (step.reasoning === "processing") {
roundLabel = "Continuing...";
}
if (roundLabel) {
detail += '<div class="agent-chat__thinking-round">' + this.escapeHtml(roundLabel) + "</div>";
}
if (step.content) {
detail += '<div class="agent-chat__thinking-chat">' + (this.lute.MarkdownStr("", step.content) || this.escapeHtml(step.content)) + "</div>";
}
if (step.toolCalls.length > 0) {
detail += '<div class="agent-chat__thinking-summary">Tool calls:</div>';
detail += '<div class="agent-chat__thinking-summary">' + (L.agentToolCall || "Tool call") + "s:</div>";
detail += '<div class="agent-chat__thinking-tools">';
for (let j = 0; j < step.toolCalls.length; j++) {
const tc = step.toolCalls[j];
const statusSvg = tc.result
? ' <svg class="agent-chat__thinking-icon"><use xlink:href="#iconCheck"></use></svg>'
: ' <svg class="agent-chat__thinking-icon"><use xlink:href="#iconUncheck"></use></svg>';
detail += '<div class="agent-chat__thinking-item">' + this.escapeHtml(tc.name) + statusSvg + "</div>";
detail += '<span class="agent-chat__thinking-tool">' + this.escapeHtml(tc.name) + statusSvg + "</span>";
}
detail += '</div>';
}
if (step.reasoningContent) {
detail += '<div class="agent-chat__thinking-round">Reasoning:</div>';
detail += "<div>" + this.escapeHtml(step.reasoningContent) + "</div>";
detail += '<div class="agent-chat__thinking-reasoning-text">' + this.escapeHtml(step.reasoningContent) + "</div>";
}
}
+1
View File
@@ -21,6 +21,7 @@ export interface AgentSession {
title: string;
titled?: boolean;
model?: string;
messages?: Array<{role: string; content: string}>;
entries?: Array<{
type: "user" | "thinking" | "assistant";
content?: string;
+3 -3
View File
@@ -43,7 +43,7 @@ export async function fetchAgentSSE(
messages: Array<{role: string; content: string}>,
language: string,
references: Array<{id: string; title: string}>,
onEvent: (event: ISSEResult) => void,
onEvent: (event: ISSEResult) => void | Promise<void>,
onError: (err: Error) => void,
signal?: AbortSignal,
sessionID?: string,
@@ -98,7 +98,7 @@ export async function fetchAgentSSE(
const data = JSON.parse(dataStr);
const result = buildSSEResult(currentEvent, data);
if (result) {
onEvent(result);
await onEvent(result);
}
} catch (e) {
// skip malformed data
@@ -119,7 +119,7 @@ export async function fetchAgentSSE(
const data = JSON.parse(dataStr);
const result = buildSSEResult(currentEvent, data);
if (result) {
onEvent(result);
await onEvent(result);
}
} catch (e) {
// skip malformed data
+3 -3
View File
@@ -254,9 +254,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
sendEvent(ch, AgentEvent{Type: "thinking", Reasoning: fmt.Sprintf("context limit reached, compacting to last %d turns...", keepTurns)})
continue
}
sendEvent(ch, AgentEvent{Type: "error", Error: "API request failed: " + streamErr.Error()})
saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
return
sendEvent(ch, AgentEvent{Type: "error", Error: "API request failed: " + streamErr.Error()})
saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
return
}
var contentBuilder strings.Builder