Skip to content

Build your personal knowledge base with Trilium Notes

feat(ai-assistant): make a follow-up a turn in the conversation

Elian Doran54165f0770c2
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.ts
index 0b17689e18..b2ddda8ae9 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,6 +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 { LlmChatConfig } from "@triliumnext/commons";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -65,17 +66,30 @@ beforeEach(() => {
});
/** Runs one completion through the built stream, collecting everything handed to `onData`. */
-async function run(context = "<p>teh</p>"): Promise<{ config: LlmChatConfig; prompt: string; rendered: string[] }> {
+async function run(context = "<p>teh</p>", history: AiConversationTurn[] = []): Promise<{
+ config: LlmChatConfig;
+ prompt: string;
+ messages: Array<{ role: string; content: string }>;
+ rendered: string[];
+ sources: string[];
+}> {
const stream = buildAiAssistantStream();
if (!stream) {
throw new Error("expected the assistant to be enabled");
}
const rendered: string[] = [];
- await stream({ query: "Fix typos", context }, (html) => rendered.push(html), new AbortController().signal);
+ const sources: string[] = [];
+ await stream({ query: "Fix typos", context, history }, (html, source) => {
+ rendered.push(html);
+ sources.push(source ?? "");
+ }, new AbortController().signal);
+ const messages = requestedMessages[0] ?? [];
return {
config: requestedConfigs[0],
- prompt: requestedMessages[0]?.find((message) => message.role === "user")?.content ?? "",
- rendered
+ prompt: messages.find((message) => message.role === "user")?.content ?? "",
+ messages,
+ rendered,
+ sources
};
}
@@ -212,6 +226,51 @@ describe("the Markdown pipeline", () => {
});
});
+describe("the conversation", () => {
+ const fence = "\u0060\u0060\u0060";
+
+ beforeEach(() => {
+ storedProviders = PROVIDER;
+ });
+
+ // What the editor records as the assistant's turn, so that a follow-up hands the model back
+ // its own Markdown rather than our rendering of it — stripped exactly as the preview shows it.
+ it("reports the Markdown each render was made from", async () => {
+ responseChunks = [fence + "markdown\n**bo", "ld**\n" + fence];
+
+ const { sources, rendered } = await run();
+ expect(sources).toEqual(["**bo", "**bold**\n"]);
+ expect(rendered.at(-1)).toContain("<strong>bold</strong>");
+ });
+
+ // The instruction behind an answer stays on the record, so "make it shorter" after a
+ // translation shortens the translation instead of quietly undoing it.
+ 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" }
+ ]);
+
+ 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");
+ expect(messages[2].content).toBe("Guten Tag");
+ // The new instruction alone: what it applies to is the answer above it.
+ expect(messages[3].content).toBe("Fix typos");
+ });
+
+ 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" }
+ ]);
+
+ expect(messages.slice(1).map((message) => message.content))
+ .toEqual(["Write a haiku", "an old silent pond", "Fix typos"]);
+ });
+});
+
describe("stripMarkdownFences", () => {
const fence = "\u0060\u0060\u0060";
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.ts
index 8636f71cda..b2f3096b8a 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
@@ -1,4 +1,4 @@
-import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";
+import type { AiCompletionRequest, AiCompletionUsage, AiConversationTurn, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";
import { getEnglishName, type LlmMessage, type LlmUsage, type Locale, type ToMarkdownResponse } from "@triliumnext/commons";
import appContext from "../../../components/app_context.js";
@@ -38,16 +38,7 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
loadMarkdownRenderer()
]);
- const messages: LlmMessage[] = [
- { role: "system", content: SYSTEM_PROMPT },
- {
- role: "user",
- content: context
- ? `Content:\n${context}\n\nTask: ${request.query}`
- : request.query
- }
- ];
-
+ const messages = buildMessages(request, context);
const config = pickModel();
let cumulative = "";
const usage = await new Promise<LlmUsage | null>((resolve, reject) => {
@@ -55,7 +46,11 @@ export default function buildAiAssistantStream(): AiStreamFunction | undefined {
streamChatCompletion(messages, config, {
onChunk: (text) => {
cumulative += text;
- onData(renderMarkdown(cumulative));
+ // The wrapper fence comes off here rather than inside the renderer: the
+ // stripped Markdown is both what the preview shows and what the assistant
+ // hands back as this turn when the user follows up on it.
+ const markdown = stripMarkdownFences(cumulative);
+ onData(renderMarkdown(markdown), markdown);
},
onUsage: (chunk) => {
reported = chunk;
@@ -358,6 +353,28 @@ Rules:
- When rewriting content, preserve its structure and formatting unless the task says otherwise.
- Respond in the same language as the content, unless the task says otherwise.`;
+/**
+ * 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.
+ */
+function buildMessages(request: AiCompletionRequest, context: 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}`
+ : turn.content
+ }))
+ ];
+}
+
/**
* 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`, which
@@ -393,7 +410,7 @@ async function loadMarkdownRenderer(): Promise<(markdown: string) => string> {
getTaskStateDefinitions()
]);
- return (markdown) => renderToHtml(stripMarkdownFences(markdown), "", {
+ return (markdown) => renderToHtml(markdown, "", {
sanitize: sanitizeNoteContentHtml,
taskStates,
wikiLink: { formatHref: (id) => `#root/${id}` }
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 27a3ba7262..3302d54f76 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, 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 } 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.ts
index 50e57811d9..064435f08c 100644
--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts
@@ -1,3 +1,16 @@
+/**
+ * One exchange of an assistant conversation, as {@link AiCompletionRequest.history} carries it.
+ */
+export interface AiConversationTurn {
+ role: "user" | "assistant";
+ /**
+ * What was said: the instruction, for a user turn; for an assistant turn, the response in the
+ * source form the host reported it in ({@link AiStreamCallback}'s `source`), or the HTML it
+ * delivered when it reported none.
+ */
+ content: string;
+}
+
/**
* A single completion request made by the AI assistant.
*/
@@ -6,18 +19,32 @@ export interface AiCompletionRequest {
query: string;
/**
- * The HTML the instruction applies to (the selection, or on a follow-up query the previous
- * response). Empty when the user generates new content from a collapsed selection.
+ * The HTML the conversation opened on — the selection the assistant was opened over, empty
+ * when the user generates new content from a collapsed selection. It is the same for every
+ * request of a conversation: a follow-up's subject is on the record in {@link history} rather
+ * than restated here.
*/
context: string;
+
+ /**
+ * 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 than
+ * a fresh instruction about the last answer: "translate this to German" then "make it shorter"
+ * only means what it says while the first instruction is still on the record.
+ */
+ history: AiConversationTurn[];
}
/**
* Called with the *cumulative* response HTML every time more of the stream arrives — the same
* contract CKEditor's premium `AITextAdapter` uses. Re-parsing the growing prefix keeps the
* preview renderable at every tick (the HTML parser auto-closes tags cut off mid-stream).
+ *
+ * `source` is what that HTML was rendered from, for a host that renders at all — Trilium's model
+ * answers in Markdown. It is what the response enters {@link AiCompletionRequest.history} as, so a
+ * follow-up hands the model back its own words instead of our rendering of them.
*/
-export type AiStreamCallback = (cumulativeHtml: string) => void;
+export type AiStreamCallback = (cumulativeHtml: string, source?: string) => void;
/**
* What a finished completion cost, shown in the review phase. All fields are optional — whatever
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts
index b225897e52..c298f85b58 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
@@ -90,12 +90,17 @@ const QUICK_ACTIONS: AiQuickActionGroup[] = [
*/
const sanitizeHtml = (html: string) => html;
-/** The requests handed to the stream, in order, plus the stub itself. */
-function createStreamStub(response = "<p>done</p>") {
+/**
+ * The requests handed to the stream, in order, plus the stub itself.
+ *
+ * @param source what a host that renders its responses would report the HTML was rendered from —
+ * omitted by one that streams HTML outright, which is delivered as its own source.
+ */
+function createStreamStub(response = "<p>done</p>", source?: string) {
const requests: AiCompletionRequest[] = [];
const stream: AiStreamFunction = async (request: AiCompletionRequest, onData: AiStreamCallback) => {
requests.push(request);
- onData(response);
+ onData(response, source);
};
return { requests, stream };
}
@@ -409,7 +414,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" });
+ expect(requests[0]).toEqual({ query: "Translate to Japanese.", context: "foo", history: [] });
});
// What a run answers to rather than an instruction for one — Trilium hangs the model picker
@@ -533,7 +538,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" });
+ expect(requests[0]).toEqual({ query: "Make it direct.", context: "foo", history: [] });
});
it("falls back to the caret's block when nothing is selected", async () => {
@@ -543,7 +548,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" });
+ expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "second", history: [] });
});
it("keeps a free-form prompt at a collapsed caret generating from scratch", async () => {
@@ -555,7 +560,7 @@ describe("AiAssistantUI toolbar entry", () => {
form.fire("submit");
await vi.waitFor(() => expect(requests).toHaveLength(1));
- expect(requests[0]).toEqual({ query: "Write a haiku.", context: "" });
+ expect(requests[0]).toEqual({ query: "Write a haiku.", context: "", history: [] });
});
it("runs the picked action against the selection and opens the dialog on it", async () => {
@@ -565,7 +570,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" });
+ expect(requests[0]).toEqual({ query: "Fix all mistakes.", context: "foo", history: [] });
const dialog = editor.plugins.get(Dialog);
expect(dialog.isOpen).toBe(true);
@@ -655,6 +660,115 @@ describe("AiAssistantUI toolbar entry", () => {
});
});
+ // 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.
+ describe("the conversation a follow-up continues", () => {
+ let editor: ClassicEditor;
+ let dropdown: QuickActionsDropdown;
+ let requests: AiCompletionRequest[];
+
+ beforeEach(async () => {
+ // A host that renders its responses reports what it rendered them from, and that is
+ // what the conversation records — the model gets its own words back, not our HTML.
+ const stub = createStreamStub("<p>Guten Tag</p>", "Guten Tag");
+ requests = stub.requests;
+ editor = await createEditor(QUICK_ACTIONS, stub.stream);
+ dropdown = createComponent(editor);
+ setModelData(editor.model, "<paragraph>[foo]</paragraph>");
+ });
+
+ /** Runs the first quick action, which is how every conversation here is opened. */
+ async function open() {
+ const [fixTypos] = quickActionButtons(dropdown);
+ fixTypos.fire("execute");
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+ return fixTypos;
+ }
+
+ /** Types a follow-up into the standing dialog and waits for the run it starts. */
+ async function followUp(query: string, expected: number) {
+ const form = openForm(editor);
+ form.query = query;
+ form.fire("submit");
+ await vi.waitFor(() => expect(requests).toHaveLength(expected));
+ }
+
+ it("carries every exchange so far, against the content it opened on", async () => {
+ await open();
+ await followUp("now make it shorter", 2);
+
+ expect(requests[1]).toEqual({
+ query: "now make it shorter",
+ // 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",
+ history: [
+ { role: "user", content: "Fix all mistakes." },
+ { role: "assistant", content: "Guten Tag" }
+ ]
+ });
+
+ await followUp("and in bullet points", 3);
+ expect(requests[2].history).toHaveLength(4);
+ expect(requests[2].history.at(-2)).toEqual({ role: "user", content: "now make it shorter" });
+ });
+
+ it("keeps a quick action picked over the open assistant in the same conversation", async () => {
+ await open();
+ const [, makeShorter] = quickActionButtons(dropdown);
+
+ makeShorter.fire("execute");
+ await vi.waitFor(() => expect(requests).toHaveLength(2));
+
+ expect(requests[1].query).toBe("Shorten it.");
+ expect(requests[1].history).toEqual([
+ { role: "user", content: "Fix all mistakes." },
+ { role: "assistant", content: "Guten Tag" }
+ ]);
+ });
+
+ it("drops the exchange a retry replaces", async () => {
+ await open();
+ await followUp("now make it shorter", 2);
+
+ openForm(editor).fire("tryAgain");
+ await vi.waitFor(() => expect(requests).toHaveLength(3));
+
+ // The retry asks the same question of the same conversation: the answer it is
+ // replacing is gone from the transcript, or the model would be refining it again.
+ expect(requests[2]).toEqual(requests[1]);
+ });
+
+ it("opens a fresh conversation each time the assistant does", async () => {
+ const fixTypos = await open();
+
+ editor.plugins.get(Dialog).hide();
+ setModelData(editor.model, "<paragraph>[bar]</paragraph>");
+ fixTypos.fire("execute");
+ await vi.waitFor(() => expect(requests).toHaveLength(2));
+
+ expect(requests[1]).toEqual({ query: "Fix all mistakes.", context: "bar", history: [] });
+ });
+
+ it("records the delivered HTML for a host that reports no source", async () => {
+ const stub = createStreamStub("<p>done</p>");
+ const htmlEditor = await createEditor(QUICK_ACTIONS, stub.stream);
+ const htmlDropdown = createComponent(htmlEditor);
+
+ setModelData(htmlEditor.model, "<paragraph>[foo]</paragraph>");
+ quickActionButtons(htmlDropdown)[0].fire("execute");
+ await vi.waitFor(() => expect(stub.requests).toHaveLength(1));
+
+ const form = openForm(htmlEditor);
+ form.query = "now make it shorter";
+ form.fire("submit");
+ await vi.waitFor(() => expect(stub.requests).toHaveLength(2));
+
+ expect(stub.requests[1].history.at(-1)).toEqual({ role: "assistant", content: "<p>done</p>" });
+ });
+ });
+
describe("the view a finished review opens on", () => {
const REVIEW_ACTIONS: AiQuickActionGroup[] = [
{
diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts
index b28d7dd9d7..5058ace1b7 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, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView } from "./ai_assistant_config.js";
+import type { AiCompletionUsage, AiConversationTurn, AiDiffResult, AiQuickAction, AiQuickActionFooter, AiQuickActionGroup, AiReviewView } 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";
@@ -92,10 +92,25 @@ export default class AiAssistantUI extends Plugin {
/** The cumulative response HTML of the current/last run, as the host delivered it. */
private _cumulative = "";
- /** The HTML the next query will run against: the selection, then each committed-to response. */
+ /**
+ * The same response in the form the host rendered it from, which is what the conversation
+ * records — a host reporting no source records the HTML instead.
+ */
+ private _cumulativeSource = "";
+ /** The HTML the conversation opened on, sent with every request it makes. */
+ private _openingContext = "";
+ /**
+ * 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
+ * diff runs against and what tells the quick actions there is something to work on.
+ */
private _context = "";
/** The context of the last run, restored by "Try again" so a retry does not chain on itself. */
private _previousContext = "";
+ /** The exchanges so far, which the next request carries — see `AiCompletionRequest.history`. */
+ private _history: AiConversationTurn[] = [];
+ /** The history of the last run, restored by "Try again" alongside {@link _previousContext}. */
+ private _previousHistory: AiConversationTurn[] = [];
private _lastQuery = "";
/**
* The view the running quick action asked its review to open on, when it named one. Null for a
@@ -514,8 +529,12 @@ export default class AiAssistantUI extends Plugin {
this._context = !range || range.isCollapsed
? ""
: editor.data.stringify(model.getSelectedContent(model.createSelection(range)));
+ this._openingContext = this._context;
this._previousContext = this._context;
+ this._history = [];
+ this._previousHistory = [];
this._cumulative = "";
+ this._cumulativeSource = "";
this._updateHasContext();
/* v8 ignore next -- the document selection always has at least one range */
@@ -584,8 +603,10 @@ export default class AiAssistantUI extends Plugin {
form.on("replace", () => this._commit("replace"));
form.on("insertBelow", () => this._commit("insertBelow"));
form.on("tryAgain", () => {
- // Retry against what the last run saw, not against its own output.
+ // Retry against what the last run saw, not against its own output — so the exchange
+ // being retried leaves the conversation along with the response it produced.
this._context = this._previousContext;
+ this._history = this._previousHistory;
void this._run(this._lastQuery);
});
@@ -605,9 +626,11 @@ export default class AiAssistantUI extends Plugin {
}
this._previousContext = this._context;
+ this._previousHistory = this._history;
this._lastQuery = query;
this.isStreaming = true;
this._cumulative = "";
+ this._cumulativeSource = "";
form.beginStreaming();
const abortController = new AbortController();
@@ -617,8 +640,9 @@ export default class AiAssistantUI extends Plugin {
let renderTimer: ReturnType<typeof setTimeout> | null = null;
let pendingHtml: string | null = null;
- const onData = (cumulative: string) => {
+ const onData = (cumulative: string, source?: string) => {
this._cumulative = cumulative;
+ this._cumulativeSource = source ?? cumulative;
if (renderTimer) {
pendingHtml = cumulative;
return;
@@ -637,7 +661,11 @@ export default class AiAssistantUI extends Plugin {
let errorMessage = "";
let usage: AiCompletionUsage | null = null;
try {
- usage = (await stream({ query, context: this._context }, onData, abortController.signal)) ?? null;
+ usage = (await stream(
+ { query, context: this._openingContext, history: this._history },
+ onData,
+ abortController.signal
+ )) ?? null;
} catch (error) {
// An abort is the user's Stop: whatever already streamed stays reviewable.
if (!(error instanceof DOMException && error.name === "AbortError")) {
@@ -656,8 +684,16 @@ export default class AiAssistantUI extends Plugin {
}
if (this._cumulative) {
- // Follow-up queries chain on the response ("now make it shorter"), premium-style.
+ // Follow-up queries chain on the response ("now make it shorter"), premium-style — and
+ // the exchange joins the conversation the next one is asked in, so the instruction
+ // behind the response is still on the record when the response is refined. Without it
+ // "translate this to German" followed by "make it shorter" shortens in English.
this._context = this._cumulative;
+ this._history = [
+ ...this._history,
+ { role: "user", content: query },
+ { role: "assistant", content: this._cumulativeSource }
+ ];
}
// A response counts as content, so content-requiring quick actions unlock for chaining.
this._updateHasContext();
@@ -890,10 +926,16 @@ export default class AiAssistantUI extends Plugin {
this._abortController?.abort();
this._cumulative = "";
+ this._cumulativeSource = "";
// Dropping the captured context hands the quick actions back to the selection; keeping it
// would leave them enabled over a closed assistant that has nothing to work on.
this._context = "";
+ this._openingContext = "";
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.
+ this._history = [];
+ this._previousHistory = [];
this._reviewView = null;
this._updateHasContext();