Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): run the AI assistant in Markdown rather than HTML

Elian Doran56cd6acd44f0
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
index 8f7e485d1a..19200fb79c 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts
@@ -1,3 +1,6 @@
+// @vitest-environment jsdom
+// The pipeline ends in DOMPurify, which needs browser-faithful NodeIterator traversal; happy-dom
+// mishandles it and drops the first node of every fragment. Same reason as sanitize_content.spec.
import type { LlmChatConfig } from "@triliumnext/commons";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -12,34 +15,62 @@ vi.mock("../../../services/options.js", () => ({
default: { getJson: () => storedProviders }
}));
vi.mock("../../../services/llm_chat.js", () => ({
- streamChatCompletion: vi.fn(async (_messages, config, callbacks) => {
+ streamChatCompletion: vi.fn(async (messages, config, callbacks) => {
requestedConfigs.push(config);
- callbacks.onChunk("<p>hi</p>");
+ requestedMessages.push(messages);
+ for (const chunk of responseChunks) {
+ callbacks.onChunk(chunk);
+ }
callbacks.onDone();
})
}));
+// The context is converted by the server: turndown lives in core, which the client cannot import.
+vi.mock("../../../services/server.js", () => ({
+ default: { post: vi.fn(async (_url: string, data: { htmlContent: string }) => toMarkdownResult(data.htmlContent)) }
+}));
+vi.mock("../../../services/task_states.js", () => ({ getTaskStateDefinitions: async () => [] }));
-import buildAiAssistantStream, { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
+import buildAiAssistantStream, { buildAiAssistantQuickActions, stripMarkdownFences } from "./ai_assistant_stream.js";
/** The `llmProviders` option as the mocked `options.getJson` will return it. */
let storedProviders: unknown = null;
/** The config each `streamChatCompletion` call was made with, in order. */
let requestedConfigs: LlmChatConfig[] = [];
+/** The messages each `streamChatCompletion` call was made with, in order. */
+let requestedMessages: Array<Array<{ role: string; content: string }>> = [];
+/** What the mocked stream emits, one `onChunk` per entry. */
+let responseChunks: string[] = ["done"];
+/** Stands in for `POST other/to-markdown`; throws to exercise the fallback. */
+let toMarkdownResult: (html: string) => { markdownContent: string } = () => ({ markdownContent: "teh" });
+
+const PROVIDER = [{ id: "cfg-openai", provider: "openai", selectedModels: [{ id: "gpt-5", isDefault: true }] }];
beforeEach(() => {
storedProviders = null;
requestedConfigs = [];
+ requestedMessages = [];
+ responseChunks = ["done"];
+ toMarkdownResult = () => ({ markdownContent: "teh" });
});
-/** Runs one completion through the built stream and returns the config it sent. */
-async function runOnce(): Promise<LlmChatConfig> {
+/** Runs one completion through the built stream, collecting everything handed to `onData`. */
+async function run(context = "<p>teh</p>"): Promise<{ config: LlmChatConfig; prompt: string; rendered: string[] }> {
const stream = buildAiAssistantStream();
if (!stream) {
throw new Error("expected the assistant to be enabled");
}
- await stream({ query: "Fix typos", context: "<p>teh</p>" }, () => {}, new AbortController().signal);
- const [config] = requestedConfigs;
- return config;
+ const rendered: string[] = [];
+ await stream({ query: "Fix typos", context }, (html) => rendered.push(html), new AbortController().signal);
+ return {
+ config: requestedConfigs[0],
+ prompt: requestedMessages[0]?.find((message) => message.role === "user")?.content ?? "",
+ rendered
+ };
+}
+
+/** Runs one completion and returns just the provider/model config it sent. */
+async function runOnce(): Promise<LlmChatConfig> {
+ return (await run()).config;
}
describe("buildAiAssistantStream", () => {
@@ -81,6 +112,88 @@ describe("buildAiAssistantStream", () => {
});
});
+describe("the Markdown pipeline", () => {
+ beforeEach(() => {
+ storedProviders = PROVIDER;
+ });
+
+ it("sends the context as Markdown, converted by the server", async () => {
+ toMarkdownResult = (html) => ({ markdownContent: html + " as markdown" });
+
+ const { prompt } = await run("<p>teh</p>");
+ expect(prompt).toContain("<p>teh</p> as markdown");
+ expect(prompt).toContain("Task: Fix typos");
+ });
+
+ it("sends no context at all when generating from scratch", async () => {
+ const { prompt } = await run("");
+ expect(prompt).toBe("Fix typos");
+ });
+
+ it("falls back to the HTML context when the conversion fails", async () => {
+ // Losing the conversion is worth far less than losing the run.
+ toMarkdownResult = () => { throw new Error("offline"); };
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ const { prompt } = await run("<p>teh</p>");
+ expect(prompt).toContain("<p>teh</p>");
+ });
+
+ it("renders the cumulative Markdown to HTML on every chunk", async () => {
+ responseChunks = ["# Ti", "tle\n\nsome ", "**bold** text"];
+
+ const { rendered } = await run();
+ expect(rendered).toHaveLength(3);
+ // Each render is of the whole buffer, so a heading cut mid-word is still a heading —
+ // demoted to <h2>, since in Trilium the note title is the document's <h1>.
+ expect(rendered[0]).toContain("<h2");
+ expect(rendered[2]).toContain("<strong>bold</strong>");
+ });
+
+ it("turns the Trilium syntaxes the prompt advertises into their markup", async () => {
+ responseChunks = [
+ "> [!TIP]\n> Watch out\n\n",
+ "- [ ] ship it\n\n",
+ "\u0060\u0060\u0060mermaid\nflowchart TD\n a-->b\n\u0060\u0060\u0060\n"
+ ];
+
+ const [, , html] = (await run()).rendered;
+ expect(html).toContain('<aside class="admonition tip">');
+ expect(html).toContain('<ul class="todo-list">');
+ expect(html).toContain("language-mermaid");
+ });
+
+ it("strips a fence the model wrapped the whole answer in", async () => {
+ responseChunks = ["\u0060\u0060\u0060markdown\n**bold**\n\u0060\u0060\u0060"];
+
+ const [html] = (await run()).rendered;
+ expect(html).toContain("<strong>bold</strong>");
+ expect(html).not.toContain("\u0060\u0060\u0060");
+ });
+});
+
+describe("stripMarkdownFences", () => {
+ const fence = "\u0060\u0060\u0060";
+
+ it("returns unfenced content unchanged", () => {
+ expect(stripMarkdownFences("plain")).toBe("plain");
+ });
+
+ it("strips a complete fence pair", () => {
+ expect(stripMarkdownFences(fence + "markdown\nhi\n" + fence)).toBe("hi\n");
+ expect(stripMarkdownFences(fence + "\nhi\n" + fence + "\n")).toBe("hi\n");
+ });
+
+ it("strips an opening fence whose closing half has not streamed in yet", () => {
+ expect(stripMarkdownFences(fence + "markdown\nst")).toBe("st");
+ });
+
+ it("does not treat a fence inside the content as a closing one", () => {
+ expect(stripMarkdownFences(fence + "markdown\nuse " + fence + " for fences\nmore"))
+ .toBe("use " + fence + " for fences\nmore");
+ });
+});
+
describe("buildAiAssistantQuickActions", () => {
function actions(groupId: string) {
const group = buildAiAssistantQuickActions().find((candidate) => candidate.id === groupId);
diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
index 16f5954953..77a945e24e 100644
--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts
@@ -1,15 +1,24 @@
import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";
-import type { LlmChatConfig, LlmMessage, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
+import type { LlmChatConfig, LlmMessage, LlmModelInfo, LlmUsage, ToMarkdownResponse } from "@triliumnext/commons";
import { t } from "../../../services/i18n.js";
import { streamChatCompletion } from "../../../services/llm_chat.js";
import options from "../../../services/options.js";
+import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";
+import server from "../../../services/server.js";
+import { getTaskStateDefinitions } from "../../../services/task_states.js";
/**
- * Builds the transport behind the editor's AI assistant balloon (`config.aiAssistant.stream`):
- * a completion streamed from the user's default LLM provider through the existing
+ * Builds the transport behind the editor's AI assistant (`config.aiAssistant.stream`): a
+ * completion streamed from the user's default LLM provider through the existing
* `/api/llm-chat/stream` endpoint, accumulated into the cumulative-HTML shape the plugin expects.
*
+ * **The model works in Markdown, not HTML.** The editor speaks HTML on both ends, so the context
+ * is converted on the way in and every streamed chunk is rendered on the way out. That buys more
+ * than cheaper tokens and a format the model is fluent in: admonitions, mermaid diagrams and task
+ * lists come out of Trilium's own Markdown renderer, from syntax the model already knows, instead
+ * of markup we would have to dictate in the system prompt and hope it reproduces byte for byte.
+ *
* Returns `undefined` when no LLM provider is configured, which disables the feature in the
* editor. Like the snippet list, the provider set is read when the editor is built — configuring
* a first provider shows the button after the editor is next rebuilt.
@@ -20,12 +29,18 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
}
return async (request, onData, signal): Promise<AiCompletionUsage> => {
+ // Both are needed before the first token and neither depends on the other.
+ const [context, renderMarkdown] = await Promise.all([
+ toMarkdown(request.context),
+ loadMarkdownRenderer()
+ ]);
+
const messages: LlmMessage[] = [
{ role: "system", content: SYSTEM_PROMPT },
{
role: "user",
- content: request.context
- ? `Content:\n${request.context}\n\nTask: ${request.query}`
+ content: context
+ ? `Content:\n${context}\n\nTask: ${request.query}`
: request.query
}
];
@@ -37,7 +52,7 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
streamChatCompletion(messages, config, {
onChunk: (text) => {
cumulative += text;
- onData(cumulative);
+ onData(renderMarkdown(cumulative));
},
onUsage: (chunk) => {
reported = chunk;
@@ -134,10 +149,10 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {
"Rewrite this content as a bulleted list, one point per item, without losing information."),
spelledOutAction("table", t("ai_assistant.reformat_table"), t("ai_assistant.command_table"),
"Reorganize this content into a table with a header row, choosing columns that fit what the content describes."),
- // Kept to a plain list: the editor's task lists need CKEditor's own `todo-list`
- // markup, which the system prompt does not describe to the model.
+ // A real task list rather than a plain one: `- [ ]` is Markdown the model already
+ // writes, and the renderer turns it into the editor's `todo-list` markup.
spelledOutAction("actionItems", t("ai_assistant.reformat_action_items"), t("ai_assistant.command_action_items"),
- "Extract the action items from this content as a bulleted list, each one short and starting with a verb. Leave out anything that is not an action.")
+ "Extract the action items from this content as an unchecked task list (`- [ ] …`), each one short and starting with a verb. Leave out anything that is not an action.")
]
},
{
@@ -188,19 +203,86 @@ function spelledOutAction(id: string, label: string, commandLabel: string, promp
}
/**
- * The assistant works HTML-in/HTML-out: the context is the selection's HTML and the response is
- * committed through the editor's data pipeline, so anything but clean HTML (markdown, fences,
- * commentary) would end up as literal text in the note.
+ * The assistant works Markdown-in/Markdown-out. Anything but the bare result — commentary, a
+ * preamble, a fence around the whole answer — is committed into the note verbatim, so the prompt
+ * is blunt about it.
+ *
+ * The syntaxes listed are the ones {@link loadMarkdownRenderer} turns into Trilium constructs, so
+ * naming them is what makes callouts, diagrams and task lists reachable without describing any
+ * markup: the model writes the Markdown it already knows and the renderer produces our HTML.
*/
const SYSTEM_PROMPT = `You are a writing assistant embedded in a rich text editor of a note-taking application.
-The user gives you a task, usually together with the HTML of the content it applies to.
+The user gives you a task, usually together with the Markdown of the content it applies to.
Rules:
-- Respond ONLY with HTML. No markdown, no code fences, no explanations, no preamble.
-- Use simple HTML: <p>, <strong>, <em>, <ul>, <ol>, <li>, <h2>-<h5>, <table>, <blockquote>, <code>, <a>.
+- Respond ONLY with the resulting Markdown. No explanations, no preamble, no code fence around the answer.
+- GitHub-flavoured Markdown is supported: headings, tables, footnotes and task lists (\`- [ ]\`).
+- \`> [!NOTE]\`, \`> [!TIP]\`, \`> [!IMPORTANT]\`, \`> [!CAUTION]\` and \`> [!WARNING]\` render as coloured callouts.
+- A \`mermaid\` code block renders as a diagram.
- When rewriting content, preserve its structure and formatting unless the task says otherwise.
- Respond in the same language as the content, unless the task says otherwise.`;
+/**
+ * The selection, as Markdown for the model. The conversion is the server's: turndown and the rules
+ * that keep admonitions, `<details>`, math and reference links intact live in `trilium-core`, which
+ * the client cannot import — and unlike the response, the context is one string sent once, so a
+ * round-trip before the stream costs a fraction of the completion that follows.
+ *
+ * A failed conversion falls back to the HTML. The model reads HTML perfectly well; losing the
+ * conversion is worth far less than losing the run.
+ */
+async function toMarkdown(html: string): Promise<string> {
+ if (!html.trim()) {
+ return "";
+ }
+ try {
+ const { markdownContent } = await server.post<ToMarkdownResponse>("other/to-markdown", { htmlContent: html });
+ return markdownContent;
+ } catch (error) {
+ console.warn("AI assistant: could not convert the context to Markdown, sending HTML", error);
+ return html;
+ }
+}
+
+/**
+ * The Markdown → HTML pass applied to the cumulative response on every chunk — the same shape the
+ * LLM chat renders streamed replies with, re-rendering the whole buffer rather than appending to
+ * it, which is what keeps a half-written table or fence from rendering as garbage.
+ *
+ * `marked` is a heavy import, so it is pulled in only once the assistant actually runs.
+ */
+async function loadMarkdownRenderer(): Promise<(markdown: string) => string> {
+ const [{ renderToHtml }, taskStates] = await Promise.all([
+ import("@triliumnext/commons/src/lib/markdown_renderer"),
+ getTaskStateDefinitions()
+ ]);
+
+ return (markdown) => renderToHtml(stripMarkdownFences(markdown), "", {
+ sanitize: sanitizeNoteContentHtml,
+ taskStates,
+ wikiLink: { formatHref: (id) => `#root/${id}` }
+ });
+}
+
+/**
+ * Removes a leading markdown code fence (\`\`\`markdown or \`\`\`) and, when present, the matching
+ * closing fence. Models add these despite instructions not to; the stripper is applied to the
+ * cumulative stream, so it must also handle a fence whose closing half has not arrived yet.
+ */
+export function stripMarkdownFences(cumulative: string): string {
+ const opening = /^\s*```[a-z]*\s*\n?/i.exec(cumulative);
+ if (!opening) {
+ return cumulative;
+ }
+
+ let body = cumulative.slice(opening[0].length);
+ const closingIndex = body.lastIndexOf("```");
+ if (closingIndex !== -1 && body.slice(closingIndex + 3).trim() === "") {
+ body = body.slice(0, closingIndex);
+ }
+ return body;
+}
+
/** The subset of a stored `llmProviders` entry this module reads. */
interface StoredProviderConfig {
id: string;
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 9ce7894f7f..ca6c5d77ca 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -18,7 +18,6 @@ import {
import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup } from "./ai_assistant_config.js";
import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";
import AiAssistantFormView from "./ai_assistant_form.js";
-import { stripMarkdownFences } from "./ai_html.js";
import aiIcon from "./theme/icons/ai.svg?raw";
import "./theme/ai_assistant.css";
@@ -71,7 +70,7 @@ export default class AiAssistantUI extends Plugin {
private _formView: AiAssistantFormView | null = null;
private _abortController: AbortController | null = null;
- /** The cumulative response of the current/last run, after fence-stripping. */
+ /** The cumulative response HTML of the current/last run, as the host delivered it. */
private _cumulative = "";
/** The HTML the next query will run against: the selection, then each committed-to response. */
private _context = "";
@@ -322,13 +321,12 @@ export default class AiAssistantUI extends Plugin {
let renderTimer: ReturnType<typeof setTimeout> | null = null;
let pendingHtml: string | null = null;
const onData = (cumulative: string) => {
- const cleaned = stripMarkdownFences(cumulative);
- this._cumulative = cleaned;
+ this._cumulative = cumulative;
if (renderTimer) {
- pendingHtml = cleaned;
+ pendingHtml = cumulative;
return;
}
- render(cleaned);
+ render(cumulative);
renderTimer = setTimeout(() => {
renderTimer = null;
if (pendingHtml !== null) {
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts
deleted file mode 100644
index 7de046e2a8..0000000000
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.spec.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { stripMarkdownFences } from "./ai_html.js";
-
-describe("stripMarkdownFences", () => {
- it("returns unfenced content unchanged", () => {
- expect(stripMarkdownFences("<p>plain</p>")).toBe("<p>plain</p>");
- });
-
- it("strips a complete ```html fence pair", () => {
- expect(stripMarkdownFences("```html\n<p>hi</p>\n```")).toBe("<p>hi</p>\n");
- expect(stripMarkdownFences("```\n<p>hi</p>\n```\n")).toBe("<p>hi</p>\n");
- });
-
- it("strips an opening fence whose closing half has not streamed in yet", () => {
- expect(stripMarkdownFences("```html\n<p>st")).toBe("<p>st");
- });
-
- it("does not treat a ``` inside the content as a closing fence", () => {
- expect(stripMarkdownFences("```html\n<p>use ``` for fences</p>\n<p>more</p>"))
- .toBe("<p>use ``` for fences</p>\n<p>more</p>");
- });
-});
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts
deleted file mode 100644
index 265ebb2d58..0000000000
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_html.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Pure HTML helpers for the AI assistant: undoing the models' habit of wrapping HTML output in
- * markdown fences.
- *
- * Sanitizing is deliberately *not* here. CKEditor ships no sanitizer and a hand-maintained strip
- * list is not one either, so the host supplies the real thing through `aiAssistant.sanitizeHtml`
- * (Trilium passes the DOMPurify pass it uses for note content) and the plugin refuses to render
- * without it.
- */
-
-/**
- * Removes a leading markdown code fence (```html or ```) and, when present, the matching closing
- * fence. Models add these despite instructions not to; the stripper is applied to the cumulative
- * stream, so it must also handle a fence whose closing half has not arrived yet.
- */
-export function stripMarkdownFences(cumulative: string): string {
- const opening = /^\s*```[a-z]*\s*\n?/i.exec(cumulative);
- if (!opening) {
- return cumulative;
- }
-
- let body = cumulative.slice(opening[0].length);
- const closingIndex = body.lastIndexOf("```");
- if (closingIndex !== -1 && body.slice(closingIndex + 3).trim() === "") {
- body = body.slice(0, closingIndex);
- }
- return body;
-}