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
feat(ai-assistant): offer "Ask AI…" from the toolbar entry's menu
Elian Doranc3782c402ced
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e2f85a62a0..075d5c10e0 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3852,6 +3852,7 @@"anchor-widget": "anchor widget","anchors": "Anchors","applies-to-the-current-paragraph": "Applies to the current paragraph.",+ "ask-ai": "Ask AI…","ask-ai-to": "Ask AI to…","ask-ai-to-rewrite-the-selection-or-generate-new-content": "Ask AI to rewrite the selection or generate new content.","box-size": "Box size",diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 6a4de45feb..868b6c155d 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -199,6 +199,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi// shredded `<ins>`/`<del>` pairs.diff: diffAiResponse,quickActions: buildAiAssistantQuickActions(),+ // The glyph the context menu gives the same row, so the two ways into a typed prompt+ // look alike.+ askIconClass: "bx bx-message-square-dots",// The model's HTML reaches the preview through `innerHTML`, so it gets the same// DOMPurify pass as any other untrusted content rendered outside the editor's// data pipeline. CKEditor ships no sanitizer of its own — like `htmlEmbed`, thediff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex ab2058de8f..fe33fd4e6b 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -199,6 +199,14 @@ export interface AiAssistantConfig {*/quickActions?: AiQuickActionGroup[];+ /**+ * The icon for the row that heads the toolbar entry's menu — the one that opens the assistant+ * for a typed prompt, the menu's equivalent of clicking the button rather than its arrow. Only+ * the icon is the host's to choose; the row is the feature's own, so it names itself. Without+ * one the row simply goes iconless, as any action configured without one does.+ */+ askIconClass?: string;+/*** Sanitizes the response HTML before it is rendered into the preview. **Required**: the* plugin has no built-in fallback and throws rather than render unsanitized model output —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 2fda537119..2adab7f9c7 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@@ -149,10 +149,16 @@ function openForm(editor: ClassicEditor) {viewMode: string;hasDiff: boolean;isUnchanged: boolean;+ previewView: { element?: HTMLElement | null };fire(event: string): void;};}+/** What the preview currently holds, for the specs that assert on rendered content. */+function previewHtml(editor: ClassicEditor): string {+ return openForm(editor).previewView.element?.innerHTML ?? "";+}+describe("AiAssistantUI toolbar entry", () => {it("is a plain button when the host configured no quick actions", async () => {const editor = await createEditor(undefined, createStreamStub().stream);@@ -557,6 +563,99 @@ describe("AiAssistantUI toolbar entry", () => {});});+ // A diagram is a `language-mermaid` code block until the content is upcast into the model,+ // which the assistant only does on commit — so the preview has to render it itself, or the+ // Diagram quick action reviews its own source and the diagram only appears once accepted.+ describe("Mermaid diagrams in the preview", () => {+ const DIAGRAM = "graph TD; A-->B;";+ const DIAGRAM_HTML = `<pre><code class="language-mermaid">graph TD; A-->B;</code></pre>`;++ const DIAGRAM_ACTION: AiQuickActionGroup[] = [{+ id: "reformat",+ label: "Reformat",+ actions: [{ id: "diagram", label: "Diagram", prompt: "Draw it.", reviewView: "result" }]+ }];++ /** Stands in for the mermaid library the host lazy-loads, one SVG per source. */+ function createMermaidStub() {+ return {+ initialize: vi.fn(),+ render: vi.fn(async (id: string, source: string) => ({ svg: `<svg data-source="${source}"></svg>` }))+ };+ }++ async function createDiagramEditor(mermaid: ReturnType<typeof createMermaidStub>, stream: AiStreamFunction) {+ return createTestEditor([Essentials, Paragraph, CodeBlockEditing, MermaidEditing, TriliumAiAssistant], {+ aiAssistant: { sanitizeHtml, quickActions: DIAGRAM_ACTION, stream },+ mermaid: { lazyLoad: () => mermaid, config: {} }+ });+ }++ it("renders the diagram a finished response holds, in place of its code block", async () => {+ const mermaid = createMermaidStub();+ const stub = createStreamStub(DIAGRAM_HTML);+ const editor = await createDiagramEditor(mermaid, stub.stream);++ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ quickActionButtons(createComponent(editor))[0].fire("execute");++ 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)).not.toContain("<pre>");++ // Nothing was done to the response itself — the note gets the code block, which the+ // editor upcasts into a diagram widget of its own.+ openForm(editor).fire("replace");+ expect(editor.getData()).toContain(`<code class="language-mermaid">`);+ });++ it("leaves a half-streamed diagram as its source", async () => {+ const mermaid = createMermaidStub();+ const editor = await createDiagramEditor(mermaid, async (request, onData) => {+ onData(`<pre><code class="language-mermaid">graph TD; A--</code></pre>`);+ await new Promise(() => {});+ });++ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ quickActionButtons(createComponent(editor))[0].fire("execute");++ // Parsing a fragment would put a parse error where the diagram is about to be, once+ // per streamed chunk. The source stands until the response is complete.+ await vi.waitFor(() => expect(previewHtml(editor)).toContain("language-mermaid"));+ expect(mermaid.render).not.toHaveBeenCalled();+ });++ 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);+ const editor = await createTestEditor([Essentials, Paragraph, CodeBlockEditing, MermaidEditing, TriliumAiAssistant], {+ aiAssistant: {+ sanitizeHtml,+ quickActions: DIAGRAM_ACTION,+ 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>`+ }+ });++ setModelData(editor.model, "<paragraph>[foo]</paragraph>");+ editor.execute("aiAssistant");+ const form = openForm(editor);+ form.query = "Draw it.";+ form.fire("submit");++ await vi.waitFor(() => expect(form.viewMode).toBe("changes"));+ expect(mermaid.render).not.toHaveBeenCalled();+ expect(previewHtml(editor)).toContain("<del>LR</del>");++ // The toggle back to the result is a render of its own, so the diagram lands there.+ form.viewMode = "result";+ await vi.waitFor(() => expect(previewHtml(editor)).toContain("<svg"));+ });+ });+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 a81b224015..71a86031ff 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -664,13 +664,14 @@ export default class AiAssistantUI extends Plugin {}const mermaid = editor.plugins.get("MermaidEditing");- for (const code of preview.querySelectorAll("pre > code.language-mermaid")) {- const source = code.textContent ?? "";+ // The `<pre>` is replaced along with the `<code>` it holds: a diagram left inside one is+ // framed as a code block in the preview and nowhere else.+ for (const pre of preview.querySelectorAll("pre:has(> code.language-mermaid)")) {+ /* v8 ignore next -- defensive fallback: textContent on an element is always a string */+ const source = pre.textContent ?? "";const diagram = preview.ownerDocument.createElement("div");diagram.className = "ck-ai-assistant-form__diagram";- // The `<pre>` goes with it: what is left has to be a plain block, or the code-block- // styling frames the diagram in the preview and nowhere else.- code.parentElement?.replaceWith(diagram);+ pre.replaceWith(diagram);void mermaid.renderMermaid(diagram, source);}}