Skip to content

Build your personal knowledge base with Trilium Notes

fix(text): drop the AI assistant button when the AI features are off

Elian Doranf83a1620dd06
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index 59d06726de..d06842555d 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -95,6 +95,14 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
// the tag list, for the same by-value reason as `customReplacements` above.
const [ htmlSupportEnabled ] = useTriliumOptionBool("textNoteHtmlSupportEnabled");
const [ allowedHtmlTags ] = useTriliumOption("allowedHtmlTags");
+ // Whether the AI assistant is offered at all, which `buildConfig()` settles at creation time:
+ // it decides both the transport the command gates on and whether the toolbars carry the
+ // assistant's entries, neither of which a live editor can be told about afterwards. Switching
+ // the AI features off has to take the button away there and then, not at the next rebuild.
+ // The provider list is a rebuild trigger for the same reason — configuring the first one (or
+ // removing the last) is what makes the feature usable.
+ const [ aiEnabled ] = useTriliumOptionBool("aiEnabled");
+ const [ llmProviders ] = useTriliumOption("llmProviders");
// Deliberately *not* a rebuild trigger — pushed into the live editor by the effect below
// instead. The enabled content languages fill the assistant's Translate submenu, which now
// offers the row that edits them, so the change is made from inside the editor and several
@@ -337,7 +345,8 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
}, [
contentLanguage, uiLanguage, isClassicEditor, multilineToolbar,
doubleQuoteStyle, singleQuoteStyle, punctuationReplacements, mathReplacements, symbolReplacements,
- customReplacements, defaultContentLanguage, htmlSupportEnabled, allowedHtmlTags
+ customReplacements, defaultContentLanguage, htmlSupportEnabled, allowedHtmlTags,
+ aiEnabled, llmProviders
]);
// Push snippet ("template") definitions into the live editor instead of rebuilding it. The premium
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 7080faeda9..4e087d091e 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
@@ -19,7 +19,10 @@ vi.mock("../../../services/i18n.js", async () => {
};
});
vi.mock("../../../services/options.js", () => ({
- default: { getJson: (key: string) => (key === "languages" ? storedLanguages : storedProviders) }
+ default: {
+ getJson: (key: string) => (key === "languages" ? storedLanguages : storedProviders),
+ is: (key: string) => (key === "aiEnabled" ? aiEnabled : false)
+ }
}));
vi.mock("../../../services/llm_chat.js", () => ({
streamChatCompletion: vi.fn(async (messages, config, callbacks) => {
@@ -49,6 +52,8 @@ import buildAiAssistantStream, { type AiNoteLocation, buildAiAssistantQuickActio
let storedProviders: unknown = null;
/** The `languages` option — the locale ids enabled as content languages. */
let storedLanguages: unknown = null;
+/** The `aiEnabled` option — the master switch over every AI feature. */
+let aiEnabled = true;
/** The config each `streamChatCompletion` call was made with, in order. */
let requestedConfigs: LlmChatConfig[] = [];
/** The messages each `streamChatCompletion` call was made with, in order. */
@@ -65,6 +70,7 @@ const PROVIDER = [{ id: "cfg-openai", provider: "openai", selectedModels: [{ id:
beforeEach(() => {
storedProviders = null;
storedLanguages = null;
+ aiEnabled = true;
requestedConfigs = [];
requestedMessages = [];
responseChunks = ["done"];
@@ -124,6 +130,17 @@ describe("buildAiAssistantStream", () => {
expect(buildAiAssistantStream()).toBeUndefined();
});
+ // Switching the AI features off leaves the configured providers stored — they are what
+ // switching it back on restores — so the master switch has to be read in its own right.
+ it("stays disabled when the AI features are switched off, provider or no provider", () => {
+ aiEnabled = false;
+ storedProviders = PROVIDER;
+ expect(buildAiAssistantStream()).toBeUndefined();
+
+ aiEnabled = true;
+ expect(buildAiAssistantStream()).toBeDefined();
+ });
+
it("uses the first provider's default model, else its first", async () => {
storedProviders = [{
id: "cfg-openai",
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 b9b281c665..0a17015e83 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
@@ -33,16 +33,17 @@ export type AiNoteLocationProvider = () => AiNoteLocation | null;
* 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.
+ * Returns `undefined` when the AI features are switched off or no LLM provider is configured,
+ * which disables the feature in the editor and drops its toolbar entry (see `buildToolbarConfig`).
+ * The master switch is checked as well as the provider set, because turning it off leaves the
+ * configured providers stored — they are what the switch turns back on.
*
* @param getNoteLocation names the note being edited, so a run can say where in Trilium it is
* writing. Read per request rather than captured: switching notes reuses
* the editor rather than rebuilding it.
*/
export default function buildAiAssistantStream(getNoteLocation?: AiNoteLocationProvider): AiStreamFunction | undefined {
- if (!readSelectedModels().hasProvider) {
+ if (!options.is("aiEnabled") || !readSelectedModels().hasProvider) {
return undefined;
}
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index c86d445ccf..872da4593a 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -1,3 +1,4 @@
+import type { EditorConfig } from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS, IMAGE_MIMES, LOCALES, SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -7,7 +8,10 @@ import { ensureMimeTypesForHighlighting } from "../../../services/syntax_highlig
import { buildConfig, type BuildEditorOptions, OPEN_SOURCE_LICENSE_KEY } from "./config.js";
// Mutable option values, reset before each test (see `beforeEach`).
-const optionsState = vi.hoisted(() => ({ map: {} as Record<string, string | undefined> }));
+const optionsState = vi.hoisted(() => ({
+ map: {} as Record<string, string | undefined>,
+ json: {} as Record<string, unknown>
+}));
// Toggles whether the editor advertises raw-image clipboard support.
const imageState = vi.hoisted(() => ({ copySupported: false }));
@@ -48,7 +52,11 @@ vi.mock("../../../services/options.js", () => ({
if (name === "codeNotesMimeTypes") {
return ["text/javascript", "application/javascript;env=frontend", "application/javascript;env=backend", "text/css"];
}
+ if (name in optionsState.json) return optionsState.json[name];
return [];
+ },
+ is(name: string) {
+ return optionsState.map[name] === "true";
}
}
}));
@@ -128,6 +136,7 @@ async function buildDynamicConfig(overrides: Partial<BuildEditorOptions> = {}) {
beforeEach(() => {
optionsState.map = {};
+ optionsState.json = {};
imageState.copySupported = false;
catalogState.bundle = undefined;
catalogState.entries = {};
@@ -582,6 +591,34 @@ describe("CK config - mention feed", () => {
});
});
+describe("CK config - AI assistant", () => {
+ const PROVIDER = [{ id: "cfg-openai", provider: "openai", selectedModels: [{ id: "gpt-5" }] }];
+
+ // The two halves are settled together: without a transport the command can never be enabled,
+ // so the button would only ever be there to be greyed out.
+ it("offers the assistant only once the feature is on and a provider is configured", async () => {
+ const off = await buildConfig(baseOpts());
+ expect(off.aiAssistant?.stream).toBeUndefined();
+ expect(toolbarItems(off)).not.toContain("aiAssistant");
+
+ // The master switch off, but a provider still stored — what disabling it actually leaves.
+ optionsState.json["llmProviders"] = PROVIDER;
+ const noSwitch = await buildConfig(baseOpts());
+ expect(noSwitch.aiAssistant?.stream).toBeUndefined();
+ expect(toolbarItems(noSwitch)).not.toContain("aiAssistant");
+
+ optionsState.map["aiEnabled"] = "true";
+ const on = await buildConfig(baseOpts());
+ expect(on.aiAssistant?.stream).toBeDefined();
+ expect(toolbarItems(on)).toContain("aiAssistant");
+ });
+});
+
+/** The built toolbar's own items, whichever of the two shapes CKEditor accepts it took. */
+function toolbarItems(config: EditorConfig): unknown[] {
+ return Array.isArray(config.toolbar) ? config.toolbar : (config.toolbar?.items ?? []);
+}
+
describe("CK config - disabled plugins", () => {
it("removes the emoji and slash-command plugins based on their option toggles", async () => {
const disabled = await buildConfig(baseOpts());
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 3ad70a9aea..ddf6652d8d 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -42,6 +42,9 @@ export interface BuildEditorOptions {
}
export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {
+ // `undefined` when the AI features are off or no LLM provider is configured. Decided once:
+ // it both disables the assistant's command and keeps its entries off the toolbar.
+ const aiAssistantStream = buildAiAssistantStream(opts.getNoteLocation);
const config: EditorConfig = {
licenseKey: OPEN_SOURCE_LICENSE_KEY,
placeholder: t("editable_text.placeholder"),
@@ -198,8 +201,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
definitions: opts.templates
},
aiAssistant: {
- // `undefined` when no LLM provider is configured, which disables the feature.
- stream: buildAiAssistantStream(opts.getNoteLocation),
+ stream: aiAssistantStream,
// The "Changes" review view: a block-aware inline diff, so that a response which
// rewrote a paragraph rather than editing it reads as a replacement instead of as
// shredded `<ins>`/`<del>` pairs.
@@ -328,7 +330,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
return {
...config,
- ...buildToolbarConfig(opts.isClassicEditor)
+ ...buildToolbarConfig(opts.isClassicEditor, !!aiAssistantStream)
};
}
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
index d047f7e97c..f40c9d3bae 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts
@@ -38,12 +38,12 @@ describe("CKEditor config", () => {
// fixed-vs-floating parity check.
const FIXED_ONLY_ITEMS = new Set(["undo", "redo"]);
- const classicToolbarConfig = buildClassicToolbar(false);
+ const classicToolbarConfig = buildClassicToolbar(false, true);
const classicToolbarItems = new Set(
traverseItems(classicToolbarConfig.toolbar).filter((item) => !FIXED_ONLY_ITEMS.has(item))
);
- const floatingToolbarConfig = buildFloatingToolbar();
+ const floatingToolbarConfig = buildFloatingToolbar(true);
const floatingToolbarItems = traverseItems(floatingToolbarConfig.toolbar);
const floatingBlockToolbarItems = traverseItems({ items: floatingToolbarConfig.blockToolbar });
const floatingToolbarAllItems = new Set([ ...floatingToolbarItems, ...floatingBlockToolbarItems ]);
@@ -55,8 +55,29 @@ describe("CKEditor config", () => {
describe("buildClassicToolbar", () => {
it("reflects the multiline flag via shouldNotGroupWhenFull", () => {
- expect(buildClassicToolbar(false).toolbar.shouldNotGroupWhenFull).toBe(false);
- expect(buildClassicToolbar(true).toolbar.shouldNotGroupWhenFull).toBe(true);
+ expect(buildClassicToolbar(false, true).toolbar.shouldNotGroupWhenFull).toBe(false);
+ expect(buildClassicToolbar(true, true).toolbar.shouldNotGroupWhenFull).toBe(true);
+ });
+});
+
+/**
+ * An assistant that is switched off (or has no provider configured) has no transport, so its
+ * command can never be enabled — the entries are left out rather than shown permanently disabled.
+ */
+describe("the AI assistant's entries", () => {
+ it("are dropped from every toolbar when the assistant is unavailable", () => {
+ expect(buildClassicToolbar(false, false).toolbar.items).not.toContain("aiAssistant");
+ expect(buildMobileToolbar(false).toolbar.items).not.toContain("aiAssistant");
+
+ const floating = buildFloatingToolbar(false);
+ expect(floating.toolbar.items).not.toContain("aiAssistant");
+ expect(floating.blockToolbar).not.toContain("aiAssistant");
+ });
+
+ // The assistant heads the block toolbar, so it takes the separator behind it along.
+ it("leave the block toolbar opening on an item rather than on a separator", () => {
+ expect(buildFloatingToolbar(true).blockToolbar.slice(0, 3)).toStrictEqual([ "aiAssistant", "|", "heading" ]);
+ expect(buildFloatingToolbar(false).blockToolbar[0]).toBe("heading");
});
});
@@ -70,13 +91,13 @@ describe("group labels", () => {
}
it("translates every group label, on both the classic and the floating toolbar", () => {
- expect(groupLabels(buildClassicToolbar(false).toolbar.items)).toStrictEqual([
+ expect(groupLabels(buildClassicToolbar(false, true).toolbar.items)).toStrictEqual([
"text-editor.toolbar-groups.text-formatting",
"text-editor.toolbar-groups.insert",
"text-editor.toolbar-groups.alignment"
]);
- const floating = buildFloatingToolbar();
+ const floating = buildFloatingToolbar(true);
expect(groupLabels(floating.toolbar.items)).toStrictEqual([ "text-editor.toolbar-groups.text-formatting" ]);
expect(groupLabels(floating.blockToolbar)).toStrictEqual([
"text-editor.toolbar-groups.insert",
@@ -87,7 +108,7 @@ describe("group labels", () => {
describe("buildMobileToolbar", () => {
it("flattens nested toolbar groups into a single flat item list", () => {
- const mobile = buildMobileToolbar();
+ const mobile = buildMobileToolbar(true);
// Items nested inside group objects (text-formatting, alignment, ...) are hoisted up.
expect(mobile.toolbar.items).toContain("underline");
@@ -110,23 +131,23 @@ describe("buildToolbarConfig dispatch", () => {
it("returns the flattened mobile toolbar on a mobile device", () => {
setDevice("mobile");
- const config = buildToolbarConfig(true);
+ const config = buildToolbarConfig(true, true);
expect(config.toolbar.items.every((item) => typeof item === "string")).toBe(true);
});
it("returns the multiline classic toolbar when on desktop and the option is enabled", () => {
optionsState.values["textNoteEditorMultilineToolbar"] = "true";
- const config = buildToolbarConfig(true) as ReturnType<typeof buildClassicToolbar>;
+ const config = buildToolbarConfig(true, true) as ReturnType<typeof buildClassicToolbar>;
expect(config.toolbar.shouldNotGroupWhenFull).toBe(true);
});
it("returns the single-line classic toolbar when the multiline option is not enabled", () => {
- const config = buildToolbarConfig(true) as ReturnType<typeof buildClassicToolbar>;
+ const config = buildToolbarConfig(true, true) as ReturnType<typeof buildClassicToolbar>;
expect(config.toolbar.shouldNotGroupWhenFull).toBe(false);
});
it("returns the floating toolbar (with a block toolbar) when not in classic mode", () => {
- const config = buildToolbarConfig(false);
+ const config = buildToolbarConfig(false, true);
expect("blockToolbar" in config).toBe(true);
});
});
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index 9b993de7e8..06420f84a8 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -25,19 +25,25 @@ export function usesClassicToolbar({ floatingToolbarRequested, isMobile, textNot
return isMobile || textNoteEditorType === "ckeditor-classic";
}
-export function buildToolbarConfig(isClassicToolbar: boolean) {
+/**
+ * @param aiAssistant whether the AI assistant is usable at all — the feature is switched on and a
+ * provider is configured (see `buildAiAssistantStream`). When it isn't, its
+ * entries are left out rather than shown permanently disabled: a button that
+ * can never be pressed says nothing about why.
+ */
+export function buildToolbarConfig(isClassicToolbar: boolean, aiAssistant: boolean) {
if (utils.isMobile()) {
- return buildMobileToolbar();
+ return buildMobileToolbar(aiAssistant);
} else if (isClassicToolbar) {
const multilineToolbar = utils.isDesktop() && options.get("textNoteEditorMultilineToolbar") === "true";
- return buildClassicToolbar(multilineToolbar);
+ return buildClassicToolbar(multilineToolbar, aiAssistant);
} else {
- return buildFloatingToolbar();
+ return buildFloatingToolbar(aiAssistant);
}
}
-export function buildMobileToolbar() {
- const classicConfig = buildClassicToolbar(false);
+export function buildMobileToolbar(aiAssistant: boolean) {
+ const classicConfig = buildClassicToolbar(false, aiAssistant);
const items: string[] = [];
for (const item of classicConfig.toolbar.items) {
@@ -59,7 +65,7 @@ export function buildMobileToolbar() {
};
}
-export function buildClassicToolbar(multilineToolbar: boolean) {
+export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: boolean) {
// For nested toolbars, refer to https://ckeditor.com/docs/ckeditor5/latest/getting-started/setup/toolbar.html#grouping-toolbar-items-in-dropdowns-nested-toolbars.
return {
toolbar: {
@@ -86,7 +92,7 @@ export function buildClassicToolbar(multilineToolbar: boolean) {
// Ahead of the overflow dropdown, which a single-line toolbar fills from the end:
// down among the last items the assistant was grouped away at every ordinary note
// width.
- "aiAssistant",
+ ...(aiAssistant ? ["aiAssistant"] : []),
"imageUpload",
"blockQuote",
"admonition",
@@ -117,7 +123,7 @@ export function buildClassicToolbar(multilineToolbar: boolean) {
};
}
-export function buildFloatingToolbar() {
+export function buildFloatingToolbar(aiAssistant: boolean) {
return {
toolbar: {
items: [
@@ -139,7 +145,7 @@ export function buildFloatingToolbar() {
// the bar outright puts it where the eye lands before the formatting it came for.
// The block toolbar keeps its own entry for the other case: at a collapsed caret a
// quick action widens to the block it sits in.
- "aiAssistant",
+ ...(aiAssistant ? ["aiAssistant"] : []),
"code",
"link",
"bookmark",
@@ -152,8 +158,8 @@ export function buildFloatingToolbar() {
},
blockToolbar: [
- "aiAssistant",
- "|",
+ // With the separator, so dropping the assistant does not leave the bar opening on one.
+ ...(aiAssistant ? ["aiAssistant", "|"] : []),
"heading",
"|",
"bulletedList",