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): nest the notes a get_subtree call read
Elian Doran35453711e952
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 77b3b54d85..4cba7bcc30 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2671,7 +2671,9 @@"child_count_one": "{{count}} child","child_count_other": "{{count}} children","search_help_count_one": "({{count}} page)",- "search_help_count_other": "({{count}} pages)"+ "search_help_count_other": "({{count}} pages)",+ "subtree_more_one": "+{{count}} more",+ "subtree_more_other": "+{{count}} more"},"sidebar_chat": {"title": "AI Chat",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 a431db452b..2303929ae7 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@@ -240,4 +240,40 @@ describe("ToolCallCard", () => {act(() => link?.click());expect(mocks.openInAppHelpFromUrl).toHaveBeenCalledExactlyOnceWith("abc");});++ it("nests the notes of a subtree, with what the depth and width limits left out", () => {+ const target = renderCard([ {+ id: "1",+ toolName: "get_subtree",+ input: { noteId: "top", depth: 2 },+ result: JSON.stringify({+ noteId: "top", title: "Top", type: "text", children: [+ { noteId: "a", title: "A", type: "text", children: [+ { noteId: "a1", title: "A1", type: "text", children: "5 children not shown (depth limit reached)" }+ ] },+ { noteId: "b", title: "B", type: "text" },+ { noteId: "", title: "... and 3 more", type: "truncated" }+ ]+ })+ } ]);+ const line = target.querySelector("details.llm-chat-tool-call");+ expect(line?.querySelector(".llm-chat-tool-call-result-count")?.textContent)+ .toBe("llm_chat.search_notes_count{\"count\":3}");++ const header = (row: Element | null | undefined) => row?.querySelector(":scope > .llm-chat-note-result-header");+ const rows = [ ...(line?.querySelectorAll(".llm-chat-note-result") ?? []) ];+ expect(rows.map(row => ({+ note: header(row)?.querySelector(".note-link-stub")?.textContent,+ detail: header(row)?.querySelector(".llm-chat-note-result-detail")?.textContent ?? null,+ parent: header(row.parentElement?.closest(".llm-chat-note-result"))?.querySelector(".note-link-stub")?.textContent ?? null+ }))).toEqual([+ { note: "a", detail: null, parent: null },+ { note: "a1", detail: "llm_chat.child_count{\"count\":5}", parent: "a" },+ { note: "b", detail: null, parent: null }+ ]);++ const more = line?.querySelector(".llm-chat-note-results-more");+ expect(more?.textContent).toBe("llm_chat.subtree_more{\"count\":3}");+ expect(more?.closest(".llm-chat-note-result")).toBeNull();+ });});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.css b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.cssindex 0a5743b6c8..ab87811361 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.css@@ -70,3 +70,19 @@align-self: center;}}++/* The notes of a `get_subtree` call, one indent and guide line per level. */+.llm-chat-subtree {+ max-height: 300px;+ overflow: auto;++ .llm-chat-note-result > ul {+ margin: 0.2rem 0 0 0.35rem;+ padding-left: 0.5rem;+ border-left: 1px solid var(--main-border-color);+ }++ .llm-chat-note-result:has(> ul) {+ padding-bottom: 0;+ }+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsxindex d934c295d5..a84c38bffe 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx@@ -60,6 +60,14 @@ export function getToolCallView(toolCall: ToolCall): ToolCallView | null {body: children.length > 0 ? <ChildNoteList notes={children} /> : undefined};}+ case "get_subtree": {+ const nodes = parseSubtreeResult(toolCall.result);+ if (!nodes) return null;+ return {+ summary: t("llm_chat.search_notes_count", { count: countSubtreeNotes(nodes) }),+ body: nodes.length > 0 ? <div className="llm-chat-note-results llm-chat-subtree"><SubtreeList nodes={nodes} /></div> : undefined+ };+ }default:return null;}@@ -143,10 +151,35 @@ function ChildNoteList({ notes }: { notes: ChildNote[] }) {);}+/** A level of a `get_subtree` result; `children` of a note are the next level, nested in its row. */+function SubtreeList({ nodes }: { nodes: SubtreeNode[] }) {+ return (+ <ul>+ {nodes.map((node, idx) => ("more" in node ? (+ <li key={idx} className="llm-chat-note-results-more">{t("llm_chat.subtree_more", { count: node.more })}</li>+ ) : (+ <NoteResultRow+ key={idx}+ noteId={node.noteId}+ nested={node.children.length > 0 && <SubtreeList nodes={node.children} />}+ >+ {node.hiddenChildren > 0 && (+ <span className="llm-chat-note-result-detail">+ {t("llm_chat.child_count", { count: node.hiddenChildren })}+ </span>+ )}+ </NoteResultRow>+ )))}+ </ul>+ );+}+/** One note in a list a tool returned: its link, muted details beside it, and a preview below. */-function NoteResultRow({ noteId, preview, onLinkClick, children }: {+function NoteResultRow({ noteId, preview, nested, onLinkClick, children }: {noteId: string;preview?: string;+ /** A list nested under the row, such as the next level of a subtree. */+ nested?: ComponentChildren;/** Takes a plain click on the link. Returns whether it handled the click. */onLinkClick?: (noteId: string) => boolean;children?: ComponentChildren;@@ -168,10 +201,68 @@ function NoteResultRow({ noteId, preview, onLinkClick, children }: {{children}</div>{preview && <div className="llm-chat-note-result-preview">{preview}</div>}+ {nested}</li>);}+/**+ * A note of a `get_subtree` result, or the marker that stands for the children past the ten a level+ * lists. `hiddenChildren` counts the children past the depth limit.+ */+type SubtreeNode = { noteId: string; children: SubtreeNode[]; hiddenChildren: number } | { more: number };++/**+ * Reads the root's children out of a `get_subtree` result. The tool reports what it left out in+ * English for the model ("... and 3 more", "5 children not shown"), so the counts are read out of+ * that text.+ */+function parseSubtreeResult(result: string): SubtreeNode[] | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(result);+ } catch {+ return null;+ }+ if (!isRecord(parsed) || typeof parsed.noteId !== "string") return null;+ return Array.isArray(parsed.children) ? parseSubtreeLevel(parsed.children) : [];+}++function parseSubtreeLevel(items: unknown[]): SubtreeNode[] {+ const nodes: SubtreeNode[] = [];+ for (const item of items) {+ if (!isRecord(item) || typeof item.noteId !== "string") continue;+ if (!item.noteId) {+ const more = firstNumber(item.title);+ if (more) nodes.push({ more });+ continue;+ }+ nodes.push({+ noteId: item.noteId,+ children: Array.isArray(item.children) ? parseSubtreeLevel(item.children) : [],+ hiddenChildren: firstNumber(item.children)+ });+ }+ return nodes;+}++function countSubtreeNotes(nodes: SubtreeNode[]): number {+ let count = 0;+ for (const node of nodes) {+ if ("noteId" in node) count += 1 + countSubtreeNotes(node.children);+ }+ return count;+}++function firstNumber(text: unknown): number {+ const match = typeof text === "string" ? /\d+/.exec(text) : null;+ return match ? Number(match[0]) : 0;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+/** Opens a User Guide page in the contextual help split, as `HelpButton` does. */function openAsHelp(noteId: string): boolean {if (!noteId.startsWith(HELP_NOTE_PREFIX)) return false;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 743708d717..11008378d5 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@@ -185,12 +185,12 @@ class="admonition note"><p>Each tool the AI uses appears in the chat as a single line naming thetool and the note or query it worked on. A line folds open only when thereis something to read inline: the notes a search found, the User Guide pages- the AI looked up (which open in the help panel), the children of a note,- the changes of an edit, or the reason a tool failed. A search also shows- how many notes it found, the part of the tree it was confined to, if any,- and how many of the matches the AI asked for; each note it lists opens- with a click. 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+ the AI looked up (which open in the help panel), the children or the whole+ subtree of a note, the changes of an edit, or the reason a tool failed.+ A search also shows how many notes it found, the part of the tree it was+ confined to, if any, and how many of the matches the AI asked for; each+ note it lists opens with a click. 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> buttonnext to it; on touch screens the button is always shown.</p><aside class="admonition warning"><p>Currently there is <strong>no permission management</strong> implementeddiff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex d9bca535ea..3c0305caa3 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -131,7 +131,7 @@ 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 notes a search found, the User Guide pages the AI looked up (which open in the help panel), the children of a note, the changes of an edit, or the reason a tool failed. A search also shows how many notes it found, the part of the tree it was confined to, if any, and how many of the matches the AI asked for; each note it lists opens with a click. 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.+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 notes a search found, the User Guide pages the AI looked up (which open in the help panel), the children or the whole subtree of a note, the changes of an edit, or the reason a tool failed. A search also shows how many notes it found, the part of the tree it was confined to, if any, and how many of the matches the AI asked for; each note it lists opens with a click. 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).