diff --git a/plugins/chat/src/test/fake-kilo-server.ts b/plugins/chat/src/test/fake-kilo-server.ts index 2ac7b4d1..2054652c 100644 --- a/plugins/chat/src/test/fake-kilo-server.ts +++ b/plugins/chat/src/test/fake-kilo-server.ts @@ -331,6 +331,7 @@ export class FakeKiloServer { const chat = this.chats.get(decodeURIComponent(id)); if (!chat) return json({ name: "NotFoundError", data: { message: "No such chat" } }, 404); if (!action && request.method === "GET") { + await this.chatReadGate; if (this.chatReadDelayMs) await new Promise((resolve) => setTimeout(resolve, this.chatReadDelayMs)); return json(this.#info(chat)); @@ -412,6 +413,9 @@ export class FakeKiloServer { /** Milliseconds a chat's details take to arrive, as from a busy server. */ chatReadDelayMs = 0; + /** Holds answering `/session/:id` (a chat's details) until the test releases it. */ + chatReadGate?: Promise; + /** Milliseconds a chat's messages take to arrive, as a long history does. */ historyReadDelayMs = 0; diff --git a/plugins/chat/src/web/composer/composer.browser.test.tsx b/plugins/chat/src/web/composer/composer.browser.test.tsx index 1ff841f1..0ca1ee59 100644 --- a/plugins/chat/src/web/composer/composer.browser.test.tsx +++ b/plugins/chat/src/web/composer/composer.browser.test.tsx @@ -1,6 +1,6 @@ import { FileTextIcon, GitBranchIcon, SparklesIcon } from "lucide-react"; import { useState } from "react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { page, userEvent } from "vitest/browser"; import { KernelCommand, type CommandHandler, type PluginEntry } from "@kilo-desktop/kernel"; @@ -751,3 +751,62 @@ describe("a kept work session's composer", () => { await expect.element(shownInput()).toHaveTextContent("After"); }); }); + +describe("the composer of a chat still opening", () => { + /** Opens chat "ses_a" in the pane, its details held until `release` is called. */ + async function openHeldChat() { + const server = new FakeKiloServer(); + server.addChat({ id: "ses_a", directory: "/projects/app", title: "Chat" }); + let release!: () => void; + server.chatReadGate = new Promise((resolve) => { + release = resolve; + }); + await renderChat({ + server, + pane: agentPane({ object: chatPaneObject("ses_a") }), + chats: [chatSummary("ses_a")], + }); + await expect.poll(() => server.requestsTo("GET", "/session/ses_a").length).toBeGreaterThan(0); + return release; + } + + it("takes no typing until the chat's thread is ready, then takes it", async () => { + const release = await openHeldChat(); + + await expect.element(input()).toHaveAttribute("contenteditable", "false"); + + release(); + await expect.element(input()).toHaveAttribute("contenteditable", "true"); + await userEvent.type(input(), "Hello"); + await expect.element(input()).toHaveTextContent("Hello"); + }); + + it("says the chat is loading while it's slow to open", async () => { + const release = await openHeldChat(); + + await expect.element(page.getByText("Loading chat…")).toBeVisible(); + + release(); + await expect.element(page.getByText("Loading chat…")).not.toBeInTheDocument(); + }); + + it("doesn't flash the loading text for a chat that opens at once", async () => { + let flashed = false; + const watcher = new MutationObserver(() => { + if (document.body.textContent?.includes("Loading chat…")) flashed = true; + }); + watcher.observe(document.body, { childList: true, subtree: true, characterData: true }); + onTestFinished(() => watcher.disconnect()); + const server = new FakeKiloServer(); + server.addChat({ id: "ses_a", directory: "/projects/app", title: "Chat" }); + await renderChat({ + server, + pane: agentPane({ object: chatPaneObject("ses_a") }), + chats: [chatSummary("ses_a")], + }); + + await expect.element(input()).toHaveAttribute("contenteditable", "true"); + watcher.disconnect(); + expect(flashed).toBe(false); + }); +}); diff --git a/plugins/chat/src/web/composer/kilo-lexical-composer-input.tsx b/plugins/chat/src/web/composer/kilo-lexical-composer-input.tsx index c4537562..876352e3 100644 --- a/plugins/chat/src/web/composer/kilo-lexical-composer-input.tsx +++ b/plugins/chat/src/web/composer/kilo-lexical-composer-input.tsx @@ -10,7 +10,7 @@ import { KEY_ENTER_COMMAND, PASTE_COMMAND, } from "lexical"; -import type { Unstable_DirectiveFormatter } from "@assistant-ui/react"; +import type { AssistantState, Unstable_DirectiveFormatter } from "@assistant-ui/react"; import { type CSSProperties, type FC, @@ -56,6 +56,7 @@ export const KiloLexicalComposerInput: FC = ({ style, }) => { const editorGeneration = useEditorGeneration(); + const slowToOpen = useSlowToOpen(); // Cached on `ref`, so a re-render doesn't detach and re-attach it (and set the label again). const attachInput = (node: HTMLDivElement | null) => { if (typeof ref === "function") ref(node); @@ -68,10 +69,11 @@ export const KiloLexicalComposerInput: FC = ({ ref={attachInput} formatter={formatter} directiveChip={KiloDirectiveChip} - placeholder={placeholder} + placeholder={slowToOpen ? "Loading chat…" : placeholder} cancelOnEscape={cancelOnEscape} submitMode={submitMode} aria-label="Message input" + aria-busy={slowToOpen || undefined} onKeyDown={onKeyDown} className={cn( "aui-composer-input caret-foreground max-h-32 w-full bg-transparent px-1 pt-0 pb-1 text-sm", @@ -80,6 +82,7 @@ export const KiloLexicalComposerInput: FC = ({ style={style} > + @@ -131,6 +134,55 @@ function LexicalInputAria({ label }: { label: string }) { return null; } +/** + * Whether the runtime shows assistant-ui's empty placeholder thread instead of + * a real one. Only the placeholder has no extras: every real thread, a draft + * included, carries its message queue controls, given by the `messageQueue` + * with `userControls` that use-chat-runtime passes react-opencode. + */ +const showsPlaceholderThread = (s: AssistantState) => s.thread.extras === undefined; + +const SLOW_TO_OPEN_DELAY_MS = 400; + +/** + * Whether the placeholder thread has been shown long enough to say so. Most + * chats replace it within a frame, where a "Loading chat…" would only flash. + */ +function useSlowToOpen(): boolean { + const opening = useAuiState(showsPlaceholderThread); + const [slow, setSlow] = useState(false); + if (!opening && slow) setSlow(false); + useEffect(() => { + if (!opening || slow) return; + const timeoutId = window.setTimeout(() => setSlow(true), SLOW_TO_OPEN_DELAY_MS); + return () => window.clearTimeout(timeoutId); + }, [opening, slow]); + return opening && slow; +} + +/** + * Keeps the editor read-only while the runtime shows assistant-ui's empty + * placeholder thread, as it does until an opened chat's thread runtime is + * attached (seconds on a server still starting). The placeholder's composer + * throws on every edit, and SyncPlugin pushes each keystroke into it from a + * Lexical listener, where nothing catches the error. + * + * LexicalComposerInput sets the editor's editable state from its own rule + * (thread disabled, dictation blocking input) first, so this repeats that rule + * and has the last word; recheck it when upgrading @assistant-ui/react-lexical. + */ +function PlaceholderThreadLockPlugin() { + const [editor] = useLexicalComposerContext(); + const editable = useAuiState( + (s) => + !showsPlaceholderThread(s) && !s.thread.isDisabled && !s.composer.dictation?.inputDisabled, + ); + useEffect(() => { + editor.setEditable(editable); + }, [editor, editable]); + return null; +} + // LexicalComposerInput has no equivalent of ComposerPrimitive.Input's // addAttachmentOnPaste, so pasted files must be intercepted here. Runs at HIGH // priority, ahead of PlainTextPlugin's EDITOR-priority text insertion; returning diff --git a/plugins/chat/src/web/runtime/use-chat-runtime.ts b/plugins/chat/src/web/runtime/use-chat-runtime.ts index 84096cd0..d7a68b8f 100644 --- a/plugins/chat/src/web/runtime/use-chat-runtime.ts +++ b/plugins/chat/src/web/runtime/use-chat-runtime.ts @@ -158,6 +158,8 @@ export function useChatRuntime(options: ChatRuntimeOptions): AssistantRuntime { }, messageQueue: { cancelBehavior: "pause", + // Also gives every real thread extras, which the composer input tells + // assistant-ui's empty placeholder thread apart by. userControls: true, create: createQueue, },