Skip to content

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

:bug: Preserve asset references and report rename failures https://github.com/siyuan-note/siyuan/issues/20344

Danielc76956e48a06
diff --git a/app/src/editor/rename.test.ts b/app/src/editor/rename.test.ts
new file mode 100644
index 0000000000..063b3c843d
--- /dev/null
+++ b/app/src/editor/rename.test.ts
@@ -0,0 +1,41 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import * as path from "node:path";
+import {test} from "node:test";
+import {ScriptTarget, transpileModule} from "typescript";
+
+test("failed asset rename keeps the dialog open and does not update or reload editors", async () => {
+ const source = transpileModule(readFileSync(path.resolve(__dirname, "rename.ts"), "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),
+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
+ const oldWindow = globalThis.window;
+ Object.defineProperty(globalThis, "window", {configurable: true, writable: true,
+ value: {siyuan: {languages: {rename: "Rename", renameAssetTip: "Updates links"}}}});
+ let options: {onConfirm: (value: string, activeDialog: typeof dialog) => Promise<void>};
+ let closes = 0;
+ let updates = 0;
+ let reloads = 0;
+ const dialog = {element: {setAttribute: () => {}}, destroy: () => closes++};
+ const assetPath = "assets/missing.pdf?box=20261009000001-abcdefg#x";
+ const renameAsset = new Function("getAssetName", "openInputDialog", "Constants", "fetchSyncPost", "getAllModels", "getAllEditor",
+ source + "\nreturn renameAsset;")(() => "missing",
+ (value: typeof options) => { options = value; return dialog; }, {},
+ async (url: string, body: {oldPath: string, newName: string}) => {
+ assert.equal(url, "/api/asset/renameAsset");
+ assert.deepEqual(body, {oldPath: assetPath, newName: "renamed"});
+ return {code: -1, msg: "Asset is missing", data: {closeTimeout: 5000}};
+ }, () => ({asset: [{path: assetPath, update: () => updates++}]}), () => [{reload: () => reloads++}]);
+ try {
+ renameAsset(assetPath);
+ await options.onConfirm("renamed", dialog);
+ assert.equal(closes, 0);
+ assert.equal(updates, 0);
+ assert.equal(reloads, 0);
+ } finally {
+ if (oldWindow) {
+ globalThis.window = oldWindow;
+ } else {
+ delete globalThis.window;
+ }
+ }
+});
diff --git a/kernel/api/asset_rename_test.go b/kernel/api/asset_rename_test.go
new file mode 100644
index 0000000000..a1a48f2167
--- /dev/null
+++ b/kernel/api/asset_rename_test.go
@@ -0,0 +1,37 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func TestRenameAssetMissingSourceContract(t *testing.T) {
+ setupAssetContractWorkspace(t)
+ model.Conf.FileTree = conf.NewFileTree()
+ engine := gin.New()
+ engine.POST("/api/asset/renameAsset", renameAsset)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/renameAsset",
+ strings.NewReader(`{"oldPath":"assets/missing-20261009000001-abcdefg.pdf?page=2#x","newName":"renamed"}`)))
+ requireAPIContract(t, "POST", "/api/asset/renameAsset", recorder)
+ var response struct {
+ Code int
+ Msg string
+ Data struct {
+ CloseTimeout int `json:"closeTimeout"`
+ NewPath string `json:"newPath"`
+ }
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != -1 || response.Msg == "" || response.Data.CloseTimeout != 5000 || response.Data.NewPath != "" {
+ t.Fatalf("missing source reported success or omitted error prompt: %s", recorder.Body.String())
+ }
+}
diff --git a/kernel/apicontract/asset.go b/kernel/apicontract/asset.go
index a42673ce1e..86e8cd9fa8 100644
--- a/kernel/apicontract/asset.go
+++ b/kernel/apicontract/asset.go
@@ -21,6 +21,9 @@ type SetAssetOCRTextRequest struct {
Text string `json:"text"`
}
+// RenameAssetRequest 重命名普通笔记本资源,并同步字面量及百分号编码的文档、数据库引用。
+// 引用及成功返回的 newPath 保留查询参数和片段;源资源解析失败返回 -1 和 5000 毫秒错误提示。
+// 加密笔记本资源仍拒绝重命名;空名称或与原文件名相同的名称保留成功但 newPath 为空的响应。
type RenameAssetRequest struct {
OldPath string `json:"oldPath"`
NewName string `json:"newName"`
diff --git a/kernel/model/asset_rename_test.go b/kernel/model/asset_rename_test.go
new file mode 100644
index 0000000000..c662775186
--- /dev/null
+++ b/kernel/model/asset_rename_test.go
@@ -0,0 +1,164 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/url"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestRenameAssetReferences(t *testing.T) {
+ const childEnv = "SIYUAN_TEST_ASSET_RENAME"
+ if os.Getenv(childEnv) == "" {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestRenameAssetReferences$", "-test.timeout=60s")
+ cmd.Env = append(os.Environ(), childEnv+"=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("%v\n%s", err, output)
+ }
+ return
+ }
+ fixture := setupFileOperationTest(t)
+ setupAttributeViewRefI18n(t)
+ util.WorkspaceDir = filepath.Dir(util.DataDir)
+ util.ConfDir = t.TempDir()
+ util.HistoryDir, util.TempDir = t.TempDir(), t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ sql.InitDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ sql.InitHistoryDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ if newPath, err := RenameAsset("assets/missing.pdf", "renamed"); err == nil || newPath != "" {
+ t.Fatalf("missing asset must fail without a new path: %s %v", newPath, err)
+ }
+
+ for _, test := range []struct {
+ name, id, suffix string
+ boxAsset bool
+ }{
+ {"global", "20261009000001-abcdefg", "", false},
+ {"fragment", "20261009000002-abcdefg", "#annotation", false},
+ {"query", "20261009000003-abcdefg", "?page=2#annotation", false},
+ {"notebook", "20261009000004-abcdefg", "?box=" + fixture.box.ID + "&page=2#annotation", true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ oldPath := "assets/习题-" + test.id + ".pdf"
+ assetDiskPath := oldPath
+ if test.boxAsset {
+ assetDiskPath = fixture.box.ID + "/" + oldPath
+ }
+ writeAssetRelinkTestFile(t, assetDiskPath, []byte("PDF content"))
+ writeAssetRelinkTestFile(t, assetDiskPath+".sya", []byte(`{"annotation":"content"}`))
+ util.SetAssetText(oldPath, "OCR content")
+ encodedPath := (&url.URL{Path: oldPath}).EscapedPath()
+ hrefs := []string{oldPath + test.suffix, encodedPath + test.suffix, encodedPath + "?page=9#other"}
+ tree := treenode.NewTree(fixture.box.ID, "/"+test.id+".sy", "/References", "References")
+ for _, href := range hrefs {
+ p := treenode.NewParagraph(ast.NewNodeID())
+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkAHref: href, TextMarkTextContent: href})
+ tree.Root.AppendChild(p)
+ }
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ t.Cleanup(func() { cache.RemoveTreeData(tree.ID) })
+ avPath := filepath.Join(util.DataDir, "storage", "av", test.id+".json")
+ avData, _ := json.Marshal(map[string]interface{}{"paths": hrefs, "text": path.Base(oldPath)})
+ writeAssetRelinkTestFile(t, "storage/av/"+test.id+".json", avData)
+
+ newPath, err := RenameAsset(oldPath+test.suffix, "习题2")
+ if err != nil || newPath == "" {
+ t.Fatalf("rename failed: %s %v", newPath, err)
+ }
+ newCleanPath := strings.TrimSuffix(newPath, test.suffix)
+ if newPath != newCleanPath+test.suffix || !strings.HasPrefix(newCleanPath, "assets/习题2-") {
+ t.Fatalf("unexpected renamed URL: %s", newPath)
+ }
+ newDiskPath := filepath.Join(filepath.Dir(filepath.Join(util.DataDir, assetDiskPath)), path.Base(newCleanPath))
+ for _, suffix := range []string{"", ".sya"} {
+ data, readErr := os.ReadFile(newDiskPath + suffix)
+ if readErr != nil || len(data) == 0 {
+ t.Fatalf("renamed file %s: %s %v", suffix, data, readErr)
+ }
+ if _, statErr := os.Stat(filepath.Join(util.DataDir, assetDiskPath) + suffix); !os.IsNotExist(statErr) {
+ t.Fatalf("old file remains: %v", statErr)
+ }
+ }
+ loaded, err := filesys.LoadTree(fixture.box.ID, tree.Path, util.NewLute())
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{newCleanPath + test.suffix, (&url.URL{Path: newCleanPath}).EscapedPath() + test.suffix,
+ (&url.URL{Path: newCleanPath}).EscapedPath() + "?page=9#other"}
+ var got []string
+ ast.Walk(loaded.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && n.IsTextMarkType("a") {
+ got = append(got, n.TextMarkAHref)
+ if n.TextMarkTextContent != n.TextMarkAHref {
+ t.Errorf("link label was not updated: %s", n.TextMarkTextContent)
+ }
+ }
+ return ast.WalkContinue
+ })
+ if strings.Join(got, "\n") != strings.Join(want, "\n") {
+ t.Fatalf("document references: %v, want %v", got, want)
+ }
+ updated, err := os.ReadFile(avPath)
+ wantAV, _ := json.Marshal(map[string]interface{}{"paths": want, "text": path.Base(oldPath)})
+ if err != nil || !bytes.Equal(updated, wantAV) {
+ t.Fatalf("database references: %s, want %s: %v", updated, wantAV, err)
+ }
+ if util.GetAssetText(newCleanPath) != "OCR content" {
+ t.Fatal("OCR metadata was not preserved")
+ }
+ })
+ }
+ const encryptedBox = "20261009000005-crypt00"
+ writeAssetRelinkTestFile(t, encryptedBox+"/.siyuan/conf.json", []byte(`{"encrypted":true}`))
+ writeAssetRelinkTestFile(t, encryptedBox+"/assets/secret.pdf", []byte("encrypted asset fixture"))
+ t.Cleanup(func() { forgetRuntimeEncryptedBox(encryptedBox) })
+ if newPath, err := RenameAsset("assets/secret.pdf?box="+encryptedBox+"#x", "renamed"); err == nil || newPath != "" {
+ t.Fatalf("encrypted asset rename must fail without a new path: %s %v", newPath, err)
+ }
+ data, err := os.ReadFile(filepath.Join(util.DataDir, encryptedBox, "assets", "secret.pdf"))
+ if err != nil || string(data) != "encrypted asset fixture" {
+ t.Fatalf("encrypted asset changed: %s %v", data, err)
+ }
+}
+
+func TestRenameAssetAttributeViewEncodedPath(t *testing.T) {
+ const oldPath = "assets/习题-20261009000001-abcdefg.pdf"
+ const newPath = "assets/习题2-20261009000002-abcdefg.pdf"
+ const avID = "20261009000003-abcdefg"
+ avPath := filepath.Join(t.TempDir(), avID+".json")
+ data, _ := json.Marshal([]string{oldPath + "?page=2#x", (&url.URL{Path: oldPath}).EscapedPath() + "?page=3#y", path.Base(oldPath)})
+ if err := os.WriteFile(avPath, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ updated, err := replaceAttributeViewAssetPath(avPath, avID, oldPath+"?page=1#z", newPath+"?page=1#z")
+ if err != nil || !updated {
+ t.Fatalf("rewrite database: %v %v", updated, err)
+ }
+ got, err := os.ReadFile(avPath)
+ want, _ := json.Marshal([]string{newPath + "?page=2#x", (&url.URL{Path: newPath}).EscapedPath() + "?page=3#y", path.Base(oldPath)})
+ if err != nil || !bytes.Equal(got, want) {
+ t.Fatalf("database references: %s, want %s: %v", got, want, err)
+ }
+}
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 6acd1aa2c4..1f1c1f174c 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -1755,14 +1755,33 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
util.PushEndlessProgress(Conf.Language(110))
defer util.PushClearProgress()
+ oldPath = strings.TrimSpace(oldPath)
+ suffix := ""
+ if idx := strings.IndexAny(oldPath, "?#"); idx >= 0 {
+ suffix = oldPath[idx:]
+ }
+ defer func() {
+ if err != nil {
+ newPath = ""
+ } else if newPath != "" {
+ newPath += suffix
+ }
+ }()
+ // 片段不参与磁盘路径解析,查询参数中的 box 仍用于定位笔记本。
+ if idx := strings.Index(oldPath, "#"); idx >= 0 {
+ oldPath = oldPath[:idx]
+ }
oldCleanPath := AssetPathWithoutQuery(oldPath)
+ oldAbsPath, err := GetAssetAbsPathInBox(oldPath, "")
+ if err != nil {
+ logging.LogErrorf("get asset [%s] abs path failed: %s", oldPath, err)
+ return
+ }
// 加密笔记本的资源磁盘文件名参与 AAD,重命名需要重新封装密文,当前不支持。
- if absPath, absErr := GetAssetAbsPathInBox(oldPath, ""); absErr == nil {
- if IsEncryptedAssetPath(absPath) {
- err = errors.New("renaming assets in encrypted notebooks is not supported")
- return
- }
+ if IsEncryptedAssetPath(oldAbsPath) {
+ err = errors.New("renaming assets in encrypted notebooks is not supported")
+ return
}
newName = strings.TrimSpace(newName)
@@ -1782,11 +1801,6 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
newName = util.AssetName(newName+filepath.Ext(oldCleanPath), ast.NewNodeID())
parentDir := path.Dir(oldCleanPath)
newPath = path.Join(parentDir, newName)
- oldAbsPath, getErr := GetAssetAbsPathInBox(oldPath, "")
- if getErr != nil {
- logging.LogErrorf("get asset [%s] abs path failed: %s", oldPath, getErr)
- return
- }
if err = ensureReadableAssetLocal(oldAbsPath); err != nil {
return
}
@@ -1801,11 +1815,11 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
}
filelock.Unlock(oldAbsPath)
- oldSya := filepath.Join(util.DataDir, oldPath+".sya")
+ oldSya := oldAbsPath + ".sya"
filelock.Lock(oldSya)
if gulu.File.IsExist(oldSya) {
// Rename the .sya annotation file when renaming a PDF asset https://github.com/siyuan-note/siyuan/issues/9390
- newSya := filepath.Join(util.DataDir, newPath+".sya")
+ newSya := newAbsPath + ".sya"
if err = os.Rename(oldSya, newSya); err != nil {
if err = gulu.File.Copy(oldSya, newSya); err != nil {
filelock.Unlock(oldSya)
@@ -1816,7 +1830,10 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
}
filelock.Unlock(oldSya)
- oldName := path.Base(oldPath)
+ oldName := path.Base(oldCleanPath)
+ oldNameBytes := []byte(oldName)
+ escapedOldNameBytes := []byte((&url.URL{Path: oldName}).EscapedPath())
+ nameReplacer := newAssetRenameReplacer(oldName, newName)
notebooks, err := ListNotebooks()
if err != nil {
@@ -1845,11 +1862,11 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
return
}
- if !bytes.Contains(data, []byte(oldName)) {
+ if !bytes.Contains(data, oldNameBytes) && !bytes.Contains(data, escapedOldNameBytes) {
continue
}
- data = bytes.Replace(data, []byte(oldName), []byte(newName), -1)
+ data = []byte(nameReplacer.Replace(string(data)))
if writeErr := filelock.WriteFile(treeAbsPath, data); nil != writeErr {
logging.LogErrorf("write data [path=%s] failed: %s", treeAbsPath, writeErr)
err = writeErr
@@ -1890,7 +1907,7 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
}
avJSONPath := filepath.Join(storageAvDir, entry.Name())
- if _, replaceErr := replaceAttributeViewAssetPath(avJSONPath, avID, oldPath, newPath); nil != replaceErr {
+ if _, replaceErr := replaceAttributeViewAssetPath(avJSONPath, avID, oldCleanPath, newPath); nil != replaceErr {
logging.LogErrorf("replace asset path in attribute view [%s] failed: %s", entry.Name(), replaceErr)
err = replaceErr
return
@@ -1900,7 +1917,7 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
}
}
- if ocrText := util.GetAssetText(oldPath); "" != ocrText {
+ if ocrText := util.GetAssetText(oldCleanPath); "" != ocrText {
// 图片重命名后 ocr-texts.json 需要更新 https://github.com/siyuan-note/siyuan/issues/12974
util.SetAssetText(newPath, ocrText)
}
@@ -1909,13 +1926,31 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
return
}
+// newAssetRenameReplacer 同时替换字面量和百分号编码形式,保留引用的路径前缀、查询参数和片段。
+func newAssetRenameReplacer(oldValue, newValue string) *strings.Replacer {
+ pairs := []string{oldValue, newValue}
+ if escapedOld := (&url.URL{Path: oldValue}).EscapedPath(); escapedOld != oldValue {
+ pairs = append(pairs, escapedOld, (&url.URL{Path: newValue}).EscapedPath())
+ }
+ return strings.NewReplacer(pairs...)
+}
+
func replaceAttributeViewAssetPath(avJSONPath, avID, oldPath, newPath string) (updated bool, err error) {
data, err := filelock.ReadFile(avJSONPath)
- if nil != err || !bytes.Contains(data, []byte(oldPath)) {
+ if nil != err {
return
}
- data = bytes.ReplaceAll(data, []byte(oldPath), []byte(newPath))
+ oldPath = strings.SplitN(AssetPathWithoutQuery(oldPath), "#", 2)[0]
+ newPath = strings.SplitN(AssetPathWithoutQuery(newPath), "#", 2)[0]
+ if oldPath == "" || oldPath == newPath {
+ return
+ }
+ replacedData := []byte(newAssetRenameReplacer(oldPath, newPath).Replace(string(data)))
+ if bytes.Equal(data, replacedData) {
+ return
+ }
+ data = replacedData
if err = filelock.WriteFile(avJSONPath, data); nil != err {
return
}