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(ai-assistant): tell the model where in the note it is writing
Elian Doran35c17343bac9
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex 0923ab930c..59d06726de 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -6,6 +6,7 @@ import froca from "../../../services/froca";import link from "../../../services/link";import linkEmbedService, { type EmbedMetadata } from "../../../services/link_embed";import { useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteContext, useSyncedRef, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import type { AiNoteLocation } from "./ai_assistant_stream";import { useAiMenuFooter, useAiQuickActions } from "./ai_quick_actions";import { buildConfig, BuildEditorOptions } from "./config";@@ -103,7 +104,12 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReconst quickActions = useAiQuickActions();const menuFooter = useAiMenuFooter();const [ editor, setEditor ] = useState<CKTextEditor>();- const { parentComponent, ntxId, note } = useNoteContext();+ const { parentComponent, ntxId, note, notePath } = useNoteContext();+ // Which note the assistant says a run is writing into. Kept in a ref for the same reason the+ // snippets are: switching notes reuses the editor rather than rebuilding it, so a captured+ // note would name whichever one happened to be open when the editor was built.+ const noteLocationRef = useRef<AiNoteLocation | null>(null);+ noteLocationRef.current = note ? { title: note.title, notePath } : null;useKeyboardShortcuts("text-detail", containerRef, parentComponent, ntxId);@@ -268,7 +274,8 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReisClassicEditor: !!isClassicEditor,uiLanguage: uiLanguage as DISPLAYABLE_LOCALE_IDS,contentLanguage: contentLanguage ?? null,- templates: templatesRef.current+ templates: templatesRef.current,+ getNoteLocation: () => noteLocationRef.current});if (isStale) {diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.tsindex b2ddda8ae9..923820f922 100644--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.spec.ts@@ -1,7 +1,7 @@// @vitest-environment jsdom// The pipeline ends in DOMPurify, which needs browser-faithful NodeIterator traversal; happy-dom// mishandles it and drops the first node of every fragment. Same reason as sanitize_content.spec.-import type { AiConversationTurn } from "@triliumnext/ckeditor5";+import type { AiConversationTurn, AiSurroundings } from "@triliumnext/ckeditor5";import type { LlmChatConfig } from "@triliumnext/commons";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -36,10 +36,14 @@ vi.mock("../../../services/server.js", () => ({default: { post: vi.fn(async (_url: string, data: { htmlContent: string }) => toMarkdownResult(data.htmlContent)) }}));vi.mock("../../../services/task_states.js", () => ({ getTaskStateDefinitions: async () => [] }));+// The breadcrumb is the tree service's own, resolved out of Froca one ancestor at a time.+vi.mock("../../../services/tree.js", () => ({+ default: { getNotePathTitle: vi.fn(async (notePath: string) => notePathTitle(notePath)) }+}));vi.mock("../../../components/app_context.js", () => ({ default: { triggerCommand: vi.fn() } }));import appContext from "../../../components/app_context.js";-import buildAiAssistantStream, { buildAiAssistantQuickActions, stripMarkdownFences } from "./ai_assistant_stream.js";+import buildAiAssistantStream, { type AiNoteLocation, buildAiAssistantQuickActions, stripMarkdownFences } from "./ai_assistant_stream.js";/** The `llmProviders` option as the mocked `options.getJson` will return it. */let storedProviders: unknown = null;@@ -53,6 +57,8 @@ let requestedMessages: Array<Array<{ role: string; content: string }>> = [];let responseChunks: string[] = ["done"];/** Stands in for `POST other/to-markdown`; throws to exercise the fallback. */let toMarkdownResult: (html: string) => { markdownContent: string } = () => ({ markdownContent: "teh" });+/** Stands in for the tree service's breadcrumb; throws to exercise the fallback. */+let notePathTitle: (notePath: string) => string = (notePath) => `Root › ${notePath}`;const PROVIDER = [{ id: "cfg-openai", provider: "openai", selectedModels: [{ id: "gpt-5", isDefault: true }] }];@@ -63,23 +69,36 @@ beforeEach(() => {requestedMessages = [];responseChunks = ["done"];toMarkdownResult = () => ({ markdownContent: "teh" });+ notePathTitle = (notePath) => `Root › ${notePath}`;});+/** What a run carries besides the content: the conversation, the note, and what surrounds it. */+interface RunOptions {+ history?: AiConversationTurn[];+ surroundings?: AiSurroundings;+ note?: AiNoteLocation | null;+}+/** Runs one completion through the built stream, collecting everything handed to `onData`. */-async function run(context = "<p>teh</p>", history: AiConversationTurn[] = []): Promise<{+async function run(context = "<p>teh</p>", opts: RunOptions = {}): Promise<{config: LlmChatConfig;prompt: string;messages: Array<{ role: string; content: string }>;rendered: string[];sources: string[];}> {- const stream = buildAiAssistantStream();+ const stream = buildAiAssistantStream(opts.note !== undefined ? () => opts.note ?? null : undefined);if (!stream) {throw new Error("expected the assistant to be enabled");}const rendered: string[] = [];const sources: string[] = [];- await stream({ query: "Fix typos", context, history }, (html, source) => {+ await stream({+ query: "Fix typos",+ context,+ surroundings: opts.surroundings ?? { before: "", after: "" },+ history: opts.history ?? []+ }, (html, source) => {rendered.push(html);sources.push(source ?? "");}, new AbortController().signal);@@ -226,6 +245,84 @@ describe("the Markdown pipeline", () => {});});+// A selection alone leaves the model writing into a document it cannot see; the note it sits in+// and the text either side of it are what place the answer, without a line of retrieval.+describe("where the run is writing", () => {+ beforeEach(() => {+ storedProviders = PROVIDER;+ });++ it("opens with the note's breadcrumb and the text around the content", async () => {+ toMarkdownResult = () => ({ markdownContent: "the target" });++ const { prompt } = await run("<p>the target</p>", {+ note: { title: "Meeting notes", notePath: "abc123" },+ surroundings: { before: "A heading\nBefore it", after: "After it" }+ });++ expect(prompt).toBe([+ "Note: Root › abc123",+ "Text before the content (context only):\nA heading\nBefore it",+ "Text after the content (context only):\nAfter it",+ "Content:\nthe target",+ "Task: Fix typos"+ ].join("\n\n"));+ });++ // The whole point of naming the sections: the model has to place the answer without touching+ // them.+ it("tells the model the background is not its to rewrite", async () => {+ const { messages } = await run();+ expect(messages[0].role).toBe("system");+ expect(messages[0].content).toContain("never rewrite, repeat or answer them");+ });++ it("names the cursor rather than the content when generating from scratch", async () => {+ const { prompt } = await run("", {+ note: { title: "Meeting notes" },+ surroundings: { before: "Before it", after: "" }+ });++ // There is no "Content" section for it to be before, and saying otherwise would name+ // something the model was never shown.+ expect(prompt).toBe("Note: Meeting notes\n\nText before the cursor (context only):\nBefore it\n\nTask: Fix typos");+ });++ it("names the note by its title alone when it has no path", async () => {+ expect((await run("", { note: { title: "Meeting notes" } })).prompt)+ .toBe("Note: Meeting notes\n\nTask: Fix typos");+ });++ // Nothing to place it against — an instruction typed into an empty note by a host that names+ // none — so it goes as it was typed rather than as the sole entry of a form.+ it("sends the instruction bare when there is nothing to place it against", async () => {+ expect((await run("", { note: null })).prompt).toBe("Fix typos");+ });++ it("falls back to the title when the breadcrumb cannot be resolved", async () => {+ notePathTitle = () => { throw new Error("gone"); };+ vi.spyOn(console, "warn").mockImplementation(() => {});++ const { prompt } = await run("", { note: { title: "Meeting notes", notePath: "abc123" } });+ expect(prompt).toBe("Note: Meeting notes\n\nTask: Fix typos");+ });++ // The note has not changed under the assistant, and the answers to it are in the transcript.+ it("places only the opening turn, leaving the follow-ups bare", async () => {+ const { messages } = await run("<p>the target</p>", {+ note: { title: "Meeting notes" },+ surroundings: { before: "Before it", after: "" },+ history: [+ { role: "user", content: "Translate to German" },+ { role: "assistant", content: "Guten Tag" }+ ]+ });++ expect(messages[1].content).toContain("Note: Meeting notes");+ expect(messages[3].content).toBe("Fix typos");+ });+});+describe("the conversation", () => {const fence = "\u0060\u0060\u0060";@@ -248,10 +345,12 @@ describe("the conversation", () => {it("sends the exchanges so far, with only the opening turn carrying the content", async () => {toMarkdownResult = (html) => ({ markdownContent: html + " as markdown" });- const { messages } = await run("<p>teh</p>", [- { role: "user", content: "Translate to German" },- { role: "assistant", content: "Guten Tag" }- ]);+ const { messages } = await run("<p>teh</p>", {+ history: [+ { role: "user", content: "Translate to German" },+ { role: "assistant", content: "Guten Tag" }+ ]+ });expect(messages.map((message) => message.role)).toEqual(["system", "user", "assistant", "user"]);expect(messages[1].content).toBe("Content:\n<p>teh</p> as markdown\n\nTask: Translate to German");@@ -261,10 +360,12 @@ describe("the conversation", () => {});it("leaves the turns bare when the conversation started from scratch", async () => {- const { messages } = await run("", [- { role: "user", content: "Write a haiku" },- { role: "assistant", content: "an old silent pond" }- ]);+ const { messages } = await run("", {+ history: [+ { role: "user", content: "Write a haiku" },+ { role: "assistant", content: "an old silent pond" }+ ]+ });expect(messages.slice(1).map((message) => message.content)).toEqual(["Write a haiku", "an old silent pond", "Fix typos"]);diff --git a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.tsindex b2f3096b8a..b9b281c665 100644--- a/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_assistant_stream.ts@@ -9,8 +9,19 @@ import options from "../../../services/options.js";import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";import server from "../../../services/server.js";import { getTaskStateDefinitions } from "../../../services/task_states.js";+import treeService from "../../../services/tree.js";import { pickModel } from "./ai_model_picker.js";+/** The note an editor is open on, as much of it as placing a run in the tree needs. */+export interface AiNoteLocation {+ title: string;+ /** Where it sits, for the ancestor titles a bare title cannot give. */+ notePath?: string | null;+}++/** Names the note an editor is open on, at the moment a run asks — see `buildAiAssistantStream`. */+export type AiNoteLocationProvider = () => AiNoteLocation | null;+/*** Builds the transport behind the editor's AI assistant (`config.aiAssistant.stream`): a* completion streamed from the user's default LLM provider through the existing@@ -25,20 +36,25 @@ import { pickModel } from "./ai_model_picker.js";* Returns `undefined` when no LLM provider is configured, which disables the feature in the* editor. Like the snippet list, the provider set is read when the editor is built — configuring* a first provider shows the button after the editor is next rebuilt.+ *+ * @param getNoteLocation names the note being edited, so a run can say where in Trilium it is+ * writing. Read per request rather than captured: switching notes reuses+ * the editor rather than rebuilding it.*/-export default function buildAiAssistantStream(): AiStreamFunction | undefined {+export default function buildAiAssistantStream(getNoteLocation?: AiNoteLocationProvider): AiStreamFunction | undefined {if (!readSelectedModels().hasProvider) {return undefined;}return async (request, onData, signal): Promise<AiCompletionUsage> => {- // Both are needed before the first token and neither depends on the other.- const [context, renderMarkdown] = await Promise.all([+ // All three are needed before the first token and none depends on the others.+ const [context, renderMarkdown, note] = await Promise.all([toMarkdown(request.context),- loadMarkdownRenderer()+ loadMarkdownRenderer(),+ describeNote(getNoteLocation?.() ?? null)]);- const messages = buildMessages(request, context);+ const messages = buildMessages(request, context, note);const config = pickModel();let cumulative = "";const usage = await new Promise<LlmUsage | null>((resolve, reject) => {@@ -347,6 +363,7 @@ The user gives you a task, usually together with the Markdown of the content itRules:- Respond ONLY with the resulting Markdown. No explanations, no preamble, no code fence around the answer.+- The task may come with the note it was given in: its title, and the text before and after the content. Those are there to place the content — write so that the answer fits in with them, but never rewrite, repeat or answer them. Only the content under "Content" is yours to work on.- GitHub-flavoured Markdown is supported: headings, tables, footnotes and task lists (\`- [ ]\`).- \`> [!NOTE]\`, \`> [!TIP]\`, \`> [!IMPORTANT]\`, \`> [!CAUTION]\` and \`> [!WARNING]\` render as coloured callouts.- A \`mermaid\` code block renders as a diagram.@@ -357,24 +374,80 @@ Rules:* The conversation as the provider takes it: the system prompt, the exchanges so far, and the new* instruction last.*- * Only the opening turn carries the content, because it is the same content for the whole- * conversation and the answers to it are in the transcript. That is what makes a follow-up a- * follow-up: "now make it shorter" after "translate this to German" reaches a model that can still- * see it was asked for German, instead of one handed German text and a bare request to shorten it.+ * Only the opening turn carries the content and its surroundings, because they are the same for+ * the whole conversation and the answers to them are in the transcript. That is what makes a+ * follow-up a follow-up: "now make it shorter" after "translate this to German" reaches a model+ * that can still see German was asked for, instead of one handed German text and a bare request+ * to shorten it.*/-function buildMessages(request: AiCompletionRequest, context: string): LlmMessage[] {+function buildMessages(request: AiCompletionRequest, context: string, note: string): LlmMessage[] {const turns: AiConversationTurn[] = [...request.history, { role: "user", content: request.query }];return [{ role: "system", content: SYSTEM_PROMPT },...turns.map((turn, index) => ({role: turn.role,- content: index === 0 && context- ? `Content:\n${context}\n\nTask: ${turn.content}`+ content: index === 0+ ? buildOpeningTurn(request, context, note, turn.content): turn.content}))];}+/**+ * The turn a conversation opens with: where in Trilium the note sits, what surrounds the content+ * there, the content itself and the instruction — each section named, and only the ones with+ * anything in them.+ *+ * The point of the first three is that a selection says nothing about where it is: asked to+ * continue a paragraph or to summarize under a heading, a model shown the selection alone is+ * writing into a document it cannot see. The instruction goes last, where it is not read as a+ * remark about the background above it.+ */+function buildOpeningTurn(request: AiCompletionRequest, context: string, note: string, query: string): string {+ const { before, after } = request.surroundings;+ // What the surroundings surround: a run with no content generates at the caret, and "before+ // the content" would be naming something the model was never shown.+ const anchor = context ? "the content" : "the cursor";+ const sections: string[] = [];++ if (note) {+ sections.push(`Note: ${note}`);+ }+ if (before) {+ sections.push(`Text before ${anchor} (context only):\n${before}`);+ }+ if (after) {+ sections.push(`Text after ${anchor} (context only):\n${after}`);+ }+ if (context) {+ sections.push(`Content:\n${context}`);+ }++ // Nothing to place it against — an instruction into an empty note — so it is sent as it was+ // typed, rather than as the sole entry of a form.+ return sections.length ? [...sections, `Task: ${query}`].join("\n\n") : query;+}++/**+ * Where the note being edited sits, as one line: its ancestors and its own title, joined the way+ * every other breadcrumb in Trilium is. Reuses the tree service's own resolver rather than walking+ * Froca here, so a hoisted or cloned note reads the same as it does in the title bar.+ *+ * A note whose path cannot be resolved is named by its title alone, which is the part that matters;+ * a caller that names no note at all leaves the section out.+ */+async function describeNote(location: AiNoteLocation | null): Promise<string> {+ if (!location?.notePath) {+ return location?.title ?? "";+ }+ try {+ return await treeService.getNotePathTitle(location.notePath);+ } catch (error) {+ console.warn("AI assistant: could not resolve the note path", error);+ return location.title;+ }+}+/*** The selection, as Markdown for the model. The conversion is the server's: turndown and the rules* that keep admonitions, `<details>`, math and reference links intact live in `trilium-core`, whichdiff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 14ccbec055..c86d445ccf 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -19,7 +19,11 @@ const catalogState = vi.hoisted(() => ({bundle: undefined as Record<string, unknown> | undefined,entries: {} as Record<string, string>}));-vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => catalogState.entries[key] ?? key }));+vi.mock("../../../services/i18n.js", () => ({+ t: (key: string) => catalogState.entries[key] ?? key,+ // Read while the AI assistant's Translate submenu is built, which every config goes through.+ getAvailableLocales: () => []+}));vi.mock("i18next", () => ({default: {// i18next binds `getResourceBundle` in `init()`, so it is absent until the app has booted —diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 868b6c155d..3ad70a9aea 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -16,7 +16,7 @@ import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../serimport { isMac } from "../../../services/utils.js";import { resolveContentLanguage } from "../../../utils/formatters.js";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";-import buildAiAssistantStream, { buildAiAssistantQuickActions } from "./ai_assistant_stream.js";+import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";import diffAiResponse from "./ai_diff.js";import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";@@ -33,6 +33,12 @@ export interface BuildEditorOptions {uiLanguage: DISPLAYABLE_LOCALE_IDS;contentLanguage: string | null;templates: SnippetDefinition[];+ /**+ * Names the note the editor is open on, for the AI assistant to say where a run is writing.+ * A getter rather than the note itself: switching notes reuses the editor, so anything captured+ * here would name the note that happened to be open when it was built.+ */+ getNoteLocation?: AiNoteLocationProvider;}export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {@@ -193,7 +199,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi},aiAssistant: {// `undefined` when no LLM provider is configured, which disables the feature.- stream: buildAiAssistantStream(),+ stream: buildAiAssistantStream(opts.getNoteLocation),// The "Changes" review view: a block-aware inline diff, so that a response which// rewrote a paragraph rather than editing it reads as a replacement instead of as// shredded `<ins>`/`<del>` pairs.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 3302d54f76..4d603a19dd 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -17,7 +17,7 @@ export type { TriliumMentionFeed } from "./plugins/mention/types.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";-export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiConversationTurn, AiDiffFunction, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView, AiSanitizeFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";+export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, AiConversationTurn, AiDiffFunction, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView, AiSanitizeFunction, AiStreamCallback, AiStreamFunction, AiSurroundings } from "./plugins/ai_assistant/ai_assistant_config.js";export { default as getCkLocale, registerCkTranslations } from "./i18n.js";export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";export * from "./utils.js";diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex 064435f08c..2e6fc4c705 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -11,6 +11,22 @@ export interface AiConversationTurn {content: string;}+/**+ * The rest of the note around the content a conversation opened on, as plain text.+ *+ * The assistant works on a selection, but a selection says nothing about where it sits: asked to+ * continue a paragraph, or to summarize under a heading, a model that can see only the selected+ * text is guessing at the document it is writing into. Plain text rather than the HTML the+ * selection is sent as, because this is for orientation and never for rewriting — the words are+ * what place it, and the markup would cost more than it says.+ */+export interface AiSurroundings {+ /** The note's text before the target, ending where the target begins. */+ before: string;+ /** The note's text after the target. */+ after: string;+}+/*** A single completion request made by the AI assistant.*/@@ -26,6 +42,12 @@ export interface AiCompletionRequest {*/context: string;+ /**+ * What surrounds {@link context} in the note, captured with it and just as unchanging: a+ * follow-up is still writing into the same place.+ */+ surroundings: AiSurroundings;+/*** The exchanges before this one, oldest first, alternating user and assistant; empty on the* first request of a conversation. What makes a follow-up a turn in a conversation rather thandiff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.tsindex c298f85b58..23ab9addac 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts@@ -47,6 +47,9 @@ interface QuickActionsDropdown {};}+/** What a target with nothing around it in the note sends. */+const NO_SURROUNDINGS = { before: "", after: "" };+const QUICK_ACTIONS: AiQuickActionGroup[] = [{id: "edit",@@ -414,7 +417,7 @@ describe("AiAssistantUI toolbar entry", () => {setModelData(editor.model, "<paragraph>[foo]</paragraph>");quickActionButtons(dropdown).find((button) => button.id === "japanese")?.fire("execute");await vi.waitFor(() => expect(requests).toHaveLength(1));- expect(requests[0]).toEqual({ query: "Translate to Japanese.", context: "foo", history: [] });+ expect(requests[0]).toEqual({ query: "Translate to Japanese.", context: "foo", surroundings: NO_SURROUNDINGS, history: [] });});// What a run answers to rather than an instruction for one — Trilium hangs the model picker@@ -538,7 +541,7 @@ describe("AiAssistantUI toolbar entry", () => {direct?.fire("execute");await vi.waitFor(() => expect(requests).toHaveLength(1));- expect(requests[0]).toEqual({ query: "Make it direct.", context: "foo", history: [] });+ expect(requests[0]).toEqual({ query: "Make it direct.", context: "foo", surroundings: NO_SURROUNDINGS, history: [] });});it("falls back to the caret's block when nothing is selected", async () => {@@ -548,7 +551,7 @@ describe("AiAssistantUI toolbar entry", () => {fixTypos.fire("execute");await vi.waitFor(() => expect(requests).toHaveLength(1));- expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "second", history: [] });+ expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "second", surroundings: { before: "first", after: "" }, history: [] });});it("keeps a free-form prompt at a collapsed caret generating from scratch", async () => {@@ -560,7 +563,7 @@ describe("AiAssistantUI toolbar entry", () => {form.fire("submit");await vi.waitFor(() => expect(requests).toHaveLength(1));- expect(requests[0]).toEqual({ query: "Write a haiku.", context: "", history: [] });+ expect(requests[0]).toEqual({ query: "Write a haiku.", context: "", surroundings: { before: "foo", after: "" }, history: [] });});it("runs the picked action against the selection and opens the dialog on it", async () => {@@ -570,7 +573,7 @@ describe("AiAssistantUI toolbar entry", () => {fixTypos.fire("execute");await vi.waitFor(() => expect(requests).toHaveLength(1));- expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "foo", history: [] });+ expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "foo", surroundings: NO_SURROUNDINGS, history: [] });const dialog = editor.plugins.get(Dialog);expect(dialog.isOpen).toBe(true);@@ -660,6 +663,85 @@ describe("AiAssistantUI toolbar entry", () => {});});+ // A selection says nothing about where in the note it sits, and "continue this" or "summarize+ // this" read differently under a heading than they do in an opening paragraph.+ describe("the note around the target", () => {+ let editor: ClassicEditor;+ let dropdown: QuickActionsDropdown;+ let requests: AiCompletionRequest[];++ beforeEach(async () => {+ const stub = createStreamStub();+ requests = stub.requests;+ editor = await createEditor(QUICK_ACTIONS, stub.stream);+ dropdown = createComponent(editor);+ });++ /** Runs the first quick action and hands back what it sent as the target's surroundings. */+ async function surroundingsOf(data: string) {+ const expected = requests.length + 1;+ setModelData(editor.model, data);+ quickActionButtons(dropdown)[0].fire("execute");+ await vi.waitFor(() => expect(requests).toHaveLength(expected));+ return requests[expected - 1].surroundings;+ }++ it("sends the text either side of it, one line per block", async () => {+ expect(await surroundingsOf([+ "<paragraph>A heading</paragraph>",+ "<paragraph>Before it</paragraph>",+ "<paragraph>[the target]</paragraph>",+ "<paragraph>After it</paragraph>"+ ].join(""))).toEqual({ before: "A heading\nBefore it", after: "After it" });+ });++ it("splits at the caret when there is no selection to work on", async () => {+ // The quick action widens a collapsed caret to its block, so the block being rewritten+ // is the target and belongs to neither side.+ expect(await surroundingsOf("<paragraph>one</paragraph><paragraph>t[]wo</paragraph><paragraph>three</paragraph>"))+ .toEqual({ before: "one", after: "three" });+ });++ it("sends nothing around a target that is the whole note", async () => {+ expect(await surroundingsOf("<paragraph>[all of it]</paragraph>")).toEqual(NO_SURROUNDINGS);+ });++ it("keeps the end nearest the target when the note is longer than the limit", async () => {+ // Numbered lines of a hundred characters each, so that only the last dozen or so of+ // the forty either side can fit in what a run sends.+ const line = (marker: string, index: number) => `${marker}${index}`.padEnd(100, ".");+ const filler = (marker: string) => Array.from({ length: 40 },+ (_, index) => `<paragraph>${line(marker, index)}</paragraph>`).join("");++ const { before, after } = await surroundingsOf(+ `${filler("b")}<paragraph>[the target]</paragraph>${filler("a")}`);++ // Whole lines only, and the ones closest to the target: the paragraph just above the+ // selection says far more about it than the note's first one does.+ expect(before.split("\n").at(-1)).toBe(line("b", 39));+ expect(before).not.toContain(line("b", 0));+ expect(after.split("\n").at(0)).toBe(line("a", 0));+ expect(after).not.toContain(line("a", 39));+ for (const side of [before, after]) {+ expect(side.length).toBeLessThanOrEqual(1500);+ expect(side.split("\n").every((entry) => /^[ab]\d+\.*$/.test(entry))).toBe(true);+ }+ });++ it("stays with the conversation it was captured for, and goes when it closes", async () => {+ await surroundingsOf("<paragraph>one</paragraph><paragraph>[two]</paragraph>");++ const form = openForm(editor);+ form.query = "now make it shorter";+ form.fire("submit");+ await vi.waitFor(() => expect(requests).toHaveLength(2));+ expect(requests[1].surroundings).toEqual({ before: "one", after: "" });++ editor.plugins.get(Dialog).hide();+ expect(await surroundingsOf("<paragraph>[nothing around it]</paragraph>")).toEqual(NO_SURROUNDINGS);+ });+ });+// A follow-up is a turn in a conversation rather than a fresh instruction about the last// answer: asked to translate and then to shorten, the model has to still see that the first// instruction was German, or it shortens the German back into English.@@ -703,6 +785,7 @@ describe("AiAssistantUI toolbar entry", () => {// The selection, still: what has been said about it is on the record instead of// being restated as the thing to work on.context: "foo",+ surroundings: NO_SURROUNDINGS,history: [{ role: "user", content: "Fix all mistakes." },{ role: "assistant", content: "Guten Tag" }@@ -748,7 +831,7 @@ describe("AiAssistantUI toolbar entry", () => {fixTypos.fire("execute");await vi.waitFor(() => expect(requests).toHaveLength(2));- expect(requests[1]).toEqual({ query: "Fix all mistakes.", context: "bar", history: [] });+ expect(requests[1]).toEqual({ query: "Fix all mistakes.", context: "bar", surroundings: NO_SURROUNDINGS, history: [] });});it("records the delivered HTML for a host that reports no source", async () => {diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex 5058ace1b7..9dcc3066c2 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -18,7 +18,7 @@ import {} from "ckeditor5";import { extractDelimiters, renderEquation } from "../math/utils.js";-import type { AiCompletionUsage, AiConversationTurn, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView } from "./ai_assistant_config.js";+import type { AiCompletionUsage, AiConversationTurn, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView, AiSurroundings } from "./ai_assistant_config.js";import AiAssistantEditing, { AI_TARGET_MARKER } from "./ai_assistant_editing.js";import AiAssistantFormView from "./ai_assistant_form.js";import aiIcon from "./theme/icons/ai.svg?raw";@@ -50,6 +50,17 @@ const MENU_FOOTER_ID = "__footer";*/const REWRITE_RATIO_THRESHOLD = 0.5;+/**+ * How much of the note either side of the target is sent as surroundings. Enough for the section+ * the target sits in, which is what places it; a note long enough to overrun this is one whose+ * distant paragraphs say nothing about the sentence being rewritten, and the assistant is not a+ * retrieval engine — it should not quietly turn every run into a whole-note upload.+ */+const SURROUNDINGS_LIMIT = 1500;++/** What a run with nothing around it sends, and what the plugin holds while it is closed. */+const EMPTY_SURROUNDINGS: AiSurroundings = { before: "", after: "" };+/*** The AI assistant's UI and orchestration: the toolbar entry (a split button whose menu holds the* host's quick actions), the dialog form, and the stream-preview-commit lifecycle.@@ -99,6 +110,8 @@ export default class AiAssistantUI extends Plugin {private _cumulativeSource = "";/** The HTML the conversation opened on, sent with every request it makes. */private _openingContext = "";+ /** What surrounds it in the note, captured with it and sent alongside it. */+ private _surroundings: AiSurroundings = EMPTY_SURROUNDINGS;/*** The HTML each response is measured against: the selection, then each response chained on.* What a run *asks* about is {@link _openingContext} plus {@link _history} — this is what the@@ -530,6 +543,7 @@ export default class AiAssistantUI extends Plugin {? "": editor.data.stringify(model.getSelectedContent(model.createSelection(range)));this._openingContext = this._context;+ this._surroundings = this._captureSurroundings(range);this._previousContext = this._context;this._history = [];this._previousHistory = [];@@ -662,7 +676,12 @@ export default class AiAssistantUI extends Plugin {let usage: AiCompletionUsage | null = null;try {usage = (await stream(- { query, context: this._openingContext, history: this._history },+ {+ query,+ context: this._openingContext,+ surroundings: this._surroundings,+ history: this._history+ },onData,abortController.signal)) ?? null;@@ -931,6 +950,7 @@ export default class AiAssistantUI extends Plugin {// would leave them enabled over a closed assistant that has nothing to work on.this._context = "";this._openingContext = "";+ this._surroundings = EMPTY_SURROUNDINGS;this._previousContext = "";// The conversation was the dialog's: the next one opens on a fresh selection, with nothing// the model should still be answering in the light of.@@ -963,6 +983,54 @@ export default class AiAssistantUI extends Plugin {this.hasContext = !!this._context || (!!range && !range.isCollapsed);}+ /**+ * The rest of the note either side of the target, as plain text — what tells the model where in+ * the note it is writing. A selection alone does not: "continue this" and "summarize this" both+ * read differently under a heading than they do in a note's opening paragraph.+ *+ * Captured once, with the context, and unchanged for the conversation: the document is not+ * modified until a response is committed, and a commit closes the assistant.+ */+ private _captureSurroundings(target: ModelRange | null): AiSurroundings {+ const model = this.editor.model;+ const root = model.document.getRoot();+ /* v8 ignore next 3 -- the target always resolves, and an editor always has a main root */+ if (!target || !root) {+ return EMPTY_SURROUNDINGS;+ }++ const before = model.createRange(model.createPositionAt(root, 0), target.start);+ const after = model.createRange(target.end, model.createPositionAt(root, "end"));+ return {+ // Each side keeps the part nearest the target: the paragraph just above the selection+ // says far more about it than the note's first one does.+ before: clampText(this._plainText(before), "end"),+ after: clampText(this._plainText(after), "start")+ };+ }++ /**+ * A range of the document as plain text, one line per block. Blocks are what the model has to+ * see — that a heading opens the passage, that the lines around it are list items — and the+ * markup carrying them is worth nothing to content nobody is asking it to rewrite.+ */+ private _plainText(range: ModelRange): string {+ const schema = this.editor.model.schema;+ let text = "";++ for (const { type, item } of range.getWalker()) {+ if (item.is("$textProxy")) {+ text += item.data;+ } else if (type === "elementEnd" && item.is("element") && schema.isBlock(item)) {+ text += "\n";+ }+ }++ // A range that starts or ends inside a block leaves that block's own line unclosed, and+ // nested blocks close one line per level; neither is worth showing as a blank line.+ return text.replace(/\n{2,}/g, "\n").trim();+ }+/*** The range a run works on: the selection, or — for a quick action at a collapsed caret — the* block it sits in, so "Fix typos" typed into a paragraph rewrites that paragraph. It is both@@ -983,6 +1051,30 @@ export default class AiAssistantUI extends Plugin {}}+/**+ * Trims one side of the surroundings to {@link SURROUNDINGS_LIMIT}, keeping the end nearest the+ * target and cutting on a line break so the model is never handed half a sentence as if it were a+ * whole one.+ *+ * @param keep which end survives: `"end"` for the text before the target, `"start"` for the text+ * after it.+ */+function clampText(text: string, keep: "start" | "end"): string {+ if (text.length <= SURROUNDINGS_LIMIT) {+ return text;+ }++ if (keep === "start") {+ const cut = text.slice(0, SURROUNDINGS_LIMIT);+ const lastBreak = cut.lastIndexOf("\n");+ return (lastBreak > 0 ? cut.slice(0, lastBreak) : cut).trimEnd();+ }++ const cut = text.slice(-SURROUNDINGS_LIMIT);+ const firstBreak = cut.indexOf("\n");+ return (firstBreak >= 0 ? cut.slice(firstBreak + 1) : cut).trimStart();+}+/*** Puts a font icon in front of a menu button's label. The menu definition has no icon field and* CKEditor builds these views itself, so the glyph is added to the button's children afterwards —