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(ai-assistant): typeset the equations a response holds
Elian Doranfc8e81b3f17f
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.tsindex 6d2bc53d29..402a29b38c 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts@@ -2,8 +2,10 @@ import { _getModelData as getModelData, _setModelData as setModelData, ButtonVieimport { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";-// The glue plugin is imported for its type augmentations alone (`config.mermaid`); the editing-// half is the one the specs load, being where the renderer lives.+// Both glue plugins are imported for their type augmentations alone (`config.math`,+// `config.mermaid`). Only Mermaid's editing half is loaded as a plugin, being where its renderer+// lives; the maths pass calls `renderEquation` directly, so the feature itself is not needed.+import type {} from "../math/math.js";import type {} from "../mermaid/mermaid.js";import MermaidEditing from "../mermaid/mermaid_editing.js";import TriliumAiAssistant from "./ai_assistant.js";@@ -678,6 +680,96 @@ describe("AiAssistantUI toolbar entry", () => {});});+ // An equation reaches the preview as its own LaTeX source, inside the `math-tex` span note HTML+ // stores it in — so a review of one used to read `\(c^2 = a^2 + b^2\)` where the note shows it+ // set. Same shape as the diagrams above: the editor only typesets on upcast.+ describe("equations in the preview", () => {+ const MATH_ACTION: AiQuickActionGroup[] = [{+ id: "edit",+ label: "Edit or review",+ actions: [{ id: "explain", label: "Explain", prompt: "Explain it.", reviewView: "result" }]+ }];++ /**+ * The typesetting engine, as the host's own function rather than KaTeX: `config.math.engine`+ * takes one, which keeps the assertions about what the assistant asks for — the equation+ * without its delimiters, and whether it is display maths.+ */+ function createEngineStub() {+ return vi.fn((equation: string, element: HTMLElement, display: boolean) => {+ element.textContent = `[${display ? "display" : "inline"}:${equation}]`;+ });+ }++ async function createMathEditor(response: string, engine?: ReturnType<typeof createEngineStub>) {+ return createTestEditor([Essentials, Paragraph, TriliumAiAssistant], {+ aiAssistant: { sanitizeHtml, quickActions: MATH_ACTION, stream: createStreamStub(response).stream },+ ...(engine ? { math: { engine } } : {})+ });+ }++ async function review(editor: ClassicEditor) {+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ quickActionButtons(createComponent(editor))[0].fire("execute");+ await vi.waitFor(() => expect(openForm(editor).phase).toBe("review"));+ }++ it("typesets the equations a finished response holds, inline and display alike", async () => {+ const engine = createEngineStub();+ const editor = await createMathEditor(+ String.raw`<p>so <span class="math-tex">\(c^2 = a^2 + b^2\)</span></p>`+ + String.raw`<span class="math-tex">\[e^{i\pi} = -1\]</span>`,+ engine+ );++ await review(editor);+ await vi.waitFor(() => expect(previewHtml(editor)).toContain("["));++ // The delimiters are the span's, not the equation's: the engine is handed the source+ // alone, and told from which pair it came whether to set it as display maths.+ expect(engine.mock.calls.map(([equation, , display]) => [equation, display])).toEqual([+ ["c^2 = a^2 + b^2", false],+ ["e^{i\\pi} = -1", true]+ ]);+ expect(previewHtml(editor)).toContain(`<span class="math-tex">[inline:c^2 = a^2 + b^2]</span>`);+ expect(previewHtml(editor)).toContain(`<span class="math-tex">[display:e^{i\\pi} = -1]</span>`);++ // The response itself is untouched, so the note is given the source the editor upcasts+ // into equations of its own.+ openForm(editor).fire("replace");+ expect(editor.getData()).toContain(String.raw`\(c^2 = a^2 + b^2\)`);+ });++ it("leaves the source standing when the host configured no maths", async () => {+ const html = String.raw`<p><span class="math-tex">\(x^2\)</span></p>`;+ const editor = await createMathEditor(html);++ await review(editor);+ expect(previewHtml(editor)).toBe(html);+ });++ it("leaves a half-streamed equation alone", async () => {+ const engine = createEngineStub();+ const editor = await createTestEditor([Essentials, Paragraph, TriliumAiAssistant], {+ aiAssistant: {+ sanitizeHtml,+ quickActions: MATH_ACTION,+ stream: async (_request, onData) => {+ onData(String.raw`<p><span class="math-tex">\(c^2 = a^2</span></p>`);+ await new Promise(() => {});+ }+ },+ math: { engine }+ });++ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ quickActionButtons(createComponent(editor))[0].fire("execute");++ await vi.waitFor(() => expect(previewHtml(editor)).toContain("math-tex"));+ expect(engine).not.toHaveBeenCalled();+ });+ });+it("is disabled when no LLM provider is configured", async () => {const editor = await createEditor(QUICK_ACTIONS);expect(createComponent(editor).isEnabled).toBe(false);diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex 4c34802edf..377215b35a 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -17,6 +17,7 @@ import {type ModelRange} from "ckeditor5";+import { extractDelimiters, renderEquation } from "../math/utils.js";import type { AiCompletionUsage, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView } from "./ai_assistant_config.js";import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";import AiAssistantFormView from "./ai_assistant_form.js";@@ -488,7 +489,7 @@ export default class AiAssistantUI extends Plugin {const editor = this.editor;const form = new AiAssistantFormView(editor.locale, {- onResultRendered: (preview) => this._renderPreviewDiagrams(preview)+ onResultRendered: (preview) => this._enrichPreview(preview)});this._formView = form;@@ -648,6 +649,45 @@ export default class AiAssistantUI extends Plugin {return sanitize(html);}+ /**+ * Everything a finished response holds that is content in source form until the editor sees it.+ * The response is note HTML rendered from Markdown, and the editor turns such a source into the+ * thing it denotes only when the content is upcast into the model — which the assistant+ * deliberately postpones until commit, so the preview has to do it for itself or the review+ * shows the source where the note will show a diagram or an equation.+ */+ private _enrichPreview(preview: HTMLElement): void {+ this._renderPreviewDiagrams(preview);+ this._renderPreviewMath(preview);+ }++ /**+ * Typesets the equations of a finished response, in place. In note HTML an equation is a+ * `math-tex` span holding its own LaTeX source, delimiters and all — which is exactly what the+ * preview showed: `\(c^2 = a^2 + b^2\)`, printed rather than set.+ *+ * The renderer is the Math feature's own, so the engine, the lazy load and the macro set are+ * the ones the note is typeset with. Without a `math` config there is nothing to typeset with+ * and the source stands, as it does for a build without the feature.+ */+ private _renderPreviewMath(preview: HTMLElement): void {+ const math = this.editor.config.get("math");+ if (!math) {+ return;+ }++ for (const span of preview.querySelectorAll<HTMLElement>("span.math-tex")) {+ /* v8 ignore next -- defensive fallback: textContent on an element is always a string */+ const { equation, display } = extractDelimiters(span.textContent ?? "");+ void renderEquation(+ equation, span, math.engine, math.lazyLoad, display,+ // Not a preview in the Math feature's sense: that is the balloon's live rendering+ // of an equation being typed, which mounts into a element of its own.+ false, "", math.previewClassName, math.katexRenderOptions+ );+ }+ }+/*** Turns the `language-mermaid` code blocks of a finished response into rendered diagrams, so* the review shows what committing it will show. The response is Markdown rendered to note