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
fix(llm): focus an AI chat's input on tab switch and on creation
Elian Doran9aec6f09369f
diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.tsindex 91d2f6f897..1b1b0944c4 100644--- a/apps/client/src/services/note_create.spec.ts+++ b/apps/client/src/services/note_create.spec.ts@@ -133,6 +133,17 @@ describe("createNote", () => {expect(triggerEvent).not.toHaveBeenCalledWith("focusAndSelectTitle", expect.anything());});+ it("focuses an AI chat's input rather than its title, which the first reply names", async () => {+ setActiveContext(true);+ await noteCreateService.createNote("root", { type: "llmChat" });+ expect(triggerEvent).toHaveBeenCalledWith("focusOnDetail", { ntxId: "ntx-1" });+ expect(triggerEvent).not.toHaveBeenCalledWith("focusAndSelectTitle", expect.anything());++ triggerEvent.mockClear();+ await noteCreateService.createNote("root", { type: "llmChat", focus: "title" });+ expect(triggerEvent).toHaveBeenCalledWith("focusAndSelectTitle", { isNewNote: true, ntxId: "ntx-1" });+ });+it("activates without firing a focus event when focus is neither title nor content", async () => {const setNote = setActiveContext(true);// an out-of-range focus value still activates the note but triggers no focus eventdiff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.tsindex 702817cefd..ef50cafb20 100644--- a/apps/client/src/services/note_create.ts+++ b/apps/client/src/services/note_create.ts@@ -59,7 +59,8 @@ async function createNote(parentNotePath: string | undefined, options: CreateNotoptions = Object.assign({activate: true,- focus: "title",+ // An AI chat takes its title from the first reply, so the input is what to type into.+ focus: options.type === "llmChat" ? "content" : "title",target: "into"},optionsdiff --git a/apps/client/src/widgets/NoteDetail.spec.ts b/apps/client/src/widgets/NoteDetail.spec.tsindex 5dc84ef815..9b21b5928e 100644--- a/apps/client/src/widgets/NoteDetail.spec.ts+++ b/apps/client/src/widgets/NoteDetail.spec.ts@@ -1,3 +1,5 @@+import { h, render } from "preact";+import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import NoteContext from "../components/note_context";@@ -8,7 +10,7 @@ import froca from "../services/froca";// global the test env doesn't provide. The pure function under test never touches the tree, so stub it.vi.mock("./note_tree", () => ({ default: class {} }));-import { getExtendedWidgetType, isContextInActiveTab } from "./NoteDetail";+import { getExtendedWidgetType, isContextInActiveTab, useDeferredDetailFocus } from "./NoteDetail";const FAKE_NOTE_ID = "blob-stub-note";@@ -102,3 +104,41 @@ describe("getExtendedWidgetType blob-stub routing", () => {expect(getBlob).not.toHaveBeenCalled();});});++describe("useDeferredDetailFocus", () => {+ const replay = vi.fn();+ let request: ReturnType<typeof useDeferredDetailFocus> | undefined;+ const host = document.createElement("div");++ function Harness({ isReady }: { isReady: boolean }) {+ request = useDeferredDetailFocus(isReady, replay);+ return null;+ }+ const renderHarness = (isReady: boolean) => act(() => render(h(Harness, { isReady }), host));++ afterEach(() => {+ render(null, host);+ replay.mockReset();+ });++ it("holds a focus that arrives before the note's type widget shows, and replays it once", () => {+ renderHarness(false);+ request?.({ ntxId: "ntx-1" });+ expect(replay).not.toHaveBeenCalled();++ renderHarness(true);+ expect(replay).toHaveBeenCalledExactlyOnceWith({ ntxId: "ntx-1" });++ renderHarness(false);+ renderHarness(true);+ expect(replay).toHaveBeenCalledOnce();+ });++ it("leaves a focus that arrives once the widget shows to the widget itself", () => {+ renderHarness(true);+ request?.({ ntxId: "ntx-1" });+ renderHarness(false);+ renderHarness(true);+ expect(replay).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsxindex 9d058eb0a9..6478cf9af8 100644--- a/apps/client/src/widgets/NoteDetail.tsx+++ b/apps/client/src/widgets/NoteDetail.tsx@@ -3,9 +3,9 @@ import "./NoteDetail.css";import clsx from "clsx";import { note } from "mermaid/dist/rendering-util/rendering-elements/shapes/note.js";import { isValidElement, VNode } from "preact";-import { useContext, useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";-import appContext from "../components/app_context";+import appContext, { type EventData } from "../components/app_context";import NoteContext from "../components/note_context";import FNote from "../entities/fnote";import type { PrintReport } from "../print";@@ -138,6 +138,15 @@ export default function NoteDetail() {}});+ // A focus requested while the note is still switching (e.g. right after creating it) reaches+ // a type widget that is hidden or not mounted yet, so it is sent again once the new one shows.+ const isTypeWidgetShown = !!note && note.noteId === noteContext?.noteId && !!type && activeNoteType === type;+ const requestDetailFocus = useDeferredDetailFocus(isTypeWidgetShown,+ (data) => parentComponent.handleEventInChildren("focusOnDetail", data));+ useTriliumEvent("focusOnDetail", (data) => {+ if (data.ntxId === ntxId) requestDetailFocus(data);+ });+// Automatically focus the editor.useTriliumEvent("activeNoteChanged", ({ ntxId: eventNtxId }) => {if (eventNtxId != ntxId) return;@@ -242,6 +251,27 @@ export default function NoteDetail() {);}+/**+ * Holds a `focusOnDetail` that arrives while `isReady` is false and calls `replay` with it once+ * `isReady` turns true. A request made while ready is left to the widgets that already received it.+ */+export function useDeferredDetailFocus(isReady: boolean, replay: (data: EventData<"focusOnDetail">) => void) {+ const pendingRef = useRef<EventData<"focusOnDetail">>();+ const replayRef = useRef(replay);+ replayRef.current = replay;++ useEffect(() => {+ const pending = pendingRef.current;+ if (!isReady || !pending) return;+ pendingRef.current = undefined;+ replayRef.current(pending);+ }, [ isReady ]);++ return useCallback((data: EventData<"focusOnDetail">) => {+ if (!isReady) pendingRef.current = data;+ }, [ isReady ]);+}+/*** True when the given context belongs to the active tab, identified by `activeMainNtxId` (the ntxId of* the active tab's main context). A tab can hold several splits, but only one of them is the "active"diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 46c58adce4..fde6c0df1c 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -154,13 +154,18 @@ export default function ChatInputBar({submitRef.current = handleSubmit;// Expose the reply-input editor to the chat hook so timeline actions (e.g. quoting a selection)- // can write into it. A stable wrapper reads the live api ref, so it works regardless of whether- // the CKEditor's imperative handle has committed by the time this effect first runs.+ // can write into it and the note can focus it. Registered once the editor has initialized, so a+ // focus the hook holds for it lands on an editor that exists.const registerInputEditor = chat.registerInputEditor;+ const [ isEditorReady, setIsEditorReady ] = useState(false);useEffect(() => {- registerInputEditor({ appendBlockQuote: (text) => editorApiRef.current?.appendBlockQuote(text) });+ if (!isEditorReady) return;+ registerInputEditor({+ appendBlockQuote: (text) => editorApiRef.current?.appendBlockQuote(text),+ focus: () => editorApiRef.current?.focus()+ });return () => registerInputEditor(undefined);- }, [registerInputEditor]);+ }, [registerInputEditor, isEditorReady]);// Reflect streaming state into CKEditor's read-only lock.useEffect(() => {@@ -342,6 +347,7 @@ export default function ChatInputBar({}}onInitialized={(editor) => {editorInstanceRef.current = editor;+ setIsEditorReady(true);const insertNewBlock = () => {insertNewBlockCommand(editor);editor.editing.view.scrollToTheSelection();diff --git a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsxindex da0d0d7c34..5e79f4acbc 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/LlmChat.tsx@@ -3,7 +3,7 @@ import "./LlmChat.css";import { useCallback, useEffect, useRef } from "preact/hooks";import { t } from "../../../services/i18n.js";-import { useEditorSpacedUpdate, useNoteLabelBoolean } from "../../react/hooks.js";+import { useEditorSpacedUpdate, useNoteLabelBoolean, useTriliumEvent } from "../../react/hooks.js";import { TypeWidgetProps } from "../type_widget.js";import { useChatContextMenu } from "./chat_context_menu.js";import { useChatHighlights } from "./chat_highlights.js";@@ -45,6 +45,11 @@ export default function LlmChat({ note, noteContext }: TypeWidgetProps) {// Make the "Show quote source" links in submitted quotes jump to the referenced message.useChatMessageJumps(chat.scrollContainerRef);+ // Switching to the tab or creating the note focuses the reply input, like other types' editors.+ useTriliumEvent("focusOnDetail", ({ ntxId }) => {+ if (ntxId === noteContext?.ntxId) chat.focusInput();+ });+const spacedUpdate = useEditorSpacedUpdate({note,noteType: "llmChat",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsxindex 54751cba7a..91e9184230 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx@@ -96,6 +96,21 @@ describe("useLlmChat", () => {streamChatCompletionMock.mockReset();});+ it("focuses the input at once when it is ready, or as soon as it registers", async () => {+ await mountChat();+ const early = { appendBlockQuote: vi.fn(), focus: vi.fn() };+ api().focusInput();+ api().registerInputEditor(early);+ expect(early.focus).toHaveBeenCalledOnce();++ // The request is spent: registering again does not steal the focus a second time.+ const ready = { appendBlockQuote: vi.fn(), focus: vi.fn() };+ api().registerInputEditor(ready);+ expect(ready.focus).not.toHaveBeenCalled();+ api().focusInput();+ expect(ready.focus).toHaveBeenCalledOnce();+ });+it("selects the default model with its provider and annotates model costs", async () => {await mountChat();diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex af003a5c67..1f188f7b6a 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -18,6 +18,7 @@ export type AttachmentBlock = ImageBlock | FileBlock | TextFileBlock;/** The subset of the reply-input editor API the chat needs to write into it imperatively. */export interface InputEditorApi {appendBlockQuote(markdown: string): void;+ focus(): void;}/** Distance (px) past the content bottom edge within which the timeline counts as "at bottom". */@@ -138,6 +139,8 @@ export interface UseLlmChatReturn {registerInputEditor: (api: InputEditorApi | undefined) => void;/** Append a preformatted block (e.g. a Markdown quote) to the reply input and focus it. */appendToInput: (text: string) => void;+ /** Focus the reply input, or, while its editor is still loading, as soon as it registers. */+ focusInput: () => void;/** Read the current reply-input draft text (kept in a ref, not state — see {@link hasInputText}). */getInput: () => string;@@ -268,11 +271,24 @@ export function useLlmChat(const pendingAttachmentsRef = useRef(pendingAttachments);pendingAttachmentsRef.current = pendingAttachments;- // The reply-input editor, registered by ChatInputBar once mounted. Held in a ref so timeline- // actions (e.g. quoting a selection) can write into it without a render-order dependency.+ // The reply-input editor, registered by ChatInputBar once its CKEditor has initialized. Held in a+ // ref so timeline actions (e.g. quoting a selection) can write into it without a render-order+ // dependency.const inputEditorRef = useRef<InputEditorApi | undefined>();+ const isInputFocusPendingRef = useRef(false);const registerInputEditor = useCallback((api: InputEditorApi | undefined) => {inputEditorRef.current = api;+ if (api && isInputFocusPendingRef.current) {+ isInputFocusPendingRef.current = false;+ api.focus();+ }+ }, []);+ const focusInput = useCallback(() => {+ if (inputEditorRef.current) {+ inputEditorRef.current.focus();+ } else {+ isInputFocusPendingRef.current = true;+ }}, []);const appendToInput = useCallback((text: string) => {inputEditorRef.current?.appendBlockQuote(text);@@ -941,6 +957,7 @@ export function useLlmChat(registerInputEditor,appendToInput,+ focusInput,getInput,// Setters