Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions plugins/chat/src/test/fake-kilo-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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<void>;

/** Milliseconds a chat's messages take to arrive, as a long history does. */
historyReadDelayMs = 0;

Expand Down
58 changes: 58 additions & 0 deletions plugins/chat/src/web/composer/composer.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -751,3 +751,61 @@ 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 });
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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: The MutationObserver leaks when an assertion above fails

watcher.disconnect() runs only on the happy path: if renderChat() throws or toHaveAttribute("contenteditable", "true") times out (a slow CI run would do it), the observer stays attached to document.body for the rest of this test file, retaining its callback and inspecting every later mutation. Disconnect it in a try/finally so a failed assertion can't leave it observing.

expect(flashed).toBe(false);
});
});
56 changes: 54 additions & 2 deletions plugins/chat/src/web/composer/kilo-lexical-composer-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -56,6 +56,7 @@ export const KiloLexicalComposerInput: FC<KiloLexicalComposerInputProps> = ({
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);
Expand All @@ -68,10 +69,11 @@ export const KiloLexicalComposerInput: FC<KiloLexicalComposerInputProps> = ({
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",
Expand All @@ -80,6 +82,7 @@ export const KiloLexicalComposerInput: FC<KiloLexicalComposerInputProps> = ({
style={style}
>
<LexicalInputAria label="Message input" />
<PlaceholderThreadLockPlugin />
<AttachmentPastePlugin />
<SteerQueueOnEnterPlugin disabled={disabled} submitMode={submitMode} />
<QueueEnterWhileRunningPlugin />
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions plugins/chat/src/web/runtime/use-chat-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down