Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6387: guard chat rename during IME composition (#7192)

Multica Eve4389b0f0757c
diff --git a/packages/views/chat/components/chat-session-header.test.tsx b/packages/views/chat/components/chat-session-header.test.tsx
new file mode 100644
index 0000000000..357721cc4d
--- /dev/null
+++ b/packages/views/chat/components/chat-session-header.test.tsx
@@ -0,0 +1,182 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { ChatSession } from "@multica/core/types";
+import enChat from "../../locales/en/chat.json";
+
+const updateMutate = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({ agentDetail: (id: string) => `/agents/${id}` }),
+}));
+
+vi.mock("@multica/core/chat/mutations", () => ({
+ useUpdateChatSession: () => ({ mutate: updateMutate }),
+ useDeleteChatSession: () => ({ mutate: vi.fn() }),
+ useSetChatSessionArchived: () => ({ mutate: vi.fn() }),
+}));
+
+vi.mock("@multica/core/chat", () => ({
+ useChatStore: (selector: (state: { setActiveSession: () => void }) => unknown) =>
+ selector({ setActiveSession: vi.fn() }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+
+vi.mock("../../navigation", () => ({
+ AppLink: ({ children }: { children: React.ReactNode }) => <a>{children}</a>,
+}));
+
+import { ChatSessionHeader } from "./chat-session-header";
+
+const TEST_RESOURCES = { en: { chat: enChat } };
+const RENAME_LABEL = enChat.header.rename;
+const OUTSIDE_LABEL = "Outside control";
+
+const session: ChatSession = {
+ id: "session-1",
+ workspace_id: "ws-1",
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: "Original title",
+ status: "active",
+ has_unread: false,
+ unread_count: 0,
+ last_message: null,
+ pinned: false,
+ created_at: new Date(0).toISOString(),
+ updated_at: new Date(0).toISOString(),
+};
+
+function startRename(): HTMLInputElement {
+ render(
+ <>
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatSessionHeader session={session} agent={null} />
+ </I18nProvider>
+ <button type="button">{OUTSIDE_LABEL}</button>
+ </>,
+ );
+ fireEvent.click(screen.getByTitle(RENAME_LABEL));
+ return screen.getByRole("textbox", { name: RENAME_LABEL });
+}
+
+describe("ChatSessionHeader rename keyboard behavior", () => {
+ beforeEach(() => {
+ updateMutate.mockReset();
+ });
+
+ it.each([
+ ["standard composition signal", { isComposing: true, keyCode: 13 }],
+ ["Safari composition signal", { isComposing: false, keyCode: 229 }],
+ ])("keeps editing when Enter carries the %s", (_name, eventInit) => {
+ const input = startRename();
+ fireEvent.change(input, { target: { value: "yanjiu" } });
+
+ fireEvent.keyDown(input, { key: "Enter", ...eventInit });
+
+ expect(updateMutate).not.toHaveBeenCalled();
+ expect(input).toBeInTheDocument();
+ expect(input).toHaveValue("yanjiu");
+ });
+
+ it("submits once on a normal Enter", () => {
+ const input = startRename();
+ fireEvent.change(input, { target: { value: "Renamed chat" } });
+
+ fireEvent.keyDown(input, { key: "Enter", isComposing: false, keyCode: 13 });
+
+ expect(updateMutate).toHaveBeenCalledTimes(1);
+ expect(updateMutate).toHaveBeenCalledWith({
+ sessionId: "session-1",
+ title: "Renamed chat",
+ });
+ expect(screen.queryByRole("textbox", { name: RENAME_LABEL })).not.toBeInTheDocument();
+ });
+
+ it("defers blur submission until an active composition ends", () => {
+ const input = startRename();
+ const outside = screen.getByRole("button", { name: OUTSIDE_LABEL });
+ fireEvent.change(input, { target: { value: "yanjiu" } });
+ fireEvent.compositionStart(input);
+
+ act(() => {
+ outside.focus();
+ });
+
+ expect(updateMutate).not.toHaveBeenCalled();
+ expect(input).toBeInTheDocument();
+ expect(outside).toHaveFocus();
+
+ fireEvent.change(input, { target: { value: "研究" } });
+ fireEvent.compositionEnd(input);
+
+ expect(updateMutate).toHaveBeenCalledTimes(1);
+ expect(updateMutate).toHaveBeenCalledWith({
+ sessionId: "session-1",
+ title: "研究",
+ });
+ expect(screen.queryByRole("textbox", { name: RENAME_LABEL })).not.toBeInTheDocument();
+ });
+
+ it("closes without saving a partial value when compositionend does not arrive", async () => {
+ const input = startRename();
+ const outside = screen.getByRole("button", { name: OUTSIDE_LABEL });
+ fireEvent.change(input, { target: { value: "yanjiu" } });
+ fireEvent.compositionStart(input);
+
+ act(() => {
+ outside.focus();
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByRole("textbox", { name: RENAME_LABEL })).not.toBeInTheDocument();
+ });
+ expect(updateMutate).not.toHaveBeenCalled();
+ expect(screen.getByText("Original title")).toBeInTheDocument();
+ });
+
+ it("still submits the current value when focus moves outside", () => {
+ const input = startRename();
+ const outside = screen.getByRole("button", { name: OUTSIDE_LABEL });
+ fireEvent.change(input, { target: { value: "Blurred title" } });
+
+ act(() => {
+ outside.focus();
+ });
+
+ expect(updateMutate).toHaveBeenCalledTimes(1);
+ expect(updateMutate).toHaveBeenCalledWith({
+ sessionId: "session-1",
+ title: "Blurred title",
+ });
+ expect(outside).toHaveFocus();
+ });
+
+ it.each([
+ ["standard composition signal", { isComposing: true, keyCode: 27 }],
+ ["Safari composition signal", { isComposing: false, keyCode: 229 }],
+ ])("keeps editing when Escape carries the %s", (_name, eventInit) => {
+ const input = startRename();
+ fireEvent.change(input, { target: { value: "yanjiu" } });
+
+ fireEvent.keyDown(input, { key: "Escape", ...eventInit });
+
+ expect(updateMutate).not.toHaveBeenCalled();
+ expect(input).toBeInTheDocument();
+ expect(input).toHaveValue("yanjiu");
+ });
+
+ it("still cancels the edit on Escape", () => {
+ const input = startRename();
+ fireEvent.change(input, { target: { value: "Discard me" } });
+
+ fireEvent.keyDown(input, { key: "Escape" });
+
+ expect(updateMutate).not.toHaveBeenCalled();
+ expect(screen.queryByRole("textbox", { name: RENAME_LABEL })).not.toBeInTheDocument();
+ expect(screen.getByText("Original title")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/chat/components/chat-session-header.tsx b/packages/views/chat/components/chat-session-header.tsx
index 6eadfde1a0..126e87db02 100644
--- a/packages/views/chat/components/chat-session-header.tsx
+++ b/packages/views/chat/components/chat-session-header.tsx
@@ -28,6 +28,7 @@ import {
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
import type { Agent, ChatSession } from "@multica/core/types";
+import { isImeComposing } from "@multica/core/utils";
import { ActorAvatar } from "../../common/actor-avatar";
import { AppLink } from "../../navigation";
import { useT } from "../../i18n";
@@ -63,6 +64,11 @@ export function ChatSessionHeader({
const [confirmDelete, setConfirmDelete] = useState(false);
const [draft, setDraft] = useState(session.title ?? "");
const inputRef = useRef<HTMLInputElement>(null);
+ const isComposingRef = useRef(false);
+ // A browser can blur the input before it emits compositionend. Remember
+ // that intent so the final composed value is committed, not the draft.
+ const commitAfterCompositionRef = useRef(false);
+ const blurCommitTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const title = session.title?.trim() || t(($) => $.window.untitled);
@@ -73,14 +79,35 @@ export function ChatSessionHeader({
}
}, [editing]);
+ useEffect(
+ () => () => {
+ if (blurCommitTimeoutRef.current !== null) {
+ clearTimeout(blurCommitTimeoutRef.current);
+ }
+ },
+ [],
+ );
+
+ const clearPendingBlurCommit = () => {
+ if (blurCommitTimeoutRef.current === null) return;
+ clearTimeout(blurCommitTimeoutRef.current);
+ blurCommitTimeoutRef.current = null;
+ };
+
const startRename = () => {
+ clearPendingBlurCommit();
+ isComposingRef.current = false;
+ commitAfterCompositionRef.current = false;
setDraft(session.title ?? "");
setEditing(true);
};
- const commitRename = () => {
+ const commitRename = (raw = draft) => {
+ clearPendingBlurCommit();
+ isComposingRef.current = false;
+ commitAfterCompositionRef.current = false;
setEditing(false);
- const trimmed = draft.trim();
+ const trimmed = raw.trim();
if (!trimmed || trimmed === session.title) return;
updateSession.mutate({ sessionId: session.id, title: trimmed });
};
@@ -113,13 +140,50 @@ export function ChatSessionHeader({
maxLength={200}
aria-label={t(($) => $.header.rename)}
onChange={(e) => setDraft(e.target.value)}
- onBlur={commitRename}
+ onCompositionStart={() => {
+ isComposingRef.current = true;
+ }}
+ onCompositionEnd={(e) => {
+ isComposingRef.current = false;
+ if (!commitAfterCompositionRef.current) return;
+ commitRename(e.currentTarget.value);
+ }}
+ onBlur={(e) => {
+ if (isComposingRef.current) {
+ commitAfterCompositionRef.current = true;
+ const input = e.currentTarget;
+ // Let a compositionend queued by the same focus change win.
+ // If it never arrives, commit on the next task instead of
+ // leaving an unfocused editor open indefinitely.
+ clearPendingBlurCommit();
+ blurCommitTimeoutRef.current = setTimeout(() => {
+ if (!commitAfterCompositionRef.current) return;
+ // Without compositionend, the current DOM value is not
+ // known to be final. Close without persisting a partial
+ // composition instead of recreating the original bug.
+ if (isComposingRef.current) {
+ clearPendingBlurCommit();
+ isComposingRef.current = false;
+ commitAfterCompositionRef.current = false;
+ setEditing(false);
+ return;
+ }
+ commitRename(input.value);
+ }, 0);
+ return;
+ }
+ commitRename(e.currentTarget.value);
+ }}
onKeyDown={(e) => {
+ if (isImeComposing(e)) return;
if (e.key === "Enter") {
e.preventDefault();
commitRename();
} else if (e.key === "Escape") {
e.preventDefault();
+ clearPendingBlurCommit();
+ isComposingRef.current = false;
+ commitAfterCompositionRef.current = false;
setEditing(false);
}
}}
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index ff3771d8eb..682bd34176 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -71,6 +71,7 @@ import { useChatInputFocus } from "./use-chat-input-focus";
import { ChatMessageList, ChatMessageSkeleton } from "./chat-message-list";
import { ChatInput } from "./chat-input";
import { ChatQueue } from "./chat-queue";
+import { SessionRenameInput } from "./session-rename-input";
import { ChatResizeHandles } from "./chat-resize-handles";
import { useChatContextItems } from "./use-chat-context-items";
import { useChatResize } from "./use-chat-resize";
@@ -1576,83 +1577,6 @@ function SessionDropdown({
);
}
-/**
- * Inline editor for a session title. Mounts focused with the existing
- * title pre-selected so the user can either replace it outright or arrow
- * into the existing text. Enter commits, Escape cancels, a real click
- * outside the input also commits.
- *
- * We do NOT commit on the input's `blur` event: the history popover can
- * move focus to sibling rows and nested actions while the user is still
- * interacting with the panel. Instead a document-level `pointerdown`
- * listener commits only when the user actually clicks outside the input.
- */
-function SessionRenameInput({
- initialValue,
- onSubmit,
- onCancel,
-}: {
- initialValue: string;
- onSubmit: (value: string) => void;
- onCancel: () => void;
-}) {
- const { t } = useT("chat");
- const [value, setValue] = useState(initialValue);
- const inputRef = useRef<HTMLInputElement>(null);
- // Hold the latest value + callback in refs so the mount-only effect's
- // listener always sees fresh state without re-subscribing on every
- // keystroke (which would briefly leave a window where pointerdown isn't
- // observed).
- const valueRef = useRef(value);
- valueRef.current = value;
- const onSubmitRef = useRef(onSubmit);
- onSubmitRef.current = onSubmit;
-
- useEffect(() => {
- inputRef.current?.focus();
- inputRef.current?.select();
-
- const handlePointerDown = (e: PointerEvent) => {
- const input = inputRef.current;
- if (!input) return;
- if (input.contains(e.target as Node)) return;
- onSubmitRef.current(valueRef.current);
- };
- // Capture phase — commit before outside-click handling can close the
- // popover and unmount this component.
- document.addEventListener("pointerdown", handlePointerDown, true);
- return () => {
- document.removeEventListener("pointerdown", handlePointerDown, true);
- };
- }, []);
-
- return (
- <input
- ref={inputRef}
- type="text"
- value={value}
- maxLength={200}
- aria-label={t(($) => $.session_history.row_rename_aria)}
- onChange={(e) => setValue(e.target.value)}
- onClick={(e) => e.stopPropagation()}
- onPointerDown={(e) => e.stopPropagation()}
- onKeyDown={(e) => {
- // Keep editing keys inside the input instead of letting the row
- // selection keyboard handler consume them.
- e.stopPropagation();
- if (e.key === "Enter") {
- e.preventDefault();
- onSubmit(value);
- } else if (e.key === "Escape") {
- e.preventDefault();
- onCancel();
- }
- }}
- className="w-full rounded-sm bg-background px-1 py-0.5 text-body outline-none ring-1 ring-border focus-visible:ring-brand"
- />
- );
-}
-
function useFormatTimeAgo(): (dateStr: string) => string {
const { t } = useT("chat");
return (dateStr: string) => {
diff --git a/packages/views/chat/components/session-rename-input.test.tsx b/packages/views/chat/components/session-rename-input.test.tsx
new file mode 100644
index 0000000000..e8a64941e9
--- /dev/null
+++ b/packages/views/chat/components/session-rename-input.test.tsx
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enChat from "../../locales/en/chat.json";
+import { SessionRenameInput } from "./session-rename-input";
+
+const TEST_RESOURCES = { en: { chat: enChat } };
+const RENAME_LABEL = enChat.session_history.row_rename_aria;
+const onSubmit = vi.fn();
+const onCancel = vi.fn();
+
+function renderInput(): HTMLInputElement {
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <SessionRenameInput
+ initialValue="Original title"
+ onSubmit={onSubmit}
+ onCancel={onCancel}
+ />
+ </I18nProvider>,
+ );
+ return screen.getByRole("textbox", { name: RENAME_LABEL });
+}
+
+describe("SessionRenameInput", () => {
+ beforeEach(() => {
+ onSubmit.mockReset();
+ onCancel.mockReset();
+ });
+
+ it.each([
+ ["standard composition signal", { isComposing: true, keyCode: 13 }],
+ ["Safari composition signal", { isComposing: false, keyCode: 229 }],
+ ])("does not submit Enter with the %s", (_name, eventInit) => {
+ const input = renderInput();
+ fireEvent.change(input, { target: { value: "yanjiu" } });
+
+ fireEvent.keyDown(input, { key: "Enter", ...eventInit });
+
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(input).toHaveValue("yanjiu");
+ });
+
+ it("submits the latest value on outside pointerdown", () => {
+ const input = renderInput();
+ fireEvent.change(input, { target: { value: "研究" } });
+ fireEvent.pointerDown(document.body);
+
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(onSubmit).toHaveBeenCalledWith("研究");
+ });
+
+ it.each([
+ ["standard composition signal", { isComposing: true, keyCode: 27 }],
+ ["Safari composition signal", { isComposing: false, keyCode: 229 }],
+ ])("does not cancel Escape with the %s", (_name, eventInit) => {
+ const input = renderInput();
+ fireEvent.change(input, { target: { value: "yanjiu" } });
+
+ fireEvent.keyDown(input, { key: "Escape", ...eventInit });
+
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(input).toHaveValue("yanjiu");
+ });
+
+ it("keeps normal Enter and Escape behavior", () => {
+ const input = renderInput();
+ fireEvent.change(input, { target: { value: "Renamed chat" } });
+
+ fireEvent.keyDown(input, { key: "Enter", isComposing: false, keyCode: 13 });
+ fireEvent.keyDown(input, { key: "Escape" });
+
+ expect(onSubmit).toHaveBeenCalledTimes(1);
+ expect(onSubmit).toHaveBeenCalledWith("Renamed chat");
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/chat/components/session-rename-input.tsx b/packages/views/chat/components/session-rename-input.tsx
new file mode 100644
index 0000000000..720868700a
--- /dev/null
+++ b/packages/views/chat/components/session-rename-input.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { isImeComposing } from "@multica/core/utils";
+import { useT } from "../../i18n";
+
+/**
+ * Inline editor for a session title. Mounts focused with the existing
+ * title pre-selected so the user can either replace it outright or arrow
+ * into the existing text. Enter commits, Escape cancels, a real click
+ * outside the input also commits.
+ *
+ * We do NOT commit on the input's `blur` event: the history popover can
+ * move focus to sibling rows and nested actions while the user is still
+ * interacting with the panel. Instead a document-level `pointerdown`
+ * listener commits only when the user actually clicks outside the input.
+ */
+export function SessionRenameInput({
+ initialValue,
+ onSubmit,
+ onCancel,
+}: {
+ initialValue: string;
+ onSubmit: (value: string) => void;
+ onCancel: () => void;
+}) {
+ const { t } = useT("chat");
+ const [value, setValue] = useState(initialValue);
+ const inputRef = useRef<HTMLInputElement>(null);
+ // Hold the latest value + callback in refs so the mount-only effect's
+ // listener always sees fresh state without re-subscribing on every
+ // keystroke (which would briefly leave a window where pointerdown isn't
+ // observed).
+ const valueRef = useRef(value);
+ valueRef.current = value;
+ const onSubmitRef = useRef(onSubmit);
+ onSubmitRef.current = onSubmit;
+
+ useEffect(() => {
+ inputRef.current?.focus();
+ inputRef.current?.select();
+
+ const handlePointerDown = (e: PointerEvent) => {
+ const input = inputRef.current;
+ if (!input) return;
+ if (input.contains(e.target as Node)) return;
+ onSubmitRef.current(valueRef.current);
+ };
+ // Capture phase — commit before outside-click handling can close the
+ // popover and unmount this component.
+ document.addEventListener("pointerdown", handlePointerDown, true);
+ return () => {
+ document.removeEventListener("pointerdown", handlePointerDown, true);
+ };
+ }, []);
+
+ return (
+ <input
+ ref={inputRef}
+ type="text"
+ value={value}
+ maxLength={200}
+ aria-label={t(($) => $.session_history.row_rename_aria)}
+ onChange={(e) => setValue(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ // Keep editing keys inside the input instead of letting the row
+ // selection keyboard handler consume them.
+ e.stopPropagation();
+ if (isImeComposing(e)) return;
+ if (e.key === "Enter") {
+ e.preventDefault();
+ onSubmit(value);
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ className="w-full rounded-sm bg-background px-1 py-0.5 text-body outline-none ring-1 ring-border focus-visible:ring-brand"
+ />
+ );
+}