Skip to content

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

:recycle: Persist agent todos through session results https://github.com/siyuan-note/siyuan/issues/20238

Daniele7022b394ac5
diff --git a/kernel/mcp/tools/todo.go b/kernel/mcp/tools/todo.go
index 6bd9937334..9a2628159a 100644
--- a/kernel/mcp/tools/todo.go
+++ b/kernel/mcp/tools/todo.go
@@ -20,7 +20,7 @@ import (
"fmt"
"strings"
- "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/88250/lute/ast"
)
var TodoWriteTool = &Tool{
@@ -47,6 +47,11 @@ var TodoWriteTool = &Tool{
Handler: todoWriteHandler,
}
+type agentTodoItem struct {
+ Content string
+ Status string
+}
+
func init() {
register(TodoWriteTool)
}
@@ -68,7 +73,7 @@ func todoWriteHandler(args map[string]any) (CallToolResult, error) {
}, nil
}
- todos := make([]model.AgentTodoItem, 0, len(items))
+ todos := make([]agentTodoItem, 0, len(items))
for _, item := range items {
obj, ok := item.(map[string]any)
if !ok {
@@ -82,7 +87,7 @@ func todoWriteHandler(args map[string]any) (CallToolResult, error) {
if status != "pending" && status != "in_progress" && status != "completed" && status != "cancelled" {
status = "pending"
}
- todos = append(todos, model.AgentTodoItem{Content: content, Status: status})
+ todos = append(todos, agentTodoItem{Content: content, Status: status})
}
sessionID, ok := args["_sessionID"].(string)
@@ -92,9 +97,9 @@ func todoWriteHandler(args map[string]any) (CallToolResult, error) {
IsError: true,
}, nil
}
- if err := model.SaveAgentTodos(sessionID, todos); err != nil {
+ if !ast.IsNodeIDPattern(sessionID) {
return CallToolResult{
- Content: []ContentItem{{Type: "text", Text: "todo_write error: " + err.Error()}},
+ Content: []ContentItem{{Type: "text", Text: "todo_write error: invalid Agent session ID"}},
IsError: true,
}, nil
}
@@ -105,7 +110,8 @@ func todoWriteHandler(args map[string]any) (CallToolResult, error) {
}, nil
}
-func formatTodoResult(todos []model.AgentTodoItem) string {
+// formatTodoResult 生成待办展示内容,由会话工具结果统一持久化与恢复。
+func formatTodoResult(todos []agentTodoItem) string {
if len(todos) == 0 {
return "Todo list is empty."
}
diff --git a/kernel/mcp/tools/todo_test.go b/kernel/mcp/tools/todo_test.go
index b08fd4b44f..83619a4802 100644
--- a/kernel/mcp/tools/todo_test.go
+++ b/kernel/mcp/tools/todo_test.go
@@ -1,46 +1,63 @@
-// SiYuan - From thought to insight, with agents
-// 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.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
package tools
-import "testing"
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
func TestTodoWriteRejectsInvalidSessionContext(t *testing.T) {
- tests := []struct {
- name string
- sessionID any
- include bool
- }{
- {name: "missing"},
- {name: "wrong type", sessionID: 1, include: true},
- {name: "invalid ID", sessionID: "..", include: true},
- }
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- args := map[string]any{"todos": []any{}}
- if test.include {
- args["_sessionID"] = test.sessionID
- }
- result, err := todoWriteHandler(args)
- if err != nil {
- t.Fatal(err)
- }
- if !result.IsError {
- t.Fatalf("invalid Agent session context was accepted: %#v", test.sessionID)
- }
- })
+ for _, sessionID := range []any{nil, "", "..", "20261008120000-invalid/child"} {
+ result, err := todoWriteHandler(map[string]any{"_sessionID": sessionID, "todos": []any{}})
+ if err != nil || !result.IsError {
+ t.Fatalf("invalid session context %v was accepted: %+v, %v", sessionID, result, err)
+ }
+ }
+}
+
+func TestTodoWriteReturnsSessionResultWithoutSeparatePersistence(t *testing.T) {
+ previous := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() { util.DataDir = previous })
+ const sessionID = "20261008120000-abcdefg"
+ args := map[string]any{
+ "_sessionID": sessionID,
+ "todos": []any{
+ map[string]any{"content": "Pending", "status": "unknown"},
+ map[string]any{"content": "Working", "status": "in_progress"},
+ map[string]any{"content": "Done", "status": "completed"},
+ map[string]any{"content": "Cancelled", "status": "cancelled"},
+ map[string]any{"content": ""},
+ "invalid",
+ },
+ }
+ want := "Todo List\n\n- [ ] Pending\n- [/] Working\n- [x] Done\n- [-] Cancelled\n"
+ result, err := todoWriteHandler(args)
+ if err != nil || result.IsError || len(result.Content) != 1 || result.Content[0].Text != want {
+ t.Fatalf("unexpected todo result: %+v, %v", result, err)
+ }
+ entries, err := os.ReadDir(util.DataDir)
+ if err != nil || len(entries) != 0 {
+ t.Fatalf("todo_write created separate persistence: %v, %v", entries, err)
+ }
+ // 已有待办文件保留原始内容,不因更新工具结果被改写或删除。
+ path := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", sessionID, "todos.json")
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ const previousTodos = `{"sessionID":"20261008120000-abcdefg","todos":[{"content":"Previous","status":"pending"}]}`
+ if err := os.WriteFile(path, []byte(previousTodos), 0600); err != nil {
+ t.Fatal(err)
+ }
+ args["todos"] = []any{}
+ result, err = todoWriteHandler(args)
+ if err != nil || result.IsError || result.Content[0].Text != "Todo list is empty." {
+ t.Fatalf("empty list: %+v, %v", result, err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil || string(data) != previousTodos {
+ t.Fatalf("existing todo data changed: %q, %v", data, err)
}
}
diff --git a/kernel/model/todo.go b/kernel/model/todo.go
deleted file mode 100644
index c2ffa01483..0000000000
--- a/kernel/model/todo.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// SiYuan - From thought to insight, with agents
-// 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.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-package model
-
-import (
- "encoding/json"
- "errors"
- "os"
- "path/filepath"
-
- "github.com/88250/lute/ast"
- "github.com/siyuan-note/filelock"
- "github.com/siyuan-note/siyuan/kernel/util"
-)
-
-type AgentTodoItem struct {
- Content string `json:"content"`
- Status string `json:"status"` // pending, in_progress, completed, cancelled
-}
-
-type AgentTodoList struct {
- SessionID string `json:"sessionID"`
- Todos []AgentTodoItem `json:"todos"`
-}
-
-func agentTodosPath(sessionID string) string {
- return filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", sessionID, "todos.json")
-}
-
-func SaveAgentTodos(sessionID string, todos []AgentTodoItem) error {
- if !ast.IsNodeIDPattern(sessionID) {
- return errors.New("invalid Agent session ID")
- }
- dir := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", sessionID)
- if err := os.MkdirAll(dir, 0755); err != nil {
- return err
- }
-
- data := AgentTodoList{
- SessionID: sessionID,
- Todos: todos,
- }
-
- b, err := json.Marshal(data)
- if err != nil {
- return err
- }
-
- return filelock.WriteFile(agentTodosPath(sessionID), b)
-}
-
-func LoadAgentTodos(sessionID string) ([]AgentTodoItem, error) {
- if !ast.IsNodeIDPattern(sessionID) {
- return nil, errors.New("invalid Agent session ID")
- }
- path := agentTodosPath(sessionID)
- if _, err := os.Stat(path); os.IsNotExist(err) {
- return nil, nil
- }
-
- b, err := filelock.ReadFile(path)
- if err != nil {
- return nil, err
- }
-
- var data AgentTodoList
- if err := json.Unmarshal(b, &data); err != nil {
- return nil, err
- }
-
- return data.Todos, nil
-}
diff --git a/kernel/model/todo_test.go b/kernel/model/todo_test.go
deleted file mode 100644
index 6db4bccb09..0000000000
--- a/kernel/model/todo_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// SiYuan - From thought to insight, with agents
-// 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.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU Affero General Public License for more details.
-//
-// You should have received a copy of the GNU Affero General Public License
-// along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-package model
-
-import "testing"
-
-func TestAgentTodosRejectInvalidSessionID(t *testing.T) {
- if err := SaveAgentTodos("..", nil); err == nil {
- t.Fatal("invalid Agent session ID was accepted for saving")
- }
- if _, err := LoadAgentTodos(".."); err == nil {
- t.Fatal("invalid Agent session ID was accepted for loading")
- }
-}