Skip to content

Build your personal knowledge base with Trilium Notes

feat(ckeditor): word-wrap the AI assistant preview and show run usage

Elian Dorand7ae265320d4
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 1def0c3f77..c4af93ab07 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2525,7 +2525,8 @@
"insert_below": "Insert below",
"try_again": "Try again",
"result": "Result",
- "changes": "Changes"
+ "changes": "Changes",
+ "tokens": "tokens"
},
"link_context_menu": {
"open_note_in_new_tab": "Open note in a new tab",
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 f195dd95e8..dbff01f6cf 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,5 +1,5 @@
-import type { AiStreamFunction } from "@triliumnext/ckeditor5";
-import type { LlmChatConfig, LlmMessage, LlmModelInfo } from "@triliumnext/commons";
+import type { AiCompletionUsage, AiStreamFunction } from "@triliumnext/ckeditor5";
+import type { LlmChatConfig, LlmMessage, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
import { streamChatCompletion } from "../../../services/llm_chat.js";
import options from "../../../services/options.js";
@@ -18,7 +18,7 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
return undefined;
}
- return async (request, onData, signal) => {
+ return async (request, onData, signal): Promise<AiCompletionUsage> => {
const messages: LlmMessage[] = [
{ role: "system", content: SYSTEM_PROMPT },
{
@@ -29,21 +29,33 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
}
];
+ const config = pickDefaultModel();
let cumulative = "";
- await new Promise<void>((resolve, reject) => {
- streamChatCompletion(messages, pickDefaultModel(), {
+ const usage = await new Promise<LlmUsage | null>((resolve, reject) => {
+ let reported: LlmUsage | null = null;
+ streamChatCompletion(messages, config, {
onChunk: (text) => {
cumulative += text;
onData(cumulative);
},
+ onUsage: (chunk) => {
+ reported = chunk;
+ },
onError: (error) => reject(new Error(error)),
- onDone: () => resolve()
+ onDone: () => resolve(reported)
}, signal).then(
// A stream that ends without a "done" event (connection dropped) still settles.
- () => resolve(),
+ () => resolve(reported),
reject
);
});
+
+ return {
+ // The server reports the model's display name; fall back to the id we asked for.
+ model: usage?.model ?? config.model,
+ totalTokens: usage?.totalTokens,
+ cost: usage?.cost
+ };
};
}
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 90c3ce9181..e17e20a530 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -14,7 +14,7 @@ export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";
-export type { AiAssistantConfig, AiCompletionRequest, AiDiffFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
+export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
export * from "./utils.js";
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
index beabca93fd..4162846a1d 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -19,20 +19,34 @@ export interface AiCompletionRequest {
*/
export type AiStreamCallback = (cumulativeHtml: string) => void;
+/**
+ * What a finished completion cost, shown in the review phase. All fields are optional — whatever
+ * the provider reports gets displayed, the rest is omitted.
+ */
+export interface AiCompletionUsage {
+ /** Identifier of the model that produced the response. */
+ model?: string;
+ /** Total tokens consumed (prompt + completion). */
+ totalTokens?: number;
+ /** Estimated cost in USD. */
+ cost?: number;
+}
+
/**
* Host-provided transport for AI completions. The plugin knows nothing about providers, endpoints
* or authentication — the client injects this the same way it injects `snippets.definitions` or
* `syntaxHighlighting.loadHighlightJs`.
*
- * The returned promise resolves when the stream finishes and rejects on transport or provider
- * error. An abort through `signal` must reject with a DOM `AbortError`; the partial content
- * already delivered through `onData` stays usable.
+ * The returned promise resolves when the stream finishes — with the run's usage, when the
+ * provider reports it — and rejects on transport or provider error. An abort through `signal`
+ * must reject with a DOM `AbortError`; the partial content already delivered through `onData`
+ * stays usable.
*/
export type AiStreamFunction = (
request: AiCompletionRequest,
onData: AiStreamCallback,
signal: AbortSignal
-) => Promise<void>;
+) => Promise<AiCompletionUsage | void>;
/**
* Renders an inline HTML diff between two HTML fragments, returning HTML in which insertions and
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 3f49981550..c76544f0d5 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
@@ -74,6 +74,25 @@ describe("AiAssistantFormView", () => {
expect(form.changesToggleView.isVisible).toBe(false);
});
+ it("shows the usage line only for a review that has one, and clears it on the next run", () => {
+ const form = makeForm();
+ const usageEl = form.element?.querySelector(".ck-ai-assistant-form__usage");
+
+ form.beginStreaming();
+ form.setPreview("<p>new</p>");
+ form.enterReview(true, null, "", "some-model · 1,234 tokens · ~$0.0042");
+ expect(form.usageText).toBe("some-model · 1,234 tokens · ~$0.0042");
+ expect(usageEl?.textContent).toBe("some-model · 1,234 tokens · ~$0.0042");
+ expect(usageEl?.classList.contains("ck-hidden")).toBe(false);
+
+ // A failed follow-up run must not keep advertising the previous run's cost.
+ form.beginStreaming();
+ expect(form.usageText).toBe("");
+ expect(usageEl?.classList.contains("ck-hidden")).toBe(true);
+ form.enterReview(false, null, "boom", "ignored — no content to review");
+ expect(form.usageText).toBe("");
+ });
+
it("falls back to the prompt phase with the error when a run produced nothing", () => {
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 4fdcd8a542..7f20e5a7fe 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts
@@ -44,6 +44,8 @@ export default class AiAssistantFormView extends View {
declare public viewMode: AiAssistantViewMode;
/** Whether the current review has a diff to offer; controls the view-mode toggle. */
declare public hasDiff: boolean;
+ /** The run's cost line ("model · tokens · price"), shown in the review actions row. */
+ declare public usageText: string;
/** The (sanitized) response HTML, kept for re-rendering when the view mode flips. */
private _resultHtml = "";
@@ -74,6 +76,7 @@ export default class AiAssistantFormView extends View {
this.set("errorMessage", "");
this.set("viewMode", "result");
this.set("hasDiff", false);
+ this.set("usageText", "");
// Re-render the preview from the stored contents whenever the toggle flips.
this.on("change:viewMode", () => this._renderPreview());
@@ -137,7 +140,18 @@ export default class AiAssistantFormView extends View {
this.stopButtonView,
this.replaceButtonView,
this.insertBelowButtonView,
- this.tryAgainButtonView
+ this.tryAgainButtonView,
+ {
+ tag: "span",
+ attributes: {
+ class: [
+ "ck",
+ "ck-ai-assistant-form__usage",
+ bind.if("usageText", "ck-hidden", (text) => !text)
+ ]
+ },
+ children: [{ text: bind.to("usageText") }]
+ }
]
}
]
@@ -199,6 +213,7 @@ export default class AiAssistantFormView extends View {
this._diffHtml = "";
this.hasDiff = false;
this.viewMode = "result";
+ this.usageText = "";
this._renderPreview();
}
@@ -210,6 +225,7 @@ export default class AiAssistantFormView extends View {
this._diffHtml = "";
this.hasDiff = false;
this.viewMode = "result";
+ this.usageText = "";
this._renderPreview();
}
@@ -224,12 +240,13 @@ export default class AiAssistantFormView extends View {
* "Changes" view when a diff is available — while a run that produced nothing falls back to
* the prompt phase, showing `errorMessage` when the run failed.
*/
- public enterReview(hasContent: boolean, diffHtml: string | null, errorMessage: string): void {
+ public enterReview(hasContent: boolean, diffHtml: string | null, errorMessage: string, usageText = ""): void {
this.phase = hasContent ? "review" : "prompt";
this.errorMessage = errorMessage;
this._diffHtml = diffHtml ?? "";
this.hasDiff = hasContent && !!this._diffHtml;
this.viewMode = this.hasDiff ? "changes" : "result";
+ this.usageText = hasContent ? usageText : "";
this._renderPreview();
}
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 7c3a7a3277..8c8cbc70d6 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
@@ -8,6 +8,7 @@ import {
} from "ckeditor5";
import { translate } from "../translate.js";
+import type { AiCompletionUsage } from "./ai_assistant_config.js";
import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";
import AiAssistantFormView from "./ai_assistant_form.js";
import { sanitizeAiHtml, stripMarkdownFences } from "./ai_html.js";
@@ -214,8 +215,9 @@ export default class AiAssistantUI extends Plugin {
};
let errorMessage = "";
+ let usage: AiCompletionUsage | null = null;
try {
- await stream({ query, context: this._context }, onData, abortController.signal);
+ usage = (await stream({ query, context: this._context }, onData, abortController.signal)) ?? null;
} catch (error) {
// An abort is the user's Stop: whatever already streamed stays reviewable.
if (!(error instanceof DOMException && error.name === "AbortError")) {
@@ -237,7 +239,29 @@ export default class AiAssistantUI extends Plugin {
// Follow-up queries chain on the response ("now make it shorter"), premium-style.
this._context = this._cumulative;
}
- form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage);
+ form.enterReview(!!this._cumulative, this._buildDiff(), errorMessage, this._formatUsage(usage));
+ }
+
+ /**
+ * The review's cost line, e.g. `claude-sonnet-5 · 1,234 tokens · ~$0.0042`. Only the fields
+ * the provider reported are shown; an aborted or failed run has none at all.
+ */
+ private _formatUsage(usage: AiCompletionUsage | null): string {
+ if (!usage) {
+ return "";
+ }
+ const parts: string[] = [];
+ if (usage.model) {
+ parts.push(usage.model);
+ }
+ if (usage.totalTokens != null) {
+ parts.push(`${usage.totalTokens.toLocaleString()} ${translate(this.editor, "ai_assistant.tokens", "tokens")}`);
+ }
+ if (usage.cost != null) {
+ // A single completion usually costs well under a cent; two decimals would show $0.00.
+ parts.push(`~$${usage.cost < 0.01 ? usage.cost.toFixed(4) : usage.cost.toFixed(2)}`);
+ }
+ return parts.join(" · ");
}
/**
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 167d212825..a8dac876da 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css
@@ -59,6 +59,14 @@
gap: var(--ck-spacing-small);
}
+/* The run's model/token/cost line, tucked to the right of the review actions. */
+.ck.ck-ai-assistant-form .ck-ai-assistant-form__usage {
+ margin-left: auto;
+ align-self: center;
+ font-size: var(--ck-font-size-small);
+ opacity: 0.7;
+}
+
/* An actions row with every button hidden should not reserve a gap's worth of height. */
.ck.ck-ai-assistant-form .ck-ai-assistant-form__actions:not(:has(.ck-button:not(.ck-hidden))) {
display: none;