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): let set_note_content change a note's type and mime
Elian Doran396024da9f04
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 2d126c9d1f..57a7d2bdcc 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@@ -401,6 +401,25 @@ describe("ToolCallCard", () => {expect(json?.querySelector(".llm-chat-written")).toBeNull();});+ it("shows what set_note_content wrote by the type and mime it changed the note to", () => {+ mocks.notes = { t: { type: "text", mime: "text/html" }, c: { type: "code", mime: "text/x-python" } };+ // A call in between keeps the two from grouping into one section.+ const target = renderCard([+ { id: "1", toolName: "set_note_content", input: { noteId: "t", content: "print(1)", type: "code", mime: "text/x-python" } },+ { id: "2", toolName: "get_note", input: { noteId: "t" } },+ { id: "3", toolName: "set_note_content", input: { noteId: "c", content: "# Title", type: "text" } }+ ]);+ const [ toCode, , toText ] = [ ...(target.querySelector(".llm-chat-tool-calls")?.children ?? []) ];++ const codeBlock = toCode?.querySelector(".llm-chat-written .code-block-stub");+ expect(codeBlock?.textContent).toBe("print(1)");+ expect(codeBlock?.getAttribute("data-mime")).toBe("text/x-python");+ expect(toCode?.querySelector(".llm-chat-written .markdown-stub")).toBeNull();++ expect(toText?.querySelector(".llm-chat-written .markdown-stub")).not.toBeNull();+ expect(toText?.querySelector(".llm-chat-written .code-block-stub")).toBeNull();+ });+it("shows an edit as blocks with colored edges, rendering Markdown on a Markdown note", () => {mocks.notes = {m: { type: "code", mime: "text/x-markdown" },diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsxindex 2000b7a0b7..b59cdb7afc 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallViews.tsx@@ -39,9 +39,14 @@ export function getToolCallView(toolCall: ToolCall): ToolCallView | null {}if (toolCall.toolName === "set_note_content" || toolCall.toolName === "append_to_note") {- const { noteId, content } = toolCall.input;+ const { noteId, content, type, mime } = toolCall.input;if (typeof noteId !== "string" || typeof content !== "string" || !content.trim()) return null;- return { body: <NoteWrittenContent noteId={noteId} content={content} appended={toolCall.toolName === "append_to_note"} /> };+ return { body: (+ <NoteWrittenContent+ noteId={noteId} content={content} appended={toolCall.toolName === "append_to_note"}+ type={typeof type === "string" ? type : undefined} mime={typeof mime === "string" ? mime : undefined}+ />+ ) };}if (!toolCall.result) return null;@@ -270,13 +275,22 @@ function WrittenContent({ type, mime, content, appended }: { type: string; mime?}/**- * The content `set_note_content` or `append_to_note` wrote. Their input names no type, so it comes- * from the note itself, and nothing shows until froca has it.+ * The content `set_note_content` or `append_to_note` wrote. The type and mime come from the input+ * when `set_note_content` changes them, otherwise from the note, so nothing shows until froca has it.*/-function NoteWrittenContent({ noteId, content, appended }: { noteId: string; content: string; appended: boolean }) {+function NoteWrittenContent({ noteId, content, appended, type, mime }: {+ noteId: string;+ content: string;+ appended: boolean;+ type?: string;+ mime?: string;+}) {const note = useNote(noteId);- if (!note || !hasWrittenContentView(note.type, content)) return null;- return <WrittenContent type={note.type} mime={note.mime} content={content} appended={appended} />;+ if (!note) return null;+ const writtenType = type ?? note.type;+ const writtenMime = mime ?? (writtenType === note.type ? note.mime : undefined);+ if (!hasWrittenContentView(writtenType, content)) return null;+ return <WrittenContent type={writtenType} mime={writtenMime} content={content} appended={appended} />;}function hasWrittenContentView(type: string, content: string): boolean {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 58dcd425b4..3ce947fa92 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@@ -152,6 +152,9 @@ class="admonition note"><ul><li>There are multiple mechanism for the LLM to edit a note: completely byre-writing it, find/replace of a text sequence or append.</li>+ <li>When re-writing a note, the LLM can also change its type (for example+ from a text note to a code note) or the language of a code note, rewriting+ the content to match.</li><li>Whenever the AI makes a change, a <a href="#root/_help_vZWERwf8U3nx">revision</a> issaved to be able to revert any unwanted changes.</li></ul>diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex 37b93c04f8..4824b95130 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -115,6 +115,7 @@ Here are a few tools that Trilium provides for the LLM:* Get the metadata or content of a note.* Edit a note* There are multiple mechanism for the LLM to edit a note: completely by re-writing it, find/replace of a text sequence or append.+ * When re-writing a note, the LLM can also change its type (for example from a text note to a code note) or the language of a code note, rewriting the content to match.* Whenever the AI makes a change, a [revision](Basic%20Concepts%20and%20Features/Notes/Note%20Revisions.md) is saved to be able to revert any unwanted changes.* Create a new note* Rename or delete a note.diff --git a/packages/trilium-core/src/services/llm/tools/helpers.ts b/packages/trilium-core/src/services/llm/tools/helpers.tsindex 703d01e10e..c5190524f3 100644--- a/packages/trilium-core/src/services/llm/tools/helpers.ts+++ b/packages/trilium-core/src/services/llm/tools/helpers.ts@@ -15,6 +15,11 @@ const ATTACHMENT_PREVIEW_MAX_LENGTH = 200;/** Skip expensive content loading/conversion for notes larger than this. */const CONTENT_PREVIEW_SIZE_THRESHOLD = 10_000;+/** Note types the LLM can create or change a note to; each one stores string content. */+export const LLM_NOTE_TYPES = [+ "text", "code", "render", "book", "mermaid", "canvas", "webView", "relationMap", "search", "mindMap"+] as const;+/** Note IDs that must not be deleted, moved, or cloned by the LLM. */export const PROTECTED_SYSTEM_NOTES = new Set(["root", "_hidden", "_share", "_lbRoot", "_globalNoteMap"]);diff --git a/packages/trilium-core/src/services/llm/tools/note_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/note_tools.spec.tsindex afc44e9dd9..7cdfc550e2 100644--- a/packages/trilium-core/src/services/llm/tools/note_tools.spec.ts+++ b/packages/trilium-core/src/services/llm/tools/note_tools.spec.ts@@ -78,6 +78,58 @@ describe("note_tools — write tools return post-write content", () => {const result = getTool("set_note_content").execute({ noteId: "missing", content: "x" });expect(result).toEqual({ error: "Note not found" });});++ it("changes the type along with the content", () => {+ const note = buildNote({ id: "text3", type: "text", mime: "text/html", content: "<pre>print(1)</pre>" });+ withMutableContent(note, "<pre>print(1)</pre>");+ note.save = vi.fn() as typeof note.save;++ const toCode = getTool("set_note_content").execute({+ noteId: "text3", content: "print(1)", type: "code", mime: "text/x-python"+ });+ expect(toCode).toEqual({+ success: true, noteId: "text3", title: note.title,+ type: "code", mime: "text/x-python", content: "print(1)"+ });+ expect(note.setContent).toHaveBeenLastCalledWith("print(1)");+ expect(note.save).toHaveBeenCalled();++ // A code note keeps its mime unless one is given; only the mime can change too.+ const mimeOnly = getTool("set_note_content").execute({+ noteId: "text3", content: "console.log(1)", mime: "text/javascript"+ });+ expect(mimeOnly).toMatchObject({ type: "code", mime: "text/javascript" });++ // Back to text: the content is Markdown again and the mime is the type's default.+ const toText = getTool("set_note_content").execute({+ noteId: "text3", content: "# Heading", type: "text"+ });+ expect(toText).toMatchObject({ type: "text", mime: "text/html" });+ expect(note.setContent).toHaveBeenLastCalledWith(expect.stringContaining("<h2>Heading</h2>"));+ });++ it("requires a mime when a note becomes code, and leaves the note untouched", () => {+ const note = buildNote({ id: "text4", type: "text", mime: "text/html", content: "<p>a</p>" });+ withMutableContent(note, "<p>a</p>");++ const result = getTool("set_note_content").execute({ noteId: "text4", content: "a", type: "code" });++ expect(result).toEqual({ error: "mime is required when changing a note to code" });+ expect(note.type).toBe("text");+ expect(note.setContent).not.toHaveBeenCalled();+ });++ it("omits type and mime from the result when neither changed", () => {+ const note = buildNote({ id: "code4", type: "code", mime: "text/plain", content: "old" });+ withMutableContent(note, "old");++ const result = getTool("set_note_content").execute({+ noteId: "code4", content: "new", type: "code", mime: "text/plain"+ });++ expect(result).not.toHaveProperty("type");+ expect(result).not.toHaveProperty("mime");+ });});describe("append_to_note", () => {diff --git a/packages/trilium-core/src/services/llm/tools/note_tools.ts b/packages/trilium-core/src/services/llm/tools/note_tools.tsindex 0f284b3276..9b980823f6 100644--- a/packages/trilium-core/src/services/llm/tools/note_tools.ts+++ b/packages/trilium-core/src/services/llm/tools/note_tools.ts@@ -4,13 +4,14 @@import becca from "../../../becca/becca.js";import markdownImport from "../../../services/import/markdown.js";+import noteTypesService from "../../../services/note_types.js";import noteService from "../../../services/notes.js";import searchService from "../../../services/search/services/search.js";import SearchContext from "../../../services/search/search_context.js";import TaskContext from "../../../services/task_context.js";import { z } from "zod";-import { applyTextEdits, getContentPreview, getNoteContentForLlm, getNoteMeta, PROTECTED_SYSTEM_NOTES, setNoteContentFromLlm,TOOL_LIMITS } from "./helpers.js";+import { applyTextEdits, getContentPreview, getNoteContentForLlm, getNoteMeta, LLM_NOTE_TYPES, PROTECTED_SYSTEM_NOTES, setNoteContentFromLlm,TOOL_LIMITS } from "./helpers.js";import { defineTools } from "./tool_registry.js";export const noteTools = defineTools({@@ -98,13 +99,21 @@ export const noteTools = defineTools({},set_note_content: {- description: "Replace the ENTIRE content of a note. Only use this for a full rewrite or for rich-text ('text') notes. For small or localized changes to a non-text note, prefer edit_note_content — resending the whole note wastes tokens. For text notes, provide Markdown content. Returns the resulting content; do not call get_note_content afterwards to verify.",+ description: [+ "Replace the ENTIRE content of a note. Only use this for a full rewrite or for rich-text ('text') notes.",+ "For small or localized changes to a non-text note, prefer edit_note_content — resending the whole note wastes tokens.",+ "For text notes, provide Markdown content.",+ "To change a note's type (e.g. text to code) or a code note's language, pass type and/or mime (same values as create_note) along with the content rewritten for the new type — for text to code, only the code itself.",+ "Returns the resulting content; do not call get_note_content afterwards to verify."+ ].join(" "),inputSchema: z.object({noteId: z.string().describe("The ID of the note to update"),- content: z.string().describe("The new content for the note (Markdown for text notes, plain text for code notes)")+ content: z.string().describe("The new content for the note (Markdown for text notes, plain text for code notes)"),+ type: z.enum(LLM_NOTE_TYPES).optional().describe("New note type. Omit to keep the current type."),+ mime: z.string().optional().describe("New MIME type, REQUIRED when changing a note to code (e.g. 'text/x-python'). Omit to keep a code note's current mime.")}),mutates: true,- execute: ({ noteId, content }) => {+ execute: ({ noteId, content, type, mime }) => {const note = becca.getNote(noteId);if (!note) {return { error: "Note not found" };@@ -116,12 +125,29 @@ export const noteTools = defineTools({return { error: `Cannot update content for note type: ${note.type}` };}+ const newType = type ?? note.type;+ const typeChanged = newType !== note.type;+ let newMime = mime ?? note.mime;+ if (typeChanged && !mime) {+ newMime = newType === "code" ? "" : noteTypesService.getDefaultMimeForNoteType(newType);+ }+ if (!newMime) {+ return { error: "mime is required when changing a note to code" };+ }+ const mimeChanged = newMime !== note.mime;+note.saveRevision({ source: "llm" });+ if (typeChanged || mimeChanged) {+ note.type = newType;+ note.mime = newMime;+ note.save();+ }setNoteContentFromLlm(note, content);return {success: true,noteId: note.noteId,title: note.getTitleOrProtected(),+ ...(typeChanged || mimeChanged ? { type: note.type, mime: note.mime } : {}),content: getNoteContentForLlm(note)};}@@ -255,7 +281,7 @@ export const noteTools = defineTools({parentNoteId: z.string().describe("The ID of the parent note. Use 'root' for top-level notes."),title: z.string().describe("The title of the new note"),content: z.string().describe("The content of the note (Markdown for text notes, plain text for code notes, empty string for render notes)"),- type: z.enum(["text", "code", "render", "book", "mermaid", "canvas", "webView", "relationMap", "search", "mindMap"]).describe("The type of note to create."),+ type: z.enum(LLM_NOTE_TYPES).describe("The type of note to create."),mime: z.string().optional().describe("MIME type, REQUIRED for code notes (e.g. 'application/javascript;env=backend', 'text/jsx'). Ignored for other types.")}),mutates: true,