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(link previews): give a favicon its own attachment role
Elian Doran52084e4f319a
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 7be1f8461e..071447731e 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -1,6 +1,6 @@import "./content_renderer.css";-import { isOfficeMimeType, normalizeMimeTypeForCKEditor, type TextRepresentationResponse } from "@triliumnext/commons";+import { isImageAttachmentRole, isOfficeMimeType, normalizeMimeTypeForCKEditor, type TextRepresentationResponse } from "@triliumnext/commons";import DOMPurify from "dompurify";import { h, type JSX, render } from "preact";@@ -656,6 +656,11 @@ function getRenderingType(entity: FNote | FAttachment) {// for reference; render them exactly like a "file" role.if (type === "importSource") {type = "file";+ } else if (isImageAttachmentRole(type)) {+ // A link preview's "favicon" is a picture like any other as far as showing it goes; the+ // role only says where it came from. Without this it would fall through to the unknown+ // type and list as a file with no preview.+ type = "image";}}diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.tsindex 4057a3ff07..7b36ab8bf0 100644--- a/apps/client/src/services/image_upload.spec.ts+++ b/apps/client/src/services/image_upload.spec.ts@@ -51,7 +51,17 @@ describe("uploadImageAttachment", () => {const url = await uploadImageAttachment("note1", "data:image/png;base64,QUJD");expect(url).toBe("api/attachments/new1/image/image.png");- expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload", expect.any(File), undefined, "POST");+ // The role travels in the URL and defaults to a plain image, which is what a caller that+ // says nothing means.+ expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload?role=image", expect.any(File), undefined, "POST");+ });++ it("asks for the role it was given, so a fetched picture is not stored as the user's own", async () => {+ serverUpload.mockResolvedValue({ uploaded: true, url: "api/attachments/new1/image/favicon.ico" });++ await uploadImageAttachment("note1", "data:image/png;base64,QUJD", "favicon");++ expect(serverUpload).toHaveBeenCalledWith("notes/note1/attachments/upload?role=favicon", expect.any(File), undefined, "POST");});it("returns null when the server reports the upload did not succeed", async () => {diff --git a/apps/client/src/services/image_upload.ts b/apps/client/src/services/image_upload.tsindex 4b66529efd..4080ef8091 100644--- a/apps/client/src/services/image_upload.ts+++ b/apps/client/src/services/image_upload.ts@@ -1,3 +1,5 @@+import type { ImageAttachmentRole } from "@triliumnext/commons";+import server from "./server.js";/**@@ -8,13 +10,19 @@ import server from "./server.js";** Format-agnostic: used by any rich note type that needs to offload inline base64 images to* attachments (e.g. the spreadsheet drawing layer).+ *+ * `role` says which kind of picture it is. The default is a plain image — the user's own — and a+ * caller passes something else only for a picture the app fetched on its behalf, such as a link+ * preview's site icon; see {@link IMAGE_ATTACHMENT_ROLES}. The server checks the value against the+ * same list rather than storing whatever it is sent.*/-export async function uploadImageAttachment(noteId: string, dataUrl: string): Promise<string | null> {+export async function uploadImageAttachment(noteId: string, dataUrl: string, role: ImageAttachmentRole = "image"): Promise<string | null> {const file = dataUrlToImageFile(dataUrl);if (!file) return null;try {- const response = await server.upload(`notes/${noteId}/attachments/upload`, file, undefined, "POST") as { uploaded?: boolean; url?: string };+ const url = `notes/${noteId}/attachments/upload?role=${encodeURIComponent(role)}`;+ const response = await server.upload(url, file, undefined, "POST") as { uploaded?: boolean; url?: string };return response?.uploaded && response.url ? response.url : null;} catch (e) {console.error("Failed to upload image attachment", e);diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex 7c19220610..2c4c9eddb5 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -132,8 +132,12 @@ describe("fetchMetadata", () => {const result = await fetchMetadata("https://example.com", "note1");- expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV");- expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/jpeg;base64,IMG");+ // Stored under different roles: the card image is a picture of the page and belongs+ // with the note's own images, while the favicon is the site's mark, fetched rather than+ // chosen — which is what lets icons be deduplicated and kept out of the tools that+ // reason about the user's own pictures.+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/x-icon;base64,FAV", "favicon");+ expect(uploadImageAttachmentMock).toHaveBeenCalledWith("note1", "data:image/jpeg;base64,IMG", "image");// Only the attachment URLs land in the note content — inlined base64 counts against the// auto-read-only size threshold, and a favicon pays that cost once per link rather than// once per note.diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsxindex ffe017507d..92e9e3a8bf 100644--- a/apps/client/src/services/link_embed.tsx+++ b/apps/client/src/services/link_embed.tsx@@ -1,6 +1,6 @@import "../widgets/type_widgets/text/LinkEmbed.css";-import { extractYouTubeVideoId, type LinkEmbedMetadata, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";+import { extractYouTubeVideoId, type ImageAttachmentRole, type LinkEmbedMetadata, safeLinkPreviewHref, safeLinkPreviewImageSrc, YOUTUBE_REGEX } from "@triliumnext/commons";import { render } from "preact";import { useState } from "preact/hooks";@@ -50,7 +50,7 @@ export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<// Uploaded together: they are two independent requests and a preview needs both before it// can be stored.const [ favicon, image ] = await Promise.all([- offloadPictureToAttachment(metadata.favicon, ownerNoteId),+ offloadPictureToAttachment(metadata.favicon, ownerNoteId, "favicon"),offloadPictureToAttachment(metadata.image, ownerNoteId)]);@@ -81,13 +81,22 @@ export async function fetchMetadata(url: string, ownerNoteId?: string): Promise<** Both pictures go through this, so both are subject to the same rule at the render sinks: only an* inline image or an attachment of this instance is ever loaded (see `isLocalPreviewImageSrc`).+ *+ * They are stored under different roles all the same. A card image is a picture of the page and+ * belongs with the note's own images; a favicon is the site's mark, fetched rather than chosen, and+ * telling the two apart is what lets icons be deduplicated and kept out of the tools that reason+ * about what the user put in the note.*/-async function offloadPictureToAttachment(picture: string | undefined, ownerNoteId: string | undefined): Promise<string | undefined> {+async function offloadPictureToAttachment(+ picture: string | undefined,+ ownerNoteId: string | undefined,+ role: ImageAttachmentRole = "image"+): Promise<string | undefined> {if (!picture || !ownerNoteId || !picture.startsWith("data:")) {return picture;}- return await uploadImageAttachment(ownerNoteId, picture) ?? picture;+ return await uploadImageAttachment(ownerNoteId, picture, role) ?? picture;}// ---------------------------------------------------------------------------diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsxindex 5d71d93425..3a9b4d5aa3 100644--- a/apps/client/src/widgets/type_widgets/Attachment.tsx+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx@@ -1,6 +1,6 @@import "./Attachment.css";-import { ConvertAttachmentToNoteResponse } from "@triliumnext/commons";+import { ConvertAttachmentToNoteResponse, isImageAttachmentRole } from "@triliumnext/commons";import { t } from "i18next";import { useContext, useEffect, useRef, useState } from "preact/hooks";@@ -165,13 +165,17 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view// "importSource" attachments (e.g. OneNote debug source) behave like ordinary files for// preview, OCR and link-copying purposes.const isFileLike = attachment.role === "file" || attachment.role === "importSource";+ const isPicture = isImageAttachmentRole(attachment.role);+ // A link preview's favicon is deliberately left out: it is 16 pixels of site mark, so there is+ // no text in it to find, and offering to read one is noise in every attachment list that has a+ // preview in it. The same goes for recompressing it further down.const supportsOcr = attachment.role === "image" || isFileLike;// Opened in full detail, an image gets the interactive zoom/pan viewer and audio/video the full media// player — both mounted here rather than through the content renderer, which has no tab context to hand// them (and it is the tab that lets them navigate between the note's other attachments). Everything else,// in either view, is rendered imperatively via the content renderer.- const isZoomableImage = !!isFullDetail && attachment.role === "image";+ const isZoomableImage = !!isFullDetail && isPicture;const isPlayableMedia = !!isFullDetail && (attachment.mime.startsWith("audio/") || attachment.mime.startsWith("video/"));const rendersItself = isZoomableImage || isPlayableMedia;const imageSrc = `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}?${modified}`;@@ -221,7 +225,7 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view}, [ isZoomableImage ]);async function copyAttachmentReferenceToClipboard() {- if (attachment.role === "image") {+ if (isPicture) {const $img = refToJQuerySelector(isZoomableImage ? imageViewerWrapper : contentWrapper).find("img");if ($img.length) image.copyImageReferenceToClipboard($img.parent());} else if (isFileLike) {diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex 94bae97160..6d47e606e6 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -118,7 +118,7 @@ describe("checkImageAttachments", () => {title: "Test",attachments: [{ title: "image.jpg", role: "image", mime: "image/jpeg" },- { title: "favicon.ico", role: "image", mime: "image/x-icon" }+ { title: "favicon.ico", role: "favicon", mime: "image/x-icon" }]});mockAttachmentSaves(note);@@ -138,7 +138,7 @@ describe("checkImageAttachments", () => {});it("keeps a mention's favicon alive, which is all an inline mention carries", () => {- const note = buildNote({ title: "Test", attachments: [{ title: "favicon.ico", role: "image", mime: "image/x-icon" }] });+ const note = buildNote({ title: "Test", attachments: [{ title: "favicon.ico", role: "favicon", mime: "image/x-icon" }] });mockAttachmentSaves(note);const [ favicon ] = note.getAttachments();favicon.utcDateScheduledForErasureSince = "2025-01-01 00:00:00.000Z";@@ -150,6 +150,19 @@ describe("checkImageAttachments", () => {expect(favicon.utcDateScheduledForErasureSince).toBeNull();});+ it("schedules an unreferenced favicon for erasure, its own role notwithstanding", () => {+ // The role exists so an icon can be told apart from the user's own pictures, not so it+ // can escape the cleanup: nothing else manages a favicon, so deleting the preview that+ // referenced it has to be what eventually takes it away.+ const note = buildNote({ title: "Test", attachments: [{ title: "favicon.ico", role: "favicon", mime: "image/x-icon" }] });+ mockAttachmentSaves(note);+ const [ favicon ] = note.getAttachments();++ checkImageAttachments(note, "<p>the preview that referenced it is gone</p>");++ expect(favicon.utcDateScheduledForErasureSince).toBeTruthy();+ });+it("schedules unreferenced attachments for erasure", () => {const note = buildNote({ title: "Test", attachments: [{ title: "test.png", role: "image", mime: "image/png" }] });mockAttachmentSaves(note);diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.tsindex 350a4c703f..6791d0a578 100644--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@ -1,4 +1,4 @@-import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";+import { isImageAttachmentRole, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import { search as searchService, SearchContext, utils } from "@triliumnext/core";import type { NextFunction, Request, Response, Router } from "express";import safeCompare from "safe-compare";@@ -350,7 +350,7 @@ function register(router: Router) {return;}- if (attachment.role === "image") {+ if (isImageAttachmentRole(attachment.role)) {addNoIndexHeader(attachment.note, res);if (attachment.mime === "image/svg+xml") {// SVG attachments require sanitization to prevent stored XSSdiff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex f9dd59974e..8b6f23755c 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -5,6 +5,7 @@ export * from "./lib/keyboard_actions_interface.js";export * from "./lib/hidden_subtree.js";export * from "./lib/rows.js";export * from "./lib/test-utils.js";+export * from "./lib/attachment_roles.js";export * from "./lib/image_mimes.js";export * from "./lib/mime_type.js";export * from "./lib/office.js";diff --git a/packages/commons/src/lib/attachment_roles.spec.ts b/packages/commons/src/lib/attachment_roles.spec.tsnew file mode 100644index 0000000000..26397c647a--- /dev/null+++ b/packages/commons/src/lib/attachment_roles.spec.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";++import { IMAGE_ATTACHMENT_ROLES, isImageAttachmentRole } from "./attachment_roles.js";++describe("isImageAttachmentRole", () => {+ it("recognises every picture role and nothing else", () => {+ for (const role of IMAGE_ATTACHMENT_ROLES) {+ expect(isImageAttachmentRole(role), role).toBe(true);+ }++ // The roles that are not pictures. "viewConfig" and "importSource" matter most: they are+ // managed by whatever created them, so treating one as a picture would put it in front of+ // the cleanup that erases unreferenced attachments.+ for (const role of [ "file", "viewConfig", "importSource", "Image", "", "favicons" ]) {+ expect(isImageAttachmentRole(role), role).toBe(false);+ }++ expect(isImageAttachmentRole(undefined)).toBe(false);+ expect(isImageAttachmentRole(null)).toBe(false);+ });++ it("covers both the user's own pictures and the ones the app fetched for them", () => {+ expect(isImageAttachmentRole("image")).toBe(true);+ expect(isImageAttachmentRole("favicon")).toBe(true);+ });+});diff --git a/packages/commons/src/lib/attachment_roles.ts b/packages/commons/src/lib/attachment_roles.tsnew file mode 100644index 0000000000..d6d1c955b4--- /dev/null+++ b/packages/commons/src/lib/attachment_roles.ts@@ -0,0 +1,22 @@+/**+ * The attachment roles whose content is a picture.+ *+ * A role is not a label — it is what the code branches on. `image` alone used to mean "this+ * attachment is a picture", so every such branch spelled it that way, and a second picture role+ * has to be admitted to all of them at once or it half-works: served but never cleaned up, cleaned+ * up but never served, listed but rendered as an unknown file.+ *+ * `favicon` is separate from `image` so a link preview's site icon can be told apart from a picture+ * the user put in the note — they are created, deduplicated and replaced on completely different+ * terms, and only one of them is something the user chose. Keeping them apart also keeps icons out+ * of the places that reason about the user's images: the compression inventory has nothing to gain+ * from a 16x16 icon, and offering to recompress one is noise.+ */+export const IMAGE_ATTACHMENT_ROLES = [ "image", "favicon" ] as const;++export type ImageAttachmentRole = typeof IMAGE_ATTACHMENT_ROLES[number];++/** Whether an attachment of this role holds a picture, whoever created it. */+export function isImageAttachmentRole(role: string | undefined | null): role is ImageAttachmentRole {+ return !!role && (IMAGE_ATTACHMENT_ROLES as readonly string[]).includes(role);+}diff --git a/packages/trilium-core/src/becca/entities/battachment.ts b/packages/trilium-core/src/becca/entities/battachment.tsindex 92d9cd0613..0ac7edd8b5 100644--- a/packages/trilium-core/src/becca/entities/battachment.ts+++ b/packages/trilium-core/src/becca/entities/battachment.ts@@ -1,6 +1,6 @@-import type { AttachmentRow } from "@triliumnext/commons";+import { type AttachmentRow, isImageAttachmentRole } from "@triliumnext/commons";import dateUtils from "../../services/utils/date";import { getLog } from "../../services/log.js";@@ -14,6 +14,9 @@ import { escapeRegExp, formatDownloadTitle, isStringNote, replaceAll } from "../const attachmentRoleToNoteTypeMapping = {image: "image",+ // A site icon converted to a note is an image note like any other; only where it came from+ // differs, and that is not something the resulting note carries.+ favicon: "image",file: "file"};@@ -187,9 +190,10 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {let fixedContent = origContent;- if (this.role === "image") {+ if (isImageAttachmentRole(this.role)) {// Rewrite embedded images (`<img src="api/attachments/{attachmentId}/image/...">`)- // to point at the new image note.+ // to point at the new image note. A link preview's `data-image` / `data-favicon`+ // carry the same URL, so replacing the prefix covers them too.const oldAttachmentUrl = `api/attachments/${attachmentId}/image/`;const newNoteUrl = `api/images/${note.noteId}/`;@@ -220,7 +224,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {}getFileName() {- const type = this.role === "image" ? "image" : "file";+ const type = isImageAttachmentRole(this.role) ? "image" : "file";return formatDownloadTitle(this.title, type, this.mime);}diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.tsindex 9a227502d7..711ec09649 100644--- a/packages/trilium-core/src/routes/api/attachments.spec.ts+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts@@ -236,6 +236,38 @@ describe("Attachments API (core)", () => {expect(attachment).toMatchObject({ role: "image", mime: "image/x-icon" });});+ it("stores an upload under a requested picture role, and serves it like any other", async () => {+ const { noteId } = await createTextNote(api, { title: "Favicon target" });++ const res = await api.post<{ uploaded: boolean; url: string }>(+ `/api/notes/${noteId}/attachments/upload?role=favicon`,+ { file: { originalname: "favicon.ico", mimetype: "image/x-icon", buffer: icoWrapping(PIXEL_PNG) } }+ );+ expect(res.status).toBe(200);+ expect(res.body.url).toContain("/image/");++ const [ attachment ] = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;+ expect(attachment.role).toBe("favicon");++ // The role decides whether the image route will serve it at all — a role it does not+ // know is answered with a 400, which would leave every preview showing a placeholder.+ expect((await api.get(`/${res.body.url}`)).status).toBe(200);+ });++ it("ignores a role it does not know rather than storing it", async () => {+ // The role is what decides whether an attachment is served, listed and cleaned up, so a+ // request must not be able to invent one and leave an attachment no code path looks at.+ const { noteId } = await createTextNote(api, { title: "Bogus role target" });++ await api.post(+ `/api/notes/${noteId}/attachments/upload?role=viewConfig`,+ { file: { originalname: "pixel.png", mimetype: "image/png", buffer: PIXEL_PNG } }+ );++ const [ attachment ] = (await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`)).body;+ expect(attachment.role).toBe("image");+ });+it("reports a missing upload when no file is present", async () => {const { noteId } = await createTextNote(api, { title: "No file target" });diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.tsindex c6c4500cb2..752eeaf65c 100644--- a/packages/trilium-core/src/routes/api/attachments.ts+++ b/packages/trilium-core/src/routes/api/attachments.ts@@ -1,4 +1,4 @@-import { ConvertAttachmentToNoteResponse, isAcceptedImageMime } from "@triliumnext/commons";+import { ConvertAttachmentToNoteResponse, type ImageAttachmentRole, isAcceptedImageMime, isImageAttachmentRole } from "@triliumnext/commons";import { ValidationError } from "../../errors";import type { Request } from "express";import type { File } from "../../services/import/common.js";@@ -65,7 +65,7 @@ async function uploadAttachment(req: FileRequest<{ noteId: string }>) {const buffer = wrapStringOrBuffer(file.buffer as string | Uint8Array);if (isAcceptedImageMime(file.mimetype)) {- const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true);+ const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true, requestedImageRole(req));// The URL below is fetched the moment this answers — the editor puts it straight into the// document as the source of an image. Answering before the bytes are stored hands it the@@ -91,6 +91,19 @@ async function uploadAttachment(req: FileRequest<{ noteId: string }>) {};}+/**+ * Which kind of picture the caller says it is uploading, defaulting to a plain image.+ *+ * Read from a fixed set rather than taken at its word: the role is what decides whether an+ * attachment is served, listed and cleaned up, so an arbitrary string from a request would be a way+ * to create attachments that no code path looks at again.+ */+function requestedImageRole(req: FileRequest<{ noteId: string }>): ImageAttachmentRole {+ const requested = req.query?.role;++ return typeof requested === "string" && isImageAttachmentRole(requested) ? requested : "image";+}+function renameAttachment(req: Request<{ attachmentId: string }>) {const { title } = req.body;const { attachmentId } = req.params;diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.tsindex 866b7040b2..0085df96ca 100644--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@ -1,4 +1,4 @@-import { type ImageCompressionOptions, isAcceptedImageMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";+import { type ImageCompressionOptions, isAcceptedImageMime, isImageAttachmentRole, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";import type { Request, Response } from "express";import type { File } from "../../services/import/common.js";@@ -97,8 +97,9 @@ function returnAttachedImage(req: Request<{ attachmentId: string }>, res: Responreturn res.sendStatus(404);}- if (!["image"].includes(attachment.role)) {- return res.setHeader("Content-Type", "text/plain").status(400).send(`Attachment '${attachment.attachmentId}' has role '${attachment.role}', but 'image' was expected.`);+ if (!isImageAttachmentRole(attachment.role)) {+ return res.setHeader("Content-Type", "text/plain").status(400)+ .send(`Attachment '${attachment.attachmentId}' has role '${attachment.role}', but a picture was expected.`);}res.set("Content-Type", attachment.mime);diff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.tsindex 27f6300621..8cf549ef4a 100644--- a/packages/trilium-core/src/services/image.ts+++ b/packages/trilium-core/src/services/image.ts@@ -3,6 +3,7 @@* Uses ImageProvider for platform-specific processing (compression, format detection).*/+import type { ImageAttachmentRole } from "@triliumnext/commons";import sanitizeFilename from "sanitize-filename";import becca from "../becca/becca.js";@@ -189,7 +190,9 @@ function saveImageToAttachment(uploadBuffer: Uint8Array,originalName: string,shrinkImageSwitch?: boolean,- trimFilename = false+ trimFilename = false,+ /** Which kind of picture this is; see {@link IMAGE_ATTACHMENT_ROLES}. */+ role: ImageAttachmentRole = "image"): { attachmentId: string | undefined; title: string } {getLog().info(`Saving image '${originalName}' as attachment into note '${noteId}'`);@@ -201,7 +204,7 @@ function saveImageToAttachment(const note = becca.getNoteOrThrow(noteId);const attachment = note.saveAttachment({- role: "image",+ role,mime: "unknown",title: fileName});diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 19765c4253..27d72525db 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -1,4 +1,4 @@-import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";+import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, isImageAttachmentRole, type NoteRow, NOTE_TYPE_IMAGE_ATTACHMENTS, type NoteType } from "@triliumnext/commons";import { t } from "i18next";import { parse as parseHtml } from "node-html-parser";import url from "url";@@ -143,7 +143,7 @@ function copyChildAttributes(parentNote: BNote, childNote: BNote, isTypeDefaultefunction copyAttachments(origNote: BNote, newNote: BNote) {for (const attachment of origNote.getAttachments()) {- if (attachment.role === "image") {+ if (isImageAttachmentRole(attachment.role)) {// Handled separately, see `checkImageAttachments`.continue;}@@ -483,10 +483,12 @@ export function checkImageAttachments(note: BNote, content: string) {const attachments = note.getAttachments();for (const attachment of attachments) {- // Only attachments that are meant to be embedded in the note content (images, files) are+ // Only attachments that are meant to be embedded in the note content (pictures, files) are// auto-scheduled for erasure when no longer referenced. Other roles (e.g. "viewConfig",// "importSource") are managed explicitly by their owners and must not be cleaned up here.- if (attachment.role !== "image" && attachment.role !== "file") {+ // A link preview's favicon belongs to the first group: nothing manages it, so deleting the+ // preview has to be what eventually takes the icon with it.+ if (!isImageAttachmentRole(attachment.role) && attachment.role !== "file") {continue;}