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): pick the model the assistant runs on from its menu
Elian Doran329537767f2b
diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsindex 138571c6ca..ba56cdf192 100644--- a/apps/client/src/menus/text_editor_context_menu.spec.ts+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -1,4 +1,4 @@-import type { AiQuickAction, AiQuickActionGroup } from "@triliumnext/ckeditor5";+import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup } from "@triliumnext/ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";const h = vi.hoisted(() => {@@ -50,6 +50,7 @@ const GROUPS: AiQuickActionGroup[] = [function fakeEditor({domRoot,groups = GROUPS,+ menuFooter = [],hasContext = true,isStreaming = false,isEnabled = true,@@ -57,13 +58,14 @@ function fakeEditor({}: {domRoot: Node | null;groups?: AiQuickActionGroup[];+ menuFooter?: AiQuickActionFooter[];hasContext?: boolean;isStreaming?: boolean;isEnabled?: boolean;hasPlugin?: boolean;}) {- // The live list is the plugin's, which the editor config only seeded.- const ui = { hasContext, isStreaming, quickActions: groups, runQuickAction: vi.fn() };+ // The live lists are the plugin's, which the editor config only seeded.+ const ui = { hasContext, isStreaming, quickActions: groups, menuFooter, runQuickAction: vi.fn() };const editor = {editing: { view: { getDomRoot: () => domRoot } },plugins: { has: () => hasPlugin, get: () => ui },@@ -190,6 +192,31 @@ describe("buildAiActionsMenuItem", () => {expect(GROUPS.find((g) => g.id === "tone")?.footer?.run).toHaveBeenCalled();});+ // The rows the menu itself ends with — what a run answers to, the model it speaks to — reached+ // through a submenu when one holds others.+ it("closes the whole menu with its footer rows", async () => {+ const run = vi.fn();+ build({+ hasContext: false,+ menuFooter: [{+ label: "Model: Sonnet 5",+ iconClass: "bx bx-chip",+ children: [{ label: "Sonnet 5", iconClass: "bx bx-check", run }]+ }]+ });+ const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;++ expect(titles(item.items ?? []).slice(-2)).toEqual(["--- separator ---", "Model: Sonnet 5"]);++ const picker = commandItems(item.items ?? []).find((i) => i.title === "Model: Sonnet 5");+ expect([picker?.enabled, picker?.uiIcon]).toEqual([true, "bx bx-chip"]);++ const [model] = commandItems(picker?.items ?? []);+ expect([model.title, model.uiIcon]).toEqual(["Sonnet 5", "bx bx-check"]);+ model.handler?.(model, null as never);+ expect(run).toHaveBeenCalled();+ });+it("runs the picked action, and opens the free-form prompt from the first row", async () => {const { editor, ui } = build();const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex 4054015892..336066b63f 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -1,4 +1,4 @@-import type { AiQuickAction, AiQuickActionGroup, CKTextEditor } from "@triliumnext/ckeditor5";+import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, CKTextEditor } from "@triliumnext/ckeditor5";import type { CommandNames } from "../components/app_context.js";import appContext from "../components/app_context.js";@@ -59,11 +59,22 @@ export async function buildAiActionsMenuItem(): Promise<MenuItem<CommandNames> |handler: () => editor.execute("aiAssistant")},{ kind: "separator" },- ...quickActions+ ...quickActions,+ ...(ui.menuFooter.length ? [{ kind: "separator" } as const, ...footerItems(ui.menuFooter)] : [])]};}+/** A footer row, or the submenu it opens onto when it has children rather than something to run. */+function footerItems(rows: ReadonlyArray<AiQuickActionFooter>): MenuItem<CommandNames>[] {+ return rows.map((row) => ({+ title: row.label,+ uiIcon: row.iconClass,+ enabled: true,+ ...(row.children ? { items: footerItems(row.children) } : { handler: row.run })+ }));+}+/*** The quick actions as menu rows, laid out the way the toolbar's dropdown lays them out: a group* marked `submenu` opens one, an inlined group contributes its actions directly, and a rule isdiff --git a/apps/client/src/services/llm_providers.ts b/apps/client/src/services/llm_providers.tsnew file mode 100644index 0000000000..26cba7c112--- /dev/null+++ b/apps/client/src/services/llm_providers.ts@@ -0,0 +1,79 @@+import type { LlmModelInfo } from "@triliumnext/commons";++import { formatModelCost } from "./llm_model_cost.js";+import options from "./options.js";++export interface ModelOption extends LlmModelInfo {+ costDescription?: string;+}++/** A configured provider and the models the user selected for it (possibly none). */+export interface ModelProviderGroup {+ /** Provider config id — stable group key. */+ id: string;+ /** User-given provider name, shown as the group header. */+ name: string;+ /** Provider type (e.g. "openai"). */+ provider: string;+ /** Selected models for this provider; empty for configs migrated from before selection existed. */+ models: ModelOption[];+}++/**+ * Read the user's selected models per configured provider. Returns:+ * - `groups`: one entry per configured provider (in config order), each with its+ * selected models — the group is kept even when it has none, so a provider+ * migrated from before selection existed still shows up with an empty group.+ * - `models`: the flattened list across all groups (for default selection and+ * the active-model lookup).+ * - `hasProvider`: whether any provider is configured at all.+ *+ * Read straight from the synced `llmProviders` option, so every surface offering a model — the+ * chat's picker, the text editor's assistant — lists the same thing without a round-trip.+ */+export function readSelectedModels(): { models: ModelOption[]; groups: ModelProviderGroup[]; hasProvider: boolean } {+ const configs = (options.getJson("llmProviders") as StoredProviderConfig[] | null) ?? [];+ const groups: ModelProviderGroup[] = configs.map(config => ({+ id: config.id,+ name: config.name,+ provider: config.provider,+ models: (config.selectedModels ?? []).map(model => ({+ ...model,+ provider: config.provider,+ providerId: config.id,+ providerName: config.name,+ costDescription: formatModelCost(model)+ }))+ }));+ const models = groups.flatMap(g => g.models);+ return { models, groups, hasProvider: configs.length > 0 };+}++/**+ * Resolve the active model from the available list. Several providers can expose+ * the same model ID (e.g. an Anthropic API key and a Claude subscription, or two+ * OpenAI-compatible endpoints), so the recorded provider type/config id narrow+ * the match; when they're absent (chats saved before they existed) we fall back+ * to the first ID match. Returns undefined when nothing matches — e.g. a saved+ * model ID that has since been deselected — which callers treat as "no model".+ */+export function resolveSelectedModel(+ availableModels: ModelOption[],+ selectedModel: string,+ selectedProvider: string | undefined,+ selectedProviderId: string | undefined+): ModelOption | undefined {+ if (!selectedModel) return undefined;+ return availableModels.find(m =>+ m.id === selectedModel+ && (!selectedProvider || m.provider === selectedProvider)+ && (!selectedProviderId || m.providerId === selectedProviderId));+}++/** Minimal shape of a provider config as stored in the `llmProviders` option. */+interface StoredProviderConfig {+ id: string;+ name: string;+ provider: string;+ selectedModels?: LlmModelInfo[];+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 39b04d6d1a..56c3968f35 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2844,6 +2844,8 @@"group_reformat": "Reformat","group_translate": "Translate","group_custom": "Custom",+ "model": "Model: {{model}}",+ "model_default": "Default","command_make_shorter": "Make shorter","command_make_longer": "Make longer","command_simplify": "Simplify language",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 5dbf563866..0b5a9ee11d 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -24,7 +24,8 @@ import { editorHtmlToMarkdown } from "./chat_input_markdown.js";import { shortModelName } from "./model_name.js";import { SafeImage } from "./retry_image.js";import { useChatAttachments } from "./useChatAttachments.js";-import { type ModelOption, resolveSelectedModel, type UseLlmChatReturn } from "./useLlmChat.js";+import { type ModelOption, resolveSelectedModel } from "../../../services/llm_providers.js";+import { type UseLlmChatReturn } from "./useLlmChat.js";const READ_ONLY_LOCK = "llm-chat-streaming";diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex bcd4811f6f..4fffb9e03f 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -3,8 +3,7 @@ import { RefObject } from "preact";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";import { streamChatCompletion } from "../../../services/llm_chat.js";-import { formatModelCost } from "../../../services/llm_model_cost.js";-import options from "../../../services/options.js";+import { type ModelOption, type ModelProviderGroup, readSelectedModels, resolveSelectedModel } from "../../../services/llm_providers.js";import { randomString } from "../../../services/utils.js";import { useTriliumEvent } from "../../react/hooks.js";import { estimateTokens, quantizeDraftTokens } from "./chat_context_usage.js";@@ -75,43 +74,6 @@ function stripQuoteSourcesFromApiContent(content: string | LlmMessagePart[]): streturn content.map(part => (part.type === "text" ? { ...part, text: stripQuoteSources(part.text) } : part));}-export interface ModelOption extends LlmModelInfo {- costDescription?: string;-}--/**- * Resolve the active model from the available list. Several providers can expose- * the same model ID (e.g. an Anthropic API key and a Claude subscription, or two- * OpenAI-compatible endpoints), so the recorded provider type/config id narrow- * the match; when they're absent (chats saved before they existed) we fall back- * to the first ID match. Returns undefined when nothing matches — e.g. a saved- * model ID that has since been deselected — which callers treat as "no model".- */-export function resolveSelectedModel(- availableModels: ModelOption[],- selectedModel: string,- selectedProvider: string | undefined,- selectedProviderId: string | undefined-): ModelOption | undefined {- if (!selectedModel) return undefined;- return availableModels.find(m =>- m.id === selectedModel- && (!selectedProvider || m.provider === selectedProvider)- && (!selectedProviderId || m.providerId === selectedProviderId));-}--/** A configured provider and the models the user selected for it (possibly none). */-export interface ModelProviderGroup {- /** Provider config id — stable group key. */- id: string;- /** User-given provider name, shown as the group header. */- name: string;- /** Provider type (e.g. "openai"). */- provider: string;- /** Selected models for this provider; empty for configs migrated from before selection existed. */- models: ModelOption[];-}-export interface LlmChatOptions {/** Default value for enableNoteTools */defaultEnableNoteTools?: boolean;@@ -998,37 +960,3 @@ export function useLlmChat(};}-/** Minimal shape of a provider config as stored in the `llmProviders` option. */-interface StoredProviderConfig {- id: string;- name: string;- provider: string;- selectedModels?: LlmModelInfo[];-}--/**- * Read the user's selected models per configured provider. Returns:- * - `groups`: one entry per configured provider (in config order), each with its- * selected models — the group is kept even when it has none, so a provider- * migrated from before selection existed still shows up with an empty group.- * - `models`: the flattened list across all groups (for default selection and- * the active-model lookup).- * - `hasProvider`: whether any provider is configured at all.- */-function readSelectedModels(): { models: ModelOption[]; groups: ModelProviderGroup[]; hasProvider: boolean } {- const configs = (options.getJson("llmProviders") as StoredProviderConfig[] | null) ?? [];- const groups: ModelProviderGroup[] = configs.map(config => ({- id: config.id,- name: config.name,- provider: config.provider,- models: (config.selectedModels ?? []).map(model => ({- ...model,- provider: config.provider,- providerId: config.id,- providerName: config.name,- costDescription: formatModelCost(model)- }))- }));- const models = groups.flatMap(g => g.models);- return { models, groups, hasProvider: configs.length > 0 };-}diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex a5443ba991..0923ab930c 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -6,7 +6,7 @@ import froca from "../../../services/froca";import link from "../../../services/link";import linkEmbedService, { type EmbedMetadata } from "../../../services/link_embed";import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";-import { useAiQuickActions } from "./ai_quick_actions";+import { useAiMenuFooter, useAiQuickActions } from "./ai_quick_actions";import { buildConfig, BuildEditorOptions } from "./config";export type BoxSize = "small" | "medium" | "full" | "expandable";@@ -101,6 +101,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe// editor itself. A rebuild for either would cost the caret and the undo history of the note// being written.const quickActions = useAiQuickActions();+ const menuFooter = useAiMenuFooter();const [ editor, setEditor ] = useState<CKTextEditor>();const { parentComponent, ntxId, note } = useNoteContext();@@ -351,6 +352,14 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe}}, [ editor, quickActions ]);+ // Likewise for the row naming the model a run speaks to, which restates itself once picked.+ useEffect(() => {+ if (!editor) return;+ if (editor.plugins.has("AiAssistantUI")) {+ editor.plugins.get("AiAssistantUI").updateMenuFooter(menuFooter);+ }+ }, [ editor, menuFooter ]);+// React to notification warning callback.useEffect(() => {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.tsindex 28366eb95d..0b17689e18 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@@ -288,7 +288,7 @@ describe("buildAiAssistantQuickActions", () => {const group = buildAiAssistantQuickActions().find((candidate) => candidate.id === "translate");expect(group?.footer?.label).toBe("note_language.configure-languages");- group?.footer?.run();+ group?.footer?.run?.();expect(appContext.triggerCommand).toHaveBeenCalledWith("showContentLanguagesDialog");// It is the only group whose contents the user chooses, so the only one with a footer.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.tsindex aeccbed29d..8636f71cda 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,13 +1,15 @@import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";-import { getEnglishName, type LlmChatConfig, type LlmMessage, type LlmModelInfo, type LlmUsage, type Locale, type ToMarkdownResponse } from "@triliumnext/commons";+import { getEnglishName, type LlmMessage, type LlmUsage, type Locale, type ToMarkdownResponse } from "@triliumnext/commons";import appContext from "../../../components/app_context.js";import { getAvailableLocales, t } from "../../../services/i18n.js";+import { readSelectedModels } from "../../../services/llm_providers.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";+import { pickModel } from "./ai_model_picker.js";/*** Builds the transport behind the editor's AI assistant (`config.aiAssistant.stream`): a@@ -25,7 +27,7 @@ import { getTaskStateDefinitions } from "../../../services/task_states.js";* a first provider shows the button after the editor is next rebuilt.*/export default function buildAiAssistantStream(): AiStreamFunction | undefined {- if (!readProviderConfigs().length) {+ if (!readSelectedModels().hasProvider) {return undefined;}@@ -46,7 +48,7 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {}];- const config = pickDefaultModel();+ const config = pickModel();let cumulative = "";const usage = await new Promise<LlmUsage | null>((resolve, reject) => {let reported: LlmUsage | null = null;@@ -428,37 +430,4 @@ export function stripMarkdownFences(cumulative: string): string {return body;}-/** The subset of a stored `llmProviders` entry this module reads. */-interface StoredProviderConfig {- id: string;- provider: string;- selectedModels?: LlmModelInfo[];-}--function readProviderConfigs(): StoredProviderConfig[] {- return (options.getJson("llmProviders") as StoredProviderConfig[] | null) ?? [];-}--/**- * The provider/model the assistant uses: the first configured provider that has a model selected,- * preferring its default. The same resolution the LLM chat starts out with — a per-run model- * picker in the balloon can come later.- *- * The provider is always named, even when no model can be: the server falls back to- * `getProviderByType("anthropic")` for a request that names none (`runChat` in- * `packages/trilium-core/src/services/llm/chat.ts`), which would fail outright for an- * OpenAI-only setup and silently use the wrong provider for a mixed one. Naming the provider- * without a model instead lets the server resolve that provider's own default.- */-function pickDefaultModel(): LlmChatConfig {- const configs = readProviderConfigs();- for (const config of configs) {- const model = config.selectedModels?.find((m) => m.isDefault) ?? config.selectedModels?.[0];- if (model) {- return { model: model.id, provider: config.provider, providerId: config.id };- }- }- const [first] = configs;- return first ? { provider: first.provider, providerId: first.id } : {};-}diff --git a/apps/client/src/widgets/type_widgets/text/ai_model_picker.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_model_picker.spec.tsnew file mode 100644index 0000000000..23481c87f6--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/ai_model_picker.spec.ts@@ -0,0 +1,121 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("../../../services/i18n.js", () => ({+ t: (key: string, values?: Record<string, string>) => (values+ ? `${key}(${Object.entries(values).map(([name, value]) => `${name}=${value}`).join(",")})`+ : key)+}));+vi.mock("../../../services/options.js", () => ({+ default: {+ getJson: (key: string) => stored[key] ?? null,+ save: vi.fn(async (key: string, value: string) => {+ stored[key] = JSON.parse(value);+ })+ }+}));++import options from "../../../services/options.js";+import { buildAiModelPicker, pickModel } from "./ai_model_picker.js";++/** Whatever the mocked options store holds, keyed as the option names. */+let stored: Record<string, unknown> = {};++const TWO_PROVIDERS = [+ {+ id: "cfg-anthropic",+ name: "Anthropic",+ provider: "anthropic",+ selectedModels: [+ { id: "claude-opus-5", name: "Claude Opus 5" },+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", isDefault: true }+ ]+ },+ {+ id: "cfg-openai",+ name: "OpenAI",+ provider: "openai",+ selectedModels: [{ id: "gpt-5", name: "GPT-5" }]+ }+];++function labelsOf(picker: ReturnType<typeof buildAiModelPicker>) {+ return (picker[0]?.children ?? []).map((row) => [row.label, row.iconClass]);+}++describe("the AI assistant's model picker", () => {+ beforeEach(() => {+ stored = {};+ vi.mocked(options.save).mockClear();+ });++ it("lists every configured model, ticking the stored one and naming it in the row above", () => {+ stored.llmProviders = TWO_PROVIDERS;+ stored.aiAssistantModel = { model: "gpt-5", provider: "openai", providerId: "cfg-openai" };++ const picker = buildAiModelPicker();+ // More than one provider is configured, so a row says which one it means: the same model id+ // can be reached through two of them.+ expect(picker[0].label).toBe("ai_assistant.model(model=GPT-5 (OpenAI))");+ expect(labelsOf(picker)).toEqual([+ ["Opus 5 (Anthropic)", "bx bx-empty"],+ ["Sonnet 5 (Anthropic)", "bx bx-empty"],+ ["GPT-5 (OpenAI)", "bx bx-check"]+ ]);+ });++ it("names the row for the default while nothing has been picked, and drops the provider with one configured", () => {+ stored.llmProviders = [TWO_PROVIDERS[0]];++ const picker = buildAiModelPicker();+ expect(picker[0].label).toBe("ai_assistant.model(model=ai_assistant.model_default)");+ expect(labelsOf(picker)).toEqual([["Opus 5", "bx bx-empty"], ["Sonnet 5", "bx bx-empty"]]);+ });++ // A row offering the only answer there is takes up space and settles nothing.+ it("offers no picker when there is nothing to choose between", () => {+ expect(buildAiModelPicker()).toEqual([]);++ stored.llmProviders = [{ ...TWO_PROVIDERS[1] }];+ expect(buildAiModelPicker()).toEqual([]);+ });++ it("stores the model picked, provider and all", () => {+ stored.llmProviders = TWO_PROVIDERS;++ buildAiModelPicker()[0].children?.[0].run?.();++ expect(options.save).toHaveBeenCalledWith("aiAssistantModel", JSON.stringify({+ model: "claude-opus-5", provider: "anthropic", providerId: "cfg-anthropic"+ }));+ });++ describe("pickModel", () => {+ it("runs on the stored model", () => {+ stored.llmProviders = TWO_PROVIDERS;+ stored.aiAssistantModel = { model: "gpt-5", provider: "openai", providerId: "cfg-openai" };++ expect(pickModel()).toEqual({ model: "gpt-5", provider: "openai", providerId: "cfg-openai" });+ });++ // A model can be deselected, or its provider deleted, long after it was picked.+ it("falls back to the flagged default when the stored model is no longer on offer", () => {+ stored.llmProviders = TWO_PROVIDERS;+ stored.aiAssistantModel = { model: "gpt-4", provider: "openai", providerId: "cfg-openai" };++ expect(pickModel()).toMatchObject({ model: "claude-sonnet-5", providerId: "cfg-anthropic" });+ });++ // Naming no provider at all makes the server fall back to Anthropic, which is wrong for an+ // OpenAI-only setup; naming one without a model lets it resolve that provider's own default.+ it("names the provider even when it has no model to name", () => {+ stored.llmProviders = [{ id: "cfg-openai", name: "OpenAI", provider: "openai" }];++ expect(pickModel()).toEqual({ provider: "openai", providerId: "cfg-openai" });+ expect(pickModel()).not.toHaveProperty("model");+ });++ it("names nothing at all when no provider is configured", () => {+ expect(pickModel()).toEqual({});+ });+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/ai_model_picker.ts b/apps/client/src/widgets/type_widgets/text/ai_model_picker.tsnew file mode 100644index 0000000000..e16eb4b3fe--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/ai_model_picker.ts@@ -0,0 +1,87 @@+import type { AiQuickActionFooter } from "@triliumnext/ckeditor5";+import type { LlmChatConfig } from "@triliumnext/commons";++import { t } from "../../../services/i18n.js";+import { type ModelOption, readSelectedModels, resolveSelectedModel } from "../../../services/llm_providers.js";+import options from "../../../services/options.js";+import { shortModelName } from "../llm_chat/model_name.js";++/**+ * The row closing the assistant's menu: which model a run speaks to, and a submenu to change it.+ *+ * The models are the ones the chat's own picker lists — both read `llmProviders` through+ * `readSelectedModels`, so the two can never disagree about what is on offer. What differs is where+ * the *choice* is kept: a chat stores it in its own note, and the assistant has no note of its own,+ * so it goes to the synced `aiAssistantModel` option and holds across notes and devices.+ *+ * Returns nothing when there is one model or none to choose between — a picker offering a single+ * answer is a row that only takes up space.+ */+export function buildAiModelPicker(): AiQuickActionFooter[] {+ const { models, groups } = readSelectedModels();+ if (models.length < 2) {+ return [];+ }++ // The same model can be reached through two configured providers, so the rows have to say which+ // one they mean — but only where there is more than one to confuse them with.+ const name = (model: ModelOption) => {+ const short = shortModelName(model.name, model.provider);+ return groups.length > 1 && model.providerName ? `${short} (${model.providerName})` : short;+ };++ const current = resolveStoredModel(models);+ return [{+ label: t("ai_assistant.model", { model: current ? name(current) : t("ai_assistant.model_default") }),+ iconClass: "bx bx-chip",+ children: models.map((model) => ({+ label: name(model),+ // The tick every checked row in Trilium wears, and the reserver that keeps the labels+ // of the unticked ones lined up with it.+ iconClass: model === current ? "bx bx-check" : "bx bx-empty",+ run: () => void options.save("aiAssistantModel", JSON.stringify({+ model: model.id,+ provider: model.provider,+ providerId: model.providerId+ } satisfies StoredModel))+ }))+ }];+}++/**+ * The model a run should use: the stored one while it is still on offer, and otherwise the same+ * first-provider default the assistant used before there was anything to store — a model can be+ * deselected or its provider deleted long after it was picked.+ *+ * The provider is always named, even when no model can be: the server falls back to+ * `getProviderByType("anthropic")` for a request that names none (`runChat` in+ * `packages/trilium-core/src/services/llm/chat.ts`), which would fail outright for an+ * OpenAI-only setup and silently use the wrong provider for a mixed one. Naming the provider+ * without a model instead lets the server resolve that provider's own default.+ */+export function pickModel(): LlmChatConfig {+ const { models, groups } = readSelectedModels();++ const chosen = resolveStoredModel(models) ?? models.find((model) => model.isDefault) ?? models[0];+ if (chosen) {+ return { model: chosen.id, provider: chosen.provider, providerId: chosen.providerId };+ }++ const [first] = groups;+ return first ? { provider: first.provider, providerId: first.id } : {};+}++/** What the `aiAssistantModel` option holds — the three fields it takes to name a model exactly. */+interface StoredModel {+ model: string;+ provider?: string;+ providerId?: string;+}++function resolveStoredModel(models: ModelOption[]): ModelOption | undefined {+ const stored = options.getJson("aiAssistantModel") as StoredModel | null;+ return stored+ ? resolveSelectedModel(models, stored.model, stored.provider, stored.providerId)+ : undefined;+}+diff --git a/apps/client/src/widgets/type_widgets/text/ai_quick_actions.ts b/apps/client/src/widgets/type_widgets/text/ai_quick_actions.tsindex 4c405f7977..de1908db1a 100644--- a/apps/client/src/widgets/type_widgets/text/ai_quick_actions.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_quick_actions.ts@@ -1,5 +1,5 @@-import type { AiQuickAction, AiQuickActionGroup } from "@triliumnext/ckeditor5";-import { useEffect, useState } from "preact/hooks";+import type { AiQuickAction, AiQuickActionFooter, AiQuickActionGroup } from "@triliumnext/ckeditor5";+import { useEffect, useMemo, useState } from "preact/hooks";import type FNote from "../../../entities/fnote.js";import debounce from "../../../services/debounce.js";@@ -9,6 +9,7 @@ import type LoadResults from "../../../services/load_results.js";import search from "../../../services/search.js";import { useTriliumEvent, useTriliumOption } from "../../react/hooks.jsx";import { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";+import { buildAiModelPicker } from "./ai_model_picker.js";/*** Everything the AI assistant's menu offers: the built-in groups, followed by the instructions the@@ -35,6 +36,17 @@ export function useAiQuickActions(): AiQuickActionGroup[] {return quickActions;}+/**+ * The rows closing the assistant's menu. Rebuilt when the model is picked or the providers change,+ * so the row restates which model is in force and moves the tick to it.+ */+export function useAiMenuFooter(): AiQuickActionFooter[] {+ const [ chosenModel ] = useTriliumOption("aiAssistantModel");+ const [ providers ] = useTriliumOption("llmProviders");++ return useMemo(buildAiModelPicker, [ chosenModel, providers ]);+}+/** The label marking a note as an instruction to offer in the assistant's menu. */const LABEL = "aiQuickAction";/** The built-in template a user makes one of these notes from. */diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex fe33fd4e6b..afa0145f45 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -137,19 +137,29 @@ export interface AiQuickAction {export type AiSanitizeFunction = (html: string) => string;/**- * A row appended to the bottom of a group's submenu, below a rule, that runs host code instead of- * asking the model — for a group whose contents the user configures, so that what configures them- * is reachable from the group itself rather than only from the settings.+ * A row that runs host code instead of asking the model, below a rule at the foot of a group's+ * submenu ({@link AiQuickActionGroup.footer}) or of the menu itself ({@link AiAssistantConfig.menuFooter}).+ * For the settings a run answers to, rather than instructions for one — what fills a group whose+ * contents the user configures, or which model the assistant speaks to.** It is not an {@link AiQuickAction}: it has no prompt, needs no content, and has no business in* the `/` palette, which lists ways to instruct the model.+ *+ * A row showing the state of what it sets — the model in force, say — says so with its+ * {@link iconClass}, the way every checked row in Trilium does: `bx bx-check` when it is the one in+ * force, `bx bx-empty` to hold the slot when it is not.*/export interface AiQuickActionFooter {/** The label shown in the menu, already translated by the host. */label: string;/** The row's icon, as a Boxicon class list. */iconClass?: string;- run: () => void;+ /**+ * Rows this one opens onto, making it a submenu rather than something that runs. A row with+ * children never runs, so {@link run} is beside the point for it.+ */+ children?: AiQuickActionFooter[];+ run?: () => void;}/** A labelled group of quick actions, rendered as a group in the menu. */@@ -199,6 +209,12 @@ export interface AiAssistantConfig {*/quickActions?: AiQuickActionGroup[];+ /**+ * Rows closing the toolbar entry's menu, below a rule under the last group — what a run answers+ * to rather than an instruction for one. Trilium hangs the model picker here.+ */+ menuFooter?: AiQuickActionFooter[];+/*** 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. Onlydiff --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 402a29b38c..0b44da4eb3 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@@ -382,6 +382,40 @@ describe("AiAssistantUI toolbar entry", () => {expect(requests[0]).toEqual({ query: "Translate to Japanese.", context: "foo" });});+ // What a run answers to rather than an instruction for one — Trilium hangs the model picker+ // here — so it closes the menu below a rule and never asks whether there is content.+ it("closes the menu with its footer rows, and opens the ones that hold others", async () => {+ const run = vi.fn();+ editor.plugins.get(AiAssistantUI).updateMenuFooter([{+ label: "Model: Sonnet 5",+ iconClass: "bx bx-chip",+ children: [+ { label: "Sonnet 5", iconClass: "bx bx-check", run },+ { label: "Opus 5", iconClass: "bx bx-empty", run: vi.fn() }+ ]+ }]);++ dropdown.isOpen = false;+ dropdown.isOpen = true;+ const entries = menuEntries(dropdown);+ expect(entries.at(-1)).toEqual({ menu: "Model: Sonnet 5", actions: ["Sonnet 5", "Opus 5"] });+ expect(entries.at(-2)).toBe("---");++ const [picker] = openMenu(dropdown).menus.filter((menu) => menu.id.startsWith("__footer"));+ expect(picker.buttonView.element?.querySelector(".ck-ai-action-icon")?.className)+ .toBe("ck-ai-action-icon bx bx-chip");++ // Nothing is selected, yet the picker and its rows stay reachable.+ setModelData(editor.model, "<paragraph>[]</paragraph>");+ expect(picker.isEnabled).toBe(true);++ const sonnet = quickActionButtons(dropdown).find((button) => button.label === "Sonnet 5");+ expect(sonnet?.isEnabled).toBe(true);+ sonnet?.fire("execute");+ expect(run).toHaveBeenCalled();+ expect(requests).toHaveLength(0);+ });+it("runs an action picked from inside a submenu", async () => {// A submenu button delegates its `execute` up through its menu to the root rather than// firing on the dropdown itself, so this is a different path from an inlined action.diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex 377215b35a..f37ee8a543 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -39,6 +39,9 @@ const DIALOG_ID = "aiAssistant";*/const ASK_ID = "__ask";+/** Prefixes the ids of the rows closing the menu, out of the way of the host's own. */+const MENU_FOOTER_ID = "__footer";+/*** How much of a response has to be a replacement rather than an edit (see* `AiDiffResult.rewriteRatio`) before the review opens on the plain result instead of the diff.@@ -106,6 +109,8 @@ export default class AiAssistantUI extends Plugin {* what is on offer.*/private _quickActions: AiQuickActionGroup[] = [];+ /** The rows closing the menu, which the config likewise only seeds. */+ private _menuFooter: AiQuickActionFooter[] = [];/*** Marks each menu built from {@link _quickActions} as owing a redraw, one closure per toolbar* showing us.@@ -116,12 +121,17 @@ export default class AiAssistantUI extends Plugin {return this._quickActions;}+ public get menuFooter(): ReadonlyArray<AiQuickActionFooter> {+ return this._menuFooter;+ }+public init(): void {const editor = this.editor;this.set("isStreaming", false);this.set("hasContext", false);this._quickActions = editor.config.get("aiAssistant")?.quickActions ?? [];+ this._menuFooter = editor.config.get("aiAssistant")?.menuFooter ?? [];editor.ui.componentFactory.add("aiAssistant", (locale) => this._createToolbarComponent(locale));@@ -158,6 +168,19 @@ export default class AiAssistantUI extends Plugin {*/public updateQuickActions(groups: AiQuickActionGroup[]): void {this._quickActions = groups;+ this._redrawMenus();+ }++ /**+ * Replaces the rows closing the menu. Same contract as {@link updateQuickActions} — and the same+ * necessity, since a row that names a setting has to restate it once the setting changes.+ */+ public updateMenuFooter(rows: AiQuickActionFooter[]): void {+ this._menuFooter = rows;+ this._redrawMenus();+ }++ private _redrawMenus(): void {for (const invalidate of this._invalidateMenu) {invalidate();}@@ -246,6 +269,18 @@ export default class AiAssistantUI extends Plugin {const groups = this._quickActions;const definition: DropdownMenuDefinition = [];+ /** Records a footer row against its id and describes it, opener or leaf, to the menu. */+ const defineFooter = (id: string, footer: AiQuickActionFooter): DropdownMenuDefinition[number] => {+ footersById.set(id, footer);+ return footer.children+ ? {+ id,+ menu: footer.label,+ children: footer.children.map((child, index) => defineFooter(`${id}:${index}`, child))+ }+ : { id, label: footer.label };+ };+// Heads the menu: the typed prompt every row below it is a shortcut past, and what the// button half of the split does. Ruled off from them, since it is a way in rather than an// instruction.@@ -256,15 +291,13 @@ export default class AiAssistantUI extends Plugin {for (const [index, group] of groups.entries()) {groupsById.set(group.id, group);- const children = group.actions.map((action) => {+ const children: DropdownMenuDefinition = group.actions.map((action) => {actionsById.set(action.id, action);return { id: action.id, label: action.label };});if (group.submenu) {if (group.footer) {- const id = `${group.id}:footer`;- footersById.set(id, group.footer);- children.push({ id, label: group.footer.label });+ children.push(defineFooter(`${group.id}:footer`, group.footer));}definition.push({ id: group.id, menu: group.label, children });} else {@@ -277,6 +310,12 @@ export default class AiAssistantUI extends Plugin {}}+ // What a run answers to, under the instructions that make one.+ if (this._menuFooter.length) {+ separatorAt.push(definition.length);+ definition.push(...this._menuFooter.map((row, index) => defineFooter(`${MENU_FOOTER_ID}:${index}`, row)));+ }+discardMenu();addMenuToDropdown(dropdownView, this.editor.ui.view.body, definition, {ariaLabel: locale.t("AI assistant")@@ -313,6 +352,14 @@ export default class AiAssistantUI extends Plugin {addIcon(button, action?.iconClass);}for (const menu of dropdownView.menuView?.menus ?? []) {+ const footer = footersById.get(menu.id);+ if (footer) {+ // A footer submenu holds settings, not instructions, so nothing about it turns+ // on there being content to work on.+ addIcon(menu.buttonView, footer.iconClass);+ continue;+ }+const group = groupsById.get(menu.id);addIcon(menu.buttonView, group?.iconClass);// A submenu with nothing runnable in it should not invite the pointer: gate the@@ -375,7 +422,8 @@ export default class AiAssistantUI extends Plugin {const footer = footersById.get(id);if (footer) {- footer.run();+ // A footer that opens onto others has nothing of its own to run.+ footer.run?.();return;}diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex b8de13de6b..22aa734f21 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -312,6 +312,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActiaiEnabled: boolean;/** JSON array of configured LLM providers with their API keys */llmProviders: string;+ /** The model the text editor's AI assistant runs on, as JSON `{ providerId, provider, model }`; empty to follow the first configured provider's default. */+ aiAssistantModel: string;/** Whether the MCP (Model Context Protocol) server endpoint is enabled. */mcpEnabled: boolean;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 3b38892a4e..10b7a1f9d5 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -155,6 +155,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([// LLM options"aiEnabled","llmProviders",+ "aiAssistantModel","mcpEnabled",// OCR options"ocrAutoProcessImages",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 2c6ed64393..0c82d0fe3b 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -364,6 +364,7 @@ const defaultOptions: DefaultOption[] = [// Was previously the "llm" experimental feature; inherit the value from there for existing users.{ name: "aiEnabled", value: (optionsMap) => optionsMap.experimentalFeatures?.includes('"llm"') ? "true" : "false", isSynced: true },{ name: "llmProviders", value: "[]", isSynced: true },+ { name: "aiAssistantModel", value: "", isSynced: true },{ name: "mcpEnabled", value: "false", isSynced: false },// OCR options