Skip to content

Build your personal knowledge base with Trilium Notes

fix(text): toast CKEditor warnings instead of crashing (closes #10859)

Elian Dorancceef5cd8e67
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index fba90c157e..e493f10b19 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4070,6 +4070,8 @@
"task-state": "Task state:",
"text-snippet": "Text snippet",
"text-snippets-found-0": "Text snippets found: %0",
+ "the-file-is-too-large-to-be-uploaded-http-413-if-trilium-is-behind-a-reverse-proxy-raise-its-request-body-size-limit": "The file is too large to be uploaded (HTTP 413). If Trilium is behind a reverse proxy, raise its request body size limit.",
+ "the-server-responded-with-http-0": "The server responded with HTTP %0.",
"tip": "Tip",
"title": "Title",
"to-do-list": "To-do list",
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 3cdc8e1d9c..c6c654dfeb 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -21,12 +21,30 @@ export interface CKEditorApi {
addImage(noteId: string): Promise<void>;
}
+/**
+ * The `EventInfo` CKEditor hands to every listener as its *first* argument. Listeners on
+ * `show:warning` receive `(evt, data)` in that order — getting it backwards throws inside the
+ * event handler, which the watchdog reports as an editor crash (see #10859).
+ */
+export interface NotificationEventInfo {
+ stop(): void;
+}
+
+/** The payload of `Notification#show:warning`, as built by `Notification#_showNotification`. */
+export interface NotificationEventData {
+ /** The notification text. `Notification#showWarning` takes it as its first argument. */
+ message: string;
+ type: "success" | "info" | "warning";
+ /** Empty string when the caller did not supply one. */
+ title: string;
+}
+
interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "className" | "tabIndex"> {
contentLanguage: string | null | undefined;
isClassicEditor?: boolean;
watchdogRef: RefObject<EditorWatchdog>;
watchdogConfig?: WatchdogConfig;
- onNotificationWarning?: (evt: any, data: any) => void;
+ onNotificationWarning?: (evt: NotificationEventInfo, data: NotificationEventData) => void;
onWatchdogStateChange?: (watchdog: EditorWatchdog) => void;
onChange: () => void;
/** Called upon whenever a new CKEditor instance is initialized, whether it's the first initialization, after a crash or after a config change that requires it (e.g. content language). */
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
new file mode 100644
index 0000000000..7dfc629e16
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * Regression tests for https://github.com/TriliumNext/Trilium/issues/10859 ("Upload pic error").
+ *
+ * The warning handler used to read the listener arguments in the wrong order, so every CKEditor
+ * warning threw inside `Notification#fire`. The watchdog reported that as an `unexpected-error`
+ * crash and restarted the editor, which reverted the note to its last saved content — the images
+ * being uploaded flickered and vanished instead of a "cannot upload" toast appearing.
+ */
+import { describe, expect, it, vi } from "vitest";
+
+const showError = vi.hoisted(() => vi.fn());
+const showErrorTitleAndMessage = vi.hoisted(() => vi.fn());
+vi.mock("../../../services/toast", () => ({ default: { showError, showErrorTitleAndMessage } }));
+
+// Imported by EditableText for editor types and content styles; irrelevant (and heavy) here.
+vi.mock("@triliumnext/ckeditor5", () => ({}));
+
+const { onNotificationWarning } = await import("./EditableText");
+
+describe("onNotificationWarning", () => {
+ /** The payload `Notification#_showNotification` builds, with the `EventInfo` before it. */
+ function warn(data: { message: string; title: string }) {
+ const evt = { stop: vi.fn() };
+ onNotificationWarning(evt, { type: "warning", ...data });
+ return evt;
+ }
+
+ it("reports a titled warning as a titled toast and stops the event", () => {
+ // What a failed upload produces: FileUploadEditing passes the rejection reason as the
+ // message and "Upload failed" as the title.
+ const message = "Cannot upload file: pic.png.";
+ const evt = warn({ message, title: "Upload failed" });
+
+ expect(showErrorTitleAndMessage).toHaveBeenCalledWith("Upload failed", message);
+ expect(showError).not.toHaveBeenCalled();
+ // Stopping the event is what keeps the notification plugin's `window.alert` fallback away.
+ expect(evt.stop).toHaveBeenCalledOnce();
+ });
+
+ it("reports an untitled warning as a plain toast rather than dropping it", () => {
+ vi.clearAllMocks();
+ // `showWarning` leaves the title an empty string when the caller supplies none.
+ const evt = warn({ message: "Something went wrong.", title: "" });
+
+ expect(showError).toHaveBeenCalledWith("Something went wrong.");
+ expect(showErrorTitleAndMessage).not.toHaveBeenCalled();
+ expect(evt.stop).toHaveBeenCalledOnce();
+ });
+
+ it("stops the event even when there is nothing to report", () => {
+ vi.clearAllMocks();
+ const evt = warn({ message: "", title: "" });
+
+ expect(showError).not.toHaveBeenCalled();
+ expect(showErrorTitleAndMessage).not.toHaveBeenCalled();
+ expect(evt.stop).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index e45a25c513..066afb37ab 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -15,7 +15,7 @@ import toast from "../../../services/toast";
import utils, { isMobile } from "../../../services/utils";
import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import { TypeWidgetProps } from "../type_widget";
-import CKEditorWithWatchdog, { CKEditorApi } from "./CKEditorWithWatchdog";
+import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";
import getTemplates, { updateTemplateCache } from "./snippets.js";
import linkEmbedService from "../../../services/link_embed";
import { usesClassicToolbar } from "./toolbar";
@@ -578,13 +578,19 @@ function useWatchdogCrashHandling() {
return onWatchdogStateChange;
}
-function onNotificationWarning(data, evt) {
- const title = data.title;
- const message = data.message.message;
+/**
+ * Renders a CKEditor warning (a failed upload, most commonly) as a Trilium toast instead of the
+ * `window.alert` the notification plugin falls back to, and stops the event so that fallback never
+ * runs.
+ *
+ * Exported for testing.
+ */
+export function onNotificationWarning(evt: NotificationEventInfo, data: NotificationEventData) {
+ const { title, message } = data;
if (title && message) {
- toast.showErrorTitleAndMessage(data.title, data.message.message);
- } else if (title) {
+ toast.showErrorTitleAndMessage(title, message);
+ } else if (title || message) {
toast.showError(title || message);
}
diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
index 3ef3955fd6..8def718225 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
@@ -17,6 +17,7 @@ class FakeXHR {
public async?: boolean;
public responseType = "";
public response: unknown = undefined;
+ public status = 0;
public sentData: unknown = undefined;
public requestHeaders: Record<string, string> = {};
@@ -63,6 +64,17 @@ class FakeXHR {
}
}
+/** Waits for the adapter to create its request and send the form data, then hands it over. */
+async function awaitSentXhr(): Promise<FakeXHR> {
+ await vi.waitFor(() => expect(FakeXHR.last).toBeDefined());
+ const xhr = FakeXHR.last;
+ if (!xhr) {
+ throw new Error("XHR was never created.");
+ }
+ await vi.waitFor(() => expect(xhr.sentData).toBeInstanceOf(FormData));
+ return xhr;
+}
+
/**
* A minimal FileLoader stand-in: only the members the adapter touches.
*/
@@ -158,10 +170,31 @@ describe("UploadimagePlugin", () => {
}
await vi.waitFor(() => expect(xhr.sentData).toBeInstanceOf(FormData));
+ xhr.status = 500;
xhr.response = { uploaded: false, error: { message: "Disk full" } };
xhr.fireLoad();
- await expect(uploadPromise).rejects.toBe("Disk full");
+ await expect(uploadPromise).rejects.toBe("Cannot upload file: pic.png. Disk full");
+ });
+
+ it("explains a failure the response body cannot, from the status code alone", async () => {
+ // A reverse proxy enforcing its own body-size limit answers HTML, which the adapter parses
+ // as JSON and gets nothing from — the status is all there is to report (#10859).
+ for (const [ status, expected ] of [
+ [ 413, "Cannot upload file: pic.png. The file is too large to be uploaded (HTTP 413). If Trilium is behind a reverse proxy, raise its request body size limit." ],
+ [ 502, "Cannot upload file: pic.png. The server responded with HTTP 502." ]
+ ] as const) {
+ FakeXHR.last = undefined;
+ const adapter = createAdapter(new File(["content"], "pic.png", { type: "image/png" }));
+ const uploadPromise = adapter.upload();
+ const xhr = await awaitSentXhr();
+
+ xhr.status = status;
+ xhr.response = null;
+ xhr.fireLoad();
+
+ await expect(uploadPromise).rejects.toBe(expected);
+ }
});
it("rejects with a generic message when the response has no usable error", async () => {
diff --git a/packages/ckeditor5/src/plugins/uploadimage.ts b/packages/ckeditor5/src/plugins/uploadimage.ts
index ab108188a9..18f981cdaf 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.ts
@@ -1,4 +1,4 @@
-import { FileRepository, Plugin, type FileLoader, type UploadAdapter } from "ckeditor5";
+import { FileRepository, Plugin, type FileLoader, type LocaleTranslate, type UploadAdapter } from "ckeditor5";
export default class UploadimagePlugin extends Plugin {
static get requires() {
@@ -10,22 +10,25 @@ export default class UploadimagePlugin extends Plugin {
}
init() {
- this.editor.plugins.get('FileRepository').createUploadAdapter = loader => new Adapter(loader);
+ const t = this.editor.t;
+ this.editor.plugins.get('FileRepository').createUploadAdapter = loader => new Adapter(loader, t);
}
}
class Adapter implements UploadAdapter {
private loader: FileLoader;
+ private t: LocaleTranslate;
private xhr?: XMLHttpRequest;
/**
* Creates a new adapter instance.
*/
- constructor(loader: FileLoader) {
+ constructor(loader: FileLoader, t: LocaleTranslate) {
/**
* FileLoader instance to use during the upload.
*/
this.loader = loader;
+ this.t = t;
}
/**
@@ -100,7 +103,8 @@ class Adapter implements UploadAdapter {
return;
}
- const genericError = 'Cannot upload file:' + ` ${file.name}.`;
+ const t = this.t;
+ const genericError = t('Cannot upload file:') + ` ${file.name}.`;
xhr.addEventListener('error', () => reject(genericError));
xhr.addEventListener('abort', () => reject());
@@ -108,7 +112,7 @@ class Adapter implements UploadAdapter {
const response = xhr.response;
if (!response || !response.uploaded) {
- return reject(response && response.error && response.error.message ? response.error.message : genericError);
+ return reject(`${genericError} ${describeUploadFailure(t, xhr.status, response)}`.trim());
}
resolve({
@@ -146,3 +150,33 @@ class Adapter implements UploadAdapter {
}
}
}
+
+/**
+ * Explains why an upload the server answered did not produce an attachment.
+ *
+ * The response is parsed as JSON, so anything that rejects the request before it reaches Trilium —
+ * a reverse proxy enforcing its own body-size limit, most commonly — leaves nothing to quote and
+ * only the status code says what happened. Reporting it beats the bare "cannot upload" that used
+ * to be the only thing such a failure produced (#10859).
+ *
+ * @param status the HTTP status of the response.
+ * @param response the parsed response body, `null` when it was not JSON.
+ * @returns a sentence to append to the generic error, or an empty string when there is nothing to
+ * add.
+ */
+function describeUploadFailure(t: LocaleTranslate, status: number, response: { error?: { message?: string } } | null): string {
+ const serverMessage = response?.error?.message;
+ if (serverMessage) {
+ return serverMessage;
+ }
+
+ if (status === 413) {
+ return t('The file is too large to be uploaded (HTTP 413). If Trilium is behind a reverse proxy, raise its request body size limit.');
+ }
+
+ if (status) {
+ return t('The server responded with HTTP %0.', String(status));
+ }
+
+ return '';
+}