Skip to content

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

Merge remote-tracking branch 'origin/dev' into dev

Vanessa8dca3b4090bc
diff --cc app/src/layout/dock/agent/AgentChat.ts
index 0e4ffc80f4,7719042a45..12d0518fe3
--- a/app/src/layout/dock/agent/AgentChat.ts
+++ b/app/src/layout/dock/agent/AgentChat.ts
@@@ -22,9 -22,10 +22,10 @@@ import {showMessage} from "../../../dia
import * as dayjs from "dayjs";
import {sendNotification} from "../../../plugin/platformUtils";
import {
+ applyAgentUserEdit,
findAgentUserEntryIndex,
- filterAgentReferencesForContent,
hasAgentExecutedToolsAfter,
+ hasAgentModelSpecificContext,
isAgentRegenerateStateCurrent
} from "./AgentHistory";
import {
diff --cc app/src/layout/dock/agent/AgentHistory.test.ts
index fd0a7a38e5,5cf20a27fb..a6b8d924a2
--- a/app/src/layout/dock/agent/AgentHistory.test.ts
+++ b/app/src/layout/dock/agent/AgentHistory.test.ts
@@@ -1,9 -1,10 +1,10 @@@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
+ applyAgentUserEdit,
findAgentUserEntryIndex,
- filterAgentReferencesForContent,
hasAgentExecutedToolsAfter,
+ hasAgentModelSpecificContext,
isAgentRegenerateStateCurrent
} from "./AgentHistory";
diff --cc kernel/agent/agent.go
index 30caa8ef1b,1462a27225..ddb69213e7
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@@ -443,7 -445,7 +445,7 @@@ type agentCheckpoint struct
LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`
}
- func AgentChat(ctx context.Context, client *openai.Client, model string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, userBlockHTML *string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {
-func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilityKey string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {
++func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilityKey string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, userBlockHTML *string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {
ch := make(chan AgentEvent, 256)
go func() {
diff --cc kernel/agent/assistant_context_test.go
index 0000000000,0ca1919cc7..23d5909ee5
mode 000000,100644..100644
--- a/kernel/agent/assistant_context_test.go
+++ b/kernel/agent/assistant_context_test.go
@@@ -1,0 -1,220 +1,220 @@@
+ // SiYuan - Refactor your thinking
+ // Copyright (c) 2020-present, b3log.org
+ //
+ // This program is free software: you can redistribute it and/or modify
+ // it under the terms of the GNU Affero General Public License as published by
+ // the Free Software Foundation, either version 3 of the License, or
+ // (at your option) any later version.
+
+ package agent
+
+ import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/sashabaranov/go-openai"
+ kernelConf "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"
+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"
+ )
+
+ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
+ useTestDataDir(t)
+ originalConf := kernelModel.Conf
+ kernelModel.Conf = kernelModel.NewAppConf()
+ kernelModel.Conf.AI = kernelConf.NewAI()
+ kernelModel.Conf.AI.MCP = nil
+ kernelModel.Conf.AI.Agent.MaxToolCallRounds = 2
+ kernelModel.Conf.Variables = kernelConf.NewVariables()
+ t.Cleanup(func() { kernelModel.Conf = originalConf })
+
+ const (
+ toolName = "test_assistant_context"
+ toolCallID = "call-original"
+ argumentsJSON = "{\n \"action\": \"list\",\n \"limit\": 9007199254740993\n}"
+ toolReasoning = "I need to call the test tool."
+ firstFinalReasoning = "The tool result is sufficient."
+ secondFinalReasoning = "I can answer from the restored context."
+ )
+ tools.SetTool(toolName, &tools.Tool{
+ Name: toolName,
+ Source: "native",
+ ReadOnlyHint: true,
+ InputSchema: tools.ToolSchema{
+ Type: "object",
+ Properties: map[string]tools.Property{
+ "action": {Type: "string"},
+ "limit": {Type: "integer"},
+ },
+ },
+ ActionEffects: map[string]tools.ToolEffects{
+ "list": {LocalRead: true},
+ },
+ Handler: func(map[string]any) (tools.CallToolResult, error) {
+ return tools.CallToolResult{
+ Content: []tools.ContentItem{{Type: "text", Text: `{"ok":true}`}},
+ }, nil
+ },
+ })
+ t.Cleanup(func() { tools.RemoveTool(toolName) })
+
+ session := map[string]any{
+ "id": testSessionID,
+ "title": "assistant context test",
+ "createdAt": int64(1),
+ "updatedAt": int64(1),
+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use the tool"}},
+ }
+ if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {
+ t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
+ }
+
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ attempt := requests.Add(1)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("read request failed: %v", err)
+ return
+ }
+ var request openai.ChatCompletionRequest
+ if err = json.Unmarshal(body, &request); err != nil {
+ t.Errorf("decode request failed: %v", err)
+ return
+ }
+
+ switch attempt {
+ case 1:
+ flusher := prepareTestStream(t, w)
+ chunk := fmt.Sprintf(
+ `data: {"id":"chatcmpl-tool","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"reasoning_content":%q,"tool_calls":[{"index":0,"id":%q,"type":"function","function":{"name":%q,"arguments":%q}}]},"finish_reason":"tool_calls"}]}`+"\n\n",
+ toolReasoning, toolCallID, toolName, argumentsJSON,
+ )
+ if _, err = io.WriteString(w, chunk); err != nil {
+ t.Errorf("write tool response failed: %v", err)
+ return
+ }
+ flusher.Flush()
+ writeTestStreamDone(t, w, flusher)
+ case 2:
+ assertRestoredAssistantContext(t, request.Messages, toolName, toolCallID, argumentsJSON, toolReasoning, "")
+ writeAssistantContextStream(t, w, firstFinalReasoning, "first answer")
+ case 3:
+ assertRestoredAssistantContext(
+ t, request.Messages, toolName, toolCallID, argumentsJSON, toolReasoning, firstFinalReasoning,
+ )
+ writeAssistantContextStream(t, w, secondFinalReasoning, "second answer")
+ default:
+ t.Errorf("unexpected request attempt: %d", attempt)
+ }
+ }))
+ defer server.Close()
+
+ firstTurnID := ""
+ events := AgentChat(
+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-1", 1,
- "use the tool", "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
++ "use the tool", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
+ )
+ for event := range events {
+ if event.Type == "turn" {
+ firstTurnID = event.TurnID
+ }
+ if event.Type == "error" {
+ t.Fatalf("first agent turn failed: %s", event.Error)
+ }
+ }
+ if firstTurnID == "" {
+ t.Fatal("first agent turn did not expose its turn ID")
+ }
+
+ recovered, err := GetSession(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ recovered["expectedRevision"] = int64(1)
+ recovered["commitTurnID"] = firstTurnID
+ revision, canonical, err := SaveSessionState(marshalSession(t, recovered))
+ if err != nil || revision != 2 {
+ t.Fatalf("commit first agent turn failed: revision=%d, err=%v", revision, err)
+ }
+
+ entries := canonical["entries"].([]any)
+ canonical["entries"] = append(entries, map[string]any{
+ "id": "user-2", "type": "user", "content": "continue",
+ })
+ canonical["expectedRevision"] = int64(2)
+ revision, err = SaveSession(marshalSession(t, canonical))
+ if err != nil || revision != 3 {
+ t.Fatalf("save follow-up user message failed: revision=%d, err=%v", revision, err)
+ }
+
+ events = AgentChat(
+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-2", 3,
- "continue", "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
++ "continue", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
+ )
+ for event := range events {
+ if event.Type == "error" {
+ t.Fatalf("second agent turn failed: %s", event.Error)
+ }
+ }
+ if requests.Load() != 3 {
+ t.Fatalf("unexpected request count: %d", requests.Load())
+ }
+
+ runtime, err := loadRuntimeState(testSessionID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if runtime.ActiveTurn == nil || len(runtime.ActiveTurn.Delta) != 1 ||
+ runtime.ActiveTurn.Delta[0].ReasoningContent != secondFinalReasoning {
+ t.Fatalf("follow-up reasoning was not checkpointed: %#v", runtime.ActiveTurn)
+ }
+ }
+
+ func assertRestoredAssistantContext(
+ t *testing.T,
+ messages []openai.ChatCompletionMessage,
+ toolName, toolCallID, argumentsJSON, toolReasoning, finalReasoning string,
+ ) {
+ t.Helper()
+ toolAssistantFound := false
+ finalAssistantFound := finalReasoning == ""
+ for _, message := range messages {
+ if message.Role != openai.ChatMessageRoleAssistant {
+ continue
+ }
+ if len(message.ToolCalls) == 1 && message.ToolCalls[0].Function.Name == toolName {
+ toolAssistantFound = message.ReasoningContent == toolReasoning &&
+ message.ToolCalls[0].ID == toolCallID &&
+ message.ToolCalls[0].Function.Arguments == argumentsJSON
+ }
+ if finalReasoning != "" && message.Content == "first answer" {
+ finalAssistantFound = message.ReasoningContent == finalReasoning
+ }
+ }
+ if !toolAssistantFound || !finalAssistantFound {
+ t.Errorf("assistant context was not restored exactly: %#v", messages)
+ }
+ }
+
+ func writeAssistantContextStream(t *testing.T, w http.ResponseWriter, reasoning, content string) {
+ t.Helper()
+ flusher := prepareTestStream(t, w)
+ chunk := fmt.Sprintf(
+ `data: {"id":"chatcmpl-final","object":"chat.completion.chunk","created":1,"model":"test-model","choices":[{"index":0,"delta":{"reasoning_content":%q,"content":%q},"finish_reason":"stop"}]}`+"\n\n",
+ reasoning, content,
+ )
+ if _, err := io.WriteString(w, chunk); err != nil {
+ t.Errorf("write assistant response failed: %v", err)
+ return
+ }
+ flusher.Flush()
+ writeTestStreamDone(t, w, flusher)
+ }
diff --cc kernel/agent/attachments_test.go
index f68e6ed4a0,dc33a65631..97663338a8
--- a/kernel/agent/attachments_test.go
+++ b/kernel/agent/attachments_test.go
@@@ -326,8 -656,8 +656,8 @@@ func TestAgentChatSendsToolAttachmentTo
defer server.Close()
events := AgentChat(
- context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1,
+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-1", 1,
- "look at the image", "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
+ "look at the image", nil, "English", nil, EditorContext{}, nil, false, time.Second, 0, "", time.Second, time.Second,
)
doneSeen := false
for event := range events {
diff --cc kernel/agent/compaction_test.go
index d95eaf5781,938e57d3c9..48ce68d33e
--- a/kernel/agent/compaction_test.go
+++ b/kernel/agent/compaction_test.go
@@@ -278,8 -278,8 +278,8 @@@ func TestAgentChatCompactsBeforeSending
defer server.Close()
events := AgentChat(
- context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,
+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", contextLimit, testSessionID,
- "user-2", 1, "start the current task", "English", nil, EditorContext{}, nil, false,
+ "user-2", 1, "start the current task", nil, "English", nil, EditorContext{}, nil, false,
time.Second, 0, "", time.Second, time.Second,
)
doneSeen := false
@@@ -373,8 -372,8 +373,8 @@@ func TestAgentChatRegenerateCompactionU
defer server.Close()
events := AgentChat(
- context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,
+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", contextLimit, testSessionID,
- "user-2", 1, editedTarget, "English", nil, EditorContext{}, nil, true,
+ "user-2", 1, editedTarget, stringPointer(editedBlockHTML), "English", nil, EditorContext{}, nil, true,
time.Second, 0, "", time.Second, time.Second,
)
for event := range events {
@@@ -471,8 -467,8 +471,8 @@@ func TestAgentChatRetriesOverflowAfterP
defer server.Close()
events := AgentChat(
- context.Background(), newTestOpenAIClient(server.URL), "test-model", contextLimit, testSessionID,
+ context.Background(), newTestOpenAIClient(server.URL), "test-model", "", contextLimit, testSessionID,
- "user-3", 1, "current task", "English", nil, EditorContext{}, nil, false,
+ "user-3", 1, "current task", nil, "English", nil, EditorContext{}, nil, false,
time.Second, 0, "", time.Second, time.Second,
)
doneSeen := false
diff --cc kernel/agent/stream_timeout_test.go
index ee26d6fc62,3068b34e50..cabdbfce24
--- a/kernel/agent/stream_timeout_test.go
+++ b/kernel/agent/stream_timeout_test.go
@@@ -210,7 -210,7 +210,7 @@@ func TestAgentChatPartialStreamTimeoutS
}))
defer server.Close()
- events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1, "hello", nil, "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
- events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-1", 1, "hello", "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
++ events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", "", 0, testSessionID, "user-1", 1, "hello", nil, "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
contentSeen := false
errorSeen := false
for event := range events {
diff --cc kernel/api/agent.go
index 55fce93bb8,7892cd78d3..578c9cc036
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@@ -136,7 -135,9 +136,9 @@@ func agentChat(c *gin.Context)
contentRevision = *req.ContentRevision
}
contextLimit := agent.ResolveModelContextLimit(selectedModel.Name, selectedModel.ContextLength)
- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.BlockHTML, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
+ imageCapabilityKey := fmt.Sprintf("%s\x00%s\x00%s\x00%s\x00%s",
+ selectedProvider.ID, selectedModel.ID, selectedProvider.BaseURL, selectedProvider.Protocol, selectedModel.Name)
- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, imageCapabilityKey, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
++ eventCh := agent.AgentChat(ctx, client, selectedModel.Name, imageCapabilityKey, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.BlockHTML, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
defer cancel()
streamClosed := false
defer func() {