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(options/llm): integrate LLM switch directly
Elian Doran64cfeccf834f
diff --git a/apps/client/src/services/experimental_features.spec.ts b/apps/client/src/services/experimental_features.spec.tsindex fd70995279..d117467a5a 100644--- a/apps/client/src/services/experimental_features.spec.ts+++ b/apps/client/src/services/experimental_features.spec.ts@@ -21,13 +21,17 @@ vi.mock("./utils.js", async (orig) => {// `enabledFeatures` is module-level cached on first read of getEnabledFeatures,// so each scenario re-imports a fresh module copy. The fresh copy binds to a// fresh `options` singleton, so we re-import and spy on THAT instance.-async function freshModule(stored: unknown, isNewLayout: boolean) {+async function freshModule(stored: unknown, opts: { newLayout?: boolean; aiEnabled?: boolean } = {}) {vi.resetModules();const options = (await import("./options.js")).default;vi.spyOn(options, "get").mockReturnValue(typeof stored === "string" ? stored : JSON.stringify(stored));- vi.spyOn(options, "is").mockReturnValue(isNewLayout);+ vi.spyOn(options, "is").mockImplementation((name) => {+ if (name === "newLayout") return opts.newLayout ?? false;+ if (name === "aiEnabled") return opts.aiEnabled ?? false;+ return false;+ });const mod = (await import("./experimental_features.js")) as typeof import("./experimental_features.js");return { mod, options };}@@ -40,7 +44,7 @@ describe("experimental_features", () => {});it("lists all features when not standalone, hides llm in standalone", async () => {- const { mod } = await freshModule([], false);+ const { mod } = await freshModule([]);ctrl.standalone = false;expect(mod.getAvailableExperimentalFeatures().map((f) => f.id)).toEqual(["new-layout", "llm"]);@@ -51,7 +55,7 @@ describe("experimental_features", () => {it("new-layout is enabled via mobile or the newLayout option", async () => {// neither mobile nor option -> disabled- const { mod } = await freshModule([], false);+ const { mod } = await freshModule([]);ctrl.mobile = false;expect(mod.isExperimentalFeatureEnabled("new-layout")).toBe(false);@@ -60,46 +64,46 @@ describe("experimental_features", () => {expect(mod.isExperimentalFeatureEnabled("new-layout")).toBe(true);// not mobile but the option is true -> enabled- const opt = await freshModule([], true);+ const opt = await freshModule([], { newLayout: true });ctrl.mobile = false;expect(opt.mod.isExperimentalFeatureEnabled("new-layout")).toBe(true);});it("llm is always disabled in standalone mode", async () => {- const { mod } = await freshModule(["llm"], false);+ const { mod } = await freshModule([], { aiEnabled: true });ctrl.standalone = true;expect(mod.isExperimentalFeatureEnabled("llm")).toBe(false);});- it("non-standalone llm enablement is driven by the persisted feature set", async () => {+ it("non-standalone llm enablement is driven by the aiEnabled option", async () => {ctrl.standalone = false;- const enabled = await freshModule(["llm"], false);+ const enabled = await freshModule([], { aiEnabled: true });expect(enabled.mod.isExperimentalFeatureEnabled("llm")).toBe(true);- const disabled = await freshModule([], false);+ // a stale "llm" entry in the persisted experimental set no longer counts+ const disabled = await freshModule(["llm"]);expect(disabled.mod.isExperimentalFeatureEnabled("llm")).toBe(false);});- it("drops new-layout from the persisted set and re-derives it separately", async () => {+ it("drops new-layout and llm from the persisted set and re-derives them separately", async () => {ctrl.standalone = false;ctrl.mobile = false;- // new-layout in the stored set is stripped; only llm survives, and- // with the option off it is not re-added- const stripped = await freshModule(["new-layout", "llm"], false);- expect(stripped.mod.getEnabledExperimentalFeatureIds()).toEqual(["llm"]);+ // both stored entries are stripped; with the options off nothing is re-added+ const stripped = await freshModule(["new-layout", "llm"]);+ expect(stripped.mod.getEnabledExperimentalFeatureIds()).toEqual([]);- // newLayout option true re-adds "new-layout"- const readded = await freshModule(["llm"], true);+ // the dedicated options re-add the respective features+ const readded = await freshModule([], { newLayout: true, aiEnabled: true });expect(readded.mod.getEnabledExperimentalFeatureIds().sort()).toEqual(["llm", "new-layout"]);});- it("adds new-layout via mobile and filters llm out in standalone", async () => {- const { mod } = await freshModule(["llm"], false);+ it("adds new-layout via mobile and keeps llm out in standalone", async () => {+ const { mod } = await freshModule([], { aiEnabled: true });ctrl.standalone = true;ctrl.mobile = true;- // mobile -> new-layout added; standalone -> llm removed+ // mobile -> new-layout added; standalone -> llm not added despite aiEnabledexpect(mod.getEnabledExperimentalFeatureIds()).toEqual(["new-layout"]);});@@ -107,14 +111,14 @@ describe("experimental_features", () => {ctrl.standalone = false;ctrl.mobile = false;const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- const { mod } = await freshModule("not-json", false);+ const { mod } = await freshModule("not-json");expect(mod.getEnabledExperimentalFeatureIds()).toEqual([]);expect(warn).toHaveBeenCalled();});it("toggleExperimentalFeature adds/removes a feature and persists the set", async () => {ctrl.standalone = false;- const { mod, options } = await freshModule([], false);+ const { mod, options } = await freshModule([]);const save = vi.spyOn(options, "save").mockResolvedValue(undefined);await mod.toggleExperimentalFeature("llm", true);diff --git a/apps/client/src/services/experimental_features.ts b/apps/client/src/services/experimental_features.tsindex 22e868d3af..28acaeb785 100644--- a/apps/client/src/services/experimental_features.ts+++ b/apps/client/src/services/experimental_features.ts@@ -35,23 +35,22 @@ export function isExperimentalFeatureEnabled(featureId: ExperimentalFeatureId):return (isMobile() || options.is("newLayout"));}- // LLM features require server-side API calls that don't work in standalone mode- // due to CORS restrictions from LLM providers (OpenAI, Google don't allow browser requests)- if (featureId === "llm" && isStandalone) {- return false;+ if (featureId === "llm") {+ // LLM features require server-side API calls that don't work in standalone mode+ // due to CORS restrictions from LLM providers (OpenAI, Google don't allow browser requests)+ return !isStandalone && options.is("aiEnabled");}return getEnabledFeatures().has(featureId);}export function getEnabledExperimentalFeatureIds() {- let values = [ ...getEnabledFeatures().values() ];+ const values = [ ...getEnabledFeatures().values() ];if (isMobile() || options.is("newLayout")) {values.push("new-layout");}- // LLM is not available in standalone mode- if (isStandalone) {- values = values.filter(v => v !== "llm");+ if (!isStandalone && options.is("aiEnabled")) {+ values.push("llm");}return values;}@@ -76,6 +75,7 @@ function getEnabledFeatures() {}enabledFeatures = new Set(features);enabledFeatures.delete("new-layout"); // handled separately.+ enabledFeatures.delete("llm"); // handled separately, via the aiEnabled option.}return enabledFeatures;}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9ddb1f2c52..5ad809de2f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2719,6 +2719,7 @@"llm": {"settings_title": "AI / LLM","settings_description": "Configure AI and Large Language Model integrations.",+ "not_available_in_standalone": "AI/LLM features are not available in the standalone version of Trilium, as LLM providers do not allow direct access from a browser.","feature_not_enabled": "Enable the LLM experimental feature in Settings → Advanced → Experimental features to use AI integrations.","add_provider": "Add Provider","add_provider_title": "Add AI Provider",diff --git a/apps/client/src/widgets/type_widgets/options/advanced.tsx b/apps/client/src/widgets/type_widgets/options/advanced.tsxindex 747ac22966..5d00cf3ab1 100644--- a/apps/client/src/widgets/type_widgets/options/advanced.tsx+++ b/apps/client/src/widgets/type_widgets/options/advanced.tsx@@ -166,7 +166,9 @@ function ExistingAnonymizedDatabases({ databases, anonymizedFolderPath }: { datafunction ExperimentalOptions() {const [enabledFeatures, setEnabledFeatures] = useTriliumOptionJson<ExperimentalFeatureId[]>("experimentalFeatures", true);- const filteredFeatures = useMemo(() => getAvailableExperimentalFeatures().filter(e => e.id !== "new-layout"), []);+ // Features with dedicated controls elsewhere (appearance settings and the AI/LLM page, respectively).+ const integratedFeatures: ExperimentalFeatureId[] = ["new-layout", "llm"];+ const filteredFeatures = useMemo(() => getAvailableExperimentalFeatures().filter(e => !integratedFeatures.includes(e.id)), []);const toggleFeature = useCallback((featureId: ExperimentalFeatureId, enabled: boolean) => {if (enabled) {diff --git a/apps/client/src/widgets/type_widgets/options/llm.tsx b/apps/client/src/widgets/type_widgets/options/llm.tsxindex 5d1d0ab3a2..03d6bd2b29 100644--- a/apps/client/src/widgets/type_widgets/options/llm.tsx+++ b/apps/client/src/widgets/type_widgets/options/llm.tsx@@ -1,8 +1,8 @@import { useCallback, useMemo, useState } from "preact/hooks";import dialog from "../../../services/dialog";-import { isExperimentalFeatureEnabled } from "../../../services/experimental_features";import { t } from "../../../services/i18n";+import { isStandalone } from "../../../services/utils";import ActionButton from "../../react/ActionButton";import Button from "../../react/Button";import FormTextBox from "../../react/FormTextBox";@@ -13,18 +13,38 @@ import OptionsSection from "./components/OptionsSection";import AddProviderModal, { type LlmProviderConfig, PROVIDER_TYPES } from "./llm/AddProviderModal";export default function LlmSettings() {- if (!isExperimentalFeatureEnabled("llm")) {+ const [aiEnabled, setAiEnabled] = useTriliumOptionBool("aiEnabled");++ if (isStandalone) {return (<OptionsSection title={t("llm.settings_title")}>- <NoItems icon="bx bx-bot" text={t("llm.feature_not_enabled")} />+ <NoItems icon="bx bx-bot" text={t("llm.not_available_in_standalone")} /></OptionsSection>);}return (<>- <ProviderSettings />- <McpSettings />+ <OptionsSection+ title={t("llm.settings_title")}+ description={t("llm.settings_description")}+ helpUrl="GBBMSlVSOIGP"+ >+ <OptionsRowWithToggle+ name="ai-enabled"+ label={t("experimental_features.llm_name")}+ description={t("experimental_features.llm_description")}+ currentValue={aiEnabled}+ onChange={setAiEnabled}+ />+ </OptionsSection>++ {aiEnabled && (+ <>+ <ProviderSettings />+ <McpSettings />+ </>+ )}</>);}@@ -55,11 +75,7 @@ function ProviderSettings() {}, [providers, setProviders]);return (- <OptionsSection- title={t("llm.settings_title")}- description={t("llm.settings_description")}- helpUrl="GBBMSlVSOIGP"- >+ <OptionsSection title={t("llm.configured_providers")}><ProviderListproviders={providers}onDelete={handleDeleteProvider}diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex e1b6036b3c..1440d7f6b1 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -200,6 +200,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActiincludeNoteDefaultBoxSize: "small" | "medium" | "full" | "expandable";// AI / LLM+ /** Whether the AI/LLM features (chat sidebar, LLM chat notes) are enabled. */+ aiEnabled: boolean;/** JSON array of configured LLM providers with their API keys */llmProviders: string;/** Whether the MCP (Model Context Protocol) server endpoint is enabled. */diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex ba87b16687..1cfbe706b8 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -123,6 +123,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["mfaEnabled","mfaMethod",// LLM options+ "aiEnabled","llmProviders","mcpEnabled",// OCR optionsdiff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 919d95c94e..486667a68a 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -264,6 +264,8 @@ const defaultOptions: DefaultOption[] = [{ name: "experimentalFeatures", value: "[]", isSynced: true },// AI / LLM+ // 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: "mcpEnabled", value: "false", isSynced: false },