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(llm_chat): choose which tool calls ask, per chat
Elian Doranb88a3d6d685d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 79e86e4f36..22b3f6b1b4 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2698,7 +2698,14 @@"tool_approval_allow_for_chat": "Always allow {{tool}} for this chat","allowed_tools": "Allowed in this chat","allowed_tools_count_one": "{{count}} tool",- "allowed_tools_count_other": "{{count}} tools"+ "allowed_tools_count_other": "{{count}} tools",+ "permissions": "Permissions",+ "permission_mode_always_ask": "Always ask",+ "permission_mode_always_ask_description": "Ask before every action, even reading",+ "permission_mode_ask_before_changes": "Ask before changes",+ "permission_mode_ask_before_changes_description": "Ask only before changing your notes",+ "permission_mode_dont_ask": "Don't ask",+ "permission_mode_dont_ask_description": "Run everything on its own, changes included"},"sidebar_chat": {"title": "AI Chat",diff --git a/apps/client/src/widgets/sidebar/SidebarChat.tsx b/apps/client/src/widgets/sidebar/SidebarChat.tsxindex e7077a8852..9856222d46 100644--- a/apps/client/src/widgets/sidebar/SidebarChat.tsx+++ b/apps/client/src/widgets/sidebar/SidebarChat.tsx@@ -404,7 +404,7 @@ export default function SidebarChat() {activeNoteId={activeNoteId ?? undefined}activeNoteTitle={activeNote?.title}onSubmit={handleSubmit}- onAllowedToolsChange={() => spacedUpdate.scheduleUpdate()}+ onPermissionsChange={() => spacedUpdate.scheduleUpdate()}/>)}</div>diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 0245403e1c..4d3be54066 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -1,7 +1,7 @@import "./ChatInputBar.css";import type { AttributeEditor as CKEditorAttributeEditor, CKTextEditor, MentionHostedFeed } from "@triliumnext/ckeditor5";-import type { DISPLAYABLE_LOCALE_IDS, LlmReasoningEffort } from "@triliumnext/commons";+import type { DISPLAYABLE_LOCALE_IDS, LlmPermissionMode, LlmReasoningEffort } from "@triliumnext/commons";import { Fragment } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";@@ -68,8 +68,8 @@ interface ChatInputBarProps {onNoteToolsChange?: () => void;/** Callback when the extended thinking switch or the reasoning effort changes */onExtendedThinkingChange?: () => void;- /** Callback when a tool allowed for the chat is revoked */- onAllowedToolsChange?: () => void;+ /** Callback when the permission mode changes or a tool allowed for the chat is revoked */+ onPermissionsChange?: () => void;/** Callback when model changes */onModelChange?: (model: string) => void;}@@ -82,7 +82,7 @@ export default function ChatInputBar({onWebSearchChange,onNoteToolsChange,onExtendedThinkingChange,- onAllowedToolsChange,+ onPermissionsChange,onModelChange}: ChatInputBarProps) {// Provider add/edit modal. `modalProvider` undefined = adding; a config = editing.@@ -175,7 +175,12 @@ export default function ChatInputBar({const handleRevokeAllowedTool = (toolName: string) => {chat.revokeAllowedTool(toolName);- onAllowedToolsChange?.();+ onPermissionsChange?.();+ };++ const handlePermissionModeChange = (mode: LlmPermissionMode) => {+ chat.setPermissionMode(mode);+ onPermissionsChange?.();};const handleExtendedThinkingToggle = (newValue: boolean) => {@@ -474,6 +479,8 @@ export default function ChatInputBar({onWebSearchChoose={chooseWebSearch}allowedTools={chat.allowedTools}onRevokeAllowedTool={handleRevokeAllowedTool}+ permissionMode={chat.permissionMode}+ onPermissionModeChange={handlePermissionModeChange}disabled={chat.isStreaming}/>{!currentModel?.reasoningEfforts?.length && (diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsxindex 2d999eaa6a..afec91fcde 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.spec.tsx@@ -48,6 +48,8 @@ vi.mock("../../react/FormList.js", async (importOriginal) => ({)}));+import type { LlmPermissionMode } from "@triliumnext/commons";+import type { WebSearchState } from "../../../services/llm_providers.js";import ChatToolsDropdown, { useChatWebSearch } from "./ChatToolsDropdown.js";@@ -66,15 +68,17 @@ afterEach(() => {const TAVILY = { id: "s1", name: "Tavily", provider: "tavily" };-function renderMenu({ enableNoteTools = false, modelProvider, webSearch = { choice: "disabled", enableWebSearch: false }, allowedTools = [] }: {+function renderMenu({ enableNoteTools = false, modelProvider, webSearch = { choice: "disabled", enableWebSearch: false }, allowedTools = [], permissionMode = "always_ask" }: {enableNoteTools?: boolean;allowedTools?: string[];+ permissionMode?: LlmPermissionMode;modelProvider?: string;webSearch?: WebSearchState;} = {}) {const onNoteToolsChange = vi.fn();const onWebSearchChoose = vi.fn();const onRevokeAllowedTool = vi.fn();+ const onPermissionModeChange = vi.fn();host = document.body.appendChild(document.createElement("div"));const target = host;act(() => render(@@ -87,6 +91,8 @@ function renderMenu({ enableNoteTools = false, modelProvider, webSearch = { choionWebSearchChoose={onWebSearchChoose}allowedTools={allowedTools}onRevokeAllowedTool={onRevokeAllowedTool}+ permissionMode={permissionMode}+ onPermissionModeChange={onPermissionModeChange}/>, target));const rows = [ ...target.querySelectorAll<HTMLElement>(".menu .dropdown-item") ];@@ -109,13 +115,25 @@ function renderMenu({ enableNoteTools = false, modelProvider, webSearch = { choi.map((candidate) => candidate.textContent),onNoteToolsChange,onWebSearchChoose,- onRevokeAllowedTool+ onRevokeAllowedTool,+ onPermissionModeChange};}const isOn = (row: HTMLElement | undefined) => row?.querySelector<HTMLInputElement>("input[type='checkbox']")?.checked;describe("ChatToolsDropdown", () => {+ it("marks the chat's permission mode, and reports a pressed one", async () => {+ const menu = renderMenu({ permissionMode: "ask_before_changes" });+ const submenus = [ ...(menu.toggle?.parentElement?.querySelectorAll(".submenu-row") ?? []) ].map(row => row.textContent);+ expect(submenus).toContain("llm_chat.permissionsllm_chat.permission_mode_ask_before_changes");+ expect(menu.marked()).toEqual(expect.arrayContaining([ expect.stringContaining("llm_chat.permission_mode_ask_before_changes") ]));+ expect(menu.marked().filter(text => text?.includes("permission_mode"))).toHaveLength(1);++ await act(async () => menu.row("llm_chat.permission_mode_dont_ask")?.click());+ expect(menu.onPermissionModeChange).toHaveBeenCalledExactlyOnceWith("dont_ask");+ });+it("lists the tools allowed for the chat, and makes the chat ask about a pressed one again", async () => {expect(renderMenu().toggle?.parentElement?.textContent).not.toContain("llm_chat.allowed_tools");@@ -143,7 +161,7 @@ describe("ChatToolsDropdown", () => {it("marks the chosen web search source, and reports a pressed one or the note access switch", async () => {const menu = renderMenu({ enableNoteTools: true, webSearch: { choice: "s1", enableWebSearch: true, webSearchProviderId: "s1" } });- expect(menu.marked()).toEqual([ "Tavily" ]);+ expect(menu.marked().filter(text => !text?.includes("permission_mode"))).toEqual([ "Tavily" ]);await act(async () => menu.row("llm_chat.web_search_builtin")?.click());expect(menu.onWebSearchChoose).toHaveBeenLastCalledWith("builtin");diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsxindex 3fdad107e3..fa0ef543a2 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatToolsDropdown.tsx@@ -1,5 +1,6 @@import "./ChatToolsDropdown.css";+import { LLM_PERMISSION_MODES, type LlmPermissionMode } from "@triliumnext/commons";import clsx from "clsx";import { useMemo } from "preact/hooks";@@ -16,12 +17,12 @@ import type { UseLlmChatReturn } from "./useLlmChat.js";/*** The Tools menu of the chat input bar: what the model can reach this turn. Note access is a row of- * its own; web search is a submenu of its sources, whose row shows the chosen one; the tools allowed- * for the chat, once there are any, are a submenu that makes the chat ask about one again. Its rows leave+ * its own; web search is a submenu of its sources, whose row shows the chosen one; which calls wait for the user is a submenu of the+ * permission modes; the tools allowed for the chat, once there are any, are a submenu that makes the chat ask about one again. Its rows leave* the menu open, so several can be changed in one visit. Its toggle shares the compact combo box* styling of the model picker beside it.*/-export default function ChatToolsDropdown({ enableNoteTools, onNoteToolsChange, modelProvider, webSearch, searchProviders, onWebSearchChoose, allowedTools, onRevokeAllowedTool, disabled }: {+export default function ChatToolsDropdown({ enableNoteTools, onNoteToolsChange, modelProvider, webSearch, searchProviders, onWebSearchChoose, allowedTools, onRevokeAllowedTool, permissionMode, onPermissionModeChange, disabled }: {enableNoteTools: boolean;/** The provider type of the current model, whose mark stands for its built-in search. */modelProvider: string | undefined;@@ -33,6 +34,8 @@ export default function ChatToolsDropdown({ enableNoteTools, onNoteToolsChange,/** The tools whose calls run without asking in this chat. */allowedTools: string[];onRevokeAllowedTool: (toolName: string) => void;+ permissionMode: LlmPermissionMode;+ onPermissionModeChange: (mode: LlmPermissionMode) => void;disabled?: boolean;}) {const anyActive = enableNoteTools || webSearch.enableWebSearch;@@ -85,6 +88,25 @@ export default function ChatToolsDropdown({ enableNoteTools, onNoteToolsChange,</FormListItem></FormDropdownSubmenu>+ <FormDropdownSubmenu+ icon="bx bxs-hand"+ title={t("llm_chat.permissions")}+ description={t(`llm_chat.permission_mode_${permissionMode}`)}+ >+ {LLM_PERMISSION_MODES.map((mode) => (+ <FormListItem+ key={mode}+ checkable+ checked={mode === permissionMode}+ description={t(`llm_chat.permission_mode_${mode}_description`)}+ closeOnSelect={false}+ onClick={() => onPermissionModeChange(mode)}+ >+ {t(`llm_chat.permission_mode_${mode}`)}+ </FormListItem>+ ))}+ </FormDropdownSubmenu>+{allowedTools.length > 0 && (<FormDropdownSubmenuicon="bx bx-check-double"diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsxindex fc2b132fb0..935b0fd57a 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx@@ -91,7 +91,7 @@ export default function LlmChat({ note, noteContext, isVisible }: TypeWidgetProponWebSearchChange={triggerSave}onNoteToolsChange={triggerSave}onExtendedThinkingChange={triggerSave}- onAllowedToolsChange={triggerSave}+ onPermissionsChange={triggerSave}onModelChange={triggerSave}/>)}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.tsindex 66bc754013..83a20df462 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts@@ -2,6 +2,7 @@ import {isToolErrorResult,type LlmCitation,type LlmErrorDetails,+ type LlmPermissionMode,type LlmReasoningEffort,type LlmUsage} from "@triliumnext/commons";@@ -208,4 +209,6 @@ export interface LlmChatContent {reasoningEffort?: LlmReasoningEffort;/** The tools the user allowed for this chat, whose calls run without asking. */allowedTools?: string[];+ /** Which tool calls of the chat wait for the user; absent means `"always_ask"`. */+ permissionMode?: LlmPermissionMode;}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsxindex c882861a89..bd967814a1 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx@@ -564,4 +564,36 @@ describe("useLlmChat", () => {});expect(api().allowedTools).toEqual([]);});+ it("keeps the chat's permission mode, sends it with each turn and saves it", async () => {+ await mountChat();+ const sentOptions = async () => {+ streamChatCompletionMock.mockClear();+ await act(async () => {+ api().setInput("hi");+ });+ await act(async () => {+ await api().handleSubmit(new Event("submit"));+ });+ return streamChatCompletionMock.mock.calls[0][1];+ };++ expect(api().permissionMode).toBe("always_ask");+ expect((await sentOptions()).permissionMode).toBe("always_ask");++ await act(async () => {+ api().setPermissionMode("ask_before_changes");+ });+ expect(api().getContent()).toMatchObject({ permissionMode: "ask_before_changes" });+ expect((await sentOptions()).permissionMode).toBe("ask_before_changes");++ await act(async () => {+ api().loadFromContent({ version: 1, messages: [], permissionMode: "dont_ask" });+ });+ expect(api().permissionMode).toBe("dont_ask");+ // A chat saved before the modes, or with a mode this version does not know.+ await act(async () => {+ api().loadFromContent({ version: 1, messages: [], permissionMode: "yolo" as "dont_ask" });+ });+ expect(api().permissionMode).toBe("always_ask");+ });});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex f96094eb84..53cfa59533 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -1,4 +1,4 @@-import { LLM_REASONING_EFFORTS, type LlmCitation, type LlmMessage, type LlmMessagePart, type LlmModelInfo, type LlmReasoningEffort, type LlmStreamStatus, type LlmToolApprovalAnswer, type LlmUsage } from "@triliumnext/commons";+import { LLM_PERMISSION_MODES, LLM_REASONING_EFFORTS, type LlmCitation, type LlmMessage, type LlmMessagePart, type LlmModelInfo, type LlmPermissionMode, type LlmReasoningEffort, type LlmStreamStatus, type LlmToolApprovalAnswer, type LlmUsage } from "@triliumnext/commons";import { RefObject } from "preact";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";@@ -135,6 +135,8 @@ export interface UseLlmChatReturn {reasoningEffort: LlmReasoningEffort | undefined;/** The tools allowed for this chat, whose calls run without asking. */allowedTools: string[];+ /** Which tool calls of the chat wait for the user. */+ permissionMode: LlmPermissionMode;contextNoteId: string | undefined;/** The chat note's ID — used as the upload target for attachments. */chatNoteId: string | undefined;@@ -174,6 +176,7 @@ export interface UseLlmChatReturn {setEnableNoteTools: (value: boolean) => void;setEnableExtendedThinking: (value: boolean) => void;setReasoningEffort: (value: LlmReasoningEffort | undefined) => void;+ setPermissionMode: (value: LlmPermissionMode) => void;setContextNoteId: (noteId: string | undefined) => void;setChatNoteId: (noteId: string | undefined) => void;/** Append a freshly uploaded image or file to the pending-attachments list. */@@ -244,6 +247,7 @@ export function useLlmChat(const [enableExtendedThinking, setEnableExtendedThinking] = useState(false);const [reasoningEffort, setReasoningEffort] = useState<LlmReasoningEffort | undefined>(undefined);const [allowedTools, setAllowedTools] = useState<string[]>([]);+ const [permissionMode, setPermissionMode] = useState<LlmPermissionMode>("always_ask");const [contextNoteId, setContextNoteId] = useState<string | undefined>(initialContextNoteId);const [chatNoteId, setChatNoteIdState] = useState<string | undefined>(initialChatNoteId);const [lastPromptTokens, setLastPromptTokens] = useState<number>(0);@@ -288,6 +292,8 @@ export function useLlmChat(enableNoteToolsRef.current = enableNoteTools;const allowedToolsRef = useRef(allowedTools);allowedToolsRef.current = allowedTools;+ const permissionModeRef = useRef(permissionMode);+ permissionModeRef.current = permissionMode;const enableExtendedThinkingRef = useRef(enableExtendedThinking);enableExtendedThinkingRef.current = enableExtendedThinking;const reasoningEffortRef = useRef(reasoningEffort);@@ -563,6 +569,7 @@ export function useLlmChat(setEnableExtendedThinking(content.enableExtendedThinking);}setReasoningEffort(LLM_REASONING_EFFORTS.find(level => level === content.reasoningEffort));+ setPermissionMode(LLM_PERMISSION_MODES.find(mode => mode === content.permissionMode) ?? "always_ask");setAllowedTools(Array.isArray(content.allowedTools)? content.allowedTools.filter((name): name is string => typeof name === "string"): []);@@ -581,7 +588,8 @@ export function useLlmChat(selectedProvider: selectedProviderRef.current || undefined,selectedProviderId: selectedProviderIdRef.current || undefined,enableWebSearch: enableWebSearchRef.current,- enableNoteTools: enableNoteToolsRef.current+ enableNoteTools: enableNoteToolsRef.current,+ permissionMode: permissionModeRef.current};if (supportsExtendedThinking) {content.enableExtendedThinking = enableExtendedThinkingRef.current;@@ -675,7 +683,8 @@ export function useLlmChat(webSearchProviderId: webSearch.webSearchProviderId,enableNoteTools,contextNoteId,- chatNoteId: chatNoteIdRef.current+ chatNoteId: chatNoteIdRef.current,+ permissionMode};if (supportsExtendedThinking) {streamOptions.enableExtendedThinking = enableExtendedThinking;@@ -928,7 +937,7 @@ export function useLlmChat(setIsStreaming(false);abortControllerRef.current = null;});- }, [selectedModel, selectedProvider, selectedProviderId, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, reasoningEffort, allowedTools, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);+ }, [selectedModel, selectedProvider, selectedProviderId, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, reasoningEffort, allowedTools, permissionMode, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);const handleSubmit = useCallback(async (e: Event) => {e.preventDefault();@@ -1068,6 +1077,7 @@ export function useLlmChat(enableExtendedThinking,reasoningEffort,allowedTools,+ permissionMode,contextNoteId,chatNoteId,lastPromptTokens,@@ -1094,6 +1104,7 @@ export function useLlmChat(setEnableNoteTools,setEnableExtendedThinking,setReasoningEffort,+ setPermissionMode,setContextNoteId,setChatNoteId,addPendingAttachment,diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.htmlindex 97c304b21b..d3aed6d835 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html@@ -281,11 +281,21 @@<p>To make a chat ask about a tool again, open the <span class="tn-icon bx bx-shield-quarter"></span> <em>Tools</em> menuat the bottom of the chat and, under <em>Allowed in this chat</em>, pressthe tool. The submenu is shown once the chat has allowed a tool.</p>-<p>Every tool call asks, including the ones that only read: searching notes,- reading a note or an attachment, and reading a web page through a search- provider. A model's built-in web search runs on the provider's side and- does not ask.</p>-<aside class="admonition important">+<p>Which calls ask depends on the chat's permission mode, chosen in the <span+ class="tn-icon bx bx-shield-quarter"></span> <em>Tools</em> menu under <em>Permissions</em>:</p>+<ul>+ <li><em>Always ask</em>, the mode a new chat starts in: every call asks, including+ the ones that only read (searching notes, reading a note or an attachment,+ and reading a web page through a search provider).</li>+ <li><em>Ask before changes</em>: the calls that only read run on their own,+ and the ones that change your notes (creating, editing, renaming, moving+ or deleting a note, and setting or deleting an attribute) ask.</li>+ <li><em>Don't ask</em>: every call runs without asking, changes included.</li>+</ul>+<p>A tool allowed for the chat runs without asking in every mode. A model's+ built-in web search runs on the provider's side and never asks.</p>+<aside+class="admonition important"><p>Among the <a class="reference-link" href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a>,Claude Code asks like any other provider. GitHub Copilot, Google Antigravityand OpenAI Codex don't ask yet: their tool calls run without approval.</p>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.htmlindex 3f48b194a6..50744bc0d6 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html@@ -68,11 +68,11 @@<li>Tools let the model search your tree and read notes, attributes and attachmentsbeyond the current one.</li><li>It decides what to fetch, and each call waits for you to allow it, unless+ the chat's permission mode lets reads or every call run on their own, oryou allowed that tool for the chat (and except with the <a class="reference-link"href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a> other than- Claude Code). There- is no per-note permission system, so the reachable scope is your whole- tree.</li>+ Claude Code). There is no per-note permission system, so the reachable+ scope is your whole tree.</li></ul></li><li><strong>Attachments and mentions</strong>, when you add them: images,@@ -127,6 +127,9 @@type.</li><li><strong>The current note:</strong> the file icon in the sidebar chat.</li><li><strong>Web search:</strong> also in the <em>Tools</em> menu.</li>+ <li><strong>Which tool calls ask first:</strong> the <em>Permissions</em> submenu+ of the <em>Tools</em> menu. <em>Always ask</em>, the mode a new chat starts+ in, has every call wait for you, reads included.</li><li><strong>The editor assistant</strong>: it has no per-run toggles. Whatyou control is whether you run it, what you select before you do and whichmodel answers.</li>diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex 0f71480764..5d34cef0dd 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -167,7 +167,13 @@ Before the AI runs a tool, the chat asks whether to allow it. The tool's line isTo make a chat ask about a tool again, open the <span class="tn-icon bx bx-shield-quarter"></span> _Tools_ menu at the bottom of the chat and, under _Allowed in this chat_, press the tool. The submenu is shown once the chat has allowed a tool.-Every tool call asks, including the ones that only read: searching notes, reading a note or an attachment, and reading a web page through a search provider. A model's built-in web search runs on the provider's side and does not ask.+Which calls ask depends on the chat's permission mode, chosen in the <span class="tn-icon bx bx-shield-quarter"></span> _Tools_ menu under _Permissions_:++* _Always ask_, the mode a new chat starts in: every call asks, including the ones that only read (searching notes, reading a note or an attachment, and reading a web page through a search provider).+* _Ask before changes_: the calls that only read run on their own, and the ones that change your notes (creating, editing, renaming, moving or deleting a note, and setting or deleting an attribute) ask.+* _Don't ask_: every call runs without asking, changes included.++A tool allowed for the chat runs without asking in every mode. A model's built-in web search runs on the provider's side and never asks.> [!IMPORTANT]> Among the <a class="reference-link" href="AI/Providers/Subscription-based%20providers.md">Subscription-based providers</a>, Claude Code asks like any other provider. GitHub Copilot, Google Antigravity and OpenAI Codex don't ask yet: their tool calls run without approval.diff --git a/docs/User Guide/User Guide/AI/Privacy.md b/docs/User Guide/User Guide/AI/Privacy.mdindex 72f4c75c62..395b466c32 100644--- a/docs/User Guide/User Guide/AI/Privacy.md+++ b/docs/User Guide/User Guide/AI/Privacy.md@@ -28,7 +28,7 @@ This is the reason the provider list is grouped this way, and why Trilium pre-se* Notes above a size threshold send a size hint instead of the text, and the model must call a tool to read further.* **Any note the model asks for, when note access is enabled.*** Tools let the model search your tree and read notes, attributes and attachments beyond the current one.- * It decides what to fetch, and each call waits for you to allow it, unless you allowed that tool for the chat (and except with the <a class="reference-link" href="Providers/Subscription-based%20providers.md">Subscription-based providers</a> other than Claude Code). There is no per-note permission system, so the reachable scope is your whole tree.+ * It decides what to fetch, and each call waits for you to allow it, unless the chat's permission mode lets reads or every call run on their own, or you allowed that tool for the chat (and except with the <a class="reference-link" href="Providers/Subscription-based%20providers.md">Subscription-based providers</a> other than Claude Code). There is no per-note permission system, so the reachable scope is your whole tree.* **Attachments and mentions**, when you add them: images, PDFs and text files are sent to the provider, and an `@` mention makes that note fetchable.* **Your search query**, when web search is enabled, the model's search terms reach the provider's own search infrastructure, or the search provider chosen in the _Tools_ menu (Brave Search, Tavily, Exa, Serper, Perplexity or your SearXNG instance).* **The pages the model reads**, when web search goes through a search provider: Trilium fetches each page the model asks for from the site itself, so the site sees a request from the machine running Trilium. The page's text is then sent to the model's provider.@@ -57,6 +57,7 @@ The same applies to the <a class="reference-link" href="../Note%20Types/Text/In* **Note access**: turn it off in the <span class="tn-icon bx bx-shield-quarter"></span> _Tools_ menu at the bottom of the chat, and the model can read nothing beyond what you type.* **The current note:** the file icon in the sidebar chat.* **Web search:** also in the _Tools_ menu.+* **Which tool calls ask first:** the _Permissions_ submenu of the _Tools_ menu. _Always ask_, the mode a new chat starts in, has every call wait for you, reads included.* **The editor assistant**: it has no per-run toggles. What you control is whether you run it, what you select before you do and which model answers.With note access and note context both off, the provider receives only the words you typed.diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.tsindex 8eb621be1e..a633cd9e25 100644--- a/packages/commons/src/lib/llm_api.ts+++ b/packages/commons/src/lib/llm_api.ts@@ -120,8 +120,18 @@ export interface LlmChatConfig {chatNoteId?: string;/** The tools the user allowed for the whole chat, whose calls run without asking. */allowedTools?: string[];+ /** Which tool calls wait for the user. Absent means `"always_ask"`. */+ permissionMode?: LlmPermissionMode;}+/**+ * Which tool calls of a chat wait for the user: all of them, only those that change notes, or none.+ * A tool the chat allowed (`allowedTools`) runs without asking in every mode.+ */+export const LLM_PERMISSION_MODES = [ "always_ask", "ask_before_changes", "dont_ask" ] as const;++export type LlmPermissionMode = (typeof LLM_PERMISSION_MODES)[number];+/*** Pricing per million tokens for a model.*/diff --git a/packages/trilium-core/src/services/llm/chat.spec.ts b/packages/trilium-core/src/services/llm/chat.spec.tsindex d206b0075e..97b2ed7adb 100644--- a/packages/trilium-core/src/services/llm/chat.spec.ts+++ b/packages/trilium-core/src/services/llm/chat.spec.ts@@ -216,6 +216,16 @@ describe("runChat", () => {expect((await turn.next()).done).toBe(true);});+ it("runs a call the permission mode lets through without announcing it", async () => {+ state.chunkNative = true;+ state.asksApproval = true;+ const turn = runChat("s1", HELLO, { permissionMode: "dont_ask" });++ expect((await turn.next()).value).toEqual(TOOL_USE);+ expect((await turn.next()).value).toEqual({ type: "text", content: "approved: true" });+ expect((await turn.next()).done).toBe(true);+ });+it("declines a waiting call when the turn is stopped", async () => {state.chunkNative = true;state.asksApproval = true;diff --git a/packages/trilium-core/src/services/llm/chat.ts b/packages/trilium-core/src/services/llm/chat.tsindex 21e60243ce..c540786420 100644--- a/packages/trilium-core/src/services/llm/chat.ts+++ b/packages/trilium-core/src/services/llm/chat.ts@@ -7,7 +7,7 @@* resolution, pricing lookup, error logging and title generation happen once.*/-import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";+import { LLM_PERMISSION_MODES, type LlmMessage, type LlmStreamChunk } from "@triliumnext/commons";import { getLog } from "../log.js";import { safeExtractMessageAndStackFromError } from "../utils/index.js";@@ -15,7 +15,7 @@ import { generateChatTitle } from "./chat_title.js";import { getProvider, getProviderByType, getSearchProviderSetup, getSelectedModel, hasConfiguredProviders, type LlmProvider, type LlmProviderConfig } from "./index.js";import { formatStreamError, streamToChunks } from "./stream.js";import { closeToolApprovals, openToolApprovals, type ToolApprovals } from "./tool_approval.js";-import { resolveToolRegistries } from "./tools/index.js";+import { isReadOnlyTool, resolveToolRegistries } from "./tools/index.js";/*** Stream one assistant turn, yielding the chunks as the provider produces them.@@ -25,9 +25,9 @@ import { resolveToolRegistries } from "./tools/index.js";* ends with a `done` chunk only when the turn completed — an errored one stops* after its `error` chunk, so a caller that needs a terminator must add its own.*- * Every tool call waits for the user, unless the chat allowed its tool (`allowedTools`): it is- * announced as a `tool_approval_request` chunk and answered through `answerToolApproval()`,- * keyed by `streamId`.+ * Every tool call waits for the user, unless the chat's `permissionMode` lets it through or the+ * chat allowed its tool (`allowedTools`): it is announced as a `tool_approval_request` chunk and+ * answered through `answerToolApproval()`, keyed by `streamId`.** @param streamId the id the client gave the turn, unique among the turns running.* @param abortSignal stops the turn early: the provider aborts its completion and any tool@@ -42,7 +42,12 @@ export async function* runChat(const allowedTools = Array.isArray(requestConfig.allowedTools)? requestConfig.allowedTools.filter((name): name is string => typeof name === "string"): [];- const toolApprovals = openToolApprovals(streamId, abortSignal, allowedTools);+ const mode = LLM_PERMISSION_MODES.find(candidate => candidate === requestConfig.permissionMode);+ const toolApprovals = openToolApprovals(streamId, abortSignal, {+ allowedTools,+ mode,+ isReadOnly: isReadOnlyTool+ });if (!toolApprovals) {yield { type: "error", error: `Stream '${streamId}' is already running.` };return;diff --git a/packages/trilium-core/src/services/llm/tool_approval.spec.ts b/packages/trilium-core/src/services/llm/tool_approval.spec.tsindex b927ccd25b..5d7fa3e408 100644--- a/packages/trilium-core/src/services/llm/tool_approval.spec.ts+++ b/packages/trilium-core/src/services/llm/tool_approval.spec.ts@@ -7,6 +7,7 @@ import { z } from "zod";import { BaseProvider } from "./providers/base_provider.js";import { streamToChunks } from "./stream.js";import { TOOL_CALL_DECLINED_REASON, ToolApprovals } from "./tool_approval.js";+import { isReadOnlyTool } from "./tools/index.js";const USAGE = {inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },@@ -133,7 +134,7 @@ describe("ToolApprovals", () => {describe("ToolApprovals allowed for the chat", () => {it("runs a tool allowed for the chat without asking", async () => {- const approvals = new ToolApprovals(undefined, [ "rename_note" ]);+ const approvals = new ToolApprovals(undefined, { allowedTools: [ "rename_note" ] });const onRequest = vi.fn();approvals.onRequest = onRequest;@@ -163,3 +164,31 @@ describe("ToolApprovals allowed for the chat", () => {expect(asked).toHaveBeenCalledOnce();});});++describe("ToolApprovals permission modes", () => {+ const isReadOnly = (toolName: string) => toolName === "get_note";+ /** Which of a read and a change ask in `mode`. */+ function asked(mode: "always_ask" | "ask_before_changes" | "dont_ask") {+ const approvals = new ToolApprovals(undefined, { mode, isReadOnly });+ const requests: string[] = [];+ approvals.onRequest = (request) => requests.push(request.toolName);+ void approvals.request({ toolCallId: "c1", toolName: "get_note", toolInput: {} });+ void approvals.request({ toolCallId: "c2", toolName: "delete_note", toolInput: {} });+ approvals.declineAll();+ return requests;+ }++ it("asks about every call, only about changes, or about none", async () => {+ expect(asked("always_ask")).toEqual([ "get_note", "delete_note" ]);+ expect(asked("ask_before_changes")).toEqual([ "delete_note" ]);+ expect(asked("dont_ask")).toEqual([]);++ const approvals = new ToolApprovals(undefined, { mode: "ask_before_changes", isReadOnly });+ await expect(approvals.request({ toolCallId: "c1", toolName: "get_note", toolInput: {} })).resolves.toBe(true);+ });++ it("counts a note tool that does not mutate and the web tools as reads, and anything unknown as a change", () => {+ expect([ "get_note", "search_notes", "web_search", "read_web_page" ].map(isReadOnlyTool)).toEqual([ true, true, true, true ]);+ expect([ "create_note", "delete_attribute", "some_mcp_tool" ].map(isReadOnlyTool)).toEqual([ false, false, false ]);+ });+});diff --git a/packages/trilium-core/src/services/llm/tool_approval.ts b/packages/trilium-core/src/services/llm/tool_approval.tsindex 908114ec05..11d2a2fc2b 100644--- a/packages/trilium-core/src/services/llm/tool_approval.ts+++ b/packages/trilium-core/src/services/llm/tool_approval.ts@@ -9,33 +9,47 @@* client does not send back.*/-import type { LlmToolApprovalAnswer, LlmToolApprovalRequest } from "@triliumnext/commons";+import type { LlmPermissionMode, LlmToolApprovalAnswer, LlmToolApprovalRequest } from "@triliumnext/commons";/** The reason the model is given for a call the user declined. */export const TOOL_CALL_DECLINED_REASON = "The user declined this tool call.";+/** What decides which calls of a turn wait for the user. */+export interface ToolApprovalPolicy {+ /** The tools the chat allowed, whose calls run without asking. */+ allowedTools?: Iterable<string>;+ /** Absent means `"always_ask"`. */+ mode?: LlmPermissionMode;+ /** Whether a tool only reads, which `"ask_before_changes"` lets run. Absent, every tool changes. */+ isReadOnly?: (toolName: string) => boolean;+}+/** The tool calls of one turn that wait for the user's answer. */export class ToolApprovals {private readonly pending = new Map<string, { toolName: string; settle: (approved: boolean) => void }>();/** The tools whose calls run without asking. */private readonly allowedTools: Set<string>;+ private readonly mode: LlmPermissionMode;+ private readonly isReadOnly: (toolName: string) => boolean;/** Called with every request, so the turn can pass it on to the client. */onRequest?: (request: LlmToolApprovalRequest) => void;- constructor(private readonly abortSignal?: AbortSignal, allowedTools: Iterable<string> = []) {- this.allowedTools = new Set(allowedTools);+ constructor(private readonly abortSignal?: AbortSignal, policy: ToolApprovalPolicy = {}) {+ this.allowedTools = new Set(policy.allowedTools);+ this.mode = policy.mode ?? "always_ask";+ this.isReadOnly = policy.isReadOnly ?? (() => false);}/*** Ask the user about a tool call. Resolves to whether it was approved; a turn that- * is stopped, or ends, before the user answers declines the call. A call of an allowed- * tool is approved without asking.+ * is stopped, or ends, before the user answers declines the call. A call the permission+ * mode lets through, or of a tool the chat allowed, is approved without asking.*/request(request: LlmToolApprovalRequest): Promise<boolean> {if (this.abortSignal?.aborted) {return Promise.resolve(false);}- if (this.allowedTools.has(request.toolName)) {+ if (this.runsUnasked(request.toolName)) {return Promise.resolve(true);}@@ -74,6 +88,12 @@ export class ToolApprovals {return true;}+ private runsUnasked(toolName: string): boolean {+ return this.mode === "dont_ask"+ || this.allowedTools.has(toolName)+ || (this.mode === "ask_before_changes" && this.isReadOnly(toolName));+ }+/** Decline every call that still waits. */declineAll(): void {for (const { settle } of [ ...this.pending.values() ]) {@@ -85,18 +105,18 @@ export class ToolApprovals {const openApprovals = new Map<string, ToolApprovals>();/**- * Open the approvals of a turn under its stream id, with the tools the chat allowed. Returns- * `undefined` when a turn with that id is already running.+ * Open the approvals of a turn under its stream id. Returns `undefined` when a turn with that id+ * is already running.*/export function openToolApprovals(streamId: string,abortSignal?: AbortSignal,- allowedTools?: Iterable<string>+ policy?: ToolApprovalPolicy): ToolApprovals | undefined {if (openApprovals.has(streamId)) {return undefined;}- const approvals = new ToolApprovals(abortSignal, allowedTools);+ const approvals = new ToolApprovals(abortSignal, policy);openApprovals.set(streamId, approvals);return approvals;}diff --git a/packages/trilium-core/src/services/llm/tools/index.ts b/packages/trilium-core/src/services/llm/tools/index.tsindex ee82b492b2..ed7eece074 100644--- a/packages/trilium-core/src/services/llm/tools/index.ts+++ b/packages/trilium-core/src/services/llm/tools/index.ts@@ -95,3 +95,24 @@ export function resolveToolRegistries(): Promise<void> {})();return inFlightResolve;}++/** The web search tools that run in place of a model's built-in search, which only read. */+const WEB_READ_TOOLS = new Set([ "web_search", "read_web_page" ]);++/**+ * Whether a tool only reads: a registered tool not marked `mutates`, or a web search tool. A tool+ * none of them names, such as one a future integration adds, counts as a change.+ */+export function isReadOnlyTool(toolName: string): boolean {+ if (WEB_READ_TOOLS.has(toolName)) {+ return true;+ }+ for (const registry of allToolRegistries) {+ for (const [ name, definition ] of registry) {+ if (name === toolName) {+ return !definition.mutates;+ }+ }+ }+ return false;+}