Skip to content

Build your personal knowledge base with Trilium Notes

fix(ai-assistant): render the Mermaid diagrams a response holds

Elian Doranbcb57a87b591
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
index 9304d2e99b..ab5bb10102 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.spec.ts
@@ -278,6 +278,26 @@ describe("AiAssistantFormView", () => {
expect(form.errorMessage).toBe("provider unreachable");
});
+ // The hook the host renders Mermaid diagrams through: only a finished result can be, so it is
+ // offered the preview at the one point at which what it holds is a whole response.
+ it("hands the preview to the host once it holds a finished result, and not before", () => {
+ const onResultRendered = vi.fn();
+ form = new AiAssistantFormView(new Locale(), { onResultRendered });
+ form.render();
+
+ form.beginStreaming();
+ form.setPreview("<p>par</p>");
+ form.setPreview("<p>partial</p>");
+ expect(onResultRendered).not.toHaveBeenCalled();
+
+ // A review opening on the diff shows two responses at once, which is nobody's content.
+ form.enterReview({ hasContent: true, diffHtml: "<p><ins>partial</ins></p>" });
+ expect(onResultRendered).not.toHaveBeenCalled();
+
+ form.resultToggleView.fire("execute");
+ expect(onResultRendered).toHaveBeenCalledWith(form.previewView.element);
+ });
+
it("reset clears the stored contents and view-mode state", () => {
const form = makeForm();
form.beginStreaming();
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
index b61c9e8c0a..2be6a11f80 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -22,6 +22,17 @@ import type { AiReviewView } from "./ai_assistant_config.js";
*/
export type AiAssistantFormPhase = "prompt" | "streaming" | "review";
+/** The hooks the orchestrating plugin hangs on the form, which is otherwise self-contained. */
+export interface AiAssistantFormOptions {
+ /**
+ * Called with the preview element whenever it has just been filled with a finished response —
+ * the point at which content that only renders as itself once processed (a Mermaid diagram)
+ * can be turned into what the note will show. See {@link AiAssistantFormView._renderPreview}
+ * for why the streaming and diff renders are not offered.
+ */
+ onResultRendered?: (preview: HTMLElement) => void;
+}
+
/** What a finished run leaves the form showing. */
export interface AiReviewOptions {
/** Whether the run produced anything at all; without it the form falls back to the prompt. */
@@ -80,11 +91,13 @@ export default class AiAssistantFormView extends View {
public readonly keystrokes = new KeystrokeHandler();
private readonly _focusables = new ViewCollection<FocusableView>();
+ private readonly _onResultRendered?: (preview: HTMLElement) => void;
- constructor(locale: Locale) {
+ constructor(locale: Locale, { onResultRendered }: AiAssistantFormOptions = {}) {
super(locale);
const t = locale.t;
+ this._onResultRendered = onResultRendered;
this.set("phase", "prompt");
this.set("query", "");
@@ -366,7 +379,16 @@ export default class AiAssistantFormView extends View {
/** Shows whichever stored content the current view mode selects. */
private _renderPreview(): void {
- this.previewView.setContent(this.viewMode === "changes" && this._diffHtml ? this._diffHtml : this._resultHtml);
+ const isDiff = this.viewMode === "changes" && !!this._diffHtml;
+ this.previewView.setContent(isDiff ? this._diffHtml : this._resultHtml);
+
+ // Only the finished result is handed on: half a diagram cannot be parsed, so rendering
+ // each streamed tick would flash a parse error where the diagram is about to be, and the
+ // "Changes" view is two responses interleaved — its code blocks are not source any more.
+ const preview = this.previewView.element;
+ if (preview && this.phase === "review" && !isDiff) {
+ this._onResultRendered?.(preview);
+ }
}
/** One half of the Result/Changes toggle, visible only when a review has a diff to offer. */
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.ts
index 2adab7f9c7..6d2bc53d29 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
@@ -1,7 +1,11 @@
-import { _getModelData as getModelData, _setModelData as setModelData, ButtonView, ClassicEditor, Dialog, Essentials, Paragraph, SplitButtonView } from "ckeditor5";
+import { _getModelData as getModelData, _setModelData as setModelData, ButtonView, ClassicEditor, CodeBlockEditing, Dialog, Essentials, Paragraph, SplitButtonView } from "ckeditor5";
import { 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.
+import type {} from "../mermaid/mermaid.js";
+import MermaidEditing from "../mermaid/mermaid_editing.js";
import TriliumAiAssistant from "./ai_assistant.js";
import type { AiCompletionRequest, AiDiffFunction, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./ai_assistant_config.js";
import AiAssistantUI from "./ai_assistant_ui.js";
@@ -580,7 +584,7 @@ describe("AiAssistantUI toolbar entry", () => {
function createMermaidStub() {
return {
initialize: vi.fn(),
- render: vi.fn(async (id: string, source: string) => ({ svg: `<svg data-source="${source}"></svg>` }))
+ render: vi.fn(async (_id: string, source: string) => ({ svg: `<svg data-source="${source}"></svg>` }))
};
}
@@ -602,7 +606,8 @@ describe("AiAssistantUI toolbar entry", () => {
await vi.waitFor(() => expect(previewHtml(editor)).toContain("<svg"));
expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), DIAGRAM);
// The `<pre>` goes with the `<code>`: what is left is the diagram, not a framed one.
- expect(previewHtml(editor)).toContain(`<div class="ck-ai-assistant-form__diagram"><svg data-source="${DIAGRAM}">`);
+ expect(previewHtml(editor))
+ .toContain(`<div class="ck-ai-assistant-form__diagram"><svg data-source="graph TD; A--&gt;B;">`);
expect(previewHtml(editor)).not.toContain("<pre>");
// Nothing was done to the response itself — the note gets the code block, which the
@@ -613,7 +618,7 @@ describe("AiAssistantUI toolbar entry", () => {
it("leaves a half-streamed diagram as its source", async () => {
const mermaid = createMermaidStub();
- const editor = await createDiagramEditor(mermaid, async (request, onData) => {
+ const editor = await createDiagramEditor(mermaid, async (_request, onData) => {
onData(`<pre><code class="language-mermaid">graph TD; A--</code></pre>`);
await new Promise(() => {});
});
@@ -627,6 +632,22 @@ describe("AiAssistantUI toolbar entry", () => {
expect(mermaid.render).not.toHaveBeenCalled();
});
+ // The library is the host's to supply (`config.mermaid.lazyLoad`), so the feature can be
+ // loaded with nothing behind it. Emptying the block for a diagram that will never arrive
+ // would lose the response; the source is at least what a commit would produce.
+ it("leaves the source standing when the host supplies no diagram library", async () => {
+ const stub = createStreamStub(DIAGRAM_HTML);
+ const editor = await createTestEditor([Essentials, Paragraph, CodeBlockEditing, MermaidEditing, TriliumAiAssistant], {
+ aiAssistant: { sanitizeHtml, quickActions: DIAGRAM_ACTION, stream: stub.stream }
+ });
+
+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");
+ quickActionButtons(createComponent(editor))[0].fire("execute");
+
+ await vi.waitFor(() => expect(openForm(editor).phase).toBe("review"));
+ expect(previewHtml(editor)).toBe(DIAGRAM_HTML);
+ });
+
it("leaves the code block alone in the diff, whose text is two responses at once", async () => {
const mermaid = createMermaidStub();
const stub = createStreamStub(DIAGRAM_HTML);
@@ -637,7 +658,8 @@ describe("AiAssistantUI toolbar entry", () => {
stream: stub.stream,
// Opens on the diff, since the action asking for the result is not the one run.
diff: () => `<pre><code class="language-mermaid">graph <del>LR</del><ins>TD</ins></code></pre>`
- }
+ },
+ mermaid: { lazyLoad: () => mermaid, config: {} }
});
setModelData(editor.model, "<paragraph>[foo]</paragraph>");
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index 71a86031ff..4c34802edf 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -654,12 +654,13 @@ export default class AiAssistantUI extends Plugin {
* HTML, in which a diagram is a code block — the editor only makes one a diagram when the
* content is upcast into the model, which the assistant deliberately postpones until commit.
*
- * Soft-coupled to the Mermaid feature by name: a build without it renders the source, which is
- * also all a commit could produce there.
+ * Soft-coupled to the Mermaid feature by name: a build without it — or one whose host supplies
+ * no diagram library — leaves the source standing, which is also all a commit could produce
+ * there, rather than emptying the block in favour of a diagram that will never arrive.
*/
private _renderPreviewDiagrams(preview: HTMLElement): void {
const editor = this.editor;
- if (!editor.plugins.has("MermaidEditing")) {
+ if (!editor.plugins.has("MermaidEditing") || !editor.config.get("mermaid")?.lazyLoad) {
return;
}
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
index ca74599693..48cc3de4af 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -66,6 +66,18 @@
}
}
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__diagram {
+ display: flex;
+ justify-content: center;
+ overflow-x: auto;
+ margin-bottom: var(--ck-spacing-medium);
+
+ svg {
+ flex-shrink: 0;
+ max-width: none;
+ }
+}
+
/* An empty preview is just a hollow frame — collapse it until there is a run to show. */
.ck.ck-ai-assistant-form:not(.ck-ai-assistant-form_streaming) .ck-ai-assistant-form__preview:empty {
display: none;
diff --git a/packages/ckeditor5/src/plugins/mermaid/README.md b/packages/ckeditor5/src/plugins/mermaid/README.md
index 9664176c3a..c5dc3e08e3 100644
--- a/packages/ckeditor5/src/plugins/mermaid/README.md
+++ b/packages/ckeditor5/src/plugins/mermaid/README.md
@@ -7,7 +7,7 @@ or both side by side. Load the `Mermaid` glue plugin; it pulls in `MermaidEditin
| File | Role |
|---|---|
| `mermaid.ts` | Glue plugin; also declares the `ckeditor5` module augmentation and the global mermaid types |
-| `mermaid_editing.ts` | Schema, conversion, and the renderer (`_renderMermaid`) |
+| `mermaid_editing.ts` | Schema, conversion, and the renderer (`renderMermaid`) |
| `mermaid_ui.ts` | The insert split button with its template dropdown, the mode buttons, the info button |
| `mermaid_toolbar.ts` | Registers the balloon toolbar shown when a diagram is selected |
| `insert_mermaid_command.ts` | `insertMermaid` — inserts a blank or pre-filled diagram |
@@ -34,9 +34,11 @@ mermaid: {
}
```
-`_renderMermaid` calls `lazyLoad` once, memoises the promise, and calls `initialize()` on the
+`renderMermaid` calls `lazyLoad` once, memoises the promise, and calls `initialize()` on the
resolved instance. Renders are generation-stamped so a slow render that has been superseded cannot
-overwrite a newer one, and a failed render shows the error message in place.
+overwrite a newer one, and a failed render shows the error message in place. It is public because
+the widget is not the only diagram on screen: the AI assistant renders the `language-mermaid` blocks
+of a finished response through it, so its review shows what committing will produce.
## Provenance
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts
index d860593f4d..e552c0e52a 100644
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts
+++ b/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.spec.ts
@@ -295,7 +295,7 @@ describe( 'MermaidEditing', () => {
let renderMermaidStub: MockInstance;
beforeEach( () => {
- renderMermaidStub = vi.spyOn( editor.plugins.get( 'MermaidEditing' ) as unknown as MermaidEditing, '_renderMermaid' );
+ renderMermaidStub = vi.spyOn( editor.plugins.get( 'MermaidEditing' ) as unknown as MermaidEditing, 'renderMermaid' );
// Using editor.setData() instead of setModelData helper because of #11365.
editor.setData(
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts
index 2c31684676..047e02f71b 100644
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts
+++ b/packages/ckeditor5/src/plugins/mermaid/mermaid_editing.ts
@@ -217,7 +217,7 @@ export default class MermaidEditing extends Plugin {
const mermaidSource = data.item.getAttribute( 'source' ) as string;
const domElement = this.toDomElement( domDocument );
- that._renderMermaid( domElement, mermaidSource );
+ that.renderMermaid( domElement, mermaidSource );
return domElement;
}
@@ -247,7 +247,7 @@ export default class MermaidEditing extends Plugin {
const domPreviewWrapper = domConverter.viewToDom( child );
if ( domPreviewWrapper ) {
- this._renderMermaid( domPreviewWrapper, newSource );
+ this.renderMermaid( domPreviewWrapper, newSource );
}
}
}
@@ -288,8 +288,14 @@ export default class MermaidEditing extends Plugin {
/**
* Renders Mermaid (a parsed `source`) in a given `domElement`.
+ *
+ * Public because the widget's preview pane is no longer the only surface showing a diagram:
+ * the AI assistant renders the `language-mermaid` blocks of a finished response the same way,
+ * so that what it previews is what committing it will produce. Everything the widget needs of
+ * the renderer — the one lazy load, the shared queue, the per-element generation — is what an
+ * outside caller needs too, so it takes this rather than a copy of it.
*/
- async _renderMermaid( domElement: HTMLElement, source: string ) {
+ async renderMermaid( domElement: HTMLElement, source: string ) {
if ( !source?.trim() ) {
// Bump generation so an in-flight render for the previous source cannot
// write its SVG back into a cleared preview.
diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts
index b87465196c..105e3f7c22 100644
--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts
+++ b/packages/ckeditor5/src/plugins/mermaid/mermaid_rendering.spec.ts
@@ -6,7 +6,7 @@ import MermaidEditing from './mermaid_editing.js';
/* global document */
/**
- * The diagram renderer: how `_renderMermaid` lazy-loads the mermaid instance, what it does with
+ * The diagram renderer: how `renderMermaid` lazy-loads the mermaid instance, what it does with
* the SVG it gets back, and how it behaves when a render fails or is superseded by a newer one.
*/
describe( 'MermaidEditing rendering', () => {
@@ -130,16 +130,16 @@ describe( 'MermaidEditing rendering', () => {
// widget and hand each render a different preview node, which is not what is under
// test here — the generation guard is.
const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
+ renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
};
const target = document.createElement( 'div' );
- const stale = plugin._renderMermaid( target, 'first' );
+ const stale = plugin.renderMermaid( target, 'first' );
await waitFor( () => pending.length >= 1 );
// Queue the newer render while the first is still in flight. Renders are serialized,
// so the second mermaid.render() only starts after the first settles — but the
// generation bump must still discard the stale SVG.
- const latest = plugin._renderMermaid( target, 'second' );
+ const latest = plugin.renderMermaid( target, 'second' );
pending[ 0 ]?.( { svg: '<svg id="first"></svg>' } );
await stale;
@@ -158,13 +158,13 @@ describe( 'MermaidEditing rendering', () => {
editor = await createEditor( { lazyLoad: async () => instance } );
const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
+ renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
};
const first = document.createElement( 'div' );
const second = document.createElement( 'div' );
- const firstRender = plugin._renderMermaid( first, 'diagram-a' );
- const secondRender = plugin._renderMermaid( second, 'diagram-b' );
+ const firstRender = plugin.renderMermaid( first, 'diagram-a' );
+ const secondRender = plugin.renderMermaid( second, 'diagram-b' );
// Serialized queue: only the first render is in flight initially.
await waitFor( () => pending.has( 'diagram-a' ) );
@@ -185,12 +185,12 @@ describe( 'MermaidEditing rendering', () => {
editor = await createEditor( { lazyLoad: async () => instance } );
const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
+ renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
};
const target = document.createElement( 'div' );
target.innerHTML = '<svg id="stale"></svg>';
- await plugin._renderMermaid( target, ' ' );
+ await plugin.renderMermaid( target, ' ' );
expect( target.innerHTML ).to.equal( '' );
expect( instance.render ).not.toHaveBeenCalled();
@@ -204,14 +204,14 @@ describe( 'MermaidEditing rendering', () => {
editor = await createEditor( { lazyLoad: async () => instance } );
const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
+ renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
};
const target = document.createElement( 'div' );
- const first = plugin._renderMermaid( target, 'graph TD; A-->B;' );
+ const first = plugin.renderMermaid( target, 'graph TD; A-->B;' );
await waitFor( () => pending.length >= 1 );
- await plugin._renderMermaid( target, ' ' );
+ await plugin.renderMermaid( target, ' ' );
expect( target.innerHTML ).to.equal( '' );
pending[ 0 ]?.( { svg: '<svg id="stale"></svg>' } );
@@ -232,11 +232,11 @@ describe( 'MermaidEditing rendering', () => {
editor = await createEditor( { lazyLoad: async () => instance } );
const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
+ renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
};
const target = document.createElement( 'div' );
- await plugin._renderMermaid( target, 'graph TD; A-->B;' );
+ await plugin.renderMermaid( target, 'graph TD; A-->B;' );
expect( target.querySelector( 'svg' ) ).to.not.equal( null );
expect( target.contains( target.querySelector( 'svg' )! ) ).to.equal( true );
@@ -310,15 +310,15 @@ describe( 'MermaidEditing rendering', () => {
editor = await createEditor( { lazyLoad: async () => instance } );
const plugin = editor.plugins.get( MermaidEditing ) as unknown as {
- _renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
+ renderMermaid( domElement: HTMLElement, source: string ): Promise<void>;
};
const target = document.createElement( 'div' );
- const stale = plugin._renderMermaid( target, 'first' );
+ const stale = plugin.renderMermaid( target, 'first' );
await waitFor( () => pending.length >= 1 );
// Clearing bumps this element's generation synchronously, so the in-flight render is
// already stale by the time it rejects.
- await plugin._renderMermaid( target, '' );
+ await plugin.renderMermaid( target, '' );
pending[ 0 ]?.( new Error( 'Parse error on line 1' ) );
await stale;