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: Complete TIFF preview integration https://github.com/siyuan-note/siyuan/issues/20764
Daniel0c2e5ff664b9
diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 8dceece046..524ddf2b1b 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -62,6 +62,7 @@ import ("github.com/siyuan-note/siyuan/kernel/heif""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/task"+ "github.com/siyuan-note/siyuan/kernel/tiffpreview""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util""github.com/studio-b12/gowebdav"@@ -483,8 +484,7 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText bcontent = gulu.Str.FromBytes(data)} else {if strings.Contains(file.Path, "assets/") { // 剔除笔记本级或者文档级资源文件路径前缀- // 加密 notebook 的 asset 在仓库里是密文,不解密直接写临时目录会泄漏密文- // 先用原始 path 检测是否加密 box,再裁剪 file.Path 到 assets/ 前缀+ // 先按原始路径确定加密笔记本身份并认证,再整理资源路径用于预览。repoBoxID := ""origPath := strings.TrimPrefix(file.Path, "/")if parts := strings.SplitN(origPath, "/", 2); len(parts) >= 1 && ast.IsNodeIDPattern(parts[0]) {@@ -503,7 +503,12 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText bplainData, decErr := DecryptAsset(repoBoxID, diskName, dek, data)clear(dek)if decErr == nil {- data = plainData+ if tiffpreview.IsPath(file.Path) {+ // TIFF 快照经认证后仍暂存原密文,HTTP 预览和下载在请求内存中解密。+ clear(plainData)+ } else {+ data = plainData+ }} else {logging.LogWarnf("decrypt repo snapshot asset [%s] failed: %s", file.Path, decErr)err = decErrdiff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 4d66634432..c7fd2dbbd5 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -1260,7 +1260,7 @@ func serveAssets(ginServer *gin.Engine) {return}if transcodeTIFF {- servePlainTIFFPreview(context, p, false)+ servePlainTIFFPreview(context, p)return}if transcodeHEIF {@@ -1761,6 +1761,7 @@ func serveRepoDiff(ginServer *gin.Engine) {// 从路径提取 boxID,加密笔记本已锁定时拒绝访问(锁定后 repo 预览解密文件仍存在磁盘上)parts := strings.SplitN(strings.TrimPrefix(requestPath, "/"), "/", 2)encryptedBoxID := ""+ var tiffDEK []byteif len(parts) >= 1 && model.IsEncryptedBox(parts[0]) {encryptedBoxID = parts[0]setEncryptedAssetCacheHeaders(context)@@ -1776,15 +1777,24 @@ func serveRepoDiff(ginServer *gin.Engine) {context.Status(http.StatusForbidden)return}- clear(dek)+ if tiffpreview.IsPath(requestPath) {+ tiffDEK = dek+ defer clear(tiffDEK)+ } else {+ clear(dek)+ }}p := filepath.Join(repoDiffBaseDir, filepath.FromSlash(strings.TrimPrefix(requestPath, "/")))if !gulu.File.IsSubPath(repoDiffBaseDir, p) {context.Status(http.StatusUnauthorized)return}+ if encryptedBoxID != "" && tiffpreview.IsPath(p) {+ serveTIFFBytes(context, p, encryptedBoxID, tiffDEK, transcodeTIFF)+ return+ }if transcodeTIFF {- servePlainTIFFPreview(context, p, encryptedBoxID != "")+ servePlainTIFFPreview(context, p)return}if transcodeHEIF {diff --git a/kernel/server/serve_tiff.go b/kernel/server/serve_tiff.goindex 77c9268317..7ee3d8a69a 100644--- a/kernel/server/serve_tiff.go+++ b/kernel/server/serve_tiff.go@@ -47,11 +47,26 @@ func serveTIFFPreview(c *gin.Context, path string) {}defer clear(dek)}+ if !encrypted {+ boxID = ""+ }+ serveTIFFBytes(c, path, boxID, dek, true)+}++// serveTIFFBytes 读取 TIFF 原件,按请求输出预览或原件;调用方持有加密笔记本的租约和读锁。+func serveTIFFBytes(c *gin.Context, path, boxID string, dek []byte, preview bool) {+ encrypted := boxID != ""limit := int64(tiffpreview.MaxInputBytes)if encrypted {limit += 2 * 1024 * 1024}- source, err := tiffpreview.ReadFileLimited(path, limit)+ var source []byte+ var err error+ if preview {+ source, err = tiffpreview.ReadFileLimited(path, limit)+ } else {+ source, err = os.ReadFile(path)+ }if err != nil {tiffPreviewError(c, err)return@@ -66,20 +81,17 @@ func serveTIFFPreview(c *gin.Context, path string) {source = decrypteddefer clear(source)}- writeTIFFPreview(c, source, encrypted)-}--// servePlainTIFFPreview 处理普通历史文件或已解密的快照预览;加密来源不写入预览缓存。-func servePlainTIFFPreview(c *gin.Context, path string, encrypted bool) {- source, err := tiffpreview.ReadFileLimited(path, tiffpreview.MaxInputBytes)- if err != nil {- tiffPreviewError(c, err)+ if preview {+ writeTIFFPreview(c, source, encrypted)return}- if encrypted {- defer clear(source)- }- writeTIFFPreview(c, source, encrypted)+ secureAssetContentHeaders(c, path, path)+ c.Data(http.StatusOK, "image/tiff", source)+}++// servePlainTIFFPreview 处理普通历史文件或快照预览。+func servePlainTIFFPreview(c *gin.Context, path string) {+ serveTIFFBytes(c, path, "", nil, true)}func writeTIFFPreview(c *gin.Context, source []byte, encrypted bool) {diff --git a/kernel/server/serve_tiff_encrypted_test.go b/kernel/server/serve_tiff_encrypted_test.goindex 6356680686..3e5ae0e72c 100644--- a/kernel/server/serve_tiff_encrypted_test.go+++ b/kernel/server/serve_tiff_encrypted_test.go@@ -46,7 +46,7 @@ func TestServeTIFFEncryptedLifecycle(t *testing.T) {}return}- root := t.TempDir()+ root := filepath.Join(t.TempDir(), "notes#1")util.WorkspaceDir = rootutil.DataDir, util.TempDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "conf"), filepath.Join(root, "history")util.QueueDir = filepath.Join(util.TempDir, "queue")@@ -91,7 +91,12 @@ func TestServeTIFFEncryptedLifecycle(t *testing.T) {historyPath := filepath.Join(util.HistoryDir, "2026-10-21-120000-update", boxID, "assets", "preview.tif")writeTIFFTestFile(t, assetPath, ciphertext)writeTIFFTestFile(t, historyPath, ciphertext)- writeTIFFTestFile(t, filepath.Join(util.TempDir, "repo", "diff", boxID, "assets", "preview.tif"), source)+ repoPath := filepath.ToSlash(filepath.Join(boxID, "assets", "preview.tif"))+ previews := openTIFFSnapshots(t, repoPath)+ stagedPath := filepath.Join(util.TempDir, "repo", "diff", filepath.FromSlash(repoPath))+ if staged, err := os.ReadFile(stagedPath); err != nil || !bytes.Equal(staged, ciphertext) {+ t.Fatalf("encrypted snapshot did not preserve ciphertext: %v", err)+ }engine := gin.New()engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator); c.Next() })serveAssets(engine)@@ -99,7 +104,7 @@ func TestServeTIFFEncryptedLifecycle(t *testing.T) {urls := []string{"/assets/preview.tif?box=" + boxID,"/history/2026-10-21-120000-update/" + boxID + "/assets/preview.tif?box=" + boxID,- "/repo/diff/" + boxID + "/assets/preview.tif?box=" + boxID,+ previews[repoPath] + "?box=" + boxID,}for _, url := range urls {for _, query := range []string{"", "&style=thumb", "&download=true"} {@@ -120,7 +125,7 @@ func TestServeTIFFEncryptedLifecycle(t *testing.T) {if _, err := os.Stat(filepath.Join(util.TempDir, "assets-cache", "tiff")); !os.IsNotExist(err) {t.Fatal("encrypted TIFF preview leaked to disk cache")}- for _, path := range []string{assetPath, historyPath} {+ for _, path := range []string{assetPath, historyPath, stagedPath} {before, _ := os.ReadFile(path)if !bytes.Equal(before, ciphertext) {t.Fatal("preview modified ciphertext")@@ -129,7 +134,7 @@ func TestServeTIFFEncryptedLifecycle(t *testing.T) {corrupt[len(corrupt)-1] ^= 1writeTIFFTestFile(t, path, corrupt)}- for _, url := range urls[:2] {+ for _, url := range urls {recorder := httptest.NewRecorder()engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, url, nil))if recorder.Code != http.StatusInternalServerError {@@ -138,6 +143,7 @@ func TestServeTIFFEncryptedLifecycle(t *testing.T) {}writeTIFFTestFile(t, assetPath, ciphertext)writeTIFFTestFile(t, historyPath, ciphertext)+ writeTIFFTestFile(t, stagedPath, ciphertext)writer := &tiffBlockedWriter{ResponseRecorder: httptest.NewRecorder(), ready: make(chan struct{}), release: make(chan struct{})}var release sync.Oncedefer release.Do(func() { close(writer.release) })diff --git a/kernel/server/serve_tiff_test.go b/kernel/server/serve_tiff_test.goindex 734353dda2..0663856c11 100644--- a/kernel/server/serve_tiff_test.go+++ b/kernel/server/serve_tiff_test.go@@ -9,9 +9,13 @@ import ("net/http/httptest""os""path/filepath"+ "strings""testing""github.com/gin-gonic/gin"+ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/dejavu/entity"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/tiffpreview""github.com/siyuan-note/siyuan/kernel/util"@@ -35,13 +39,16 @@ func tiffTestEngine(t *testing.T) *gin.Engine {t.Helper()originalData, originalTemp, originalHistory, originalConf := util.DataDir, util.TempDir, util.HistoryDir, model.ConforiginalWorkspace := util.WorkspaceDir- root := t.TempDir()+ originalRepo, originalConfDir := util.RepoDir, util.ConfDir+ root := filepath.Join(t.TempDir(), "notes#1")util.WorkspaceDir = rootutil.DataDir, util.TempDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "history")+ util.RepoDir, util.ConfDir = filepath.Join(root, "repo"), filepath.Join(root, "conf")model.Conf = model.NewAppConf()t.Cleanup(func() {util.DataDir, util.TempDir, util.HistoryDir, model.Conf = originalData, originalTemp, originalHistory, originalConfutil.WorkspaceDir = originalWorkspace+ util.RepoDir, util.ConfDir = originalRepo, originalConfDir})engine := gin.New()engine.Use(func(c *gin.Context) {@@ -53,6 +60,97 @@ func tiffTestEngine(t *testing.T) *gin.Engine {return engine}+// openTIFFSnapshots 从真实仓库文件元数据走快照预览生产链路,不预先构造临时预览文件。+func openTIFFSnapshots(t *testing.T, paths ...string) map[string]string {+ t.Helper()+ model.Conf.Repo.Store(conf.NewRepo())+ model.Conf.Repo.Load().Key = []byte("0123456789abcdef0123456789abcdef")+ if model.Conf.System.Load() == nil {+ model.Conf.System.Store(conf.NewSystem())+ }+ if model.Conf.Sync.Load() == nil {+ model.Conf.Sync.Store(conf.NewSync())+ }+ model.Conf.Sync.Load().Provider = conf.ProviderLocal+ model.Conf.Sync.Load().Local = &conf.Local{Endpoint: filepath.Join(util.WorkspaceDir, "cloud")}+ model.Conf.Sync.Load().CloudName = "tiff-test"+ util.RepoDir = filepath.Join(util.WorkspaceDir, "repo")+ for _, directory := range []string{util.ConfDir, util.TempDir, util.HistoryDir} {+ if err := os.MkdirAll(directory, 0700); err != nil {+ t.Fatal(err)+ }+ }+ repo, err := dejavu.NewRepo(util.DataDir, util.RepoDir, util.HistoryDir, util.TempDir,+ "tiff-test", "tiff-test", "windows", model.Conf.Repo.Load().Key, nil, nil)+ if err != nil {+ t.Fatal(err)+ }+ index, err := repo.Index("TIFF preview", true, nil)+ if err != nil {+ t.Fatal(err)+ }+ files := map[string]string{}+ if err = repo.GetFilesIter(index, func(file *entity.File) error {+ files[strings.TrimPrefix(file.Path, "/")] = file.ID+ return nil+ }); err != nil {+ t.Fatal(err)+ }+ previews := map[string]string{}+ for _, path := range paths {+ id := files[path]+ if id == "" {+ t.Fatalf("TIFF missing from snapshot: %s", path)+ }+ _, content, _, _, err := model.OpenRepoSnapshotFile(id)+ if err != nil {+ t.Fatal(err)+ }+ if content != "repo/diff/"+path {+ t.Fatalf("TIFF snapshot preview missing: %q", content)+ }+ previews[path] = "/" + content+ }+ return previews+}++func TestServeTIFFRealRepoSnapshots(t *testing.T) {+ engine := tiffTestEngine(t)+ source := tiffSource(t)+ paths := []string{"assets/image.tif", "assets/image.TIFF"}+ for _, path := range paths {+ writeTIFFTestFile(t, filepath.Join(util.DataDir, filepath.FromSlash(path)), source)+ }+ previews := openTIFFSnapshots(t, paths...)+ for _, path := range paths {+ staged, err := os.ReadFile(filepath.Join(util.TempDir, "repo", "diff", filepath.FromSlash(path)))+ if err != nil || !bytes.Equal(staged, source) {+ t.Fatalf("snapshot preview source was not staged: %v", err)+ }+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, previews[path], nil))+ assertTIFFPreview(t, recorder)+ }+}++func TestServeTIFFWorkspaceWithHash(t *testing.T) {+ engine := tiffTestEngine(t)+ if !strings.Contains(util.WorkspaceDir, "#") {+ t.Fatal("test workspace must contain a hash")+ }+ source := tiffSource(t)+ for _, test := range []struct{ url, path string }{+ {"/assets/image.tif", filepath.Join(util.DataDir, "assets", "image.tif")},+ {"/history/2026-10-21-120000-update/assets/image.tif", filepath.Join(util.HistoryDir, "2026-10-21-120000-update", "assets", "image.tif")},+ {"/repo/diff/assets/image.tif", filepath.Join(util.TempDir, "repo", "diff", "assets", "image.tif")},+ } {+ writeTIFFTestFile(t, test.path, source)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.url+"?style=thumb", nil))+ assertTIFFPreview(t, recorder)+ }+}+func writeTIFFTestFile(t *testing.T, path string, data []byte) {t.Helper()if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {@@ -159,7 +257,7 @@ func TestServeTIFFLockedNotebook(t *testing.T) {writeTIFFTestFile(t, filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), []byte(`{"encrypted":true}`))writeTIFFTestFile(t, filepath.Join(util.DataDir, boxID, "assets", "image.tif"), []byte("SYAE"))writeTIFFTestFile(t, filepath.Join(util.HistoryDir, "2026-10-21-120000-update", boxID, "assets", "image.tif"), []byte("SYAE"))- writeTIFFTestFile(t, filepath.Join(util.TempDir, "repo", "diff", boxID, "assets", "image.tif"), tiffSource(t))+ writeTIFFTestFile(t, filepath.Join(util.TempDir, "repo", "diff", boxID, "assets", "image.tif"), []byte("SYAE"))for _, url := range []string{"/assets/image.tif?box=" + boxID,"/history/2026-10-21-120000-update/" + boxID + "/assets/image.tif",diff --git a/kernel/sql/av_card_cover_test.go b/kernel/sql/av_card_cover_test.gonew file mode 100644index 0000000000..1b2ea49b50--- /dev/null+++ b/kernel/sql/av_card_cover_test.go@@ -0,0 +1,30 @@+package sql++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+)++func TestTIFFAssetFieldCardCovers(t *testing.T) {+ for _, source := range []string{"assets/image.tif", "assets/image.TIFF?box=20261021000000-tiffbox#preview"} {+ t.Run(source, func(t *testing.T) {+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{{+ Key: &av.Key{ID: "assets", Type: av.KeyTypeMAsset},+ Values: []*av.Value{{BlockID: "row", Type: av.KeyTypeMAsset, MAsset: []*av.ValueAsset{+ {Type: av.AssetTypeFile, Content: "assets/document.pdf"},+ {Type: av.AssetTypeImage, Content: source},+ }}},+ }}}+ view := &av.View{Gallery: av.NewLayoutGallery(), Kanban: av.NewLayoutKanban()}+ view.Gallery.CoverFrom, view.Gallery.CoverFromAssetKeyID = av.CoverFromAssetField, "assets"+ view.Kanban.CoverFrom, view.Kanban.CoverFromAssetKeyID = av.CoverFromAssetField, "assets"+ gallery, kanban := &av.GalleryCard{}, &av.KanbanCard{}+ fillAttributeViewGalleryCardCover(attrView, view, nil, gallery, "row", nil, nil)+ fillAttributeViewKanbanCardCover(attrView, view, nil, kanban, "row", nil, nil)+ if gallery.CoverURL != source || kanban.CoverURL != source {+ t.Fatalf("TIFF asset cover missing: gallery=%q kanban=%q", gallery.CoverURL, kanban.CoverURL)+ }+ })+ }+}diff --git a/kernel/tiffpreview/convert.go b/kernel/tiffpreview/convert.goindex 3122d0964f..8541504a43 100644--- a/kernel/tiffpreview/convert.go+++ b/kernel/tiffpreview/convert.go@@ -35,8 +35,8 @@ var (ErrImageTooLarge = errors.New("TIFF image exceeds the dimension limit"))+// IsPath 按文件系统路径识别 TIFF;URL 查询参数由调用方解析,不截断合法路径中的井号。func IsPath(path string) bool {- path = strings.SplitN(strings.SplitN(path, "?", 2)[0], "#", 2)[0]ext := strings.ToLower(filepath.Ext(path))return ext == ".tif" || ext == ".tiff"}diff --git a/kernel/tiffpreview/convert_test.go b/kernel/tiffpreview/convert_test.goindex 4eec2b4790..73a1baf358 100644--- a/kernel/tiffpreview/convert_test.go+++ b/kernel/tiffpreview/convert_test.go@@ -8,12 +8,29 @@ import ("image""image/color""image/png"+ "path/filepath""sort""testing""golang.org/x/image/tiff")+func TestIsPathPreservesFilesystemCharacters(t *testing.T) {+ for _, path := range []string{+ "image.tif", "image.TIFF", filepath.Join("notes#1", "assets", "image.tif"),+ filepath.Join("notes?1", "assets", "image.tiff"), filepath.Join("assets", "image#1.tif"),+ } {+ if !IsPath(path) {+ t.Fatalf("TIFF filesystem path was not recognized: %s", path)+ }+ }+ for _, path := range []string{"image.png", "image.tif.txt", "image.tif?style=thumb", "image.tif#preview"} {+ if IsPath(path) {+ t.Fatalf("non-TIFF filesystem path was accepted: %s", path)+ }+ }+}+func encodeTIFF(t *testing.T, img image.Image, compression tiff.CompressionType) []byte {t.Helper()var buffer bytes.Bufferdiff --git a/kernel/util/path.go b/kernel/util/path.goindex e4cc044b22..e31437322f 100644--- a/kernel/util/path.go+++ b/kernel/util/path.go@@ -337,7 +337,7 @@ func IsAssetLinkDest(dest []byte, includeServePath bool) bool {}var (- SiYuanAssetsImage = []string{".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif", ".heic", ".heif"}+ SiYuanAssetsImage = []string{".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif", ".tiff", ".tif", ".heic", ".heif"}SiYuanAssetsAudio = []string{".mp3", ".wav", ".ogg", ".m4a", ".aac", ".flac"}SiYuanAssetsVideo = []string{".mov", ".weba", ".mkv", ".mp4", ".webm"})diff --git a/kernel/util/path_test.go b/kernel/util/path_test.goindex 3380866218..cd30d98817 100644--- a/kernel/util/path_test.go+++ b/kernel/util/path_test.go@@ -45,13 +45,26 @@ func TestIsPossiblyImageWithQueryAndFragment(t *testing.T) {"assets/photo.heic","assets/photo.HEIF?box=20260816000000-abcdefg","assets/photo.heic?box=20260816000000-abcdefg#preview",+ "assets/photo.tif",+ "assets/photo.TIFF?box=20260816000000-abcdefg#preview",} {if !IsPossiblyImage(assetPath) {- t.Fatalf("HEIF asset was not recognized as an image: %s", assetPath)+ t.Fatalf("asset was not recognized as an image: %s", assetPath)}}}+func TestIsDisplayableAssetTIFF(t *testing.T) {+ for _, path := range []string{"assets/photo.tif", "assets/photo.TIFF", "20261021000000-tiffbox/assets/photo.tiff"} {+ if !IsDisplayableAsset(path) {+ t.Fatalf("TIFF snapshot asset was not displayable: %s", path)+ }+ }+ if IsDisplayableAsset("assets/photo.tiff.txt") {+ t.Fatal("a TIFF name without a TIFF extension was displayable")+ }+}+func TestFilterSelfChildDocsRemovesChildrenAndDuplicates(t *testing.T) {parentPath := "/20260810000001-abcdefg.sy"childPath := "/20260810000001-abcdefg/20260810000002-abcdefg.sy"