Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(canvas): detect orphaned image attachments server-side
Elian Doran4581986b01a0
diff --git a/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.ts b/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.tsindex 912a86ed04..4f9657b82e 100644--- a/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.ts+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.spec.ts@@ -2,7 +2,7 @@ import { BinaryFileData } from "@excalidraw/excalidraw/types";import { afterEach, describe, expect, it, vi } from "vitest";import type FNote from "../../../entities/fnote";-import { buildNewImageAttachments, findOrphanImageAttachments, loadImageAttachments } from "./image_attachments";+import { buildNewImageAttachments, loadImageAttachments } from "./image_attachments";function file(dataURL: string, mimeType = "image/png"): BinaryFileData {return { id: "x", dataURL, mimeType, created: 0 } as BinaryFileData;@@ -55,32 +55,6 @@ describe("buildNewImageAttachments", () => {});});-describe("findOrphanImageAttachments", () => {- it("splits loaded attachments into removed (orphan) and still-referenced (remaining)", () => {- const loaded = [- { fileId: "a", attachmentId: "att-a" },- { fileId: "b", attachmentId: "att-b" },- { fileId: "c", attachmentId: "att-c" }- ];-- const { orphans, remaining } = findOrphanImageAttachments(loaded, new Set([ "a", "c" ]));-- expect(orphans).toEqual([ { fileId: "b", attachmentId: "att-b" } ]);- expect(remaining).toEqual([- { fileId: "a", attachmentId: "att-a" },- { fileId: "c", attachmentId: "att-c" }- ]);- });-- it("returns no orphans when every loaded image is still on the canvas", () => {- const loaded = [ { fileId: "a", attachmentId: "att-a" } ];- const { orphans, remaining } = findOrphanImageAttachments(loaded, new Set([ "a" ]));-- expect(orphans).toEqual([]);- expect(remaining).toEqual(loaded);- });-});-describe("loadImageAttachments", () => {afterEach(() => vi.unstubAllGlobals());diff --git a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts b/apps/client/src/widgets/type_widgets/canvas/image_attachments.tsindex dd56c298f6..2908565b47 100644--- a/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts+++ b/apps/client/src/widgets/type_widgets/canvas/image_attachments.ts@@ -26,7 +26,7 @@ export const CANVAS_EXPORT_TITLE = "canvas-export.svg";* data URL, since Excalidraw renders only from inline data URLs (it has no external-URL provider).*/export async function loadImageAttachments(note: FNote): Promise<{ files: BinaryFileData[]; metadata: ImageAttachmentMetadata[] }> {- const attachments = (await note.getAttachmentsByRole(IMAGE_ROLE)).filter((attachment) => attachment.title !== CANVAS_EXPORT_TITLE);+ const attachments = await getCanvasImageAttachments(note);const files: BinaryFileData[] = [];const metadata: ImageAttachmentMetadata[] = [];@@ -83,18 +83,12 @@ export function buildNewImageAttachments(activeFiles: Record<string, BinaryFileD}/**- * Partitions previously-loaded image attachments into those whose image is gone from the canvas- * (`orphans`, to be deleted) and those still referenced (`remaining`).+ * Returns the note's `image`-role attachments that back canvas images (i.e. excluding the SVG+ * export), used to reload images on open. Orphan cleanup of removed images is handled server-side+ * (saveLinks/checkImageAttachments scanning the scene JSON), not here.*/-export function findOrphanImageAttachments(loaded: readonly ImageAttachmentMetadata[], activeFileIds: ReadonlySet<string>) {- const orphans: ImageAttachmentMetadata[] = [];- const remaining: ImageAttachmentMetadata[] = [];-- for (const entry of loaded) {- (activeFileIds.has(entry.fileId) ? remaining : orphans).push(entry);- }-- return { orphans, remaining };+async function getCanvasImageAttachments(note: FNote) {+ return (await note.getAttachmentsByRole(IMAGE_ROLE)).filter((attachment) => attachment.title !== CANVAS_EXPORT_TITLE);}/** Reads a blob as a base64 `data:` URL. */diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex 22b21c6064..9416fb4c32 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -8,7 +8,7 @@ import NoteContext from "../../../components/note_context";import FNote from "../../../entities/fnote";import server from "../../../services/server";import { SavedData, useEditorSpacedUpdate } from "../../react/hooks";-import { buildNewImageAttachments, CANVAS_EXPORT_TITLE, findOrphanImageAttachments, IMAGE_ROLE, ImageAttachmentMetadata, loadImageAttachments } from "./image_attachments";+import { buildNewImageAttachments, CANVAS_EXPORT_TITLE, IMAGE_ROLE, loadImageAttachments } from "./image_attachments";interface AttachmentMetadata {title: string;@@ -41,11 +41,9 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteconst libraryCache = useRef<LibraryItem[]>([]);const attachmentMetadata = useRef<AttachmentMetadata[]>([]);- // Image attachments present at load (fileId -> attachmentId), used to delete attachments whose- // image was removed from the canvas this session (mirrors the library-item cleanup above).- const loadedImageAttachments = useRef<ImageAttachmentMetadata[]>([]);- // fileIds already persisted as attachments (loaded at start + uploaded this session), so each- // image is written once rather than re-encoded into every save.+ // fileIds of images this session owns as attachments (loaded at start + uploaded this session).+ // Drives both skip-reupload and orphan cleanup: an owned fileId no longer on the canvas marks+ // its attachment for deletion (mirrors the library-item cleanup above).const persistedImageFileIds = useRef<Set<string>>(new Set());const appStateToCompare = useRef<Partial<ImportantAppState>>({});@@ -60,7 +58,6 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteContelibraryCache.current = [];attachmentMetadata.current = [];- loadedImageAttachments.current = [];persistedImageFileIds.current = new Set();// load saved content into excalidraw canvas@@ -86,7 +83,6 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteif (files.length > 0) {api.addFiles(files);}- loadedImageAttachments.current = metadata;persistedImageFileIds.current = new Set(metadata.map((m) => m.fileId));});@@ -109,21 +105,15 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteconst { content, svg, activeFiles } = await getData(api, appStateToCompare);const attachments: SavedData["attachments"] = [{ role: IMAGE_ROLE, title: CANVAS_EXPORT_TITLE, mime: "image/svg+xml", content: svg, position: 0 }];- // Persist newly inserted images as attachments and drop the ones whose image was removed.- // `content` carries only the fileId references (see getData), so the bytes live here.- const activeFileIds = new Set(Object.keys(activeFiles));+ // Persist newly inserted images as attachments. `content` carries only the fileId+ // references (see getData), so the bytes live here. Removed images are not deleted from+ // the client: the server's saveLinks/checkImageAttachments scans the saved scene JSON and+ // schedules now-unreferenced image attachments for erasure (same as the spreadsheet).for (const attachment of buildNewImageAttachments(activeFiles, persistedImageFileIds.current)) {attachments.push(attachment);persistedImageFileIds.current.add(attachment.title);}- const { orphans, remaining } = findOrphanImageAttachments(loadedImageAttachments.current, activeFileIds);- for (const { attachmentId, fileId } of orphans) {- await server.remove(`attachments/${attachmentId}`);- persistedImageFileIds.current.delete(fileId);- }- loadedImageAttachments.current = remaining;-// libraryChanged is unset in dataSaved()if (libraryChanged.current) {// there's no separate method to get library items, so have to abuse this onediff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex 08b1708114..302935c997 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -1,6 +1,6 @@-import { BAttribute, becca_easy_mocking, checkImageAttachments, findBookmarks, findLlmChatLinks, saveLinks } from "@triliumnext/core";+import { BAttribute, becca, becca_easy_mocking, checkImageAttachments, collectCanvasImageFileIds, findBookmarks, findLlmChatLinks, saveLinks } from "@triliumnext/core";import { beforeEach, describe, expect, it, vi } from "vitest";-import { becca } from "@triliumnext/core";+import { randomString } from "./utils.js";const { buildNote } = becca_easy_mocking;@@ -25,6 +25,24 @@ vi.mock("./entity_changes.js", () => ({default: { putEntityChange: () => {} }}));+describe("collectCanvasImageFileIds", () => {+ it("collects fileIds from image elements in the scene JSON", () => {+ const content = JSON.stringify({+ elements: [+ { type: "image", fileId: "file-1" },+ { type: "rectangle" },+ { type: "image", fileId: "file-2" }+ ]+ });+ expect(collectCanvasImageFileIds(content)).toEqual(new Set([ "file-1", "file-2" ]));+ });++ it("returns an empty set for malformed content (e.g. note type just changed)", () => {+ expect(collectCanvasImageFileIds("not json")).toEqual(new Set());+ expect(collectCanvasImageFileIds(JSON.stringify({}))).toEqual(new Set());+ });+});+describe("findBookmarks", () => {it("extracts bookmark IDs from empty anchor tags", () => {const content = `<p>Hello</p><a id="chapter-1"></a><p>World</p>`;@@ -264,6 +282,73 @@ describe("checkImageAttachments", () => {});});+ describe("Canvas content", () => {+ /** Wraps image fileIds into the JSON shape a canvas note persists (one element per fileId). */+ function canvasContent(...fileIds: string[]) {+ return JSON.stringify({+ type: "excalidraw",+ version: 2,+ elements: fileIds.map((fileId) => ({ type: "image", fileId })),+ files: {},+ appState: {}+ });+ }++ it("keeps an image referenced by the scene (attachment titled with its fileId) alive", () => {+ const note = buildNote({ title: "Canvas", type: "canvas", mime: "application/json", attachments: [{ title: "fileId-1", role: "image", mime: "image/png" }] });+ mockAttachmentSaves(note);+ const [att] = note.getAttachments();++ checkImageAttachments(note, canvasContent("fileId-1"));++ expect(att.save).not.toHaveBeenCalled();+ });++ it("schedules an inserted-then-removed image for erasure", () => {+ const note = buildNote({ title: "Canvas", type: "canvas", mime: "application/json", attachments: [{ title: "fileId-1", role: "image", mime: "image/png" }] });+ mockAttachmentSaves(note);+ const [att] = note.getAttachments();++ // Scene no longer references fileId-1 (the image was deleted from the canvas).+ checkImageAttachments(note, canvasContent("fileId-2"));++ expect(att.save).toHaveBeenCalled();+ expect(att.utcDateScheduledForErasureSince).toBeTruthy();+ });++ it("never schedules the SVG export preview for erasure even though it is unreferenced", () => {+ const note = buildNote({ title: "Canvas", type: "canvas", mime: "application/json", attachments: [{ title: "canvas-export.svg", role: "image", mime: "image/svg+xml" }] });+ mockAttachmentSaves(note);+ const [exportPreview] = note.getAttachments();++ checkImageAttachments(note, canvasContent());++ expect(exportPreview.save).not.toHaveBeenCalled();+ expect(exportPreview.utcDateScheduledForErasureSince).toBeFalsy();+ });++ it("cancels erasure when the image is re-referenced (e.g. undo)", () => {+ const note = buildNote({ title: "Canvas", type: "canvas", mime: "application/json", attachments: [{ title: "fileId-1", role: "image", mime: "image/png" }] });+ mockAttachmentSaves(note);+ const [att] = note.getAttachments();+ att.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";++ checkImageAttachments(note, canvasContent("fileId-1"));++ expect(att.save).toHaveBeenCalled();+ expect(att.utcDateScheduledForErasureSince).toBeNull();+ });++ it("does not perform foreign-attachment copying (no forceFrontendReload)", () => {+ const note = buildNote({ title: "Canvas", type: "canvas", mime: "application/json", attachments: [{ title: "fileId-1", role: "image", mime: "image/png" }] });+ mockAttachmentSaves(note);++ const result = checkImageAttachments(note, canvasContent("fileId-1"));++ expect(result.forceFrontendReload).toBe(false);+ });+ });+describe("foreign attachment copying", () => {it("replaces foreign attachment IDs in HTML content", () => {const note = buildNote({ title: "Test" });diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 104687ea15..a2a4b3d933 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -92,7 +92,7 @@ export { default as SearchContext } from "./services/search/search_context";export { default as search, } from "./services/search/services/search";export { type default as SearchResult } from "./services/search/search_result";export { type SearchParams } from "./services/search/services/types";-export { checkImageAttachments, default as note_service, findBookmarks, findLlmChatLinks, saveLinks } from "./services/notes";+export { checkImageAttachments, collectCanvasImageFileIds, default as note_service, findBookmarks, findLlmChatLinks, saveLinks } from "./services/notes";export type { NoteParams } from "./services/notes";export * as sanitize from "./services/sanitizer";export * as routes from "./routes";diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex f760e8a3b8..f9b66e305d 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -423,29 +423,44 @@ function protectNote(note: BNote, protect: boolean) {*/const SPREADSHEET_PREVIEW_ATTACHMENT_TITLE = "spreadsheet-export.png";+/**+ * Title of the canvas SVG export image. Like the spreadsheet thumbnail, it is the note's rendered+ * preview (looked up by title, not referenced from the scene JSON), so it must be exempt from the+ * orphan-erasure scheduling below.+ */+const CANVAS_EXPORT_ATTACHMENT_TITLE = "canvas-export.svg";+export function checkImageAttachments(note: BNote, content: string) {+ // Canvas references images by the Excalidraw fileId stored as the attachment *title* in its+ // scene JSON, so orphans are detected by title; every other type references them by attachmentId+ // embedded in the content (an image URL or attachment link).+ const isCanvas = note.type === "canvas";const foundAttachmentIds = new Set<string>();- let match;-- // Spreadsheet content is JSON storing inline images as bare `api/attachments/{id}/image/...`- // URLs (no `src="..."` wrapper), so it scans with the same loose pattern as Markdown.- const patterns = (note.isMarkdown() || note.type === "spreadsheet")- ? [- //  or similar markdown image syntax- /api\/attachments\/([a-zA-Z0-9_]+)\/image/g,- // [...](#root/{noteId}?viewMode=attachments&attachmentId={id})- /attachmentId=([a-zA-Z0-9_]+)/g- ]- : [- // <img src="api/attachments/{id}/image/...">- /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,- // <a href="...attachmentId={id}">- /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g- ];-- for (const pattern of patterns) {- while ((match = pattern.exec(content))) {- foundAttachmentIds.add(match[1]);+ const foundCanvasFileIds = isCanvas ? collectCanvasImageFileIds(content) : new Set<string>();++ if (!isCanvas) {+ let match;++ // Spreadsheet content is JSON storing inline images as bare `api/attachments/{id}/image/...`+ // URLs (no `src="..."` wrapper), so it scans with the same loose pattern as Markdown.+ const patterns = (note.isMarkdown() || note.type === "spreadsheet")+ ? [+ //  or similar markdown image syntax+ /api\/attachments\/([a-zA-Z0-9_]+)\/image/g,+ // [...](#root/{noteId}?viewMode=attachments&attachmentId={id})+ /attachmentId=([a-zA-Z0-9_]+)/g+ ]+ : [+ // <img src="api/attachments/{id}/image/...">+ /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,+ // <a href="...attachmentId={id}">+ /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g+ ];++ for (const pattern of patterns) {+ while ((match = pattern.exec(content))) {+ foundAttachmentIds.add(match[1]);+ }}}@@ -465,7 +480,14 @@ export function checkImageAttachments(note: BNote, content: string) {continue;}- const attachmentInContent = attachment.attachmentId && foundAttachmentIds.has(attachment.attachmentId);+ // Likewise for the canvas SVG export preview.+ if (isCanvas && attachment.title === CANVAS_EXPORT_ATTACHMENT_TITLE) {+ continue;+ }++ const attachmentInContent = isCanvas+ ? foundCanvasFileIds.has(attachment.title)+ : !!attachment.attachmentId && foundAttachmentIds.has(attachment.attachmentId);if (attachment.utcDateScheduledForErasureSince && attachmentInContent) {attachment.utcDateScheduledForErasureSince = null;@@ -476,6 +498,12 @@ export function checkImageAttachments(note: BNote, content: string) {}}+ // Canvas references images by title, not by attachmentId, so the foreign-attachment copy step+ // (which keys off attachmentIds found in the content) does not apply.+ if (isCanvas) {+ return { forceFrontendReload: false, content };+ }+const existingAttachmentIds = new Set<string | undefined>(attachments.map((att) => att.attachmentId));const unknownAttachmentIds = Array.from(foundAttachmentIds).filter((foundAttId) => !existingAttachmentIds.has(foundAttId));const unknownAttachments = becca.getAttachments(unknownAttachmentIds);@@ -519,6 +547,29 @@ export function checkImageAttachments(note: BNote, content: string) {};}+/**+ * Collects the Excalidraw `fileId`s referenced by a canvas note's scene JSON. Canvas images are+ * stored as attachments titled with these fileIds, so the set identifies which image attachments are+ * still in use (the persisted scene contains only non-deleted elements). Returns an empty set for+ * malformed content rather than throwing, so a save is never blocked.+ */+export function collectCanvasImageFileIds(content: string): Set<string> {+ const fileIds = new Set<string>();++ try {+ const parsed = JSON.parse(content) as { elements?: { fileId?: string }[] };+ for (const element of parsed.elements ?? []) {+ if (element.fileId) {+ fileIds.add(element.fileId);+ }+ }+ } catch {+ // Malformed content (e.g. note type just changed) — treat as referencing nothing.+ }++ return fileIds;+}+function findImageLinks(content: string, foundLinks: FoundLink[]) {const re = /src="[^"]*api\/images\/([a-zA-Z0-9_]+)\//g;let match;@@ -907,7 +958,7 @@ function saveAttachments(note: BNote, content: string) {export function saveLinks(note: BNote, content: string | Uint8Array) {- if ((note.type !== "text" && note.type !== "relationMap" && note.type !== "llmChat" && note.type !== "spreadsheet" && !note.isMarkdown()) || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {+ if ((note.type !== "text" && note.type !== "relationMap" && note.type !== "llmChat" && note.type !== "spreadsheet" && note.type !== "canvas" && !note.isMarkdown()) || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {return {forceFrontendReload: false,content@@ -936,6 +987,11 @@ export function saveLinks(note: BNote, content: string | Uint8Array) {// orphans (inserted-then-removed images) so they get scheduled for erasure. There are no// Trilium internal links to extract from spreadsheet content.({ forceFrontendReload, content } = checkImageAttachments(note, content));+ } else if (note.type === "canvas" && typeof content === "string") {+ // Canvas images are stored as attachments titled with the Excalidraw fileId referenced from+ // the scene JSON; scan for orphans (inserted-then-removed images) so they get scheduled for+ // erasure. There are no Trilium internal links to extract from canvas content.+ ({ forceFrontendReload, content } = checkImageAttachments(note, content));} else if (note.type === "relationMap" && typeof content === "string") {findRelationMapLinks(content, foundLinks);} else if (note.type === "llmChat" && typeof content === "string") {