An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Correct CLI notebook creation and closed-notebook writes https://github.com/siyuan-note/siyuan/issues/18526
Danielce86663f4deb
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex 65d0e883ea..5c7378d5de 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -79,7 +79,7 @@ var documentCreateCmd = &cobra.Command{id := ast.NewNodeID()docPath := path.Join(dir, id+".sy")if err := model.ValidateCreateDoc(notebook, docPath, title); err != nil {- return err+ return formatNotebookWriteError(notebook, err)}if dryRun {@@ -89,7 +89,7 @@ var documentCreateCmd = &cobra.Command{_, err := model.CreateDocByMd(notebook, docPath, title, markdown, nil, nil)if err != nil {- return err+ return formatNotebookWriteError(notebook, err)}model.AppendPushCreateEntry(notebook, docPath)fmt.Println(id)diff --git a/kernel/cli/cmd/import.go b/kernel/cli/cmd/import.goindex 3e9b414867..3580afa8f8 100644--- a/kernel/cli/cmd/import.go+++ b/kernel/cli/cmd/import.go@@ -56,7 +56,7 @@ var importMdCmd = &cobra.Command{}if err := model.ImportFromLocalPath(notebook, absPath, resolvePath(notebook, toPath, hpath)); err != nil {- return err+ return formatNotebookWriteError(notebook, err)}model.AppendPushReloadFiletreeEntry()fmt.Println("ok")diff --git a/kernel/cli/cmd/notebook.go b/kernel/cli/cmd/notebook.goindex 05e87712fe..0de1154918 100644--- a/kernel/cli/cmd/notebook.go+++ b/kernel/cli/cmd/notebook.go@@ -18,6 +18,7 @@ package cmdimport ("encoding/json"+ "errors""fmt""math/rand""os"@@ -77,12 +78,25 @@ var notebookCreateCmd = &cobra.Command{if err != nil {return err}+ if _, err = model.Mount(id); err != nil {+ return fmt.Errorf("notebook [%s] was created but could not be opened: %w", id, err)+ }model.AppendPushReloadFiletreeEntry()fmt.Println(id)return nil},}+func formatNotebookWriteError(boxID string, err error) error {+ if errors.Is(err, model.ErrBoxClosed) {+ return fmt.Errorf("notebook [%s] is closed; run `notebook open --id %s` first", boxID, boxID)+ }+ if errors.Is(err, model.ErrBoxNotFound) {+ return fmt.Errorf("notebook [%s] not found", boxID)+ }+ return err+}+var notebookRemoveCmd = &cobra.Command{Use: "remove --id <id>",Short: "Remove a notebook",diff --git a/kernel/cli/cmd/notebook_test.go b/kernel/cli/cmd/notebook_test.gonew file mode 100644index 0000000000..de31c9a6a0--- /dev/null+++ b/kernel/cli/cmd/notebook_test.go@@ -0,0 +1,43 @@+// 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.+//+// 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 cmd++import (+ "errors"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestFormatNotebookWriteError(t *testing.T) {+ boxID := "20260803000000-abcdefg"+ closedErr := formatNotebookWriteError(boxID, model.ErrBoxClosed)+ if !strings.Contains(closedErr.Error(), "notebook open --id "+boxID) {+ t.Fatalf("closed notebook error does not include the open command: %v", closedErr)+ }++ notFoundErr := formatNotebookWriteError(boxID, model.ErrBoxNotFound)+ if got, want := notFoundErr.Error(), "notebook ["+boxID+"] not found"; got != want {+ t.Fatalf("unexpected missing notebook error: got %q, want %q", got, want)+ }++ otherErr := errors.New("other error")+ if got := formatNotebookWriteError(boxID, otherErr); got != otherErr {+ t.Fatalf("unexpected unrelated error replacement: got %v, want %v", got, otherErr)+ }+}diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.goindex 5558aaa3c1..54e6b815e1 100644--- a/kernel/mcp/tools/notebook.go+++ b/kernel/mcp/tools/notebook.go@@ -96,12 +96,18 @@ func notebookCreate(args map[string]any) (CallToolResult, error) {if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "create notebook failed: " + err.Error()}}, IsError: true}, nil}+ existed, err := model.Mount(id)+ if err != nil {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("notebook created but opening failed: %s (id: %s)", err, id)}}, IsError: true}, nil+ }- if box := model.Conf.Box(id); nil != box {- evt := util.NewCmdResult("createnotebook", 0, util.PushModeBroadcast)- evt.Data = map[string]any{"box": box}- util.PushEvent(evt)+ box := model.Conf.Box(id)+ if nil == box {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook created but opened notebook not found: " + id}}, IsError: true}, nil}+ evt := util.NewCmdResult("createnotebook", 0, util.PushModeBroadcast)+ evt.Data = map[string]any{"box": box, "existed": existed}+ util.PushEvent(evt)return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook created: " + name + " (id: " + id + ")"}}}, nil}diff --git a/kernel/model/file.go b/kernel/model/file.goindex a8e0ff2063..bcaf7d9217 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1283,9 +1283,8 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string, arg map[string]ancreateDocLock.Lock()defer createDocLock.Unlock()- box := Conf.Box(boxID)- if nil == box {- err = errors.New(Conf.Language(0))+ box, err := getOpenedBox(boxID)+ if nil != err {return}@@ -2215,9 +2214,9 @@ func validateCreateDoc(boxID, p, title string, titleEmpty bool) (ret *createDocVreturn nil, errors.New(Conf.Language(13))}- box := Conf.Box(boxID)- if nil == box {- return nil, errors.New(Conf.Language(0))+ box, boxErr := getOpenedBox(boxID)+ if nil != boxErr {+ return nil, boxErr}folder := path.Dir(p)diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex 40df2b9ed5..41790228ba 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -145,6 +145,20 @@ func TestValidateCreateDocDoesNotWrite(t *testing.T) {}}+func TestValidateCreateDocReportsClosedNotebook(t *testing.T) {+ fixture := setupFileOperationTest(t)+ boxConf := fixture.box.GetConf()+ boxConf.Closed = true+ if err := fixture.box.SaveConf(boxConf); err != nil {+ t.Fatalf("close test notebook failed: %v", err)+ }++ err := ValidateCreateDoc(fixture.box.ID, "/20260718000003-abcdefg.sy", "Closed notebook document")+ if !errors.Is(err, ErrBoxClosed) {+ t.Fatalf("expected closed notebook to return ErrBoxClosed, got [%v]", err)+ }+}+func TestGetBoxesByPathsStrictRejectsInvalidPaths(t *testing.T) {fixture := setupFileOperationTest(t)tests := []struct {diff --git a/kernel/model/import.go b/kernel/model/import.goindex 4afd10eeaf..6c5c99d186 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -1171,6 +1171,10 @@ func ImportData(zipPath string) (err error) {}func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {+ box, err := getOpenedBox(boxID)+ if nil != err {+ return err+ }toPath = normalizeBoxDocTarget(boxID, toPath)util.PushEndlessProgress(Conf.Language(73))defer func() {@@ -1623,7 +1627,6 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {convertWikiLinksAndTags()mergeTextAndHandlerNestedInlines()- box := Conf.Box(boxID)for i, tree := range importTrees {indexWriteTreeIndexQueue(tree)if 0 == i%4 {diff --git a/kernel/model/import_test.go b/kernel/model/import_test.goindex afbbda4f8b..ed26010e5b 100644--- a/kernel/model/import_test.go+++ b/kernel/model/import_test.go@@ -16,7 +16,14 @@package model-import "testing"+import (+ "errors"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)func TestIsSYNotebookExport(t *testing.T) {tests := []struct {@@ -39,6 +46,37 @@ func TestIsSYNotebookExport(t *testing.T) {}}+func TestImportFromLocalPathRejectsClosedNotebookBeforeWriting(t *testing.T) {+ fixture := setupFileOperationTest(t)+ boxConf := fixture.box.GetConf()+ boxConf.Closed = true+ if err := fixture.box.SaveConf(boxConf); err != nil {+ t.Fatalf("close test notebook failed: %v", err)+ }++ markdownPath := filepath.Join(t.TempDir(), "document.md")+ if err := os.WriteFile(markdownPath, []byte("# Document"), 0644); err != nil {+ t.Fatalf("write Markdown fixture failed: %v", err)+ }+ pattern := filepath.Join(util.DataDir, fixture.box.ID, "*.sy")+ before, err := filepath.Glob(pattern)+ if err != nil {+ t.Fatalf("list documents before import failed: %v", err)+ }++ err = ImportFromLocalPath(fixture.box.ID, markdownPath, "/")+ if !errors.Is(err, ErrBoxClosed) {+ t.Fatalf("expected closed notebook import to return ErrBoxClosed, got [%v]", err)+ }+ after, err := filepath.Glob(pattern)+ if err != nil {+ t.Fatalf("list documents after import failed: %v", err)+ }+ if len(after) != len(before) {+ t.Fatalf("closed notebook import wrote documents: before=%d, after=%d", len(before), len(after))+ }+}+func TestReplaceAssetNamePreservesExistingQuery(t *testing.T) {assetNameMap := map[string]string{"document.pdf": "encrypted.pdf"}boxSuffix := "?box=20260731190414-j45dgmm"diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex 447074c37d..5d108d7643 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -47,6 +47,16 @@ func GetBoxByName(name string) (ret *Box) {return}+func getOpenedBox(boxID string) (ret *Box, err error) {+ if ret = Conf.Box(boxID); nil != ret {+ return+ }+ if nil != Conf.GetBox(boxID) {+ return nil, ErrBoxClosed+ }+ return nil, ErrBoxNotFound+}+func CreateBox(name string) (id string, err error) {return createBox(name, true)}diff --git a/kernel/model/tree.go b/kernel/model/tree.goindex c737c77aa2..fae835a7a4 100644--- a/kernel/model/tree.go+++ b/kernel/model/tree.go@@ -200,6 +200,7 @@ func loadTreeByData(localPath string, data []byte, luteEngine *lute.Lute) (ret *var (ErrBoxNotFound = errors.New("notebook not found")+ ErrBoxClosed = errors.New("notebook closed")ErrBlockNotFound = errors.New("block not found")ErrTreeNotFound = errors.New("tree not found")ErrIndexing = errors.New("indexing")