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): show a tool call's raw input and result in a dialog
Elian Doran738a838df56f
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 333a6d96d3..bc2eb3f4e6 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -33,6 +33,7 @@ import type { ItemPickerDialogOptions } from "../widgets/dialogs/item_picker.js"import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";import type NoteTreeWidget from "../widgets/note_tree.js";import type { RightPaneTabId } from "../widgets/sidebar/RightPaneTabs.jsx";+import type { ToolCall } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";import Component from "./component.js";import Entrypoints from "./entrypoints.js";import MainTreeExecutors from "./main_tree_executors.js";@@ -158,6 +159,7 @@ export type CommandMappings = {showNotePickerDialog: NotePickerDialogOptions;showInfoDialog: InfoProps;showLightbox: LightboxOptions;+ showToolCallDetails: { toolCall: ToolCall };showConfirmDialog: ConfirmWithMessageOptions;showRecentChanges: CommandData & { ancestorNoteId: string };showDeletedNotes: CommandData & { ancestorNoteId?: string };diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsxindex 3c00ac670c..7582a8df4f 100644--- a/apps/client/src/layouts/layout_commons.tsx+++ b/apps/client/src/layouts/layout_commons.tsx@@ -34,6 +34,7 @@ export function applyModals(rootContainer: RootContainer) {.child(<LazyDialog triggerEvents={["showDeleteNotesDialog"]} loader={() => import("../widgets/dialogs/delete_notes.js")} />).child(<LazyDialog triggerEvents={["showPrintPreview"]} loader={() => import("../widgets/dialogs/print_preview.jsx")} />).child(<LazyDialog triggerEvents={["showLightbox"]} loader={() => import("../widgets/dialogs/lightbox.js")} />)+ .child(<LazyDialog triggerEvents={["showToolCallDetails"]} loader={() => import("../widgets/dialogs/tool_call_details.js")} />).child(<LazyDialog triggerEvents={["showInfoDialog"]} loader={() => import("../widgets/dialogs/info.js")} />).child(<LazyDialog triggerEvents={["showConfirmDialog", "showConfirmDeleteNoteBoxWithNoteDialog"]} loader={() => import("../widgets/dialogs/confirm.js")} />).child(<LazyDialog triggerEvents={["showPromptDialog"]} loader={() => import("../widgets/dialogs/prompt.js")} />)diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 7c071f5773..5daf1fd74d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2609,7 +2609,6 @@"thought_process": "Thought process","tool_calls": "{{count}} tool call(s)","input": "Input",- "input_streaming": "Input (streaming…)","edit_index": "Edit {{index}} of {{total}}","result": "Result","error": "Error",@@ -2659,7 +2658,9 @@"stream_status": {"starting_agent": "Starting the agent. This can take a while.","waiting_for_reply": "Waiting for the reply…"- }+ },+ "show_tool_call_details": "Show input and output",+ "tool_call_no_result": "No result yet."},"sidebar_chat": {"title": "AI Chat",diff --git a/apps/client/src/widgets/dialogs/tool_call_details.css b/apps/client/src/widgets/dialogs/tool_call_details.cssnew file mode 100644index 0000000000..2156c83238--- /dev/null+++ b/apps/client/src/widgets/dialogs/tool_call_details.css@@ -0,0 +1,32 @@+.modal.tool-call-details-dialog {+ .modal-title {+ display: flex;+ align-items: baseline;+ gap: 0.5rem;+ }++ .tool-call-details-name {+ font-size: 0.8rem;+ font-weight: normal;+ color: var(--muted-text-color);+ }++ .tool-call-details-section + .tool-call-details-section {+ margin-top: 1rem;+ }++ h6 {+ font-size: 0.8rem;+ color: var(--muted-text-color);+ }++ .code-block {+ margin: 0;+ }++ .tool-call-details-empty {+ margin: 0;+ color: var(--muted-text-color);+ font-style: italic;+ }+}diff --git a/apps/client/src/widgets/dialogs/tool_call_details.spec.tsx b/apps/client/src/widgets/dialogs/tool_call_details.spec.tsxnew file mode 100644index 0000000000..3a673dcffc--- /dev/null+++ b/apps/client/src/widgets/dialogs/tool_call_details.spec.tsx@@ -0,0 +1,64 @@+import { act } from "preact/test-utils";+import { beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../components/component";+import { renderInto } from "../../test/render";+import type { ToolCall } from "../type_widgets/llm_chat/llm_chat_types";+import { ParentComponent } from "../react/react_utils";+import ToolCallDetailsDialog from "./tool_call_details";++vi.mock("../../services/i18n", () => ({+ t: (key: string, options?: { defaultValue?: string }) => (key.startsWith("llm.tools.") ? options?.defaultValue ?? key : key)+}));+vi.mock("../../services/syntax_highlight", () => ({+ applySingleBlockSyntaxHighlight: vi.fn(),+ isSyntaxHighlightEnabled: () => false+}));++async function open(toolCall: ToolCall) {+ const host = new Component();+ renderInto(+ <ParentComponent.Provider value={host}>+ <ToolCallDetailsDialog />+ </ParentComponent.Provider>+ );+ await act(async () => {+ await host.handleEvent("showToolCallDetails", { toolCall });+ });+}++function sections() {+ return [ ...document.querySelectorAll(".tool-call-details-dialog .tool-call-details-section") ].map(section => ({+ heading: section.querySelector("h6")?.textContent,+ code: section.querySelector("code")?.textContent,+ empty: section.querySelector(".tool-call-details-empty")?.textContent+ }));+}++describe("ToolCallDetailsDialog", () => {+ beforeEach(() => {+ document.body.innerHTML = "";+ });++ it("shows the input and a JSON result pretty-printed, and a plain result as it is", async () => {+ await open({ id: "1", toolName: "get_note", input: { noteId: "a" }, result: "{\"title\":\"A\"}" });+ expect(document.querySelector(".tool-call-details-dialog .modal-title")?.textContent).toContain("get_note");+ expect(sections()).toEqual([+ { heading: "llm_chat.input", code: "{\n \"noteId\": \"a\"\n}", empty: undefined },+ { heading: "llm_chat.result", code: "{\n \"title\": \"A\"\n}", empty: undefined }+ ]);++ document.body.innerHTML = "";+ await open({ id: "2", toolName: "web_search", input: { query: "rocket" }, result: "Sunny", isError: true });+ expect(sections()[1]).toEqual({ heading: "llm_chat.error", code: "Sunny", empty: undefined });+ });++ it("says so when a call has no result yet", async () => {+ await open({ id: "1", toolName: "read_web_page", input: { url: "https://triliumnotes.org" } });+ expect(sections()[1]).toEqual({+ heading: "llm_chat.result",+ code: undefined,+ empty: "llm_chat.tool_call_no_result"+ });+ });+});diff --git a/apps/client/src/widgets/dialogs/tool_call_details.tsx b/apps/client/src/widgets/dialogs/tool_call_details.tsxnew file mode 100644index 0000000000..3ebd64f742--- /dev/null+++ b/apps/client/src/widgets/dialogs/tool_call_details.tsx@@ -0,0 +1,68 @@+import "./tool_call_details.css";++import { useState } from "preact/hooks";++import { t } from "../../services/i18n";+import CodeBlock from "../react/CodeBlock";+import { useTriliumEvent } from "../react/hooks";+import Modal from "../react/Modal";+import type { ToolCall } from "../type_widgets/llm_chat/llm_chat_types";++/**+ * Shows the raw input and result of an LLM tool call. Summon it with+ * `appContext.triggerEvent("showToolCallDetails", { toolCall })`.+ */+export default function ToolCallDetailsDialog() {+ const [ toolCall, setToolCall ] = useState<ToolCall>();+ const [ shown, setShown ] = useState(false);++ useTriliumEvent("showToolCallDetails", ({ toolCall }) => {+ setToolCall(toolCall);+ setShown(true);+ });++ const title = toolCall && (+ <h5 className="modal-title">+ {t(`llm.tools.${toolCall.toolName}`, { defaultValue: toolCall.toolName })}+ <code className="tool-call-details-name">{toolCall.toolName}</code>+ </h5>+ );++ return (+ <Modal+ className="tool-call-details-dialog"+ title={title}+ size="lg"+ scrollable+ show={shown}+ onHidden={() => setShown(false)}+ >+ {toolCall && (+ <>+ <section className="tool-call-details-section">+ <h6>{t("llm_chat.input")}</h6>+ {toolCall.inputStreaming !== undefined+ ? <CodeBlock code={toolCall.inputStreaming} wrap />+ : <CodeBlock code={JSON.stringify(toolCall.input, null, 2)} mimeType="application/json" wrap />}+ </section>+ <section className="tool-call-details-section">+ <h6>{toolCall.isError ? t("llm_chat.error") : t("llm_chat.result")}</h6>+ {toolCall.result+ ? <ResultBlock result={toolCall.result} />+ : <p className="tool-call-details-empty">{t("llm_chat.tool_call_no_result")}</p>}+ </section>+ </>+ )}+ </Modal>+ );+}++/** A JSON result pretty-printed and highlighted; any other result as plain text. */+function ResultBlock({ result }: { result: string }) {+ try {+ const parsed: unknown = JSON.parse(result);+ return <CodeBlock code={JSON.stringify(parsed, null, 2)} mimeType="application/json" wrap />;+ } catch {+ return <CodeBlock code={result} wrap />;+ }+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ExpandableCard.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ExpandableCard.tsxindex d0c5739299..2475e7c4ff 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ExpandableCard.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ExpandableCard.tsx@@ -9,6 +9,8 @@ interface ExpandableSectionProps {/** Whether the section is expanded on initial render. */open?: boolean;children?: ComponentChildren;+ /** Buttons placed after the chevron. Their click handlers must prevent the default toggle. */+ actions?: ComponentChildren;/*** `card` is a row of an ExpandableCard; `line` is a bare muted line whose body hangs off a rule* under the icon, as used by thoughts and tool calls.@@ -17,13 +19,14 @@ interface ExpandableSectionProps {}/** A collapsible section, either a row of an ExpandableCard or a standalone disclosure line. */-export function ExpandableSection({ icon, label, className, open, children, variant = "card" }: ExpandableSectionProps) {+export function ExpandableSection({ icon, label, className, open, children, actions, variant = "card" }: ExpandableSectionProps) {return (<details className={`expandable-section ${variant === "line" ? "expandable-line" : ""} ${className ?? ""}`} open={open}><summary className="expandable-section-summary"><span className={icon} /><span className="expandable-section-label">{label}</span><span className="bx bx-chevron-down expandable-section-chevron" />+ {actions}</summary><div className="expandable-section-body">{children}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.css b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.cssindex dd3b6191f8..5b6dd5fa8a 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.css@@ -19,80 +19,32 @@margin-left: 0.25rem;}-/* Section body (input + result) */-.llm-chat-tool-call-input,-.llm-chat-tool-call-result {- padding: 0.25rem 0;- max-height: 300px;- overflow: auto;-}--.expandable-section-body pre {- margin: 0;- padding: 0;- font-size: 0.8rem;- font-family: var(--monospace-font-family, monospace);-}--.llm-chat-tool-call-input strong,-.llm-chat-tool-call-result strong {- display: block;- font-size: 0.75rem;- color: var(--muted-text-color);- margin-bottom: 0.25rem;- text-transform: uppercase;-}--/* Tool call key-value table */-.llm-chat-tool-call-table {- width: 100%;- table-layout: auto;- border-collapse: collapse;- font-size: 0.8rem;-}--.llm-chat-tool-call-table td {- padding: 0.25rem 0;- padding-right: 0.75rem;- vertical-align: top;-}--.llm-chat-tool-call-table tr:last-child td {- border-bottom: none;-}+/* Shown on hover, on focus, on an open line, and always where there is no hover. */+.llm-chat-tool-call-debug.icon-action {+ --icon-button-size: 1.4rem;+ --icon-button-icon-ratio: 0.7;-.llm-chat-tool-call-table-key {- font-weight: 600;- white-space: nowrap;- width: 0;- color: var(--muted-text-color);+ opacity: 0;}-.llm-chat-tool-call-table-value pre {- margin: 0;- padding: 0;- white-space: pre-wrap;- word-break: break-word;+.llm-chat-tool-call > :is(.expandable-section-summary, .expandable-line-header):is(:hover, :focus-within) > .llm-chat-tool-call-debug,+.llm-chat-tool-call[open] > .expandable-section-summary > .llm-chat-tool-call-debug {+ opacity: 1;}-/* Nested tables */-.llm-chat-tool-call-table-value .llm-chat-tool-call-table {- width: auto;- min-width: 100%;+@media (hover: none) {+ .llm-chat-tool-call-debug.icon-action {+ opacity: 1;+ }}-.llm-chat-tool-call-table-array {- display: flex;- flex-direction: column;-}--.llm-chat-tool-call-table-array > .llm-chat-tool-call-table + .llm-chat-tool-call-table {- border-top: 1px solid var(--main-border-color);+.llm-chat-tool-call-diff {+ max-height: 300px;+ overflow: auto;}-/* Tool call error styling */-/* Outranks the summary's hover color, so an errored call stays red. */-.llm-chat-tool-call.llm-chat-tool-call-error > .expandable-section-summary {+/* An errored call's summary. This outranks the summary's hover color, so it stays red. */+.llm-chat-tool-call.llm-chat-tool-call-error > :is(.expandable-section-summary, .expandable-line-header) {color: var(--danger-color, #dc3545);}@@ -103,21 +55,27 @@opacity: 0.8;}-.llm-chat-tool-call-result-error pre {- color: var(--danger-color, #dc3545);+.llm-chat-tool-call-error-message {+ margin: 0;+ white-space: pre-wrap;+ overflow-wrap: anywhere;}-/* Streaming-input view: raw JSON arriving from the LLM, shown until it's parsed.- The trailing block-caret hints that text is still landing. */-.llm-chat-tool-call-input-streaming pre {+/* Raw JSON arriving from the LLM, shown until it parses. The blinking caret marks it as still+ arriving. */+.llm-chat-tool-call-streaming {+ margin: 0;+ max-height: 300px;+ overflow: auto;+ font-size: 0.8rem;white-space: pre-wrap;- word-break: break-word;-}+ overflow-wrap: anywhere;-.llm-chat-tool-call-input-streaming pre::after {- content: "▍";- color: var(--muted-text-color);- animation: llm-chat-tool-call-caret 1s steps(1) infinite;+ &::after {+ content: "▍";+ color: var(--muted-text-color);+ animation: llm-chat-tool-call-caret 1s steps(1) infinite;+ }}@keyframes llm-chat-tool-call-caret {diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsxindex f718c19398..b493685e18 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx@@ -5,6 +5,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";vi.mock("../../../services/i18n.js", () => ({t: (key: string, options?: { defaultValue?: string }) => (key.startsWith("llm.tools.") ? key.slice("llm.tools.".length) : options?.defaultValue ?? key)}));+const mocks = vi.hoisted(() => ({ triggerEvent: vi.fn() }));+vi.mock("../../../components/app_context.js", () => ({ default: { triggerEvent: mocks.triggerEvent } }));vi.mock("../../react/NoteLink.js", () => ({NewNoteLink: ({ notePath }: { notePath: string }) => <a className="note-link-stub">{notePath}</a>}));@@ -15,6 +17,7 @@ import type { ToolCall } from "./llm_chat_types.js";let host: HTMLElement | undefined;afterEach(() => {+ mocks.triggerEvent.mockClear();if (host) {render(null, host);host.remove();@@ -40,7 +43,7 @@ describe("ToolCallCard", () => {.toEqual([ "rocket", "weather Sibiu", "https://triliumnotes.org" ]);});- it("lists the calls as bare disclosure lines rather than in a card", () => {+ it("lists the calls as bare lines, folding only those with something to show inline", () => {const target = renderCard([{ id: "1", toolName: "get_note", input: { noteId: "a" }, result: "{}" },{ id: "2", toolName: "get_note", input: { noteId: "b" }, result: "{}" },@@ -48,8 +51,35 @@ describe("ToolCallCard", () => {]);expect(target.querySelector(".expandable-card")).toBeNull();const lines = [ ...(target.querySelector(".llm-chat-tool-calls")?.children ?? []) ];- expect(lines.map(line => line instanceof HTMLDetailsElement && line.classList.contains("llm-chat-tool-call")))- .toEqual([ true, true ]);- expect(lines[0]?.querySelectorAll(".expandable-section-body > details.llm-chat-tool-call")).toHaveLength(2);+ expect(lines.map(line => line.classList.contains("llm-chat-tool-call"))).toEqual([ true, true ]);+ expect(lines.map(line => line instanceof HTMLDetailsElement)).toEqual([ true, false ]);+ const grouped = lines[0]?.querySelectorAll(".expandable-section-body > .llm-chat-tool-call");+ expect([ ...(grouped ?? []) ].map(line => line instanceof HTMLDetailsElement)).toEqual([ false, false ]);+ expect(target.textContent).not.toContain("Sunny");+ });++ it("opens the input and result of a call in a dialog", () => {+ const call: ToolCall = { id: "1", toolName: "web_search", input: { query: "rocket" }, result: "Sunny" };+ const target = renderCard([ call ]);+ const button = target.querySelector<HTMLButtonElement>(".llm-chat-tool-call-debug");+ expect(button).not.toBeNull();+ act(() => button?.click());+ expect(mocks.triggerEvent).toHaveBeenCalledExactlyOnceWith("showToolCallDetails", { toolCall: call });+ });++ it("shows why a call failed inline, and opening the dialog leaves the line folded", () => {+ const target = renderCard([ {+ id: "1",+ toolName: "get_note",+ input: { noteId: "a" },+ result: JSON.stringify({ error: "Note not found" }),+ isError: true+ } ]);+ const line = target.querySelector("details.llm-chat-tool-call");+ expect(line?.querySelector(".llm-chat-tool-call-error-message")?.textContent).toBe("Note not found");++ act(() => line?.querySelector<HTMLButtonElement>(".llm-chat-tool-call-debug")?.click());+ expect(mocks.triggerEvent).toHaveBeenCalledOnce();+ expect((line as HTMLDetailsElement | null)?.open).toBe(false);});});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsxindex 72be3254fa..8e5954e012 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.tsx@@ -2,7 +2,9 @@ import "./ToolCallCard.css";import { Trans } from "react-i18next";+import appContext from "../../../components/app_context.js";import { t } from "../../../services/i18n.js";+import ActionButton from "../../react/ActionButton.js";import { NewNoteLink } from "../../react/NoteLink.js";import { EditNoteContentDiff, isSmallEdit, parseNoteContentEdits } from "./EditNoteContentDiff.js";import { ExpandableSection } from "./ExpandableCard.js";@@ -71,85 +73,17 @@ function toolCallIcon(toolCall: ToolCall): string {return toolNameIcon(toolCall.toolName);}-/** Try to parse a JSON string into a structured value. */-function tryParseJson(data: unknown): unknown {- if (typeof data === "string") {- try {- return JSON.parse(data);- } catch {- return data;- }- }- return data;-}--/** Check if a value is a plain object (not null, not array). */-function isPlainObject(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--const MAX_TABLE_DEPTH = 2;--/** Render a single value — recurse for objects/arrays up to max depth. */-function ValueCell({ value, depth }: { value: unknown; depth: number }) {- if (value === null || value === undefined) return <pre />;-- // Beyond max depth, fall back to JSON.- if (depth >= MAX_TABLE_DEPTH) {- if (isPlainObject(value) || Array.isArray(value)) {- return <pre>{JSON.stringify(value, null, 2)}</pre>;- }- return <pre>{String(value)}</pre>;- }-- if (isPlainObject(value)) {- return <KeyValueTable data={value} depth={depth} />;- }-- if (Array.isArray(value)) {- if (value.length === 0) return <pre>{"[]"}</pre>;-- // Array of objects: render each as a nested table.- if (value.every(isPlainObject)) {- return (- <div className="llm-chat-tool-call-table-array">- {value.map((item, idx) => (- <KeyValueTable key={idx} data={item} depth={depth} />- ))}- </div>- );+/** The message of a failed call: the `error` field of a JSON result, or else the whole result. */+function getErrorMessage(result: string): string {+ try {+ const parsed: unknown = JSON.parse(result);+ if (typeof parsed === "object" && parsed !== null && "error" in parsed && typeof parsed.error === "string") {+ return parsed.error;}-- // Array of primitives: comma-separated.- return <pre>{value.map(String).join(", ")}</pre>;- }-- return <pre>{String(value)}</pre>;-}--/** Renders a data object as a recursive two-column key-value table. */-function KeyValueTable({ data, className, depth = 0 }: { data: unknown; className?: string; depth?: number }) {- const obj = tryParseJson(data);-- if (!isPlainObject(obj)) {- const raw = typeof data === "string" ? data : JSON.stringify(data, null, 2);- return <pre className={className}>{raw}</pre>;+ } catch {+ // A result that is not JSON is the message itself.}-- return (- <table className={`llm-chat-tool-call-table ${className ?? ""}`}>- <tbody>- {Object.entries(obj).map(([key, value]) => (- <tr key={key}>- <td className="llm-chat-tool-call-table-key">{key}</td>- <td className="llm-chat-tool-call-table-value">- <ValueCell value={value} depth={depth + 1} />- </td>- </tr>- ))}- </tbody>- </table>- );+ return result;}/** Build the label content for a tool call section. */@@ -183,50 +117,74 @@ function ToolCallLabel({ toolCall }: { toolCall: ToolCall }) {);}-/** A single tool call section within a ToolCallCard. */+/**+ * A single tool call. It folds open only for what is worth reading inline: the input while it+ * streams, the diff of an `edit_note_content` call, or why the call failed. The raw input and+ * result are in the dialog the debug button opens.+ */function ToolCallSection({ toolCall }: { toolCall: ToolCall }) {const hasError = toolCall.isError;const isStreamingInput = toolCall.inputStreaming !== undefined;- // The `edit_note_content` tool gets a fancy unified diff instead of a raw input table.- // Suppress the diff view while input is still streaming — the partial JSON isn't parseable yet.+ // The partial JSON of a streaming input does not parse, so the diff waits for the whole input.const noteContentEdits = !isStreamingInput && toolCall.toolName === "edit_note_content"? parseNoteContentEdits(toolCall.input?.edits): null;+ const errorMessage = hasError && toolCall.result ? getErrorMessage(toolCall.result) : null;++ const className = `llm-chat-tool-call ${hasError ? "llm-chat-tool-call-error" : ""}`;+ const icon = toolCallIcon(toolCall);+ const label = <ToolCallLabel toolCall={toolCall} />;+ const debugButton = <ToolCallDebugButton toolCall={toolCall} />;++ if (!isStreamingInput && !noteContentEdits && !errorMessage) {+ return (+ <div className={`expandable-line ${className}`}>+ <div className="expandable-line-header">+ <span className={icon} />+ <span className="expandable-section-label">{label}</span>+ {debugButton}+ </div>+ </div>+ );+ }return (<ExpandableSection- icon={toolCallIcon(toolCall)}- label={<ToolCallLabel toolCall={toolCall} />}+ icon={icon}+ label={label}+ actions={debugButton}variant="line"- className={`llm-chat-tool-call ${hasError ? "llm-chat-tool-call-error" : ""}`}+ className={className}open={noteContentEdits ? isSmallEdit(noteContentEdits) : isStreamingInput || undefined}>- <div className={`llm-chat-tool-call-input ${isStreamingInput ? "llm-chat-tool-call-input-streaming" : ""}`}>- {isStreamingInput ? (- <>- <strong>{t("llm_chat.input_streaming")}</strong>- <pre>{toolCall.inputStreaming}</pre>- </>- ) : noteContentEdits ? (+ {isStreamingInput && <pre className="llm-chat-tool-call-streaming">{toolCall.inputStreaming}</pre>}+ {noteContentEdits && (+ <div className="llm-chat-tool-call-diff"><EditNoteContentDiff edits={noteContentEdits} />- ) : (- <>- <strong>{t("llm_chat.input")}</strong>- <KeyValueTable data={toolCall.input} />- </>- )}- </div>- {toolCall.result && (!noteContentEdits || hasError) && (- <div className={`llm-chat-tool-call-result ${hasError ? "llm-chat-tool-call-result-error" : ""}`}>- <strong>{hasError ? t("llm_chat.error") : t("llm_chat.result")}</strong>- <KeyValueTable data={toolCall.result} /></div>)}+ {errorMessage && <p className="llm-chat-tool-call-error-message">{errorMessage}</p>}</ExpandableSection>);}+/** Opens the raw input and result of a call in `ToolCallDetailsDialog`. */+function ToolCallDebugButton({ toolCall }: { toolCall: ToolCall }) {+ return (+ <ActionButton+ className="llm-chat-tool-call-debug"+ icon="bx bx-code-alt"+ text={t("llm_chat.show_tool_call_details")}+ onClick={(e) => {+ // Inside a summary, the click would also fold the line open or shut.+ e.preventDefault();+ void appContext.triggerEvent("showToolCallDetails", { toolCall });+ }}+ />+ );+}+/** Fold a section showing multiple invocations of the same tool under a single header. */function ToolCallGroupSection({ toolCalls }: { toolCalls: ToolCall[] }) {const first = toolCalls[0];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 6ec3da068c..48fe2803ff 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@@ -182,6 +182,12 @@ class="admonition note"></li><li>Skills (see the dedicated section).</li></ul>+<p>Each tool the AI uses appears in the chat as a single line naming the+ tool and the note or query it worked on. A line folds open only when there+ is something to read inline: the changes of an edit, or the reason a tool+ failed. To see exactly what the AI sent to a tool and what it got back,+ hover the line and press the <span class="tn-icon bx bx-code-alt"></span> button+ next to it; on touch screens the button is always shown.</p><aside class="admonition warning"><p>Currently there is <strong>no permission management</strong> implementedfor note tools, meaning that the LLM could potentially remove existingdiff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex 226a400bc1..e791d4d862 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -131,6 +131,8 @@ Here are a few tools that Trilium provides for the LLM:* Get the content of an attachment.* Skills (see the dedicated section).+Each tool the AI uses appears in the chat as a single line naming the tool and the note or query it worked on. A line folds open only when there is something to read inline: the changes of an edit, or the reason a tool failed. To see exactly what the AI sent to a tool and what it got back, hover the line and press the <span class="tn-icon bx bx-code-alt"></span> button next to it; on touch screens the button is always shown.+> [!WARNING]> Currently there is **no permission management** implemented for note tools, meaning that the LLM could potentially remove existing notes or clutter the tree with notes. Generally most actions are easily reversible (deleting the notes, restoring deleted notes, reverting modifications to a note), but there are some that are harder to revert (e.g. setting an attribute because there is no attribute history).