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): offer the model beside the dialog's prompt
Elian Doran666301ecdda7
diff --git a/apps/client/src/widgets/type_widgets/text/ai_model_picker.ts b/apps/client/src/widgets/type_widgets/text/ai_model_picker.tsindex 44a1ab6250..58f2459819 100644--- a/apps/client/src/widgets/type_widgets/text/ai_model_picker.ts+++ b/apps/client/src/widgets/type_widgets/text/ai_model_picker.ts@@ -43,8 +43,10 @@ export function buildAiModelPicker(): AiQuickActionFooter[] {// model can be reached through two of them, and a name saying so in brackets on every// row says it over and over....(index === 0 && groups.length > 1 ? { heading: group.name } : {}),+ isCurrent: model === current,// The tick every checked row in Trilium wears, and the reserver that keeps the labels- // of the unticked ones lined up with it.+ // of the unticked ones lined up with it. Only the menu needs them: the dialog's picker+ // has a check column of its own and reads `isCurrent`.iconClass: model === current ? "bx bx-check" : "bx bx-empty",run: () => void options.save("aiAssistantModel", JSON.stringify({model: model.id,diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.tsindex 5512f39b9c..50e57811d9 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -160,6 +160,12 @@ export interface AiQuickActionFooter {* which is where a list long enough to want dividing ends up.*/heading?: string;+ /**+ * Whether this row is the choice currently in force. The menu draws its own tick through+ * {@link iconClass}, since its rows have no selected state of their own; the dialog's picker has+ * one and reads this instead — and names its button after whichever row says yes.+ */+ isCurrent?: boolean;/*** Rows this one opens onto, making it a submenu rather than something that runs. A row with* children never runs, so {@link run} is beside the point for it.diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.tsindex 2be6a11f80..980b41f00d 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_form.ts@@ -1,19 +1,26 @@import { IconArrowUp, IconCheck, IconRefresh, IconStop } from "@ckeditor/ckeditor5-icons";import {+ addListToDropdown,ButtonView,+ Collection,+ createDropdown,FocusCycler,FocusTracker,IconView,InputTextView,KeystrokeHandler,submitHandler,+ UIModel,View,ViewCollection,+ type DropdownView,type FocusableView,+ type ListDropdownButtonDefinition,+ type ListDropdownItemDefinition,type Locale} from "ckeditor5";-import type { AiReviewView } from "./ai_assistant_config.js";+import type { AiQuickActionFooter, AiReviewView } from "./ai_assistant_config.js";/*** Where the form is in its lifecycle: taking a prompt, streaming a response into the preview, or@@ -71,6 +78,8 @@ export default class AiAssistantFormView extends View {declare public isUnchanged: boolean;/** The run's cost line ("model · tokens · price"), shown in the review actions row. */declare public usageText: string;+ /** Whether the host gave the prompt row a setting to offer; without one it is not drawn. */+ declare public hasPicker: boolean;/** The (sanitized) response HTML, kept for re-rendering when the view mode flips. */private _resultHtml = "";@@ -86,12 +95,21 @@ export default class AiAssistantFormView extends View {public readonly replaceButtonView: ButtonView;public readonly insertBelowButtonView: ButtonView;public readonly tryAgainButtonView: ButtonView;+ /**+ * The setting a run answers to, offered beside the prompt — Trilium hangs the model here. Its+ * list is bound to {@link _pickerItems}, so replacing the picker re-renders it in place.+ */+ public readonly pickerView: DropdownView;public readonly focusTracker = new FocusTracker();public readonly keystrokes = new KeystrokeHandler();private readonly _focusables = new ViewCollection<FocusableView>();private readonly _onResultRendered?: (preview: HTMLElement) => void;+ /** What the picker offers. Bound to its list, so refilling it redraws the list in place. */+ private readonly _pickerItems = new Collection<ListDropdownItemDefinition>();+ /** The choices behind those rows, in the order the rows carry as their index. */+ private _pickerChoices: AiQuickActionFooter[] = [];constructor(locale: Locale, { onResultRendered }: AiAssistantFormOptions = {}) {super(locale);@@ -106,6 +124,8 @@ export default class AiAssistantFormView extends View {this.set("hasDiff", false);this.set("isUnchanged", false);this.set("usageText", "");+ // Nothing to answer to until the host says otherwise, so the row starts without it.+ this.set("hasPicker", false);// Re-render the preview from the stored contents whenever the toggle flips.this.on("change:viewMode", () => this._renderPreview());@@ -114,6 +134,7 @@ export default class AiAssistantFormView extends View {this.changesToggleView = this._createViewModeButton(locale, t("Changes"), "changes");this.promptInputView = this._createPromptInput(locale);this.sendButtonView = this._createSendButton(locale);+ this.pickerView = this._createPicker(locale);this.previewView = new AiPreviewView(locale);// A response that changed nothing is the text the user is already looking at, so the// placeholder stands in its place rather than sitting under a copy of it.@@ -242,7 +263,22 @@ export default class AiAssistantFormView extends View {attributes: { class: ["ck", "ck-ai-assistant-form__prompt-row"] },// Send and Stop share the slot at the end of the row; the phase decides which// of the two is on show.- children: [this.promptInputView, this.sendButtonView, this.stopButtonView]+ children: [+ {+ tag: "div",+ attributes: {+ class: [+ "ck",+ "ck-ai-assistant-form__picker",+ bind.if("hasPicker", "ck-hidden", (hasPicker) => !hasPicker)+ ]+ },+ children: [this.pickerView]+ },+ this.promptInputView,+ this.sendButtonView,+ this.stopButtonView+ ]},{// Reserved from the moment a run is asked for, its buttons inert until there is@@ -290,6 +326,7 @@ export default class AiAssistantFormView extends View {this.resultToggleView,this.changesToggleView,this.tryAgainButtonView,+ this.pickerView.buttonView,this.promptInputView,this.sendButtonView,this.stopButtonView,@@ -436,6 +473,81 @@ export default class AiAssistantFormView extends View {return input;}+ /**+ * Replaces what the picker offers, or takes it off the row entirely when the host has nothing+ * to offer. Rebuilding the definitions is enough: the list is bound to them.+ *+ * A row's children become the choices, grouped by the {@link AiQuickActionFooter.heading} they+ * open a block with — CKEditor's own list groups here, rather than the headings the menu has to+ * insert by hand, because a plain list can express a group and a nested menu definition cannot.+ */+ public setPicker(picker: AiQuickActionFooter | null): void {+ this._pickerItems.clear();+ this._pickerChoices = [];++ const choices = picker?.children ?? [];+ this.hasPicker = choices.length > 0;+ if (!this.hasPicker) {+ return;+ }++ let group: { type: "group"; label: string; items: Collection<ListDropdownButtonDefinition> } | null = null;+ for (const choice of choices) {+ const definition = this._createPickerChoice(choice);++ if (choice.heading) {+ group = { type: "group", label: choice.heading, items: new Collection() };+ this._pickerItems.add(group);+ }++ // Everything up to the first heading, and everything at all when there are none, sits+ // at the top level — a group is opened by the row that names it, not assumed around it.+ (group?.items ?? this._pickerItems).add(definition);+ }++ // The button says what is in force rather than repeating the picker's own name: the row it+ // sits in is already about the run, and the name of the setting is what the tooltip is for.+ const current = choices.find((choice) => choice.isCurrent);+ this.pickerView.buttonView.set({ label: current?.label ?? picker?.label, tooltip: picker?.label });+ }++ private _createPicker(locale: Locale): DropdownView {+ const dropdown = createDropdown(locale);++ dropdown.buttonView.set({ withText: true, tooltip: true });+ dropdown.class = "ck-ai-assistant-form__picker-dropdown";+ // Nothing to pick between mid-run: the model a response is streaming from is settled.+ dropdown.bind("isEnabled").to(this, "phase", (phase) => phase !== "streaming");+ addListToDropdown(dropdown, this._pickerItems, { role: "menu" });++ // A list definition is a bag of *properties*, bound onto the button CKEditor builds from it+ // — it is not something that can be listened to. So the row carries its index, the way+ // CKEditor's own dropdowns carry a command name, and the choice is looked up on execute.+ dropdown.on("execute", (evt) => {+ dropdown.isOpen = false;+ const { choiceIndex } = evt.source as { choiceIndex?: number };+ if (choiceIndex !== undefined) {+ this._pickerChoices[choiceIndex]?.run?.();+ }+ });++ return dropdown;+ }++ /** One choice, as a checkable list row — the check column and its alignment are CKEditor's. */+ private _createPickerChoice(choice: AiQuickActionFooter): ListDropdownButtonDefinition {+ return {+ type: "button",+ model: new UIModel({+ label: choice.label,+ withText: true,+ role: "menuitemcheckbox",+ isOn: !!choice.isCurrent,+ choiceIndex: this._pickerChoices.push(choice) - 1+ })+ };+ }+private _createSendButton(locale: Locale) {const button = new ButtonView(locale);button.set({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.tsindex 33d1e9ed1c..b225897e52 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@@ -156,10 +156,40 @@ function openForm(editor: ClassicEditor) {hasDiff: boolean;isUnchanged: boolean;previewView: { element?: HTMLElement | null };+ hasPicker: boolean;+ pickerView: {+ isOpen: boolean;+ isEnabled: boolean;+ buttonView: { label?: string; tooltip?: string | boolean };+ listView?: { items: Iterable<PickerListItem> };+ };fire(event: string): void;};}+/**+ * A row of the dialog's picker, or the group heading one opens: a group carries its own `label` and+ * holds its rows in `items`, while a plain row wraps its button in `children`.+ */+interface PickerListItem {+ label?: string;+ items?: Iterable<PickerListItem>;+ children?: { first?: PickerButton | null };+}++interface PickerButton {+ label?: string;+ isOn?: boolean;+ fire(event: string): void;+}++/** The picker's rows, flattened out of their groups, each paired with the heading it sits under. */+function pickerRows(form: ReturnType<typeof openForm>): Array<[string, string, boolean]> {+ return [ ...(form.pickerView.listView?.items ?? []) ].flatMap((item) => (item.items+ ? [ ...item.items ].map((row) => [item.label ?? "", row.children?.first?.label ?? "", !!row.children?.first?.isOn] as [string, string, boolean])+ : [["", item.children?.first?.label ?? "", !!item.children?.first?.isOn] as [string, string, boolean]]));+}+/** What the preview currently holds, for the specs that assert on rendered content. */function previewHtml(editor: ClassicEditor): string {return openForm(editor).previewView.element?.innerHTML ?? "";@@ -440,6 +470,60 @@ describe("AiAssistantUI toolbar entry", () => {.toEqual(["Anthropic", "OpenAI"]);});+ // The menu can only be reached before anything opens; the dialog stays open across a+ // follow-up and a retry, which is when the setting is actually worth changing.+ it("offers the same setting beside the prompt, grouped and ticked by the picker's own list", () => {+ const run = vi.fn();+ editor.plugins.get(AiAssistantUI).updateMenuFooter([{+ label: "Model: Sonnet 5",+ children: [+ { label: "Sonnet 5", heading: "Anthropic", isCurrent: true, run: vi.fn() },+ { label: "Opus 5", run },+ { label: "GPT-5", heading: "OpenAI", run: vi.fn() }+ ]+ }]);++ editor.execute("aiAssistant");+ const form = openForm(editor);+ expect(form.hasPicker).toBe(true);++ // The button names what is in force, not the setting — the setting's name is the tooltip.+ expect(form.pickerView.buttonView.label).toBe("Sonnet 5");+ expect(form.pickerView.buttonView.tooltip).toBe("Model: Sonnet 5");++ // A heading opens a group and the rows after it belong to it — CKEditor's own list+ // groups, with the tick and the column reserving it theirs too, rather than the+ // headings and the empty icons the menu has to supply by hand.+ form.pickerView.isOpen = true;+ expect(pickerRows(form)).toEqual([+ ["Anthropic", "Sonnet 5", true],+ ["Anthropic", "Opus 5", false],+ ["OpenAI", "GPT-5", false]+ ]);+ });++ it("closes the dialog's picker once a choice is made, and runs it", () => {+ const run = vi.fn();+ editor.plugins.get(AiAssistantUI).updateMenuFooter([{+ label: "Model: Sonnet 5",+ children: [{ label: "Opus 5", run }]+ }]);++ editor.execute("aiAssistant");+ const form = openForm(editor);+ form.pickerView.isOpen = true;+ [ ...(form.pickerView.listView?.items ?? []) ][0].children?.first?.fire("execute");++ expect(run).toHaveBeenCalled();+ expect(form.pickerView.isOpen).toBe(false);+ expect(requests).toHaveLength(0);+ });++ it("keeps the prompt row bare when the host offers no setting", () => {+ editor.execute("aiAssistant");+ expect(openForm(editor).hasPicker).toBe(false);+ });+it("runs an action picked from inside a submenu", async () => {// A submenu button delegates its `execute` up through its menu to the root rather than// firing on the dropdown itself, so this is a different path from an inlined action.diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex 57f8811790..b28d7dd9d7 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -178,6 +178,17 @@ export default class AiAssistantUI extends Plugin {public updateMenuFooter(rows: AiQuickActionFooter[]): void {this._menuFooter = rows;this._redrawMenus();+ // The dialog offers the same setting beside its prompt, and outlives the menu: it stays+ // open across a follow-up and a retry, which is exactly when the model is worth changing.+ this._formView?.setPicker(this._pickerRow());+ }++ /**+ * The footer row the dialog offers as a picker: the one that opens onto choices. A row that+ * simply runs is a menu action, and the dialog has its own buttons for those.+ */+ private _pickerRow(): AiQuickActionFooter | null {+ return this._menuFooter.find((row) => row.children?.length) ?? null;}private _redrawMenus(): void {@@ -556,6 +567,7 @@ export default class AiAssistantUI extends Plugin {onResultRendered: (preview) => this._enrichPreview(preview)});this._formView = form;+ form.setPicker(this._pickerRow());form.on("submit", () => {const query = form.query.trim();diff --git a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.cssindex d121802b7b..9353fe660a 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css+++ b/packages/ckeditor5/src/plugins/ai_assistant/theme/ai_assistant.css@@ -50,6 +50,20 @@min-width: 0;}+/* The prompt is what the row is for, so the picker gives way to it: it is allowed to shrink, down+ to a name of a few characters, and truncates rather than pushing the input narrower. */+.ck.ck-ai-assistant-form .ck-ai-assistant-form__picker {+ flex-shrink: 1;+ min-width: 0;+}++.ck.ck-ai-assistant-form .ck-ai-assistant-form__picker .ck-button__label {+ max-width: 12ch;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.ck.ck-ai-assistant-form .ck-ai-assistant-form__preview {max-height: 320px;overflow-y: auto;