An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve copying selected rich text and images in the desktop app https://github.com/siyuan-note/siyuan/issues/18377
Danielcf578cf16690
diff --git a/app/electron/main.js b/app/electron/main.jsindex 33c4538c7d..5475d71c01 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -37,6 +37,7 @@ const {} = require("electron");const path = require("path");const fs = require("fs");+const {pathToFileURL} = require("url");const gNet = require("net");const childProcess = require("child_process");const remote = require("@electron/remote/main");@@ -72,7 +73,10 @@ let gracefulSystemShutdownPromise;let keepAppOpenDuringSystemShutdown = false;let updateInstallPromise;let keepAppOpenDuringUpdate = false;+let richClipboardOperation;+let richClipboardSequence = 0;const openDialogSingletons = new Set();+const normalizeClipboardText = (text) => text.replace(/\r\n?/g, "\n");const isOpenAsHidden = function () {return 1 === workspaces.length && openAsHidden;};@@ -1428,6 +1432,70 @@ app.whenReady().then(() => {if (data.cmd === "clipboardRead") {return clipboard.read(data.format);}+ if (data.cmd === "beginRichClipboard") {+ richClipboardOperation = undefined;+ const text = clipboard.readText();+ const html = clipboard.readHTML();+ if (typeof data.text !== "string" || typeof data.marker !== "string" ||+ normalizeClipboardText(text) !== normalizeClipboardText(data.text) ||+ !data.marker || !html.includes(data.marker)) {+ return;+ }++ richClipboardSequence++;+ const token = `${Date.now()}-${richClipboardSequence}`;+ richClipboardOperation = {+ token,+ senderId: event.sender.id,+ requestedText: data.text,+ text,+ html+ };+ return token;+ }+ if (data.cmd === "completeRichClipboard") {+ const operation = richClipboardOperation;+ if (!operation || operation.token !== data.token || operation.senderId !== event.sender.id) {+ return false;+ }+ if (operation.requestedText !== data.text || clipboard.readText() !== operation.text ||+ clipboard.readHTML() !== operation.html || typeof data.html !== "string" ||+ !Array.isArray(data.replacements) || 1024 < data.replacements.length) {+ richClipboardOperation = undefined;+ return false;+ }++ let html = data.html;+ for (const replacement of data.replacements) {+ let isFile = false;+ if (replacement && typeof replacement.path === "string" && path.isAbsolute(replacement.path)) {+ try {+ isFile = fs.statSync(replacement.path).isFile();+ } catch {+ isFile = false;+ }+ }+ if (!replacement || typeof replacement.placeholder !== "string" || !replacement.placeholder ||+ !isFile || !html.includes(replacement.placeholder)) {+ richClipboardOperation = undefined;+ return false;+ }+ const fileURL = pathToFileURL(replacement.path).href.replaceAll("&", "&");+ html = html.split(replacement.placeholder).join(fileURL);+ }++ richClipboardOperation = undefined;+ clipboard.write({+ text: data.text,+ html+ });+ return true;+ }+ if (data.cmd === "cancelRichClipboard") {+ if (richClipboardOperation?.token === data.token && richClipboardOperation.senderId === event.sender.id) {+ richClipboardOperation = undefined;+ }+ }if (data.cmd === "showOpenDialog") {if (data.singleton) {const singleton = `${event.sender.id}:${data.singleton}`;diff --git a/app/src/protyle/util/richClipboard.ts b/app/src/protyle/util/richClipboard.tsnew file mode 100644index 0000000000..536587e211--- /dev/null+++ b/app/src/protyle/util/richClipboard.ts@@ -0,0 +1,210 @@+import {Constants} from "../../constants";+/// #if !BROWSER+import {ipcRenderer} from "electron";+/// #endif++interface IRichClipboardSource {+ element: HTMLImageElement;+ index: number;+ path: string;+ box: string;+}++interface IRichClipboardPrepared {+ batch: string;+ groups: string[];+ assets: {+ index: number;+ path: string;+ }[];+}++const richClipboardImageExts = new Set([+ "apng",+ "avif",+ "bmp",+ "cur",+ "gif",+ "ico",+ "jfif",+ "jpe",+ "jpeg",+ "jpg",+ "pjp",+ "pjpeg",+ "png",+ "webp",+]);++const postRichClipboard = async (url: string, data: Record<string, unknown>) => {+ const response = await fetch(url, {+ method: "POST",+ body: JSON.stringify(data),+ });+ return response.json() as Promise<IWebSocketData>;+};++const cleanupRichClipboard = async (prepared: IRichClipboardPrepared) => {+ try {+ await postRichClipboard("/api/clipboard/cleanupRichText", {+ batch: prepared.batch,+ groups: prepared.groups,+ });+ } catch (e) {+ console.warn("Cleanup rich clipboard error:", e);+ }+};++const getRichClipboardSources = (template: HTMLTemplateElement, notebookID: string) => {+ const sources: IRichClipboardSource[] = [];+ template.content.querySelectorAll("img[src]").forEach((element: HTMLImageElement) => {+ const src = element.getAttribute("src")?.trim();+ if (!src) {+ return;+ }++ let assetPath: string;+ if (src.startsWith("assets/")) {+ assetPath = src;+ } else if (src.startsWith("./assets/")) {+ assetPath = src.substring(2);+ } else if (src.startsWith("/assets/")) {+ assetPath = src.substring(1);+ } else {+ try {+ const url = new URL(src, window.location.href);+ if (url.origin !== window.location.origin || !url.pathname.startsWith("/assets/")) {+ return;+ }+ assetPath = url.pathname.substring(1) + url.search;+ } catch {+ return;+ }+ }+ const hashStart = assetPath.indexOf("#");+ if (hashStart > -1) {+ assetPath = assetPath.substring(0, hashStart);+ }++ const pathWithoutQuery = assetPath.split("?", 1)[0];+ const ext = pathWithoutQuery.substring(pathWithoutQuery.lastIndexOf(".") + 1).toLowerCase();+ if (!richClipboardImageExts.has(ext)) {+ return;+ }++ const queryStart = assetPath.indexOf("?");+ const queryEnd = assetPath.indexOf("#", queryStart);+ const query = queryStart > -1 ? assetPath.substring(queryStart + 1, queryEnd > -1 ? queryEnd : undefined) : "";+ sources.push({+ element,+ index: sources.length,+ path: assetPath,+ box: new URLSearchParams(query).get("box") || notebookID,+ });+ });+ return sources;+};++export const enhanceRichClipboard = (text: string, html: string, notebookID: string) => {+ /// #if !BROWSER+ window.setTimeout(async () => {+ const template = document.createElement("template");+ template.innerHTML = html;+ const sources = getRichClipboardSources(template, notebookID);+ if (sources.length === 0 || 1024 < sources.length) {+ return;+ }++ const marker = html.match(/<!--data-siyuan='[^']+'-->/)?.[0];+ if (!marker) {+ return;+ }++ let token: string;+ try {+ token = await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "beginRichClipboard",+ text,+ marker,+ });+ } catch (e) {+ console.warn("Begin rich clipboard error:", e);+ return;+ }+ if (!token) {+ return;+ }++ let prepared: IRichClipboardPrepared | undefined;+ try {+ const response = await postRichClipboard("/api/clipboard/prepareRichText", {+ assets: sources.map((source) => ({+ index: source.index,+ path: source.path,+ box: source.box,+ })),+ });+ prepared = response.code === 0 ? response.data as IRichClipboardPrepared : undefined;+ if (!prepared?.batch || !Array.isArray(prepared.groups) || !Array.isArray(prepared.assets)) {+ await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "cancelRichClipboard",+ token,+ });+ return;+ }+ } catch (e) {+ await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "cancelRichClipboard",+ token,+ });+ console.warn("Prepare rich clipboard error:", e);+ return;+ }++ const replacements: { placeholder: string; path: string }[] = [];+ const preparedIndexes = new Set<number>();+ for (const asset of prepared.assets) {+ const source = sources[asset.index];+ if (!source || preparedIndexes.has(asset.index) || typeof asset.path !== "string" || !asset.path) {+ await cleanupRichClipboard(prepared);+ await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "cancelRichClipboard",+ token,+ });+ return;+ }+ preparedIndexes.add(asset.index);+ const placeholder = `siyuan-rich-clipboard-${prepared.batch}-${asset.index}`;+ source.element.setAttribute("src", placeholder);+ replacements.push({+ placeholder,+ path: asset.path,+ });+ }+ if (preparedIndexes.size !== sources.length) {+ await cleanupRichClipboard(prepared);+ await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "cancelRichClipboard",+ token,+ });+ return;+ }++ try {+ const written = await ipcRenderer.invoke(Constants.SIYUAN_GET, {+ cmd: "completeRichClipboard",+ token,+ text,+ html: template.innerHTML,+ replacements,+ });+ if (!written) {+ await cleanupRichClipboard(prepared);+ }+ } catch (e) {+ await cleanupRichClipboard(prepared);+ console.warn("Complete rich clipboard error:", e);+ }+ }, 0);+ /// #endif+};diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex cbd9bc1fe3..f38e027974 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -111,6 +111,7 @@ import {setFold} from "../util/blockFold";import {BlockPanel} from "../../block/Panel";import {isEncryptedBox, parseSiYuanUriInfo} from "../../util/pathName";import {processSiYuanUri} from "../../util/uri";+import {enhanceRichClipboard} from "../util/richClipboard";export class WYSIWYG {public lastHTMLs: { [key: string]: string } = {};@@ -593,6 +594,7 @@ export class WYSIWYG {console.log("Copy write clipboard error:", e);}}+ enhanceRichClipboard(textPlain, textHTML, protyle.notebookId);}});diff --git a/kernel/api/clipboard.go b/kernel/api/clipboard.goindex f2fff973fd..58598c74f7 100644--- a/kernel/api/clipboard.go+++ b/kernel/api/clipboard.go@@ -17,8 +17,10 @@package apiimport (+ "fmt""net/http""os"+ "strings""github.com/88250/clipboard""github.com/88250/gulu"@@ -93,3 +95,89 @@ func writeFilePath(c *gin.Context) {return}}++func prepareRichText(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ assetsArg, ok := util.ParseJsonArg[[]any]("assets", arg, ret, true, true)+ if !ok {+ return+ }++ assets := make([]model.RichClipboardAsset, 0, len(assetsArg))+ for i, rawAsset := range assetsArg {+ assetArg, typeOK := rawAsset.(map[string]any)+ if !typeOK {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [assets.%d] should be of type [Object]", i)+ return+ }++ index, indexOK := assetArg["index"].(float64)+ path, pathOK := assetArg["path"].(string)+ if !indexOK || index < 0 || index != float64(int(index)) || !pathOK || strings.TrimSpace(path) == "" {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Invalid rich clipboard asset at index [%d]", i)+ return+ }++ box := ""+ if boxArg, exists := assetArg["box"]; exists {+ box, typeOK = boxArg.(string)+ if !typeOK {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [assets.%d.box] should be of type [String]", i)+ return+ }+ }+ assets = append(assets, model.RichClipboardAsset{+ Index: int(index),+ Path: strings.TrimSpace(path),+ Box: strings.TrimSpace(box),+ })+ }++ prepared, err := model.PrepareRichClipboardAssets(assets)+ if err != nil {+ logging.LogWarnf("prepare rich clipboard assets failed: %s", err)+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = prepared+}++func cleanupRichText(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ batch, ok := util.ParseJsonArg[string]("batch", arg, ret, true, true)+ if !ok {+ return+ }+ groupsArg, ok := util.ParseJsonArg[[]any]("groups", arg, ret, true, true)+ if !ok {+ return+ }++ groups := make([]string, 0, len(groupsArg))+ for i, rawGroup := range groupsArg {+ group, typeOK := rawGroup.(string)+ if !typeOK {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [groups.%d] should be of type [String]", i)+ return+ }+ groups = append(groups, group)+ }+ model.CleanupRichClipboardBatch(batch, groups)+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 713f72d0f1..1d85494f1f 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -337,6 +337,8 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/clipboard/readFilePaths", model.CheckAuth, model.CheckAdminRole, readFilePaths)ginServer.Handle("POST", "/api/clipboard/writeFilePath", model.CheckAuth, model.CheckAdminRole, writeFilePath)+ ginServer.Handle("POST", "/api/clipboard/prepareRichText", model.CheckAuth, model.CheckAdminRole, prepareRichText)+ ginServer.Handle("POST", "/api/clipboard/cleanupRichText", model.CheckAuth, model.CheckAdminRole, cleanupRichText)ginServer.Handle("POST", "/api/asset/uploadCloud", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, uploadCloud)ginServer.Handle("POST", "/api/asset/uploadCloudByAssetsPaths", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, uploadCloudByAssetsPaths)diff --git a/kernel/model/box.go b/kernel/model/box.goindex 045133f718..deb48a2691 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -772,6 +772,9 @@ func ClearTempFiles() {repoTmp := filepath.Join(util.TempDir, "repo")clearTempDir(repoTmp, &count, &size)++ clipboardTmp := filepath.Join(util.TempDir, "clipboard")+ clearTempDir(clipboardTmp, &count, &size)}func clearTempDir(dir string, count *int, size *int64) {diff --git a/kernel/model/clipboard.go b/kernel/model/clipboard.gonew file mode 100644index 0000000000..8fd09a16fe--- /dev/null+++ b/kernel/model/clipboard.go@@ -0,0 +1,179 @@+// 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 model++import (+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const richClipboardGlobalGroup = "_global"++var richClipboardImageExts = map[string]struct{}{+ ".apng": {},+ ".avif": {},+ ".bmp": {},+ ".cur": {},+ ".gif": {},+ ".ico": {},+ ".jfif": {},+ ".jpe": {},+ ".jpeg": {},+ ".jpg": {},+ ".pjp": {},+ ".pjpeg": {},+ ".png": {},+ ".webp": {},+}++type RichClipboardAsset struct {+ Index int+ Path string+ Box string+}++type RichClipboardPreparedAsset struct {+ Index int `json:"index"`+ Path string `json:"path"`+}++type RichClipboardPrepared struct {+ Batch string `json:"batch"`+ Groups []string `json:"groups"`+ Assets []RichClipboardPreparedAsset `json:"assets"`+}++func PrepareRichClipboardAssets(assets []RichClipboardAsset) (ret *RichClipboardPrepared, err error) {+ if len(assets) < 1 || 1024 < len(assets) {+ return nil, fmt.Errorf("invalid rich clipboard asset count [%d]", len(assets))+ }++ batch := util.RandString(24)+ groups := map[string]struct{}{}+ copied := map[string]string{}+ ret = &RichClipboardPrepared{Batch: batch}+ defer func() {+ if err != nil {+ cleanupRichClipboardGroups(batch, groups)+ }+ }()++ for _, asset := range assets {+ if asset.Index < 0 {+ return nil, fmt.Errorf("invalid rich clipboard asset index [%d]", asset.Index)+ }++ ext := strings.ToLower(filepath.Ext(AssetPathWithoutQuery(asset.Path)))+ if _, ok := richClipboardImageExts[ext]; !ok {+ return nil, fmt.Errorf("unsupported rich clipboard image extension [%s]", ext)+ }++ absPath, resolveErr := GetAssetAbsPathInBox(asset.Path, asset.Box)+ if resolveErr != nil {+ return nil, resolveErr+ }++ destPath, ok := copied[absPath]+ if !ok {+ group := ExtractBoxIDFromAssetsPath(absPath)+ if group == "" {+ group = richClipboardGlobalGroup+ }+ groups[group] = struct{}{}++ destDir := filepath.Join(util.TempDir, "clipboard", group, batch)+ if mkdirErr := os.MkdirAll(destDir, 0700); mkdirErr != nil {+ return nil, mkdirErr+ }+ destPath = filepath.Join(destDir, fmt.Sprintf("%d%s", len(copied), ext))+ if copyErr := copyAssetDecryptIfEncrypted(absPath, destPath); copyErr != nil {+ return nil, copyErr+ }+ if chmodErr := os.Chmod(destPath, 0600); chmodErr != nil {+ return nil, chmodErr+ }+ copied[absPath] = destPath+ }++ ret.Assets = append(ret.Assets, RichClipboardPreparedAsset{+ Index: asset.Index,+ Path: destPath,+ })+ }++ for group := range groups {+ ret.Groups = append(ret.Groups, group)+ }+ sort.Strings(ret.Groups)+ return ret, nil+}++func CleanupRichClipboardBatch(batch string, groups []string) {+ if !isRichClipboardBatch(batch) {+ return+ }++ validGroups := map[string]struct{}{}+ for _, group := range groups {+ if group == richClipboardGlobalGroup || ast.IsNodeIDPattern(group) {+ validGroups[group] = struct{}{}+ }+ }+ cleanupRichClipboardGroups(batch, validGroups)+}++func ClearRichClipboard() {+ os.RemoveAll(filepath.Join(util.TempDir, "clipboard"))+}++func ClearRichClipboardBox(boxID string) {+ if !ast.IsNodeIDPattern(boxID) {+ return+ }+ os.RemoveAll(filepath.Join(util.TempDir, "clipboard", boxID))+}++func cleanupRichClipboardGroups(batch string, groups map[string]struct{}) {+ for group := range groups {+ dir := filepath.Join(util.TempDir, "clipboard", group, batch)+ os.RemoveAll(dir)+ parent := filepath.Dir(dir)+ if util.IsEmptyDir(parent) {+ os.Remove(parent)+ }+ }+}++func isRichClipboardBatch(batch string) bool {+ if batch == "" || 64 < len(batch) {+ return false+ }+ for _, char := range batch {+ if ('a' <= char && char <= 'z') || ('A' <= char && char <= 'Z') || ('0' <= char && char <= '9') ||+ char == '-' || char == '_' {+ continue+ }+ return false+ }+ return true+}diff --git a/kernel/model/clipboard_test.go b/kernel/model/clipboard_test.gonew file mode 100644index 0000000000..52c2a20439--- /dev/null+++ b/kernel/model/clipboard_test.go@@ -0,0 +1,186 @@+package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/gulu"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPrepareAndCleanupRichClipboardAssets(t *testing.T) {+ originalWorkspaceDir := util.WorkspaceDir+ originalDataDir := util.DataDir+ originalTempDir := util.TempDir+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir = filepath.Join(root, "data")+ util.TempDir = filepath.Join(root, "temp")+ defer func() {+ util.WorkspaceDir = originalWorkspaceDir+ util.DataDir = originalDataDir+ util.TempDir = originalTempDir+ }()++ sourcePath := filepath.Join(util.DataDir, "assets", "image.png")+ if err := os.MkdirAll(filepath.Dir(sourcePath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(sourcePath, []byte("image"), 0600); err != nil {+ t.Fatal(err)+ }++ prepared, err := PrepareRichClipboardAssets([]RichClipboardAsset{+ {Index: 0, Path: "assets/image.png"},+ {Index: 1, Path: "assets/image.png"},+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(prepared.Groups) != 1 || prepared.Groups[0] != richClipboardGlobalGroup {+ t.Fatalf("unexpected rich clipboard groups: %#v", prepared.Groups)+ }+ if len(prepared.Assets) != 2 || prepared.Assets[0].Path != prepared.Assets[1].Path {+ t.Fatalf("duplicated source should reuse one temporary file: %#v", prepared.Assets)+ }+ content, err := os.ReadFile(prepared.Assets[0].Path)+ if err != nil {+ t.Fatal(err)+ }+ if string(content) != "image" {+ t.Fatalf("unexpected temporary asset content: %q", content)+ }++ CleanupRichClipboardBatch(prepared.Batch, prepared.Groups)+ if _, err = os.Stat(prepared.Assets[0].Path); !os.IsNotExist(err) {+ t.Fatalf("rich clipboard batch should be removed: %v", err)+ }+}++func TestPrepareRichClipboardAssetsRejectsSVG(t *testing.T) {+ originalWorkspaceDir := util.WorkspaceDir+ originalDataDir := util.DataDir+ originalTempDir := util.TempDir+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir = filepath.Join(root, "data")+ util.TempDir = filepath.Join(root, "temp")+ defer func() {+ util.WorkspaceDir = originalWorkspaceDir+ util.DataDir = originalDataDir+ util.TempDir = originalTempDir+ }()++ sourcePath := filepath.Join(util.DataDir, "assets", "image.svg")+ if err := os.MkdirAll(filepath.Dir(sourcePath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(sourcePath, []byte("<svg></svg>"), 0600); err != nil {+ t.Fatal(err)+ }++ if _, err := PrepareRichClipboardAssets([]RichClipboardAsset{{Index: 0, Path: "assets/image.svg"}}); err == nil {+ t.Fatal("SVG should not be prepared for the rich clipboard")+ }+ if _, err := os.Stat(filepath.Join(util.TempDir, "clipboard")); !os.IsNotExist(err) {+ t.Fatalf("rejected rich clipboard assets should not leave temporary files: %v", err)+ }+}++func TestPrepareRichClipboardAssetsDecryptsEncryptedNotebook(t *testing.T) {+ originalWorkspaceDir := util.WorkspaceDir+ originalDataDir := util.DataDir+ originalTempDir := util.TempDir+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir = filepath.Join(root, "data")+ util.TempDir = filepath.Join(root, "temp")+ boxID := "20260726120000-hijklmn"+ defer func() {+ LockBox(boxID)+ util.WorkspaceDir = originalWorkspaceDir+ util.DataDir = originalDataDir+ util.TempDir = originalTempDir+ }()++ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ confData, err := gulu.JSON.MarshalIndentJSON(boxConf, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if err = os.MkdirAll(filepath.Dir(confPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(confPath, confData, 0600); err != nil {+ t.Fatal(err)+ }++ dek, err := util.GenerateDEK()+ if err != nil {+ t.Fatal(err)+ }+ setDEKForTest(boxID, dek)+ plaintext := []byte("encrypted image")+ ciphertext, err := EncryptAsset(boxID, "image.png", dek, plaintext)+ if err != nil {+ t.Fatal(err)+ }+ sourcePath := filepath.Join(util.DataDir, boxID, "assets", "image.png")+ if err = os.MkdirAll(filepath.Dir(sourcePath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(sourcePath, ciphertext, 0600); err != nil {+ t.Fatal(err)+ }++ prepared, err := PrepareRichClipboardAssets([]RichClipboardAsset{{+ Index: 0,+ Path: "assets/image.png?box=" + boxID,+ Box: boxID,+ }})+ if err != nil {+ t.Fatal(err)+ }+ if len(prepared.Groups) != 1 || prepared.Groups[0] != boxID {+ t.Fatalf("unexpected encrypted rich clipboard groups: %#v", prepared.Groups)+ }+ content, err := os.ReadFile(prepared.Assets[0].Path)+ if err != nil {+ t.Fatal(err)+ }+ if string(content) != string(plaintext) {+ t.Fatalf("unexpected decrypted rich clipboard content: %q", content)+ }+}++func TestClearRichClipboardBox(t *testing.T) {+ originalTempDir := util.TempDir+ util.TempDir = t.TempDir()+ defer func() {+ util.TempDir = originalTempDir+ }()++ boxID := "20260726120000-abcdefg"+ boxAsset := filepath.Join(util.TempDir, "clipboard", boxID, "batch", "image.png")+ globalAsset := filepath.Join(util.TempDir, "clipboard", richClipboardGlobalGroup, "batch", "image.png")+ for _, asset := range []string{boxAsset, globalAsset} {+ if err := os.MkdirAll(filepath.Dir(asset), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(asset, []byte("image"), 0600); err != nil {+ t.Fatal(err)+ }+ }++ ClearRichClipboardBox(boxID)+ if _, err := os.Stat(boxAsset); !os.IsNotExist(err) {+ t.Fatalf("notebook rich clipboard files should be removed: %v", err)+ }+ if _, err := os.Stat(globalAsset); err != nil {+ t.Fatalf("global rich clipboard files should be preserved: %v", err)+ }+}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 1c14c9132d..ac23661cfc 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -1349,6 +1349,7 @@ func clearWorkspaceTemp(preserveInstallPkgs bool) {os.RemoveAll(filepath.Join(util.TempDir, "import"))os.RemoveAll(filepath.Join(util.TempDir, "convert"))os.RemoveAll(filepath.Join(util.TempDir, "repo"))+ ClearRichClipboard()os.RemoveAll(filepath.Join(util.TempDir, "os"))os.RemoveAll(filepath.Join(util.TempDir, "base64"))os.RemoveAll(filepath.Join(util.TempDir, "ai"))diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex fc0769088f..537d6f8c55 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -1055,6 +1055,7 @@ func LockBox(boxID string) {// lockBoxHeld 在已持有 box 写锁的前提下执行该 box 的锁定清理(不含全局缓存刷新)。func lockBoxHeld(boxID string) {RevokeManagedEncryptedExportsForBox(boxID)+ ClearRichClipboardBox(boxID)cachedDEKsLock.Lock()if dek, ok := cachedDEKs[boxID]; ok {diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.goindex f51cec37d7..008a30a662 100644--- a/kernel/model/encrypted_export_test.go+++ b/kernel/model/encrypted_export_test.go@@ -52,6 +52,13 @@ func TestLockBoxRevokesAndRemovesManagedExport(t *testing.T) {if err = os.WriteFile(artifact, []byte("plaintext"), 0600); err != nil {t.Fatal(err)}+ clipboardArtifact := filepath.Join(util.TempDir, "clipboard", boxID, "batch", "image.png")+ if err = os.MkdirAll(filepath.Dir(clipboardArtifact), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(clipboardArtifact, []byte("plaintext"), 0600); err != nil {+ t.Fatal(err)+ }relativePath := registerManagedEncryptedExport(boxID, filepath.Join("repo", exportID), artifact)LockBox(boxID)@@ -61,6 +68,9 @@ func TestLockBoxRevokesAndRemovesManagedExport(t *testing.T) {if _, statErr := os.Stat(artifact); !os.IsNotExist(statErr) {t.Fatalf("locking the notebook should remove the managed export artifact: %v", statErr)}+ if _, statErr := os.Stat(clipboardArtifact); !os.IsNotExist(statErr) {+ t.Fatalf("locking the notebook should remove rich clipboard assets: %v", statErr)+ }}func TestClearEncryptedExportTempOnBoot(t *testing.T) {diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex ed4d1752e9..67d673538d 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -183,6 +183,7 @@ func RemoveBox(boxID string) (err error) {// 删目录前缓存加密状态:删目录后 conf.json 不复存在,IsEncryptedBox 会返回 falseisEncrypted := IsEncryptedBox(boxID)unmount0(boxID)+ ClearRichClipboardBox(boxID)if !isEncrypted {unindex(boxID)}diff --git a/kernel/util/working.go b/kernel/util/working.goindex 2a6af80125..ccd3f6a4a9 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -367,6 +367,7 @@ func initWorkspaceDir(workspaceArg string) {os.RemoveAll(filepath.Join(TempDir, "repo"))// export 目录只保存临时文件,启动时统一清理;插件不得依赖其中的文件跨进程存续。os.RemoveAll(filepath.Join(TempDir, "export"))+ os.RemoveAll(filepath.Join(TempDir, "clipboard"))os.Setenv("TMPDIR", osTmpDir)os.Setenv("TEMP", osTmpDir)os.Setenv("TMP", osTmpDir)