diff --git a/app/src/assets/scss/business/_agentChat.scss b/app/src/assets/scss/business/_agentChat.scss index a6698cd84..8d590099d 100644 --- a/app/src/assets/scss/business/_agentChat.scss +++ b/app/src/assets/scss/business/_agentChat.scss @@ -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); diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts index b0931572b..bebd88fa8 100644 --- a/app/src/layout/dock/AgentChat.ts +++ b/app/src/layout/dock/AgentChat.ts @@ -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 = '
' + + let bodyHTML = '
' + '
' + this.escapeHtml(roundLabel) + "
" + detailLines + "
"; @@ -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 = '
' + (this.lute.MarkdownStr("", savedContent) || this.escapeHtml(savedContent)) + "
"; + 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 = '
' + (this.lute.MarkdownStr("", savedContent) || this.escapeHtml(savedContent)) + "
"; + 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 += '
' + this.escapeHtml(roundLabel) + "
"; + } + if (step.content) { + detail += '
' + (this.lute.MarkdownStr("", step.content) || this.escapeHtml(step.content)) + "
"; + } if (step.toolCalls.length > 0) { - detail += '
Tool calls:
'; + detail += '
' + (L.agentToolCall || "Tool call") + "s:
"; + detail += '
'; for (let j = 0; j < step.toolCalls.length; j++) { const tc = step.toolCalls[j]; const statusSvg = tc.result ? ' ' : ' '; - detail += '
' + this.escapeHtml(tc.name) + statusSvg + "
"; + detail += '' + this.escapeHtml(tc.name) + statusSvg + ""; } + detail += '
'; } if (step.reasoningContent) { detail += '
Reasoning:
'; - detail += "
" + this.escapeHtml(step.reasoningContent) + "
"; + detail += '
' + this.escapeHtml(step.reasoningContent) + "
"; } } diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.ts index 67fd81ab9..fa4d65f1e 100644 --- a/app/src/layout/dock/SessionStore.ts +++ b/app/src/layout/dock/SessionStore.ts @@ -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; diff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.ts index a6214cf9f..5120131cc 100644 --- a/app/src/util/agentSSE.ts +++ b/app/src/util/agentSSE.ts @@ -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, 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 diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go index b748f119f..fcd929388 100644 --- a/kernel/agent/agent.go +++ b/kernel/agent/agent.go @@ -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