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
fix(clipper): say why a save failed instead of a bare "Saving to Trilium failed"
Elian Doran438390d0cb4c
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.htmlindex 405a4b8ff8..29fc7c96fd 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html@@ -241,6 +241,9 @@one the message names.</li><li>Trilium rejected the request: the message includes the reason Triliumgave.</li>+ <li>The popup could not reach the extension's background script, or it gave+ no answer: close the popup and open it again. If the extension was just+ updated or reloaded, reload the page as well.</li><li>A PDF could not be saved: Trilium is older than v0.107.0, the websiterefused to send the PDF again, or the PDF is larger than 100 MB. The extensiondownloads the PDF with the browser's cookies for that website, so a PDFdiff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex 91587f8c0a..fb8cd5b3dd 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -294,7 +294,14 @@ describe("background", () => {await onCommand("saveSelection");expect(await lastToast()).toMatchObject({...GENERIC_FAILURE_TOAST,- message: expect.stringContaining("unexpected")+ message: "Saving to Trilium failed: unexpected"+ });++ // An error from another realm, or a value that is not an error at all, still names its cause.+ facade.callService.mockRejectedValue({ message: "Could not establish connection." });+ await onCommand("saveSelection");+ expect(await lastToast()).toMatchObject({+ message: "Saving to Trilium failed: Could not establish connection."});});diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex 8f0737b8a9..8b9e5ff957 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -2,7 +2,7 @@ import {MAX_PART_HEIGHT, type ScreenshotSlice, ScreenshotStitcher, type StitchMessage, type StitchRequest} from "@/screenshot";import {- extractPage, isPdfTab, OPTIONAL_REQUEST_TIMEOUT_MS, randomString, type Rect, type SaveOutcome, type Saved+ describeError, extractPage, isPdfTab, OPTIONAL_REQUEST_TIMEOUT_MS, randomString, type Rect, type SaveOutcome, type Saved} from "@/utils";import setupContextMenu from "./context_menu";@@ -883,8 +883,7 @@ function decodeComponent(value: string) {function failureMessage(error: unknown) {if (error instanceof TriliumError) return error.message;- const details = error instanceof Error ? error.message : "";- return details ? `Saving to Trilium failed: ${details}` : "Saving to Trilium failed.";+ return `Saving to Trilium failed: ${describeError(error)}`;}function delay(ms: number) {diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex b1d44fcc87..da5fa18e2c 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -28,7 +28,9 @@ import type { ComponentChildren } from "preact";import { Fragment, render } from "preact";import { useEffect, useRef, useState } from "preact/hooks";-import { extractPage, isPdfTab, type PageVariant, type ReadablePage, type SaveOutcome } from "@/utils";+import {+ describeError, extractPage, isPdfTab, type PageVariant, type ReadablePage, type SaveOutcome+} from "@/utils";import type { TriliumSearchNoteStatus, TriliumSearchStatus } from "../background/trilium_server_facade";@@ -211,8 +213,7 @@ export function Popup() {/** Keeps the popup open while Trilium saves, and shows how it went. */async function save(message: object, clip?: ClipChoice) {setSaveState({ status: "saving", clip });- const outcome = await sendMessage(message) as SaveOutcome | undefined;- setSaveState({ ...outcome ?? { error: "Saving to Trilium failed." }, clip });+ setSaveState({ ...await requestSave(message), clip });}const status = describeStatus(searchStatus);@@ -955,6 +956,22 @@ function isConnected(status: TriliumSearchStatus) {return status.status === "found-desktop" || status.status === "found-server" || status.status === "version-mismatch";}+/** Sends a save to the background, and answers how it went, or why the background did not answer. */+async function requestSave(message: object): Promise<SaveOutcome> {+ let outcome: SaveOutcome | undefined;+ try {+ console.log("Sending message", message);+ outcome = await browser.runtime.sendMessage(message);+ } catch (e) {+ console.error("Sending the save to the background script failed:", e);+ return {+ error: "Saving to Trilium failed: the popup could not reach the extension's background script"+ + ` (${describeError(e)}).`+ };+ }+ return outcome ?? { error: "Saving to Trilium failed: the extension's background script gave no answer." };+}+async function sendMessage(message: object) {try {console.log("Sending message", message);diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex 52dbbfe0e6..fc283654a9 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -447,13 +447,21 @@ describe("popup", () => {expect(frameDocument()).toBe(previewDocument(selection as typeof SELECTION));});- it("tells the user when the background script cannot be reached", async () => {+ it("tells the user when the background script cannot be reached, with the reason for a save", async () => {const alertMock = vi.fn();vi.stubGlobal("alert", alertMock);sendMessage.mockRejectedValueOnce(new Error("Receiving end does not exist."));-await click("All tabs in this window");+ await flush();+ expect(saveStatus()).toEqual({+ kind: "callout callout-error save-status",+ text: "Saving to Trilium failed: the popup could not reach the extension's background script"+ + " (Receiving end does not exist.)."+ });+ expect(alertMock).not.toHaveBeenCalled();+ sendMessage.mockRejectedValueOnce(new Error("Receiving end does not exist."));+ await click("Check the connection again");expect(alertMock).toHaveBeenCalledWith("Calling browser runtime failed. Refreshing page might help.");});@@ -832,7 +840,8 @@ describe("popup", () => {sendMessage.mockResolvedValueOnce(undefined);await click("Save PDF to Trilium");await flush();- expect(saveStatus()?.text).toBe("Saving to Trilium failed.");+ expect(saveStatus()?.text)+ .toBe("Saving to Trilium failed: the extension's background script gave no answer.");expect(sendMessageCalls("save-pdf")).toBe(2);expect(closeWindow).not.toHaveBeenCalled();});diff --git a/apps/web-clipper/utils.spec.ts b/apps/web-clipper/utils.spec.tsindex 2bc983bfbe..15b2915cb3 100644--- a/apps/web-clipper/utils.spec.ts+++ b/apps/web-clipper/utils.spec.ts@@ -3,7 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fakeBrowser } from "wxt/testing/fake-browser";import {- createLink, extractPage, getPageLocationOrigin, isPdfTab, OPTIONAL_REQUEST_TIMEOUT_MS, randomString+ createLink, describeError, extractPage, getPageLocationOrigin, isPdfTab, OPTIONAL_REQUEST_TIMEOUT_MS,+ randomString} from "./utils";describe("randomString", () => {@@ -73,6 +74,17 @@ describe("extractPage", () => {});+describe("describeError", () => {+ it("names the cause of whatever was thrown", () => {+ expect(describeError(new TypeError("Failed to fetch"))).toBe("Failed to fetch");+ expect(describeError(new DOMException("", "AbortError"))).toBe("AbortError");+ expect(describeError({ message: "Could not establish connection." })).toBe("Could not establish connection.");+ expect(describeError({ message: "" })).toBe("[object Object]");+ expect(describeError("Too tall")).toBe("Too tall");+ expect(describeError(undefined)).toBe("undefined");+ });+});+describe("isPdfTab", () => {const TAB = { id: 7, url: "https://example.com/report" };const executeScript = vi.fn(async ({ func }: { func: () => unknown }) => [ { result: func() } ]);diff --git a/apps/web-clipper/utils.ts b/apps/web-clipper/utils.tsindex 2caaa6ad41..7122edd376 100644--- a/apps/web-clipper/utils.ts+++ b/apps/web-clipper/utils.ts@@ -77,6 +77,17 @@ export function isPdfType(contentType: string | null) {return contentType?.split(";")[0]?.trim().toLowerCase() === "application/pdf";}+/**+ * The cause of a thrown value, which might be an error from another realm, which `instanceof Error`+ * rejects, an error without a message, or not an error at all.+ */+export function describeError(error: unknown) {+ if (error instanceof Error) return error.message || error.name;+ const message = (error as { message?: unknown } | null | undefined)?.message;+ if (typeof message === "string" && message) return message;+ return String(error);+}+export function randomString(len: number) {let text = "";const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex 44fbb8da50..2295cf2c9a 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -106,6 +106,7 @@ After each clipping made with a keyboard shortcut or the context menu, a notific* Trilium was not found: start the desktop application, or check the server address and token in the extension's options.* The versions of Trilium and the extension are not compatible: update the one the message names.* Trilium rejected the request: the message includes the reason Trilium gave.+* The popup could not reach the extension's background script, or it gave no answer: close the popup and open it again. If the extension was just updated or reloaded, reload the page as well.* A PDF could not be saved: Trilium is older than v0.107.0, the website refused to send the PDF again, or the PDF is larger than 100 MB. The extension downloads the PDF with the browser's cookies for that website, so a PDF behind a login can be saved while you are logged in.The extension downloads the images of a clipping itself, so that they are stored in Trilium together with the note. If some of them cannot be downloaded (for example because the website refuses the request), the clipping is still saved, and the notification says how many images are missing. Those images keep their address on the original website: Trilium tries to download them once more if _Download images automatically_ is enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Media_, and otherwise the note shows them from the website for as long as it serves them.