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): add tool for picking icons
Elian Doranf41d3e5ba76a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ab06d79e90..98aa3af230 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2771,7 +2771,8 @@"rename_note": "Rename note","delete_note": "Delete note","move_note": "Move note",- "clone_note": "Clone note"+ "clone_note": "Clone note",+ "search_icons": "Search icons"}},"common": {diff --git a/apps/server/src/assets/llm/skills/dashboards.md b/apps/server/src/assets/llm/skills/dashboards.mdindex 2867afad73..d2478fff75 100644--- a/apps/server/src/assets/llm/skills/dashboards.md+++ b/apps/server/src/assets/llm/skills/dashboards.md@@ -22,6 +22,8 @@ A widget is just a child note, rendered with its normal content. Pick the note t| A drawing | `canvas` || **Dynamic / interactive content** | `render` + a Preact JSX child note (see below) |+After creating a widget note, ALWAYS give it an icon: find a fitting one with `search_icons` and assign it with `set_attribute` as the widget note's `iconClass` label (e.g. `bx bx-line-chart`). The icon is shown in the widget's title bar. Never prepend an emoji to the widget title instead.+## Interactive widgets (Preact render notes) — preferred for dynamic contentFor widgets that compute something, fetch data, or respond to clicks, use a render note backed by a Preact JSX component:@@ -69,7 +71,6 @@ export default function RecentNotesWidget() {- Keep widget content compact — widgets clip overflowing content with scrollbars.- Give widgets meaningful titles; the title bar is always visible and doubles as the drag handle.-- An icon can be set on a widget note with the `iconClass` label (e.g. `bx bx-line-chart`).## Anti-patterns (do NOT do this)@@ -78,3 +79,4 @@ export default function RecentNotesWidget() {- ❌ Directing the user to set `~renderNote` on the dashboard note itself — it belongs on the `render`-type child.- ❌ Writing the `dashboard.json` attachment to lay out widgets — the UI owns it; rely on auto-placement.- ❌ Setting `#viewType=dashboard` on a `text` note — the view type only applies to `book` (and search) notes.+- ❌ Prepending an emoji to a widget title to decorate it — find an icon with `search_icons` and set the `iconClass` label instead.diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex 09840fe46d..e8e81922dc 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -208,6 +208,9 @@ export abstract class BaseProvider implements LlmProvider {parts.push(`After a successful write tool call (set_note_content, append_to_note, edit_note_content, create_note), the tool's result already contains the resulting content of the note. Do not call get_note_content to verify the write — trust the returned content.`);+ parts.push(+ `Never prepend emojis or other decorative characters to note titles. To give a note a visual marker, find a fitting icon with search_icons and assign it via set_attribute as the note's 'iconClass' label (e.g. value 'bx bx-rocket').`+ );} else if (config.contextNoteId) {parts.push(`You can see the current note's metadata above, but you cannot search or access other notes. If the user asks about other notes, inform them that "Note access" is disabled and they need to enable it in the chat settings (click on the model name dropdown and toggle "Note access").`diff --git a/apps/server/src/services/llm/tools/icon_tools.spec.ts b/apps/server/src/services/llm/tools/icon_tools.spec.tsnew file mode 100644index 0000000000..5fde9b0c65--- /dev/null+++ b/apps/server/src/services/llm/tools/icon_tools.spec.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from "vitest";++import { iconTools, scoreIcon } from "./icon_tools.js";+import type { ToolDefinition } from "./tool_registry.js";++function getTool(name: string): ToolDefinition {+ for (const [n, def] of iconTools) {+ if (n === name) return def;+ }+ throw new Error(`Tool ${name} not registered`);+}++interface SearchResult {+ totalResults: number;+ results: { iconClass: string; terms: string[] }[];+}++describe("icon_tools", () => {+ describe("search_icons", () => {+ it("finds icons by keyword and returns their icon class with terms", () => {+ const result = getTool("search_icons").execute({ query: "rocket" }) as SearchResult;+ expect(result.totalResults).toBeGreaterThanOrEqual(2);+ const rocket = result.results.find((r) => r.iconClass === "bx bx-rocket");+ expect(rocket).toMatchObject({ iconClass: "bx bx-rocket", terms: ["rocket"] });+ });++ it("matches multi-keyword queries against hyphenated terms and ranks them first", () => {+ const result = getTool("search_icons").execute({ query: "check circle" }) as SearchResult;+ expect(result.results[0].iconClass).toMatch(/^bx bxs?-check-circle$/);+ });++ it("respects the limit and reports the full match count", () => {+ const result = getTool("search_icons").execute({ query: "circle", limit: 3 }) as SearchResult;+ expect(result.results).toHaveLength(3);+ expect(result.totalResults).toBeGreaterThan(3);+ });++ it("returns no results for an unmatched keyword", () => {+ const result = getTool("search_icons").execute({ query: "xyzzyplugh" }) as SearchResult;+ expect(result).toEqual({ totalResults: 0, results: [] });+ });++ it("rejects an empty or whitespace-only query", () => {+ expect(getTool("search_icons").execute({ query: "" }))+ .toEqual({ error: "Query must not be empty" });+ expect(getTool("search_icons").execute({ query: " " }))+ .toEqual({ error: "Query must not be empty" });+ });+ });++ describe("scoreIcon", () => {+ it("ranks exact term and segment matches above substring matches and rejects non-matches", () => {+ // Exact term match.+ expect(scoreIcon("bx-rocket", ["rocket"], ["rocket"])).toBe(2);+ // Exact hyphen-segment match.+ expect(scoreIcon("bx-check-circle", ["check-circle"], ["circle"])).toBe(2);+ // Substring-only match scores lower.+ expect(scoreIcon("bx-checkbox", ["checkbox"], ["check"])).toBe(1);+ // Match on the icon name itself.+ expect(scoreIcon("bx-rocket", ["launch"], ["rocket"])).toBe(1);+ // Every keyword must match.+ expect(scoreIcon("bx-rocket", ["rocket"], ["rocket", "banana"])).toBe(0);+ // Scores accumulate across keywords.+ expect(scoreIcon("bx-check-circle", ["check-circle"], ["check", "circle"])).toBe(4);+ });+ });+});diff --git a/apps/server/src/services/llm/tools/icon_tools.ts b/apps/server/src/services/llm/tools/icon_tools.tsnew file mode 100644index 0000000000..f796f76e5c--- /dev/null+++ b/apps/server/src/services/llm/tools/icon_tools.ts@@ -0,0 +1,70 @@+/**+ * LLM tools for finding note icons across the available icon packs.+ */++import { icon_packs } from "@triliumnext/core";+import { z } from "zod";++import { defineTools } from "./tool_registry.js";++const DEFAULT_LIMIT = 20;++export const iconTools = defineTools({+ search_icons: {+ description: [+ "Search the available icon packs (e.g. Boxicons) for a note icon by keyword.",+ "Returns icon classes such as 'bx bx-rocket', ordered by relevance.",+ "To give a note an icon, assign the icon class to the note's 'iconClass' label via set_attribute.",+ "ALWAYS use this instead of prepending an emoji to a note's title."+ ].join(" "),+ inputSchema: z.object({+ query: z.string().describe("One or more keywords describing the desired icon, e.g. 'rocket' or 'check circle'"),+ limit: z.number().optional().describe("Maximum number of icons to return. Defaults to 20.")+ }),+ execute: ({ query, limit = DEFAULT_LIMIT }) => {+ const keywords = query.toLowerCase().split(/\s+/).filter(Boolean);+ if (!keywords.length) {+ return { error: "Query must not be empty" };+ }++ const matches: { iconClass: string; terms: string[]; score: number }[] = [];+ for (const pack of icon_packs.getIconPacks()) {+ for (const [name, icon] of Object.entries(pack.manifest.icons)) {+ if (!name || !icon?.terms) {+ continue;+ }+ const score = scoreIcon(name, icon.terms, keywords);+ if (score > 0) {+ matches.push({ iconClass: `${pack.prefix} ${name}`, terms: icon.terms, score });+ }+ }+ }+ matches.sort((a, b) => b.score - a.score);++ return {+ totalResults: matches.length,+ results: matches.slice(0, limit).map(({ iconClass, terms }) => ({ iconClass, terms }))+ };+ }+ }+});++/**+ * Score an icon against the search keywords. Every keyword must match the icon+ * name or one of its terms, otherwise the icon is rejected (score 0). Exact+ * matches on a term or on a hyphen-separated segment of a term ("circle" in+ * "check-circle") rank above plain substring matches.+ */+export function scoreIcon(name: string, terms: string[], keywords: string[]): number {+ let score = 0;+ for (const keyword of keywords) {+ if (terms.some((term) => term === keyword || term.split("-").includes(keyword))) {+ score += 2;+ } else if (terms.some((term) => term.includes(keyword)) || name.includes(keyword)) {+ score += 1;+ } else {+ return 0;+ }+ }+ return score;+}diff --git a/apps/server/src/services/llm/tools/index.ts b/apps/server/src/services/llm/tools/index.tsindex 1af4e4bef5..2ef3a54849 100644--- a/apps/server/src/services/llm/tools/index.ts+++ b/apps/server/src/services/llm/tools/index.ts@@ -7,6 +7,7 @@ export { noteTools } from "./note_tools.js";export { attributeTools } from "./attribute_tools.js";export { attachmentTools } from "./attachment_tools.js";export { hierarchyTools } from "./hierarchy_tools.js";+export { iconTools } from "./icon_tools.js";export { skillTools } from "../skills/index.js";export type { ToolDefinition } from "./tool_registry.js";export { ToolRegistry } from "./tool_registry.js";@@ -15,6 +16,7 @@ import { noteTools } from "./note_tools.js";import { attributeTools } from "./attribute_tools.js";import { attachmentTools } from "./attachment_tools.js";import { hierarchyTools } from "./hierarchy_tools.js";+import { iconTools } from "./icon_tools.js";import { skillTools } from "../skills/index.js";import type { ToolRegistry } from "./tool_registry.js";@@ -24,5 +26,6 @@ export const allToolRegistries: ToolRegistry[] = [attributeTools,attachmentTools,hierarchyTools,+ iconTools,skillTools];