An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797
Daniel5c2c11f70347
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.tsindex b3bca74f42..2046aebed4 100644--- a/app/src/layout/dock/AgentChat.ts+++ b/app/src/layout/dock/AgentChat.ts@@ -85,6 +85,7 @@ export class AgentChat extends Model {private renderedToolNames: Record<string, boolean> = {};private hasInterveningCard = false;private modelSelect: HTMLSelectElement;+ private userScrolledUp = false;constructor(app: App, tab: Tab) {super({app: app});@@ -192,13 +193,9 @@ export class AgentChat extends Model {ex.addEventListener("click", () => {const text = ex.getAttribute("data-text") || "";if (text && this.composer) {- // 不支持 setSendText,直接用 sendMessage 发送+ this.messagesContainer.innerHTML = "";this.entries.push({type: "user", content: text});this.appendUserMessage(text);- if (!this.hasTitled) {- this.hasTitled = true;- this.generateTitle();- }this.setStreaming(true);const apiMessages = this.entries.filter((e) => e.type === "user" || e.type === "assistant").map((e) => ({role: e.type === "user" ? "user" as const : "assistant" as const,@@ -271,6 +268,11 @@ export class AgentChat extends Model {this.composer.focus();}});++ this.messagesContainer.addEventListener("scroll", () => {+ const { scrollTop, scrollHeight, clientHeight } = this.messagesContainer;+ this.userScrolledUp = scrollHeight - scrollTop - clientHeight >= 50;+ });}private async initSessions() {@@ -297,7 +299,7 @@ export class AgentChat extends Model {this.titleElement.textContent = session.title;this.updateTokenDisplay();this.renderLoadedSession(session);- this.scrollToBottom();+ this.scrollToBottom(true);return;}}@@ -363,7 +365,7 @@ export class AgentChat extends Model {this.messagesContainer.innerHTML = "";this.titleElement.textContent = session.title;this.renderLoadedSession(session);- this.scrollToBottom();+ this.scrollToBottom(true);this.messagesContainer.classList.remove("agent-chat__messages--switching");}, {once: true});}@@ -572,17 +574,15 @@ export class AgentChat extends Model {this.composer.clear();this.entries.push({type: "user", content: text});+ if (this.entries.length === 1) {+ this.messagesContainer.innerHTML = "";+ }this.appendUserMessage(text);if (this.composer) {this.composer.pushHistory(text);}await this.saveSession();- if (!this.hasTitled && this.entries.length === 1) {- this.hasTitled = true;- this.generateTitle();- }-this.requestStartTime = Date.now();const apiMessages = this.entries.filter((e) => e.type === "user" || e.type === "assistant").map((e) => ({@@ -676,7 +676,7 @@ export class AgentChat extends Model {el.className = "agent-chat__msg agent-chat__msg--user";el.innerHTML = '<div class="agent-chat__body">' + escapeHtml(text) + "</div>";this.messagesContainer.appendChild(el);- this.scrollToBottom();+ this.scrollToBottom(true);}private createAIMessagePlaceholder(): HTMLElement {@@ -749,7 +749,7 @@ export class AgentChat extends Model {el.className = "agent-chat__msg agent-chat__msg--tool";el.innerHTML = renderTodoList(result);this.insertBeforeAI(el);- this.scrollToBottom();+ this.scrollToBottom(true);this.hasInterveningCard = true;}@@ -1093,6 +1093,7 @@ export class AgentChat extends Model {this.updateTokenDisplay();this.setStreaming(false);await this.saveSession();+ this.tryGenerateTitle();}private flushThinkingStep() {@@ -1119,13 +1120,15 @@ export class AgentChat extends Model {}}- private generateTitle() {- const firstUser = this.entries.find((e) => e.type === "user");- const firstMsg = firstUser ? (firstUser as { content: string }).content.slice(0, 500) : "";+ private tryGenerateTitle() {+ if (this.hasTitled) { return; }+ this.hasTitled = true;+ const userMsg = this.entries.find((e) => e.type === "user")?.content?.slice(0, 500) || "";+ const aiMsg = this.entries.find((e) => e.type === "assistant")?.content?.slice(0, 500) || "";fetch("/api/ai/agent/title", {method: "POST",headers: {"Content-Type": "application/json"},- body: JSON.stringify({message: firstMsg}),+ body: JSON.stringify({message: userMsg, assistantReply: aiMsg}),}).then((resp) => resp.json()).then((data) => {if (data.code === 0 && data.data && data.data !== this.sessionTitle) {this.sessionTitle = data.data;@@ -1148,7 +1151,7 @@ export class AgentChat extends Model {el.className = "agent-chat__msg agent-chat__msg--error";el.innerHTML = '<div class="agent-chat__body agent-chat__body--error">' + escapeHtml(message) + "</div>";this.messagesContainer.appendChild(el);- this.scrollToBottom();+ this.scrollToBottom(true);this.flushThinkingStep();await this.saveSession();}@@ -1162,7 +1165,7 @@ export class AgentChat extends Model {el.className = "agent-chat__msg agent-chat__msg--thinking";el.innerHTML = renderRetryCardHTML(attempt, maxRetries);this.insertBeforeAI(el);- this.scrollToBottom();+ this.scrollToBottom(true);this.hasInterveningCard = true;}@@ -1284,7 +1287,7 @@ export class AgentChat extends Model {});}this.insertBeforeAI(el);- this.scrollToBottom();+ this.scrollToBottom(true);this.hasInterveningCard = true;this.pendingConfirms.push({type: "confirm", name, args, confirmID, status: "pending"});}@@ -1355,7 +1358,7 @@ export class AgentChat extends Model {}this.insertBeforeAI(el);- this.scrollToBottom();+ this.scrollToBottom(true);this.hasInterveningCard = true;}@@ -1513,7 +1516,8 @@ export class AgentChat extends Model {}}- private scrollToBottom() {+ private scrollToBottom(force = false) {+ if (!force && this.userScrolledUp) { return; }requestAnimationFrame(() => {this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;});diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 786c5b500a..9c298bc6e2 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -499,33 +499,30 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionreturn ch}-func GenerateTitle(client *openai.Client, model string, msg string) string {- runes := []rune(msg)- if len(runes) > 500 {- msg = string(runes[:500])- }+func GenerateTitle(client *openai.Client, model string, userMsg string, aiReply string, language string) string {resp, err := client.CreateChatCompletion(context.Background(), openai.ChatCompletionRequest{Model: model,Messages: []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: "Generate a short conversation title (max 10 words) based on the user's first message. Return ONLY the title, no quotes, no punctuation at the end."},- {Role: openai.ChatMessageRoleUser, Content: msg},+ {Role: openai.ChatMessageRoleSystem, Content: "Generate a concise conversation title based on the conversation below. Reply in " + language + ". Return only the title, no quotes."},+ {Role: openai.ChatMessageRoleUser, Content: userMsg},+ {Role: openai.ChatMessageRoleAssistant, Content: aiReply},},MaxTokens: 30,})if err != nil || len(resp.Choices) == 0 {- runes = []rune(msg)+ runes := []rune(userMsg)if len(runes) > 30 {return string(runes[:30]) + "..."}- return msg+ return userMsg}title := strings.TrimSpace(resp.Choices[0].Message.Content)if title == "" {- runes = []rune(msg)+ runes := []rune(userMsg)if len(runes) > 30 {return string(runes[:30]) + "..."}- return msg+ return userMsg}return title}diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex d7f767d9a7..22bca62e33 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -174,7 +174,8 @@ func agentChatQuestion(c *gin.Context) {}type agentTitleReq struct {- Message string `json:"message"`+ Message string `json:"message"`+ AssistantReply string `json:"assistantReply"`}func agentChatTitle(c *gin.Context) {@@ -197,7 +198,7 @@ func agentChatTitle(c *gin.Context) {selectedProvider.APIProvider,)- title := agent.GenerateTitle(client, selectedProvider.APIModel, req.Message)+ title := agent.GenerateTitle(client, selectedProvider.APIModel, req.Message, req.AssistantReply, model.Conf.Lang)ret := gulu.Ret.NewResult()ret.Data = titlec.JSON(http.StatusOK, ret)