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(web-clipper): show why a clipping failed instead of failing silently
Elian Dorand89027cbed52
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 7079d6523f..58a181a90c 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@@ -61,6 +61,21 @@<p>It's also possible to configure the <a href="#root/_help_WOcw2SLH6tbX">server</a> addressif you don't run the desktop application, or want it to work without thedesktop application running.</p>+<h3>When a clipping fails</h3>+<p>After each clipping, a notification in the corner of the page confirms+ that it was saved, with a link to open the new note in Trilium. If the+ clipping could not be saved, the notification says why instead:</p>+<ul>+ <li>Trilium was not found: start the desktop application, or check the server+ address and token in the extension's options.</li>+ <li>The versions of Trilium and the extension are not compatible: update the+ one the message names.</li>+ <li>Trilium rejected the request: the message includes the reason Trilium+ gave.</li>+</ul>+<p>The notification is shown on the page itself, so it does not appear on+ pages where extensions cannot run (such as the browser's own settings pages+ and the extension stores).</p><h2>Testing development versions</h2><p>Development versions are version pre-release versions, generally meantfor testing purposes. These are not available in the Google or Firefoxdiff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex 61a1385550..e0d7a3828c 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -1,14 +1,24 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fakeBrowser } from "wxt/testing/fake-browser";-const facade = vi.hoisted(() => ({- callService: vi.fn<(method: string, path: string, body?: unknown) => Promise<any>>(),- triggerSearchForTrilium: vi.fn(),- sendTriliumSearchStatusToPopup: vi.fn(),- triggerSearchNoteByUrl: vi.fn()+const { facade, TriliumError } = vi.hoisted(() => ({+ facade: {+ callService: vi.fn<(method: string, path: string, body?: unknown) => Promise<any>>(),+ triggerSearchForTrilium: vi.fn(),+ sendTriliumSearchStatusToPopup: vi.fn(),+ triggerSearchNoteByUrl: vi.fn()+ },+ TriliumError: class extends Error {++ constructor(readonly reason: string, message: string) {+ super(message);+ }++ }}));vi.mock("./trilium_server_facade", () => ({+ TriliumError,default: class {callService = facade.callService;@@ -36,6 +46,9 @@ const PNG_DATA_URL = /^data:image\/png;base64,/;const PAGE_URL = "https://example.com/page";const MENU_URL = "https://example.com/menu";const ACTIVE_TAB: Tab = { id: 7, title: "Active page", url: PAGE_URL };+const TRILIUM_FAILURE = new TriliumError("not-found", "Trilium was not found.");+const FAILURE_TOAST = { name: "toast", message: "Trilium was not found.", noteId: null };+const GENERIC_FAILURE_TOAST = { name: "toast", message: expect.any(String), noteId: null };let onCommand: (command: string) => Promise<void>;let onContextMenuClicked: (info: ContextMenuClick) => Promise<void>;@@ -150,24 +163,46 @@ describe("background", () => {.toMatchObject({ name: "toast", noteId: "saved", tabIds: null });});- it("is bound to the keyboard shortcut and shows no toast when saving fails", async () => {+ it("is bound to the keyboard shortcut and shows why saving failed", async () => {tabMessageHandler = () => ({ title: "Page", content: "x" });- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);await onCommand("saveSelection");expect(facade.callService).toHaveBeenCalledWith("POST", "clippings", { title: "Page", content: "x" });- expect(await lastToast()).toBeUndefined();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);});- it("fails when there is no active tab", async () => {+ it("shows a toast when the page returns nothing or something else fails", async () => {+ await onCommand("saveSelection");+ expect(facade.callService).not.toHaveBeenCalled();+ expect(await lastToast()).toMatchObject(GENERIC_FAILURE_TOAST);++ tabMessageHandler = () => ({ title: "Page", content: "x" });+ facade.callService.mockRejectedValue(new Error("unexpected"));+ await onCommand("saveSelection");+ expect(await lastToast()).toMatchObject({+ ...GENERIC_FAILURE_TOAST,+ message: expect.stringContaining("unexpected")+ });+ });++ it("logs the failure when no page can show a toast", async () => {tabs = [];- await expect(onCommand("saveSelection")).rejects.toThrow("No active tab.");+ await expect(onCommand("saveSelection")).resolves.toBeUndefined();tabs = [ { title: "Tab without id" } ];- await expect(onCommand("saveSelection")).rejects.toThrow("No active tab.");+ await expect(onCommand("saveSelection")).resolves.toBeUndefined();++ tabs = [ ACTIVE_TAB ];+ tabMessageHandler = () => {+ throw new Error("Could not establish connection.");+ };+ await expect(onCommand("saveSelection")).resolves.toBeUndefined();+ await lastToast();expect(facade.callService).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledTimes(3);});});@@ -184,10 +219,10 @@ describe("background", () => {expect(facade.callService).toHaveBeenLastCalledWith("POST", "notes", page);expect(await lastToast()).toMatchObject({ noteId: "saved" });- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);tabsSendMessage.mockClear();await onCommand("saveWholePage");- expect(await lastToast()).toBeUndefined();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);});});@@ -237,10 +272,21 @@ describe("background", () => {}));expect(lastPayload()).toMatchObject({ pageUrl: MENU_URL });- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);tabsSendMessage.mockClear();await sendRuntimeMessage({ name: "save-cropped-screenshot" });expect(lastPayload()).toMatchObject({ pageUrl: PAGE_URL });+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);+ });++ it("saves nothing and shows nothing when the crop is cancelled", async () => {+ tabMessageHandler = (message) => {+ return message.name === "toast" ? undefined : { rect: null };+ };++ await expect(onCommand("saveCroppedScreenshot")).resolves.toBeUndefined();++ expect(facade.callService).not.toHaveBeenCalled();expect(await lastToast()).toBeUndefined();});@@ -255,11 +301,11 @@ describe("background", () => {});expect(await lastToast()).toMatchObject({ noteId: "saved" });- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);tabsSendMessage.mockClear();await sendRuntimeMessage({ name: "save-whole-screenshot" });expect(lastPayload()).toMatchObject({ pageUrl: PAGE_URL });- expect(await lastToast()).toBeUndefined();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);});it("crops the screenshot on a canvas under Manifest V2", async () => {@@ -284,10 +330,14 @@ describe("background", () => {});getContext.mockReturnValue(null);- await expect(onCommand("saveCroppedScreenshot")).rejects.toBeUndefined();+ tabsSendMessage.mockClear();+ await onCommand("saveCroppedScreenshot");+ expect(await lastToast()).toMatchObject(GENERIC_FAILURE_TOAST);image.fail = true;- await expect(onCommand("saveCroppedScreenshot")).rejects.toBeInstanceOf(Event);+ tabsSendMessage.mockClear();+ await onCommand("saveCroppedScreenshot");+ expect(await lastToast()).toMatchObject(GENERIC_FAILURE_TOAST);});});@@ -312,13 +362,13 @@ describe("background", () => {});expect(await lastToast()).toMatchObject({ noteId: "saved" });- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);tabsSendMessage.mockClear();await onContextMenuClicked({menuItemId: "trilium-save-image",srcUrl: "https://example.com/cat.png"});- expect(await lastToast()).toBeUndefined();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);});it("saves a link, with its URL as the text when the browser gives none", async () => {@@ -338,7 +388,7 @@ describe("background", () => {});expect(await lastToast()).toMatchObject({ noteId: "saved" });- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);tabsSendMessage.mockClear();await onContextMenuClicked({menuItemId: "trilium-save-link",@@ -347,7 +397,7 @@ describe("background", () => {expect(lastPayload()).toMatchObject({content: "<a href=\"https://example.com/target\">https://example.com/target</a>"});- expect(await lastToast()).toBeUndefined();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);});it("ignores unknown items and commands", async () => {@@ -384,17 +434,17 @@ describe("background", () => {expect(await lastToast()).toMatchObject({ noteId: "saved", tabIds: [ 1, 2, 4, 5 ] });});- it("adds no ellipsis for up to three tabs and shows no toast on failure", async () => {+ it("adds no ellipsis for up to three tabs and shows why saving failed", async () => {tabs = [{ id: 1, title: "A", url: "https://a.com/" },{ id: 2, title: "B", url: "https://b.com/" }];- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);await sendRuntimeMessage({ name: "save-tabs" });expect(lastPayload()).toMatchObject({ title: "2 browser tabs: a.com, b.com" });- expect(await lastToast()).toBeUndefined();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);});});@@ -415,8 +465,8 @@ describe("background", () => {});expect(await lastToast()).toMatchObject({ noteId: "saved" });- facade.callService.mockResolvedValue(null);- await expect(saveWithTitle("Mine")).resolves.toBe(false);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);+ await expect(saveWithTitle("Mine")).resolves.toBeUndefined();expect(lastPayload()).toMatchObject({ title: "Mine" });tabs = [ { id: 7, url: "https://example.com/untitled" } ];@@ -433,10 +483,12 @@ describe("background", () => {await openNote();expect(facade.callService).toHaveBeenLastCalledWith("POST", "open/n1");- facade.callService.mockResolvedValue(null);+ facade.callService.mockRejectedValue(TRILIUM_FAILURE);await openNote();+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);facade.callService.mockResolvedValue({ result: "open-in-browser" });+ vi.mocked(console.error).mockClear();await openNote();expect(console.error).toHaveBeenCalledOnce();expect(create).not.toHaveBeenCalled();diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex b5eb43d3be..58706e6a37 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -1,7 +1,7 @@import { randomString, type Rect } from "@/utils";import setupContextMenu from "./context_menu";-import TriliumServerFacade from "./trilium_server_facade";+import TriliumServerFacade, { TriliumError } from "./trilium_server_facade";type BackgroundMessage = {name: "toast";@@ -16,11 +16,14 @@ type BackgroundMessage = {name: "trilium-save-page";};+/** `linkText` is only available on Firefox. */+type ContextMenuInfo = Browser.contextMenus.OnClickData & { linkText?: string };+export default defineBackground(() => {const triliumServerFacade = new TriliumServerFacade();// Keyboard shortcuts- browser.commands.onCommand.addListener(async (command) => {+ browser.commands.onCommand.addListener((command) => showFailures(async () => {switch (command) {case "saveSelection":await saveSelection();@@ -39,7 +42,7 @@ export default defineBackground(() => {default:console.log("Unrecognized command", command);}- });+ }));setupContextMenu();@@ -156,9 +159,30 @@ export default defineBackground(() => {message,noteId,tabIds+ }).catch(() => {+ // Browser pages and the extension stores run no content script to show it.});}+ /** Runs a user action, and reports its failure in a toast instead of rejecting. */+ async function showFailures<T>(action: () => Promise<T>) {+ try {+ return await action();+ } catch (e) {+ console.error("Web clipper action failed", e);+ toast(failureMessage(e));+ return undefined;+ }+ }++ async function requestFromPage(message: BackgroundMessage) {+ const response = await sendMessageToActiveTab(message);+ if (!response) {+ throw new Error("The page could not be read. Reload it and try again.");+ }+ return response;+ }+function blob2base64(blob: Blob) {return new Promise<string | null>(resolve => {const reader = new FileReader();@@ -201,16 +225,12 @@ export default defineBackground(() => {}async function saveSelection() {- const payload = await sendMessageToActiveTab({name: 'trilium-save-selection'});+ const payload = await requestFromPage({name: 'trilium-save-selection'});await postProcessImages(payload);const resp = await triliumServerFacade.callService('POST', 'clippings', payload);- if (!resp) {- return;- }-toast("Selection has been saved to Trilium.", resp.noteId);}@@ -233,7 +253,10 @@ export default defineBackground(() => {}async function saveCroppedScreenshot(pageUrl: string | null | undefined) {- const { rect, devicePixelRatio } = await sendMessageToActiveTab({name: 'trilium-get-rectangle-for-screenshot'});+ const { rect, devicePixelRatio } = await requestFromPage({+ name: 'trilium-get-rectangle-for-screenshot'+ });+ if (!rect) return;const src = await takeCroppedScreenshot(rect, devicePixelRatio);@@ -241,10 +264,6 @@ export default defineBackground(() => {const resp = await triliumServerFacade.callService("POST", "clippings", payload);- if (!resp) {- return;- }-toast("Screenshot has been saved to Trilium.", resp.noteId);}@@ -255,10 +274,6 @@ export default defineBackground(() => {const resp = await triliumServerFacade.callService("POST", "clippings", payload);- if (!resp) {- return;- }-toast("Screenshot has been saved to Trilium.", resp.noteId);}@@ -267,24 +282,16 @@ export default defineBackground(() => {const resp = await triliumServerFacade.callService("POST", "clippings", payload);- if (!resp) {- return;- }-toast("Image has been saved to Trilium.", resp.noteId);}async function saveWholePage() {- const payload = await sendMessageToActiveTab({name: 'trilium-save-page'});+ const payload = await requestFromPage({name: 'trilium-save-page'});await postProcessImages(payload);const resp = await triliumServerFacade.callService('POST', 'notes', payload);- if (!resp) {- return;- }-toast("Page has been saved to Trilium.", resp.noteId);}@@ -302,10 +309,6 @@ export default defineBackground(() => {pageUrl: activeTab.url});- if (!resp) {- return false;- }-toast("Link with note has been saved to Trilium.", resp.noteId);return true;@@ -345,13 +348,12 @@ export default defineBackground(() => {const payload = await getTabsPayload(tabs);const resp = await triliumServerFacade.callService('POST', 'notes', payload);- if (!resp) return;const tabIds = tabs.map(tab => tab.id).filter(id => id !== undefined) as number[];toast(`${tabs.length} links have been saved to Trilium.`, resp.noteId, tabIds);}- browser.contextMenus.onClicked.addListener(async (info: globalThis.Browser.contextMenus.OnClickData & { linkText?: string; }) => {+ browser.contextMenus.onClicked.addListener((info: ContextMenuInfo) => showFailures(async () => {if (info.menuItemId === 'trilium-save-selection') {await saveSelection();}@@ -378,7 +380,6 @@ export default defineBackground(() => {pageUrl: info.pageUrl});- if (!resp) return;toast("Link has been saved to Trilium.", resp.noteId);}else if (info.menuItemId === 'trilium-save-page') {@@ -387,18 +388,14 @@ export default defineBackground(() => {else {console.log("Unrecognized menuItemId", info.menuItemId);}- });+ }));- browser.runtime.onMessage.addListener(async request => {+ browser.runtime.onMessage.addListener((request) => showFailures(async () => {console.log("Received", request);if (request.name === 'openNoteInTrilium') {const resp = await triliumServerFacade.callService('POST', `open/${request.noteId}`);- if (!resp) {- return;- }-// desktop app is not available so we need to open in browserif (resp.result === 'open-in-browser') {const {triliumServerUrl} = await browser.storage.sync.get("triliumServerUrl");@@ -451,5 +448,11 @@ export default defineBackground(() => {triliumServerFacade.triggerSearchNoteByUrl(activeTab.url);}}- });+ }));});++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.";+}diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.tsindex 07c4e998f9..e4acad173b 100644--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fakeBrowser } from "wxt/testing/fake-browser";-import TriliumServerFacade from "./trilium_server_facade";+import TriliumServerFacade, { TriliumError } from "./trilium_server_facade";const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise<Response>>();const SERVER = { triliumServerUrl: "https://trilium.example", authToken: "secret" };@@ -150,20 +150,28 @@ describe("TriliumServerFacade", () => {expect(fetchMock.mock.lastCall?.[1]).not.toHaveProperty("body");});- it("sends no token to the desktop app and returns null when a request fails", async () => {+ it("sends no token to the desktop app and reports why a request failed", async () => {fetchMock.mockResolvedValue(handshake("1.0"));const facade = await createFacade();+ const openNote = () => facade.callService("POST", "open/abc");- fetchMock.mockResolvedValue(new Response("Note not found", { status: 404 }));- await expect(facade.callService("POST", "open/abc")).resolves.toBeNull();+ const notFound = Response.json({ message: "Note 'abc' not found" }, { status: 404 });+ fetchMock.mockResolvedValue(notFound);+ await expect(openNote()).rejects.toThrow(requestFailed("Note 'abc' not found"));expect(fetchMock).toHaveBeenLastCalledWith("http://127.0.0.1:37742/api/clipper/open/abc",expect.objectContaining({headers: expect.objectContaining({ Authorization: "" })}));+ fetchMock.mockResolvedValue(new Response("Bad gateway", { status: 502 }));+ await expect(openNote()).rejects.toThrow(requestFailed("Bad gateway"));++ fetchMock.mockResolvedValue(new Response("", { status: 500 }));+ await expect(openNote()).rejects.toThrow(requestFailed("500"));+fetchMock.mockRejectedValue(new Error("connection reset"));- await expect(facade.callService("POST", "open/abc")).resolves.toBeNull();+ await expect(openNote()).rejects.toThrow(requestFailed("connection reset"));});it("waits for a running search and rejects once Trilium is not found", async () => {@@ -183,14 +191,18 @@ describe("TriliumServerFacade", () => {fetchMock.mockReset();fetchMock.mockRejectedValue(new Error("connection refused"));await facade.triggerSearchForTrilium();- await expect(facade.callService("GET", "notes-by-url/x")).rejects.toThrow();+ await expect(facade.callService("GET", "notes-by-url/x"))+ .rejects.toThrow(expect.objectContaining({ reason: "not-found" }));});- it("returns undefined while Trilium has a different protocol version", async () => {+ it("rejects while Trilium has a different protocol version", async () => {fetchMock.mockResolvedValue(handshake("0.9"));const facade = await createFacade();- await expect(facade.callService("GET", "notes-by-url/x")).resolves.toBeUndefined();+ const call = facade.callService("GET", "notes-by-url/x");+ await expect(call).rejects.toBeInstanceOf(TriliumError);+ await expect(call)+ .rejects.toThrow(expect.objectContaining({ reason: "version-mismatch" }));expect(fetchMock).toHaveBeenCalledTimes(1);});});@@ -209,12 +221,18 @@ describe("TriliumServerFacade", () => {searchNote: { status: "found", noteId: "n1" }});- fetchMock.mockResolvedValue(Response.json({ noteId: null }));- await facade.triggerSearchNoteByUrl("https://example.com/b");- expect(sendMessage).toHaveBeenLastCalledWith({+ const notFound = {name: "trilium-previously-visited",searchNote: { status: "not-found", noteId: null }- });+ };+ fetchMock.mockResolvedValue(Response.json({ noteId: null }));+ await facade.triggerSearchNoteByUrl("https://example.com/b");+ expect(sendMessage).toHaveBeenLastCalledWith(notFound);++ sendMessage.mockClear();+ fetchMock.mockRejectedValue(new Error("connection reset"));+ await facade.triggerSearchNoteByUrl("https://example.com/c");+ expect(sendMessage).toHaveBeenLastCalledWith(notFound);});it("formats the local time with the time zone offset", async () => {@@ -239,6 +257,13 @@ describe("TriliumServerFacade", () => {});});+function requestFailed(message: string) {+ return expect.objectContaining({+ reason: "request-failed",+ message: expect.stringContaining(message)+ });+}+function handshake(protocolVersion: string) {return Response.json({ appName: "trilium", protocolVersion });}diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.tsindex c73f0ae364..2d3d3e28f9 100644--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts@@ -26,6 +26,18 @@ type TriliumSearchNoteStatus = {noteId: string};+/** A request to Trilium that failed, with a message that can be shown to the user. */+export class TriliumError extends Error {++ constructor(+ readonly reason: "not-found" | "version-mismatch" | "request-failed",+ message: string+ ) {+ super(message);+ }++}+export default class TriliumServerFacade {private triliumSearch?: TriliumSearchStatus;private triliumSearchNote?: TriliumSearchNoteStatus;@@ -155,7 +167,8 @@ export default class TriliumServerFacade {}async triggerSearchNoteByUrl(noteUrl: string) {- const resp = await this.callService('GET', `notes-by-url/${encodeURIComponent(noteUrl)}`);+ const resp = await this.callService('GET', `notes-by-url/${encodeURIComponent(noteUrl)}`)+ .catch(() => null);let newStatus: TriliumSearchNoteStatus;if (resp && resp.noteId) {newStatus = {@@ -176,7 +189,7 @@ export default class TriliumServerFacade {if (this.triliumSearch?.status === "searching") {setTimeout(checkStatus, 500);} else if (this.triliumSearch?.status === 'not-found') {- rej(new Error("Trilium instance has not been found."));+ rej(notFound());} else {res();}@@ -198,13 +211,23 @@ export default class TriliumServerFacade {async callService(method: string, path: string, body?: string | object) {await this.waitForTriliumSearch();- if (!this.triliumSearch || (this.triliumSearch.status !== 'found-desktop' && this.triliumSearch.status !== 'found-server')) return;+ const search = this.triliumSearch;+ if (search?.status === "version-mismatch") {+ const { extensionMajor, triliumMajor } = search;+ const outdated = extensionMajor > triliumMajor ? "Trilium" : "the web clipper";+ throw new TriliumError("version-mismatch", "This version of the web clipper does not "+ + `work with this version of Trilium. Update ${outdated} to the latest version.`);+ }+ if (search?.status !== "found-desktop" && search?.status !== "found-server") {+ throw notFound();+ }+ let response: Response;try {const fetchOptions: RequestInit = {method,headers: {- Authorization: "token" in this.triliumSearch ? this.triliumSearch.token ?? "" : "",+ Authorization: search.status === "found-server" ? search.token : "",'Content-Type': 'application/json','trilium-local-now-datetime': this.localNowDateTime()},@@ -214,23 +237,21 @@ export default class TriliumServerFacade {fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body);}- const url = `${this.triliumSearch.url}/api/clipper/${path}`;+ const url = `${search.url}/api/clipper/${path}`;console.log(`Sending ${method} request to ${url}`);- const response = await fetch(url, fetchOptions);-- if (!response.ok) {- throw new Error(await response.text());- }-- return await response.json();+ response = await fetch(url, fetchOptions);}catch (e) {- console.log("Sending request to trilium failed", e);+ throw requestFailed(e instanceof Error ? e.message : String(e));+ }- return null;+ if (!response.ok) {+ throw requestFailed(await readErrorMessage(response));}++ return await response.json();}localNowDateTime() {@@ -246,3 +267,24 @@ export default class TriliumServerFacade {return `${localTime}${sign}${hours}:${minutes}`;}}++function notFound() {+ return new TriliumError("not-found", "Trilium was not found. Start the desktop app, or check "+ + "the server address and token in the clipper's options.");+}++function requestFailed(details: string) {+ return new TriliumError("request-failed", `The request to Trilium failed: ${details}`);+}++/** Trilium answers a failed API request with `{ message }`; a proxy in front of it might not. */+async function readErrorMessage(response: Response) {+ const text = (await response.text()).trim();+ try {+ const { message } = JSON.parse(text) as { message?: unknown };+ if (typeof message === "string" && message) return message;+ } catch {+ // Not JSON, so the text is the message.+ }+ return text || `HTTP ${response.status}`;+}diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex 97cfdb371e..e61273da9f 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -55,6 +55,16 @@ The extension needs to connect to a running Trilium instance. By default, it scaIt's also possible to configure the [server](Server%20Installation.md) address if you don't run the desktop application, or want it to work without the desktop application running.+### When a clipping fails++After each clipping, a notification in the corner of the page confirms that it was saved, with a link to open the new note in Trilium. If the clipping could not be saved, the notification says why instead:++* 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 notification is shown on the page itself, so it does not appear on pages where extensions cannot run (such as the browser's own settings pages and the extension stores).+## Testing development versionsDevelopment versions are version pre-release versions, generally meant for testing purposes. These are not available in the Google or Firefox web stores, but can be downloaded from either: