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): reach the content languages from the Translate submenu
Elian Dorand0a758a112fa
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 2258cb846d..882008d8bd 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -128,6 +128,7 @@ export type CommandMappings = {showOptions: CommandData & {section?: string;};+ showContentLanguagesDialog: CommandData;showExportDialog: CommandData & {notePath: string;defaultType: "single" | "subtree";diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsxindex 907197bb46..37e460b016 100644--- a/apps/client/src/layouts/layout_commons.tsx+++ b/apps/client/src/layouts/layout_commons.tsx@@ -36,6 +36,7 @@ export function applyModals(rootContainer: RootContainer) {.child(<LazyDialog triggerEvents={["showPromptDialog"]} loader={() => import("../widgets/dialogs/prompt.js")} />).child(<LazyDialog triggerEvents={["showCpuArchWarning"]} loader={() => import("../widgets/dialogs/incorrect_cpu_arch.js")} />).child(<LazyDialog triggerEvents={["showOptions"]} loader={() => import("../widgets/dialogs/OptionsDialog.jsx")} />)+ .child(<LazyDialog triggerEvents={["showContentLanguagesDialog"]} loader={() => import("../widgets/dialogs/content_languages.js")} />).child(<LazyDialog triggerEvents={["showOcrTextDialog"]} loader={() => import("../widgets/dialogs/ocr_text.js")} />).child(<LazyDialog triggerEvents={["showNoteAttributes"]} loader={() => import("../widgets/dialogs/note_attributes.jsx")} />).child(<LazyDialog triggerEvents={["showUploadAttachmentsDialog"]} loader={() => import("../widgets/dialogs/upload_attachments.js")} />)diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsindex b4909fecf9..2a99ab6256 100644--- a/apps/client/src/menus/text_editor_context_menu.spec.ts+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -41,7 +41,8 @@ const GROUPS: AiQuickActionGroup[] = [id: "tone",label: "Change tone",submenu: true,- actions: [{ id: "casual", label: "Casual", prompt: "…" }]+ actions: [{ id: "casual", label: "Casual", prompt: "…" }],+ footer: { label: "Configure…", iconClass: "bx bx-cog", run: vi.fn() }}];@@ -168,10 +169,27 @@ describe("buildAiActionsMenuItem", () => {"Fix typos": false,Draft: true,Adjust: false,- "Change tone": false+ // Its actions all need content, but the row that configures them does not, so the+ // submenu still opens.+ "Change tone": true});});+ // A group whose contents are configurable ends with the row that configures them, below a rule+ // and runnable whatever the selection is.+ it("closes a group's submenu with its footer, and leaves it runnable without content", async () => {+ build({ hasContext: false });+ const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;+ const tone = commandItems(item.items ?? []).find((i) => i.title === "Change tone");++ expect(titles(tone?.items ?? [])).toEqual(["Casual", "--- separator ---", "Configure…"]);++ const configure = commandItems(tone?.items ?? []).find((i) => i.title === "Configure…");+ expect([configure?.enabled, configure?.uiIcon]).toEqual([true, "bx bx-cog"]);+ configure?.handler?.(configure, null as never);+ expect(GROUPS.find((g) => g.id === "tone")?.footer?.run).toHaveBeenCalled();+ });+it("runs the picked action, and opens the free-form prompt from the first row", async () => {const { editor, ui } = build();const item = await buildAiActionsMenuItem() as MenuCommandItem<string>;diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex 9f682846c5..39556d318f 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -81,7 +81,7 @@ function buildQuickActionItems(const items: MenuItem<CommandNames>[] = [];for (const [index, group] of groups.entries()) {- const children = group.actions.map((action) => ({+ const children: MenuItem<CommandNames>[] = group.actions.map((action) => ({title: action.label,uiIcon: action.iconClass,enabled: canRun(action),@@ -89,10 +89,20 @@ function buildQuickActionItems(}));if (group.submenu) {+ if (group.footer) {+ children.push({ kind: "separator" }, {+ title: group.footer.label,+ uiIcon: group.footer.iconClass,+ // Configures the group rather than running against the document, so it stays+ // reachable when everything above it is closed off — as does its submenu.+ enabled: true,+ handler: group.footer.run+ });+ }items.push({title: group.label,uiIcon: group.iconClass,- enabled: group.actions.some(canRun),+ enabled: !!group.footer || group.actions.some(canRun),items: children});} else {diff --git a/apps/client/src/widgets/dialogs/content_languages.tsx b/apps/client/src/widgets/dialogs/content_languages.tsxnew file mode 100644index 0000000000..ede213e0c8--- /dev/null+++ b/apps/client/src/widgets/dialogs/content_languages.tsx@@ -0,0 +1,21 @@+import { useState } from "preact/hooks";++import { useTriliumEvent } from "../react/hooks.jsx";+import { ContentLanguagesModal } from "../ribbon/BasicPropertiesTab.jsx";++/**+ * The content-languages modal, summoned by a command rather than owned by whatever offers it.+ *+ * The ribbon and the status bar each hold their own copy behind a `useState`, which works because+ * both are components sitting next to the switcher they belong to. The AI assistant's Translate+ * submenu is neither: it is a CKEditor menu and a right-click menu, both built imperatively, with+ * nowhere to hang a modal. So the dialog joins the registry in `layout_commons`, where a command is+ * all it takes to raise one.+ */+export default function ContentLanguagesDialog() {+ const [ shown, setShown ] = useState(false);++ useTriliumEvent("showContentLanguagesDialog", () => setShown(true));++ return <ContentLanguagesModal modalShown={shown} setModalShown={setShown} />;+}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 2174a4d977..28366eb95d 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@@ -35,7 +35,9 @@ 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 () => [] }));+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";/** The `llmProviders` option as the mocked `options.getJson` will return it. */@@ -280,6 +282,19 @@ describe("buildAiAssistantQuickActions", () => {]);});+ // The list is configurable, so what configures it closes the submenu — the same row the status+ // bar and the ribbon end their language pickers with, raising the same modal.+ it("closes the Translate submenu with the row that configures the list", () => {+ const group = buildAiAssistantQuickActions().find((candidate) => candidate.id === "translate");+ expect(group?.footer?.label).toBe("note_language.configure-languages");++ group?.footer?.run();+ expect(appContext.triggerCommand).toHaveBeenCalledWith("showContentLanguagesDialog");++ // It is the only group whose contents the user chooses, so the only one with a footer.+ expect(buildAiAssistantQuickActions().filter((candidate) => candidate.footer)).toHaveLength(1);+ });+// Nothing is enabled on a fresh install, and an empty Translate submenu would say the feature// was broken rather than unconfigured.it("falls back to the original six when no content language is enabled", () => {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 b0bc44c682..aeccbed29d 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,6 +1,7 @@import type { AiCompletionUsage, AiQuickAction, AiQuickActionGroup, AiStreamFunction } from "@triliumnext/ckeditor5";import { getEnglishName, type LlmChatConfig, type LlmMessage, type LlmModelInfo, type LlmUsage, type Locale, type ToMarkdownResponse } from "@triliumnext/commons";+import appContext from "../../../components/app_context.js";import { getAvailableLocales, t } from "../../../services/i18n.js";import { streamChatCompletion } from "../../../services/llm_chat.js";import options from "../../../services/options.js";@@ -167,7 +168,16 @@ export function buildAiAssistantQuickActions(): AiQuickActionGroup[] {id: "translate",label: t("ai_assistant.group_translate"),submenu: true,- actions: buildTranslateActions()+ actions: buildTranslateActions(),+ // The one group whose contents are the user's to choose, so the way to choose them+ // closes it — as it closes the note's own language picker in the status bar and the+ // ribbon, and for the same reason: nobody looking at the list would think to go+ // hunting through the settings for what fills it.+ footer: {+ label: t("note_language.configure-languages"),+ iconClass: "bx bx-cog",+ run: () => appContext.triggerCommand("showContentLanguagesDialog")+ }}]);}diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex e37cc17307..27a3ba7262 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, AiQuickActionGroup, AiReviewView, AiSanitizeFunction, AiStreamCallback, AiStreamFunction } from "./plugins/ai_assistant/ai_assistant_config.js";+export type { AiAssistantConfig, AiCompletionRequest, AiCompletionUsage, 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.tsindex ebc958cd4a..ab2058de8f 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_config.ts@@ -136,6 +136,22 @@ export interface AiQuickAction {*/export type AiSanitizeFunction = (html: string) => string;+/**+ * A row appended to the bottom of a group's submenu, below a rule, that runs host code instead of+ * asking the model — for a group whose contents the user configures, so that what configures them+ * is reachable from the group itself rather than only from the settings.+ *+ * It is not an {@link AiQuickAction}: it has no prompt, needs no content, and has no business in+ * the `/` palette, which lists ways to instruct the model.+ */+export interface AiQuickActionFooter {+ /** The label shown in the menu, already translated by the host. */+ label: string;+ /** The row's icon, as a Boxicon class list. */+ iconClass?: string;+ run: () => void;+}+/** A labelled group of quick actions, rendered as a group in the menu. */export interface AiQuickActionGroup {id: string;@@ -154,6 +170,8 @@ export interface AiQuickActionGroup {* suits actions that already read as commands on their own ("Fix typos", "Summarize").*/submenu?: boolean;+ /** A row closing the group's submenu. Only rendered when the group is a {@link submenu}. */+ footer?: AiQuickActionFooter;}export interface AiAssistantConfig {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 4a29063d28..341d5b4e8f 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@@ -271,6 +271,42 @@ describe("AiAssistantUI toolbar entry", () => {expect(generate.isEnabled).toBe(true);});+ // A group whose contents the host lets the user choose ends with the row that chooses them,+ // which is not an action: no prompt, nothing to work on, and nothing for the model to do.+ it("closes a group's submenu with its footer, below a rule and reachable without content", async () => {+ const run = vi.fn();+ const stub = createStreamStub();+ const editorWithFooter = await createEditor([{+ id: "translate",+ label: "Translate",+ submenu: true,+ actions: [{ id: "german", label: "German", prompt: "Translate to German." }],+ footer: { label: "Configure languages…", iconClass: "bx bx-cog", run }+ }], stub.stream);+ const dropdownWithFooter = createComponent(editorWithFooter);+ const [translate] = openMenu(dropdownWithFooter).menus;++ expect(translate.listView.items.map((item) => item.childView?.label ?? "---"))+ .toEqual(["German", "---", "Configure languages…"]);++ // Its one action needs content; the footer does not, so neither the row nor the submenu+ // holding it closes off with nothing selected.+ setModelData(editorWithFooter.model, "<paragraph>[]</paragraph>");+ expect(translate.isEnabled).toBe(true);++ const configure = quickActionButtons(dropdownWithFooter)+ .find((button) => button.id === "translate:footer");+ expect(configure?.isEnabled).toBe(true);+ expect(configure?.element?.querySelector(".ck-ai-action-icon")?.className)+ .toBe("ck-ai-action-icon bx bx-cog");++ configure?.fire("execute");+ expect(run).toHaveBeenCalled();+ // It runs host code instead of the assistant: no request, and no dialog.+ expect(stub.requests).toHaveLength(0);+ expect(editorWithFooter.plugins.get(Dialog).id).toBeNull();+ });+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.