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
refactor(text): report editor errors instead of restarting through the watchdog
Elian Doran5511d6f2b98d
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 103941857f..e8f76f7afa 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -22,7 +22,7 @@ import imageContextMenuService from "../menus/image_context_menu.js";import { t } from "../services/i18n.js";import { type MediaEnvironment, showsFileActions } from "../widgets/type_widgets/file/media_environment.js";import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";-import type { BoxSize } from "../widgets/type_widgets/text/CKEditorWithWatchdog.js";+import type { BoxSize } from "../widgets/type_widgets/text/CKEditor.js";import renderText, {postProcessRichContent, renderChildrenList, renderTextContent} from "./content_renderer_text.js";diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex f092897dd4..92a49bd510 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1551,15 +1551,14 @@},"editable_text": {"placeholder": "Type the content of your note here...",- "editor_crashed_title": "The text editor crashed",- "editor_crashed_content": "Your content was recovered successfully, but a few of your most recent changes may not have been saved.","editor_crashed_details_button": "View more details...","editor_crashed_details_intro": "If you experience this error several times, consider reporting it on GitHub by pasting the information below.","editor_crashed_details_title": "Technical information","auto-detect-language": "Auto-detected",- "keeps-crashing": "Editing component keeps crashing. Please try restarting Trilium. If problem persists, consider creating a bug report.","nothing_selected_to_cut": "Select some text first to cut it into a sub-note.",- "uploading_attachment": "Uploading attachment"+ "uploading_attachment": "Uploading attachment",+ "editor_error_title": "The text editor ran into an error",+ "editor_error_content": "The editor is still open, but it might not work correctly until you reload Trilium. If anything looks wrong, copy your latest changes somewhere safe first."},"empty": {"open_note_instruction": "Open a note by typing the note's title into the input below or choose a note in the tree.",diff --git a/apps/client/src/widgets/dialogs/content_embed.tsx b/apps/client/src/widgets/dialogs/content_embed.tsxindex 4da6db3f94..2629eac905 100644--- a/apps/client/src/widgets/dialogs/content_embed.tsx+++ b/apps/client/src/widgets/dialogs/content_embed.tsx@@ -10,7 +10,7 @@ import { Suggestion } from "../../services/note_autocomplete";import tree from "../../services/tree";import froca from "../../services/froca";import { useNote, useTriliumEvent } from "../react/hooks";-import type { BoxSize, CKEditorApi } from "../type_widgets/text/CKEditorWithWatchdog";+import type { BoxSize, CKEditorApi } from "../type_widgets/text/CKEditor";export interface ContentEmbedOpts {editorApi: Pick<CKEditorApi, "addContentEmbed" | "addImage">;diff --git a/apps/client/src/widgets/dialogs/markdown_import.tsx b/apps/client/src/widgets/dialogs/markdown_import.tsxindex 4842205b33..d083eb0168 100644--- a/apps/client/src/widgets/dialogs/markdown_import.tsx+++ b/apps/client/src/widgets/dialogs/markdown_import.tsx@@ -10,7 +10,7 @@ import utils from "../../services/utils";import Button from "../react/Button";import { useTriliumEvent } from "../react/hooks";import Modal from "../react/Modal";-import type { CKEditorApi } from "../type_widgets/text/CKEditorWithWatchdog";+import type { CKEditorApi } from "../type_widgets/text/CKEditor";export interface MarkdownImportOpts {editorApi: CKEditorApi;diff --git a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsxindex 22744c4062..c5c606cb15 100644--- a/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx+++ b/apps/client/src/widgets/sidebar/TableOfContents.spec.tsx@@ -31,7 +31,7 @@ describe("useActiveHeading", () => {afterEach(() => vi.useRealTimers());it("re-subscribes when getHeadingElement changes, even though the container element does not", () => {- // The editor is swapped (watchdog recovery) while .scrolling-container, an ancestor of the+ // The editor is swapped (a rebuild) while .scrolling-container, an ancestor of the// editor root, stays put — so the listener has to follow getHeadingElement, not the container.const container = scrollingContainer();const probe = mount(container, headingLookup({ first: 0, second: 500 }));diff --git a/apps/client/src/widgets/sidebar/TableOfContents.tsx b/apps/client/src/widgets/sidebar/TableOfContents.tsxindex 7e7732cac1..4240fdfa2b 100644--- a/apps/client/src/widgets/sidebar/TableOfContents.tsx+++ b/apps/client/src/widgets/sidebar/TableOfContents.tsx@@ -198,7 +198,7 @@ export function useActiveHeading<T extends RawHeading>({ headings, scrollingContwindow.clearTimeout(timeoutId);scrollingContainer.removeEventListener("scroll", handleScroll);};- // getHeadingElement must re-subscribe the listener: when the watchdog replaces the editor,+ // getHeadingElement must re-subscribe the listener: when a rebuild replaces the editor,// .scrolling-container is an ancestor of the editor root and stays the same element, so// scrollingContainer alone would keep the listener mapping through the destroyed editor.}, [scrollingContainer, getHeadingElement]);diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsxsimilarity index 59%rename from apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsxrename to apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsxindex dd73078cfe..8782d588bd 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.spec.tsx@@ -1,27 +1,33 @@-import type { EditorWatchdog } from "@triliumnext/ckeditor5";+import type { CKEditorError, CKTextEditor } from "@triliumnext/ckeditor5";import { createRef, render } from "preact";import { useRef } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import link from "../../../services/link";-import CKEditorWithWatchdog, { type CKEditorApi } from "./CKEditorWithWatchdog";+import CKEditor, { type CKEditorApi } from "./CKEditor";const mocks = vi.hoisted(() => ({options: {} as Record<string, string | boolean>,create: vi.fn(async () => {}),destroy: vi.fn(async () => {}),+ stopReportingErrors: vi.fn(),+ reportError: undefined as ((error: Error) => void) | undefined,+ reportingEditor: undefined as unknown,note: undefined as { noteId: string; title: string } | undefined,handlers: {} as Record<string, (...args: unknown[]) => unknown>}));vi.mock("@triliumnext/ckeditor5", () => {- class MockEditorWatchdog {- setCreator() {}- on() {}- create() {- return mocks.create();+ class MockEditor {+ plugins = { has: () => false };+ model = { document: { on() {}, off() {} } };++ static async create() {+ await mocks.create();+ return new MockEditor();}+destroy() {return mocks.destroy();}@@ -29,9 +35,13 @@ vi.mock("@triliumnext/ckeditor5", () => {return {CKTextEditor: class {},- ClassicEditor: class {},- EditorWatchdog: MockEditorWatchdog,- PopupEditor: class {}+ ClassicEditor: MockEditor,+ PopupEditor: MockEditor,+ onTextEditorError: (editor: unknown, callback: (error: Error) => void) => {+ mocks.reportingEditor = editor;+ mocks.reportError = callback;+ return mocks.stopReportingErrors;+ }};});@@ -65,56 +75,73 @@ beforeEach(() => {mocks.note = undefined;mocks.create.mockClear();mocks.destroy.mockClear();+ mocks.stopReportingErrors.mockClear();+ mocks.reportError = undefined;+ mocks.reportingEditor = undefined;host = document.body.appendChild(document.createElement("div"));});-afterEach(() => {- render(null, host);+afterEach(async () => {+ // The unmount cleanup runs after paint and destroys the editor on the build queue, so both+ // are flushed before the next test counts calls.+ await act(async () => render(null, host));+ await new Promise((resolve) => setTimeout(resolve));document.body.innerHTML = "";});-describe("CKEditorWithWatchdog", () => {+describe("CKEditor", () => {it("rebuilds an open editor when the MathLive option changes", async () => {- const watchdogRef = createRef<EditorWatchdog>();- const editorApi = createRef<CKEditorApi>();const props = {contentLanguage: null,- watchdogRef,+ editorRef: createRef<CKTextEditor>(),onChange: vi.fn(),- editorApi,+ editorApi: createRef<CKEditorApi>(),templates: []};await act(async () => {- render(<CKEditorWithWatchdog {...props} />, host);+ render(<CKEditor {...props} />, host);});await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledTimes(1));+ const firstEditor = props.editorRef.current;mocks.options.mathFieldEnabled = false;await act(async () => {- render(<CKEditorWithWatchdog {...props} className="force-rerender" />, host);+ render(<CKEditor {...props} className="force-rerender" />, host);});await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledTimes(2));expect(mocks.destroy).toHaveBeenCalledTimes(1);+ expect(mocks.stopReportingErrors).toHaveBeenCalledTimes(1);+ expect(props.editorRef.current).not.toBe(firstEditor);+ expect(mocks.reportingEditor).toBe(props.editorRef.current);});- it("destroys its editor when it goes away", async () => {+ it("hands the errors of its editor to onEditorError, until it destroys the editor", async () => {+ const onEditorError = vi.fn();const props = {contentLanguage: null,- watchdogRef: createRef<EditorWatchdog>(),+ editorRef: createRef<CKTextEditor>(),onChange: vi.fn(),+ onEditorError,editorApi: createRef<CKEditorApi>(),templates: []};await act(async () => {- render(<CKEditorWithWatchdog {...props} />, host);+ render(<CKEditor {...props} />, host);});await vi.waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ expect(props.editorRef.current).not.toBeNull();+ expect(mocks.reportingEditor).toBe(props.editorRef.current);+ const error = new Error("editor-error") as CKEditorError;+ mocks.reportError?.(error);+ expect(onEditorError).toHaveBeenCalledExactlyOnceWith(error);+await act(async () => render(null, host));await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce());- expect(props.watchdogRef.current).toBeNull();+ expect(mocks.stopReportingErrors).toHaveBeenCalledOnce();+ expect(props.editorRef.current).toBeNull();});it("labels its reference links as links in the note it edits", async () => {@@ -123,13 +150,13 @@ describe("CKEditorWithWatchdog", () => {.mockResolvedValue(undefined);const props = {contentLanguage: null,- watchdogRef: createRef<EditorWatchdog>(),+ editorRef: createRef<CKTextEditor>(),onChange: vi.fn(),editorApi: createRef<CKEditorApi>(),templates: []};await act(async () => {- render(<CKEditorWithWatchdog {...props} />, host);+ render(<CKEditor {...props} />, host);});const $el = $("<span>");diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxsimilarity index 81%rename from apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxrename to apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex e238fbd2ed..56a8202dc1 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -1,4 +1,4 @@-import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, SnippetDefinition, type WatchdogConfig } from "@triliumnext/ckeditor5";+import { type CKEditorError, CKTextEditor, ClassicEditor, onTextEditorError, PopupEditor, SnippetDefinition } from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import { HTMLAttributes, RefObject } from "preact";import { useEffect, useImperativeHandle, useRef, useState } from "preact/hooks";@@ -27,7 +27,7 @@ export interface CKEditorApi {/*** 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).+ * event handler, which reaches `onEditorError` as an editor error (see #10859).*/export interface NotificationEventInfo {stop(): void;@@ -42,25 +42,28 @@ export interface NotificationEventData {title: string;}-interface CKEditorWithWatchdogProps extends Pick<HTMLAttributes<HTMLDivElement>, "className" | "tabIndex"> {+interface CKEditorProps extends Pick<HTMLAttributes<HTMLDivElement>, "className" | "tabIndex"> {contentLanguage: string | null | undefined;isClassicEditor?: boolean;- watchdogRef: RefObject<EditorWatchdog | null>;- watchdogConfig?: WatchdogConfig;+ editorRef: RefObject<CKTextEditor | null>;onNotificationWarning?: (evt: NotificationEventInfo, data: NotificationEventData) => void;onNotificationInfo?: (evt: NotificationEventInfo, data: NotificationEventData) => void;- onWatchdogStateChange?: (watchdog: EditorWatchdog) => void;+ /** Called with each error that escapes the editor. The editor keeps running after it. */+ onEditorError?: (error: CKEditorError) => 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). */+ /** Called each time a CKEditor instance is built: on the first render and after a config change that requires it (e.g. content language). */onEditorInitialized?: (editor: CKTextEditor) => void;editorApi: RefObject<CKEditorApi | null>;templates: SnippetDefinition[];containerRef?: RefObject<HTMLDivElement | null>;}-export default function CKEditorWithWatchdog({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, watchdogRef: externalWatchdogRef, watchdogConfig, onNotificationWarning, onNotificationInfo, onWatchdogStateChange, onChange, onEditorInitialized, editorApi, templates }: CKEditorWithWatchdogProps) {+export default function CKEditor({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError, onChange, onEditorInitialized, editorApi, templates }: CKEditorProps) {const containerRef = useSyncedRef<HTMLDivElement>(externalContainerRef, null);- const watchdogRef = useRef<EditorWatchdog>(null);+ const editorRef = useRef<CKTextEditor>(null);+ const stopReportingErrorsRef = useRef<() => void>(undefined);+ const onEditorErrorRef = useRef(onEditorError);+ onEditorErrorRef.current = onEditorError;// Serializes editor build/teardown so overlapping effect runs never operate on the same// container concurrently. Under Vite + Prefresh HMR, effects are force-re-run (ignoring the// dependency array) and can fire several times in quick succession; without this queue two@@ -126,13 +129,13 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReuseImperativeHandle(editorApi, () => ({hasSelection() {- const model = watchdogRef.current?.editor?.model;+ const model = editorRef.current?.model;const selection = model?.document.selection;return !selection?.isCollapsed;},getSelectedText() {- const range = watchdogRef.current?.editor?.model.document.selection.getFirstRange();+ const range = editorRef.current?.model.document.selection.getFirstRange();let text = "";if (!range) {@@ -148,7 +151,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRereturn text;},addLink(notePath, linkTitle, externalLink) {- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) return;if (linkTitle) {@@ -164,15 +167,15 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReeditor.editing.view.focus();},addLinkToEditor(linkHref, linkTitle) {- watchdogRef.current?.editor?.model.change((writer) => {- const insertPosition = watchdogRef.current?.editor?.model.document.selection.getFirstPosition();+ editorRef.current?.model.change((writer) => {+ const insertPosition = editorRef.current?.model.document.selection.getFirstPosition();if (insertPosition) {writer.insertText(linkTitle, { linkHref }, insertPosition);}});},addContentEmbed(noteId, boxSize) {- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) return;editor?.model.change((writer) => {@@ -187,7 +190,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe});},addHtmlToEditor(html: string) {- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) return;editor.model.change((writer) => {@@ -207,7 +210,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReeditor.editing.view.focus();},async addImage(noteId) {- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) return;const note = await froca.getNote(noteId);@@ -250,6 +253,15 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe}});+ async function destroyEditor() {+ const editor = editorRef.current;+ editorRef.current = null;+ externalEditorRef.current = null;+ stopReportingErrorsRef.current?.();+ stopReportingErrorsRef.current = undefined;+ await editor?.destroy();+ }+useEffect(() => {const container = containerRef.current;if (!container) return;@@ -262,57 +274,35 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReconst scrollContainer = container.closest<HTMLElement>(".scrolling-container");const scrollTop = scrollContainer?.scrollTop ?? 0;- // Ensure any previous watchdog is fully destroyed- if (watchdogRef.current) {- try {- await watchdogRef.current.destroy();- } catch (e) {- console.warn("Watchdog destroy failed", e);- }- watchdogRef.current = null;- }-+ await destroyEditor();if (isStale) return;- const watchdog = buildWatchdog(!!isClassicEditor, watchdogConfig);- watchdogRef.current = watchdog;- externalWatchdogRef.current = watchdog;-- watchdog.setCreator(async () => {- if (isStale) {- throw new Error("Editor creation cancelled");- }-- const editor = await buildEditor(container, !!isClassicEditor, {- isClassicEditor: !!isClassicEditor,- uiLanguage: uiLanguage as DISPLAYABLE_LOCALE_IDS,- contentLanguage: contentLanguage ?? null,- templates: templatesRef.current,- getNoteLocation: () => noteLocationRef.current- });-- if (isStale) {- await editor.destroy();- throw new Error("Editor creation cancelled");- }-- setEditor(editor);-- if (import.meta.env.VITE_CKEDITOR_ENABLE_INSPECTOR === "true") {- const CKEditorInspector = (await import("@ckeditor/ckeditor5-inspector")).default;- CKEditorInspector.attach(editor);- }+ const editor = await buildEditor(container, !!isClassicEditor, {+ isClassicEditor: !!isClassicEditor,+ uiLanguage: uiLanguage as DISPLAYABLE_LOCALE_IDS,+ contentLanguage: contentLanguage ?? null,+ templates: templatesRef.current,+ getNoteLocation: () => noteLocationRef.current+ });- onEditorInitialized?.(editor);+ if (isStale) {+ await editor.destroy();+ return;+ }- return editor;+ editorRef.current = editor;+ externalEditorRef.current = editor;+ stopReportingErrorsRef.current = onTextEditorError(editor, (error) => {+ onEditorErrorRef.current?.(error);});+ setEditor(editor);- if (onWatchdogStateChange) {- watchdog.on("stateChange", () => onWatchdogStateChange(watchdog));+ if (import.meta.env.VITE_CKEDITOR_ENABLE_INSPECTOR === "true") {+ const CKEditorInspector = (await import("@ckeditor/ckeditor5-inspector")).default;+ CKEditorInspector.attach(editor);}- await watchdog.create(container, {});+ onEditorInitialized?.(editor);if (isStale || !scrollContainer || !scrollTop) return;@@ -357,14 +347,9 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe// Destroys the editor when the component goes away, after a build still in progress.useEffect(() => () => {buildQueueRef.current = buildQueueRef.current- .then(async () => {- const watchdog = watchdogRef.current;- watchdogRef.current = null;- externalWatchdogRef.current = null;- await watchdog?.destroy();- })+ .then(destroyEditor).catch((e) => {- console.warn("Watchdog destroy failed", e);+ console.warn("CKEditor destroy failed", e);});}, []);@@ -423,14 +408,6 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe);}-function buildWatchdog(isClassicEditor: boolean, watchdogConfig?: WatchdogConfig): EditorWatchdog {- if (isClassicEditor) {- return new EditorWatchdog(ClassicEditor, watchdogConfig);- }- return new EditorWatchdog(PopupEditor, watchdogConfig);--}-async function buildEditor(element: HTMLElement, isClassicEditor: boolean, opts: BuildEditorOptions) {const editorClass = isClassicEditor ? ClassicEditor : PopupEditor;const config = await buildConfig(opts);diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex 08c3b95f61..e3fa5ab789 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -6,7 +6,7 @@* 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 type { CKTextEditor, FileUploadData } from "@triliumnext/ckeditor5";+import type { CKEditorError, CKTextEditor, FileUploadData } from "@triliumnext/ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import type LoadResults from "../../../services/load_results";@@ -24,6 +24,9 @@ vi.mock("../../../services/i18n", async (importOriginal) => ({t: (key: string) => key}));+const showInfoDialog = vi.hoisted(() => vi.fn());+vi.mock("../../../services/dialog", () => ({ default: { info: showInfoDialog } }));+// Imported by EditableText for editor types and content styles; irrelevant (and heavy) here.vi.mock("@triliumnext/ckeditor5", () => ({}));@@ -33,11 +36,41 @@ const {notifyAttachmentChanges,onNotificationInfo,onNotificationWarning,+ reportEditorError,revealLinkTargetWhenReady,showFileUploadProgress,watchEditorBlocks} = await import("./EditableText");+describe("reportEditorError", () => {+ it("logs the error and shows a toast that opens its details", () => {+ vi.clearAllMocks();+ const logError = vi.fn();+ vi.stubGlobal("logError", logError);+ const error = new Error("unexpected-error Original error: TypeError: boom") as CKEditorError;++ reportEditorError(error);++ expect(logError).toHaveBeenCalledExactlyOnceWith(expect.stringContaining("TypeError: boom"));+ expect(showPersistent).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({+ id: "editor-error",+ title: "editable_text.editor_error_title",+ message: "editable_text.editor_error_content"+ }));++ const [ { buttons } ] = showPersistent.mock.calls[0];+ const dismissToast = vi.fn();+ buttons[0].onClick({ dismissToast });+ expect(dismissToast).toHaveBeenCalledOnce();+ expect(showInfoDialog).toHaveBeenCalledExactlyOnceWith(+ expect.anything(),+ expect.objectContaining({ title: "editable_text.editor_error_title", copyToClipboardButton: true })+ );+ expect(JSON.stringify(showInfoDialog.mock.calls[0][0])).toContain("TypeError: boom");+ vi.unstubAllGlobals();+ });+});+describe("onNotificationWarning", () => {/** The payload `Notification#_showNotification` builds, with the `EventInfo` before it. */function warn(data: { message: string; title: string }) {diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex de29fd3e97..2c94aff46f 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -3,15 +3,15 @@ import "./LinkEmbed.css";import {type AttachmentLinkChange,+ type CKEditorError,CKTextEditor,- EditorWatchdog,type FileUploadData,type FileUploadEvent,SnippetDefinition} from "@triliumnext/ckeditor5";import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";import { createPortal } from "preact";-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import {@@ -37,7 +37,7 @@ import IconPicker from "../../react/IconPicker";import { setEditorNoteId } from "../../react/NoteStore";import { TypeWidgetProps } from "../type_widget";import AttachmentSaves, { useNoteEditor } from "./attachment_saves";-import CKEditorWithWatchdog, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditorWithWatchdog";+import CKEditor, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditor";import { getContentEmbedTools } from "./content_embed_tools";import { useEmbedEditors } from "./editable_embed";import getTemplates, { updateTemplateCache } from "./snippets.js";@@ -71,12 +71,12 @@ export default function EditableText({}: EditableTextProps) {const containerRef = useRef<HTMLDivElement>(null);const contentRef = useRef<string>("");- /** The note `contentRef` holds the content of, so a restarted editor can be marked as holding it. */+ /** The note `contentRef` holds the content of, so a rebuilt editor can be marked as holding it. */const contentNoteIdRef = useRef<string | undefined>(undefined);const pendingAttachmentChangesRef = useRef<PendingAttachmentChanges | undefined>(undefined);/** The attachment whose embed takes the focus when it renders next. */const focusedAttachmentIdRef = useRef<string | undefined>(undefined);- const watchdogRef = useRef<EditorWatchdog>(null);+ const editorRef = useRef<CKTextEditor>(null);const stopWatchingEmbedsRef = useRef<(() => void) | undefined>(undefined);const editorApiRef = useRef<CKEditorApi>(null);/** The open icon picker request and its balloon container, or `null` when none is open. */@@ -105,16 +105,16 @@ export default function EditableText({noteType: "text",block,getData() {- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) {- // There is nothing to save, most likely a result of the editor crashing and reinitializing.+ // The editor is still being built, so there is nothing to save.return;}const attachments = attachmentSaves.collect();const savedAttachments = attachments.length ? { attachments } : {};if (block !== undefined) {- return { ...getBlockData(editor as CKTextEditor, block), ...savedAttachments };+ return { ...getBlockData(editor, block), ...savedAttachments };}const content = editor.getData() ?? "";@@ -129,14 +129,13 @@ export default function EditableText({attachmentSaves.setNoteId(note?.noteId);contentRef.current = newContent;contentNoteIdRef.current = note?.noteId;- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (editor && note) {setEditorNoteId(editor, note.noteId);}editor?.setData(newContent);if (editor && note) {- const textEditor = editor as CKTextEditor;- applyPendingAttachmentChanges(textEditor, note.noteId, pendingAttachmentChangesRef);+ applyPendingAttachmentChanges(editor, note.noteId, pendingAttachmentChangesRef);}// Jump to the first search match when navigated from search results.@@ -148,7 +147,7 @@ export default function EditableText({);},dataSaved(savedData) {- // Store back the saved data in order to retrieve it in case the CKEditor crashes.+ // Keeps the saved data, which a rebuilt editor loads in `onEditorInitialized`.contentRef.current = savedData.content;contentNoteIdRef.current = note?.noteId;attachmentSaves.markSaved(savedData.attachments);@@ -165,13 +164,13 @@ export default function EditableText({});function revealLinkTarget() {- const root = watchdogRef.current?.editor?.editing.view.getDomRoot();+ const root = editorRef.current?.editing.view.getDomRoot();consumeBookmark(root, noteContext?.viewScope);consumeBlockReference(root, noteContext?.viewScope);}async function copyReference(copy = copyBlockReference) {- const editor = watchdogRef.current?.editor as CKTextEditor | undefined;+ const editor = editorRef.current;if (!editor) return;const notePath = noteContext?.notePath ?? `root/${note.noteId}`;@@ -181,7 +180,7 @@ export default function EditableText({}useTriliumEvent("scrollToEnd", () => {- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) return;editor.model.change((writer) => {@@ -195,7 +194,7 @@ export default function EditableText({useTriliumEvent("focusOnDetail", async ({ ntxId: eventNtxId, insertNewlineAtTop }) => {if (eventNtxId !== ntxId) return;- const editor = await waitForEditor() as CKTextEditor | undefined;+ const editor = await waitForEditor();if (!editor) return;if (insertNewlineAtTop) {placeCursorInNewTopParagraph(editor);@@ -348,7 +347,7 @@ export default function EditableText({// This component's own editor, rather than noteContext.getTextEditor(): that one races the// round trip through the event bus against a 200 ms timeout and resolves to null when it// loses, which again meant an empty sub-note and a selection left where it was.- const textEditor = await waitForEditor() as CKTextEditor | undefined;+ const textEditor = await waitForEditor();if (!sourceNote || !parentNotePath || !textEditor) return;if (!textEditor.getSelectedHtml()) {@@ -377,7 +376,7 @@ export default function EditableText({useEffect(() => () => stopWatchingEmbedsRef.current?.(), []);useTriliumEvent("entitiesReloaded", ({ loadResults }) => {- const editor = watchdogRef.current?.editor as CKTextEditor | null | undefined;+ const editor = editorRef.current;if (editor && note) {notifyAttachmentChanges(editor,@@ -391,7 +390,7 @@ export default function EditableText({useTriliumEvent("executeWithTextEditor", async ({ callback, resolve, ntxId: eventNtxId }) => {if (eventNtxId !== ntxId) return;- const editor = await waitForEditor() as CKTextEditor | undefined;+ const editor = await waitForEditor();if (!editor) return;if (callback) callback(editor);resolve(editor);@@ -399,7 +398,7 @@ export default function EditableText({async function waitForEditor() {await initialized.current;- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (!editor) return;return editor;}@@ -419,8 +418,6 @@ export default function EditableText({addTextToEditor(text);});- const onWatchdogStateChange = useWatchdogCrashHandling();-useEffect(() => {document.body.style.setProperty("--code-block-tab-width", codeBlockTabWidth || "4");}, [codeBlockTabWidth]);@@ -593,31 +590,23 @@ export default function EditableText({return (<>- {note && !!templates && <CKEditorWithWatchdog+ {note && !!templates && <CKEditorcontainerRef={containerRef}className={`note-detail-editable-text-editor use-tn-links ${codeBlockWordWrap ? "word-wrap" : ""}`}tabIndex={300}contentLanguage={language}isClassicEditor={isClassicEditor}editorApi={editorApiRef}- watchdogRef={watchdogRef}- watchdogConfig={{- // An average number of milliseconds between the last editor errors (defaults to 5000). When the period of time between errors is lower than that and the crashNumberLimit is also reached, the watchdog changes its state to crashedPermanently, and it stops restarting the editor. This prevents an infinite restart loop.- minimumNonErrorTimePeriod: 5000,- // A threshold specifying the number of errors (defaults to 3). After this limit is reached and the time between last errors is shorter than minimumNonErrorTimePeriod, the watchdog changes its state to crashedPermanently, and it stops restarting the editor. This prevents an infinite restart loop.- crashNumberLimit: 10,- // A minimum number of milliseconds between saving the editor data internally (defaults to 5000). Note that for large documents, this might impact the editor performance.- saveInterval: Number.MAX_SAFE_INTEGER- }}+ editorRef={editorRef}templates={templates}onNotificationWarning={onNotificationWarning}onNotificationInfo={onNotificationInfo}- onWatchdogStateChange={onWatchdogStateChange}+ onEditorError={reportEditorError}onChange={() => {spacedUpdate.scheduleUpdate();- const editor = watchdogRef.current?.editor;+ const editor = editorRef.current;if (editor) {- reportBlocks?.(editor as CKTextEditor);+ reportBlocks?.(editor);}}}onEditorInitialized={(editor) => {@@ -637,8 +626,8 @@ export default function EditableText({editor.plugins.get("BlockReferenceEditing").editRange();}initialized.current.resolve();- // Restore the data, either on the first render or if the editor crashes.- // We are not using CKEditor's built-in watch dog content, instead we are using the data we store regularly in the spaced update (see `dataSaved`).+ // Loads the content on the first build and after a rebuild, from the data the+ // spaced update last saved (see `dataSaved`).if (contentNoteIdRef.current) {setEditorNoteId(editor, contentNoteIdRef.current);}@@ -760,62 +749,44 @@ function useTemplates() {return templates;}-function useWatchdogCrashHandling() {- const hasCrashed = useRef(false);- const onWatchdogStateChange = useCallback((watchdog: EditorWatchdog) => {- const currentState = watchdog.state;- logInfo(`CKEditor state changed to ${currentState}`);-- if (currentState === "ready" && hasCrashed.current) {- hasCrashed.current = false;- watchdog.editor?.focus();- }-- if (!["crashed", "crashedPermanently"].includes(currentState)) {- return;- }-- hasCrashed.current = true;- const formattedCrash = JSON.stringify(watchdog.crashes, null, 4);- logError(`CKEditor crash logs: ${formattedCrash}`);-- if (currentState === "crashed") {- toast.showPersistent({- id: "editor-crashed",- icon: "bx bx-bug",- title: t("editable_text.editor_crashed_title"),- message: t("editable_text.editor_crashed_content"),- buttons: [- {- text: t("editable_text.editor_crashed_details_button"),- onClick: ({ dismissToast }) => {- dismissToast();- dialog.info(<>- <p>{t("editable_text.editor_crashed_details_intro")}</p>- <h3>{t("editable_text.editor_crashed_details_title")}</h3>- <pre><code class="language-application-json">{formattedCrash}</code></pre>- </>, {- title: t("editable_text.editor_crashed_title"),- size: "lg",- copyToClipboardButton: true- });- }- }- ],- timeout: 20_000- });- } else if (currentState === "crashedPermanently") {- toast.showPersistent({- id: "editor-crashed-permanently",- icon: "bx bx-error-circle",- title: t("editable_text.editor_crashed_title"),- message: t("editable_text.keeps-crashing")- });- watchdog.editor?.enableReadOnlyMode("crashed-editor");- }- }, []);-- return onWatchdogStateChange;+/**+ * Logs an error that escaped the editor and tells the user about it in a toast, which opens the+ * error details for a bug report. The editor keeps running, so a later error replaces the toast.+ *+ * Exported for testing.+ */+export function reportEditorError(error: CKEditorError) {+ const details = JSON.stringify({+ message: error.message,+ stack: error.stack,+ date: new Date().toISOString()+ }, null, 4);+ logError(`CKEditor error: ${details}`);++ toast.showPersistent({+ id: "editor-error",+ icon: "bx bx-bug",+ title: t("editable_text.editor_error_title"),+ message: t("editable_text.editor_error_content"),+ buttons: [+ {+ text: t("editable_text.editor_crashed_details_button"),+ onClick: ({ dismissToast }) => {+ dismissToast();+ dialog.info(<>+ <p>{t("editable_text.editor_crashed_details_intro")}</p>+ <h3>{t("editable_text.editor_crashed_details_title")}</h3>+ <pre><code class="language-application-json">{details}</code></pre>+ </>, {+ title: t("editable_text.editor_error_title"),+ size: "lg",+ copyToClipboardButton: true+ });+ }+ }+ ],+ timeout: 20_000+ });}/**diff --git a/packages/ckeditor5/src/custom_watchdog.spec.ts b/packages/ckeditor5/src/custom_watchdog.spec.tsdeleted file mode 100644index b05ed2cae3..0000000000--- a/packages/ckeditor5/src/custom_watchdog.spec.ts+++ /dev/null@@ -1,124 +0,0 @@-import { CKEditorError, ClassicEditor, EditorWatchdog } from "ckeditor5";-import { beforeEach, describe, expect, it, vi } from "vitest";--import CustomWatchdog from "./custom_watchdog.js";--/**- * Creates a minimal CKEditorError-shaped object for use as a test double.- * The method under test only reads `.message`, so a plain Error with the right- * message and a cast is sufficient.- */-function makeCKEditorError(message: string): CKEditorError {- const err = new Error(message) as unknown as CKEditorError;- return err;-}--describe("CustomWatchdog", () => {- let watchdog: CustomWatchdog;-- beforeEach(() => {- // Pass null as the Editor class — the watchdog can be instantiated without- // creating an actual editor instance, which is all we need here.- watchdog = new CustomWatchdog(null);- });-- describe("_isErrorComingFromThisItem", () => {- it("returns false when the error message contains the first ignored pattern", () => {- const error = makeCKEditorError(- "TypeError: Cannot read properties of null (reading 'parent')"- );- expect(watchdog._isErrorComingFromThisItem(error)).toBe(false);- });-- it("returns false when the error message contains the second ignored pattern", () => {- const error = makeCKEditorError(- "Uncaught model-nodelist-offset-out-of-bounds error"- );- expect(watchdog._isErrorComingFromThisItem(error)).toBe(false);- });-- it("returns false for error message that exactly equals the first ignored string", () => {- const error = makeCKEditorError(- "TypeError: Cannot read properties of null (reading 'parent')"- );- expect(watchdog._isErrorComingFromThisItem(error)).toBe(false);- });-- it("delegates to super._isErrorComingFromThisItem when the error is not ignored", () => {- const unrelatedError = makeCKEditorError("Some unrelated editor error");-- // Spy on the prototype of the *parent* class so we can observe the super call- // and control the return value.- const superSpy = vi- .spyOn(EditorWatchdog.prototype, "_isErrorComingFromThisItem")- .mockReturnValue(true);-- const result = watchdog._isErrorComingFromThisItem(unrelatedError);-- expect(superSpy).toHaveBeenCalledWith(unrelatedError);- expect(result).toBe(true);-- superSpy.mockRestore();- });-- it("propagates the super return value of false when the error is not ignored", () => {- const unrelatedError = makeCKEditorError("Another unrelated error");-- const superSpy = vi- .spyOn(EditorWatchdog.prototype, "_isErrorComingFromThisItem")- .mockReturnValue(false);-- const result = watchdog._isErrorComingFromThisItem(unrelatedError);-- expect(superSpy).toHaveBeenCalledWith(unrelatedError);- expect(result).toBe(false);-- superSpy.mockRestore();- });-- it("does NOT call super when the first ignored pattern matches (short-circuits)", () => {- const error = makeCKEditorError(- "TypeError: Cannot read properties of null (reading 'parent') — stack ..."- );-- const superSpy = vi.spyOn(- EditorWatchdog.prototype,- "_isErrorComingFromThisItem"- );-- const result = watchdog._isErrorComingFromThisItem(error);-- expect(result).toBe(false);- expect(superSpy).not.toHaveBeenCalled();-- superSpy.mockRestore();- });-- it("does NOT call super when the second ignored pattern matches (short-circuits)", () => {- const error = makeCKEditorError("model-nodelist-offset-out-of-bounds");-- const superSpy = vi.spyOn(- EditorWatchdog.prototype,- "_isErrorComingFromThisItem"- );-- const result = watchdog._isErrorComingFromThisItem(error);-- expect(result).toBe(false);- expect(superSpy).not.toHaveBeenCalled();-- superSpy.mockRestore();- });- });-- describe("class identity", () => {- it("is an instance of EditorWatchdog", () => {- expect(watchdog).toBeInstanceOf(EditorWatchdog);- });-- it("can be constructed with a real Editor class", () => {- const watchdogWithEditor = new CustomWatchdog(ClassicEditor);- expect(watchdogWithEditor).toBeInstanceOf(CustomWatchdog);- });- });-});diff --git a/packages/ckeditor5/src/custom_watchdog.ts b/packages/ckeditor5/src/custom_watchdog.tsdeleted file mode 100644index ba0a732fd1..0000000000--- a/packages/ckeditor5/src/custom_watchdog.ts+++ /dev/null@@ -1,23 +0,0 @@-import { CKEditorError, EditorWatchdog } from "ckeditor5";--const IGNORED_ERRORS = [- // See: https://github.com/TriliumNext/Trilium/issues/5776- "TypeError: Cannot read properties of null (reading 'parent')",-- // See: https://github.com/TriliumNext/Trilium/issues/7739- "model-nodelist-offset-out-of-bounds"-]--export default class CustomWatchdog extends EditorWatchdog {-- _isErrorComingFromThisItem(error: CKEditorError): boolean {- for (const ignoredError of IGNORED_ERRORS) {- if (error.message.includes(ignoredError)) {- return false;- }- }-- return super._isErrorComingFromThisItem(error);- }--}diff --git a/packages/ckeditor5/src/editor_errors.spec.ts b/packages/ckeditor5/src/editor_errors.spec.tsnew file mode 100644index 0000000000..80e8078025--- /dev/null+++ b/packages/ckeditor5/src/editor_errors.spec.ts@@ -0,0 +1,49 @@+import { CKEditorError, Essentials, Paragraph } from "ckeditor5";+import { describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../test/editor-kit.js";+import { onTextEditorError } from "./editor_errors.js";++describe("onTextEditorError", () => {+ it("reports the errors of its editor, except the ignored ones, until it is stopped", async () => {+ const editor = await createTestEditor([Essentials, Paragraph]);+ const otherEditor = await createTestEditor([Essentials, Paragraph]);+ const callback = vi.fn();+ const stop = onTextEditorError(editor, callback);++ const reported = new CKEditorError("some-editor-error", editor);+ escape(reported);+ escape(new CKEditorError("other-editor-error", otherEditor));+ escape(new CKEditorError("model-nodelist-offset-out-of-bounds", editor));+ const unexpected = new Error("Cannot read properties of null (reading 'parent')");+ unexpected.name = "TypeError";+ escape(wrapUnexpectedError(unexpected, editor));++ expect(callback).toHaveBeenCalledExactlyOnceWith(reported);++ stop();+ escape(new CKEditorError("after-stop-error", editor));+ expect(callback).toHaveBeenCalledOnce();+ });+});++/**+ * Fires the `error` event a thrown error reaches `window` with, which `onEditorError()` listens to.+ * Vitest reports an `error` event as unhandled only while no other listener is registered.+ */+function escape(error: Error) {+ const listener = () => {};+ window.addEventListener("error", listener);+ window.dispatchEvent(new ErrorEvent("error", { error }));+ window.removeEventListener("error", listener);+}++/** The `unexpected-error` that CKEditor wraps a native error in before it leaves the editor. */+function wrapUnexpectedError(error: Error, context: object) {+ try {+ CKEditorError.rethrowUnexpectedError(error, context);+ } catch (wrapped) {+ return wrapped as CKEditorError;+ }+ throw new Error("rethrowUnexpectedError() did not throw");+}diff --git a/packages/ckeditor5/src/editor_errors.ts b/packages/ckeditor5/src/editor_errors.tsnew file mode 100644index 0000000000..8ea769ecfb--- /dev/null+++ b/packages/ckeditor5/src/editor_errors.ts@@ -0,0 +1,27 @@+import { type CKEditorError, type Editor, onEditorError } from "ckeditor5";++const IGNORED_ERRORS = [+ // See: https://github.com/TriliumNext/Trilium/issues/5776+ "TypeError: Cannot read properties of null (reading 'parent')",++ // See: https://github.com/TriliumNext/Trilium/issues/7739+ "model-nodelist-offset-out-of-bounds"+];++/**+ * Calls `callback` with each error that escapes `editor`, except the known errors in+ * `IGNORED_ERRORS`, and returns a function that stops the reporting.+ *+ * `onEditorError()` only reports: the editor keeps running after the error.+ */+export function onTextEditorError(editor: Editor, callback: (error: CKEditorError) => void) {+ return onEditorError(({ error, source }) => {+ if (source === editor && !isIgnoredError(error)) {+ callback(error);+ }+ });+}++function isIgnoredError(error: CKEditorError) {+ return IGNORED_ERRORS.some((ignoredError) => error.message.includes(ignoredError));+}diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 718ac5cb3f..2894f22c75 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -9,9 +9,9 @@ import type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.import type { PasteTarget } from "./plugins/cuttonote.js";import { CLASSIC_EDITOR_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";-export { default as EditorWatchdog } from "./custom_watchdog";+export { onTextEditorError } from "./editor_errors.js";export { CHAT_INPUT_PLUGINS, MEMO_PLUGINS } from "./plugins.js";-export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTransformationConfig, TextTypingTransformationDescription, WatchdogConfig, WatchdogState } from "ckeditor5";+export type { CKEditorError, EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTransformationConfig, TextTypingTransformationDescription } from "ckeditor5";export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";export type { PasteTarget } from "./plugins/cuttonote.js";