feat(webui): rename sidebar topics inline

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-18 01:48:42 +08:00
1 parent 7edd377352
commit d9537bcc94
23 files changed
+736 -68

No files matched your search

+7 -40
View File
@@ -1212,6 +1212,7 @@ function Shell({
state: sidebarState,
loading: sidebarStateLoading,
update: updateSidebarState,
rename: onRequestRename,
} =
useSidebarState(sessions, sessionsLoaded);
const initialRouteRef = useRef<ShellRoute | null>(null);
@@ -1262,10 +1263,6 @@ function Shell({
items: SidebarDeleteItem[];
automations?: SessionAutomationJob[];
} | null>(null);
const [pendingRename, setPendingRename] = useState<{
key: string;
label: string;
} | null>(null);
const [pendingTabRename, setPendingTabRename] = useState<{
key: string;
label: string;
@@ -1983,32 +1980,6 @@ function Shell({
[updateSidebarState],
);
const onRequestRename = useCallback((key: string, label: string) => {
setPendingRename({ key, label });
}, []);
const onConfirmRename = useCallback(
(title: string) => {
if (!pendingRename) return;
const key = pendingRename.key;
setPendingRename(null);
void updateSidebarState((current) => {
const titleOverrides = { ...current.title_overrides };
const cleaned = title.trim();
if (cleaned) {
titleOverrides[key] = cleaned;
} else {
delete titleOverrides[key];
}
return {
...current,
title_overrides: titleOverrides,
};
});
},
[pendingRename, updateSidebarState],
);
const onRequestRenameTab = useCallback((key: string, label: string) => {
setPendingTabRename({ key, label });
}, []);
@@ -2926,6 +2897,12 @@ function Shell({
>
<SheetContent
ref={mobileSidebarRef}
onEscapeKeyDown={(event) => {
if (event.target instanceof Element
&& event.target.closest("[data-sidebar-topic-rename]")) {
event.preventDefault();
}
}}
onOpenAutoFocus={(event) => {
// Keep opening navigation from focusing the search tooltip trigger.
event.preventDefault();
@@ -3177,16 +3154,6 @@ function Shell({
/>
</Suspense>
) : null}
{pendingRename ? (
<Suspense fallback={null}>
<RenameChatDialog
open
title={pendingRename.label}
onCancel={() => setPendingRename(null)}
onConfirm={onConfirmRename}
/>
</Suspense>
) : null}
{pendingTabRename ? (
<Suspense fallback={null}>
<RenameChatDialog
+50 -10
View File
@@ -47,6 +47,7 @@ import {
HoverHint,
} from "@/components/ui/tooltip";
import { MAX_WORKBENCH_PANES } from "@/components/workbench/workbench-model";
import { SidebarTopicRename } from "@/components/SidebarTopicRename";
import {
SIDEBAR_SELECTION_ITEM_CLASS,
SidebarSelectionHighlight,
@@ -225,7 +226,7 @@ interface ChatListProps {
onRequestDelete: (key: string, label: string) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[]) => void;
onTogglePin: (key: string) => void;
onRequestRename: (key: string, label: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
onRequestRenameTab?: (key: string, label: string) => void;
onToggleArchive: (key: string) => void;
paneGroups?: Record<string, SidebarPaneGroup>;
@@ -339,6 +340,22 @@ export const ChatList = memo(function ChatList({
const [paneDropTarget, setPaneDropTarget] = useState<string | null>(null);
const [deleteSelectionMode, setDeleteSelectionMode] = useState(false);
const [openActionMenuId, setOpenActionMenuId] = useState<string | null>(null);
const [renamingTopic, setRenamingTopic] = useState<{ key: string } | null>(null);
const renamingKey = renamingTopic?.key ?? null;
const previousRenamingKeyRef = useRef<string | null>(null);
const beginRename = (key: string) => setRenamingTopic({ key });
const endRename = () => {
setRenamingTopic((current) => current === renamingTopic ? null : current);
};
useLayoutEffect(() => {
const previousKey = previousRenamingKeyRef.current;
previousRenamingKeyRef.current = renamingKey;
if (renamingKey !== null || previousKey === null) return;
const row = Array.from(scrollViewportRef.current?.querySelectorAll<HTMLElement>(
"[data-chat-row]",
) ?? []).find((element) => element.dataset.chatRow === previousKey);
row?.querySelector<HTMLButtonElement>("button")?.focus({ preventScroll: true });
}, [renamingKey]);
const [selectedDeleteKeys, setSelectedDeleteKeys] = useState<Set<string>>(
() => new Set(),
);
@@ -904,6 +921,9 @@ export const ChatList = memo(function ChatList({
onSelectPane={onSelectPane}
onRequestDelete={onRequestDelete}
onRequestRename={onRequestRename}
renamingKey={renamingKey}
onBeginRename={beginRename}
onEndRename={endRename}
onTogglePin={onTogglePin}
onToggleArchive={onToggleArchive}
pinned={pinnedPanes}
@@ -968,7 +988,14 @@ export const ChatList = memo(function ChatList({
&& "bg-sidebar-accent/55 text-sidebar-accent-foreground",
)}
>
<button
{renamingKey === s.key ? (
<SidebarTopicRename
key={s.key}
title={title}
onSave={(nextTitle) => onRequestRename(s.key, nextTitle)}
onClose={endRename}
/>
) : <button
type="button"
onClick={(event) => {
if (deleteSelectionMode) {
@@ -1011,9 +1038,9 @@ export const ChatList = memo(function ChatList({
</span>
{isPinned ? <PinnedChatIndicator /> : null}
</span>
</button>
</button>}
<SessionActivityIndicator state={activityState} />
{!deleteSelectionMode ? (
{!deleteSelectionMode && renamingKey !== s.key ? (
<DropdownMenu
modal={false}
open={actionMenus.openId === actionMenuId}
@@ -1043,7 +1070,7 @@ export const ChatList = memo(function ChatList({
{isPinned ? t("chat.unpin") : t("chat.pin")}
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => onRequestRename(s.key, title)}
onSelect={() => beginRename(s.key)}
>
<Pencil className="h-4 w-4 shrink-0" />
{t("chat.rename")}
@@ -1319,6 +1346,9 @@ function ActivePaneRows({
onSelectPane,
onRequestDelete,
onRequestRename,
renamingKey,
onBeginRename,
onEndRename,
onTogglePin,
onToggleArchive,
pinned,
@@ -1343,7 +1373,10 @@ function ActivePaneRows({
recovery: ReadonlySet<string>;
onSelectPane?: (tabKey: string, paneKey: string) => void;
onRequestDelete: (key: string, label: string) => void;
onRequestRename: (key: string, label: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
renamingKey: string | null;
onBeginRename: (key: string) => void;
onEndRename: () => void;
onTogglePin: (key: string) => void;
onToggleArchive: (key: string) => void;
pinned: ReadonlySet<string>;
@@ -1414,7 +1447,14 @@ function ActivePaneRows({
&& "bg-sidebar-accent/55 text-sidebar-accent-foreground",
)}
>
<button
{renamingKey === pane.key ? (
<SidebarTopicRename
key={pane.key}
title={pane.title}
onSave={(nextTitle) => onRequestRename(pane.key, nextTitle)}
onClose={onEndRename}
/>
) : <button
type="button"
onClick={(event) => {
if (deleteSelectionMode) {
@@ -1450,9 +1490,9 @@ function ActivePaneRows({
{isPinned ? <PinnedChatIndicator /> : null}
</span>
</button>
</button>}
<SessionActivityIndicator state={activityState} />
{!deleteSelectionMode ? <DropdownMenu
{!deleteSelectionMode && renamingKey !== pane.key ? <DropdownMenu
modal={false}
open={actionMenus.openId === actionMenuId}
onOpenChange={(open) => actionMenus.onOpenChange(actionMenuId, open)}
@@ -1479,7 +1519,7 @@ function ActivePaneRows({
{isPinned ? t("chat.unpin") : t("chat.pin")}
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => onRequestRename(pane.key, pane.title)}
onSelect={() => onBeginRename(pane.key)}
>
<Pencil className="h-4 w-4 shrink-0" />
{t("chat.rename")}
+1 -1
View File
@@ -49,7 +49,7 @@ interface SidebarProps {
onRequestDelete: (key: string, label: string) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[]) => void;
onTogglePin: (key: string) => void;
onRequestRename: (key: string, label: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
onRequestRenameTab?: (key: string, label: string) => void;
onToggleArchive: (key: string) => void;
paneGroups?: Record<string, SidebarPaneGroup>;
+115
View File
@@ -0,0 +1,115 @@
import { useEffect, useId, useRef, useState } from "react";
import { Check, Loader2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Input } from "@/components/ui/input";
interface SidebarTopicRenameProps {
title: string;
onSave: (title: string) => Promise<void>;
onClose: () => void;
}
export function SidebarTopicRename({ title, onSave, onClose }: SidebarTopicRenameProps) {
const { t } = useTranslation();
const [value, setValue] = useState(title);
const [saving, setSaving] = useState(false);
const [failed, setFailed] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const savingRef = useRef(false);
const composingRef = useRef(false);
const errorId = useId();
useEffect(() => {
inputRef.current?.focus();
inputRef.current?.select();
}, []);
const save = async () => {
const cleaned = value.trim();
if (!cleaned || savingRef.current) return;
savingRef.current = true;
setSaving(true);
setFailed(false);
try {
await onSave(cleaned);
onClose();
} catch {
setFailed(true);
inputRef.current?.focus();
} finally {
savingRef.current = false;
setSaving(false);
}
};
return (
<form
data-sidebar-topic-rename
className="min-w-0 flex-1 py-0.5"
aria-busy={saving}
onSubmit={(event) => {
event.preventDefault();
void save();
}}
onClick={(event) => event.stopPropagation()}
onPointerDown={(event) => event.stopPropagation()}
onContextMenu={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
const composing = composingRef.current
|| event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229;
if (event.key === "Enter" && event.target === inputRef.current) {
event.preventDefault();
if (!composing) void save();
} else if (event.key === "Escape" && !composing) {
event.preventDefault();
if (!savingRef.current) onClose();
}
}}
>
<div className="flex min-w-0 items-center gap-0.5">
<Input
ref={inputRef}
className="h-7 min-w-0 flex-1 rounded-md border-sidebar-border bg-sidebar px-1.5 py-0 text-[13px]"
aria-label={t("chat.renamePlaceholder")}
aria-invalid={failed || undefined}
aria-describedby={failed ? errorId : undefined}
placeholder={t("chat.renamePlaceholder")}
value={value}
maxLength={160}
readOnly={saving}
onCompositionStart={() => { composingRef.current = true; }}
onCompositionEnd={() => { composingRef.current = false; }}
onChange={(event) => {
setValue(event.target.value);
setFailed(false);
}}
/>
<button
type="submit"
aria-label={t("chat.renameSave")}
disabled={saving || !value.trim()}
className="touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-foreground disabled:opacity-40"
>
{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
: <Check className="h-3.5 w-3.5" aria-hidden />}
</button>
<button
type="button"
aria-label={t("deleteConfirm.cancel")}
disabled={saving}
onClick={onClose}
className="touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground disabled:opacity-40"
>
<X className="h-3.5 w-3.5" aria-hidden />
</button>
</div>
{failed ? (
<p id={errorId} role="alert" className="px-1.5 py-1 text-xs text-destructive">
{t("chat.renameFailed")}
</p>
) : null}
</form>
);
}
+4 -1
View File
@@ -65,7 +65,10 @@ function ChatsPreview() {
loading={mode === "loading"}
onTogglePin={(key) => setPinned(toggle(pinned, key))} onToggleArchive={(key) => setArchived(toggle(archived, key))}
onRequestDelete={(key) => setSessions((items) => items.filter((item) => item.key !== key))}
onRequestRename={(_, label) => setAction(`选择重命名:${label}`)} /></div>
onRequestRename={async (key, label) => {
setSessions((items) => items.map((item) => item.key === key ? { ...item, title: label } : item));
setAction(`已重命名:${label}`);
}} /></div>
<p role="status" className="mt-4 text-sm text-muted-foreground">{action || `选择的会话:${active ?? "无"}`}</p></>;
}
+65 -9
View File
@@ -130,6 +130,24 @@ function sameState(a: SidebarStatePayload, b: SidebarStatePayload): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
function withTitleOverride(
state: SidebarStatePayload,
key: string,
title: string | undefined,
): SidebarStatePayload {
const titles = { ...state.title_overrides };
if (title === undefined) delete titles[key];
else titles[key] = title;
return { ...state, title_overrides: titles };
}
type PendingRename = {
key: string;
title: string;
resolve: () => void;
reject: (error: unknown) => void;
};
export function useSidebarState(
sessions: ChatSummary[],
sessionsLoaded: boolean,
@@ -139,6 +157,7 @@ export function useSidebarState(
update: (
updater: (state: SidebarStatePayload) => SidebarStatePayload,
) => Promise<void>;
rename: (key: string, title: string) => Promise<void>;
} {
const { client, token } = useClient();
const tokenRef = useRef(token);
@@ -146,6 +165,7 @@ export function useSidebarState(
const loadedRef = useRef(false);
const connectionOpenRef = useRef(client.status === "open");
const pendingPersistenceRef = useRef<SidebarStatePayload | null>(null);
const pendingRenamesRef = useRef<PendingRename[]>([]);
const persistenceInFlightRef = useRef(false);
const flushPersistenceRef = useRef<() => void>(() => {});
const [state, setState] = useState<SidebarStatePayload>(DEFAULT_SIDEBAR_STATE);
@@ -180,34 +200,58 @@ export function useSidebarState(
};
}, []);
const rejectPendingRenames = useCallback((error: unknown) => {
for (const request of pendingRenamesRef.current.splice(0)) request.reject(error);
}, []);
const flushPersistence = useCallback(() => {
if (
!loadedRef.current
|| persistenceInFlightRef.current
|| !connectionOpenRef.current
|| pendingPersistenceRef.current === null
) return;
const next = pendingPersistenceRef.current;
const pending = pendingPersistenceRef.current;
// Optimistic snapshots must drain before a rename takes its own snapshot.
const rename = pending === null ? pendingRenamesRef.current.shift() : undefined;
const next = rename
? normalizeSidebarState(withTitleOverride(stateRef.current, rename.key, rename.title))
: pending;
if (next === null) return;
pendingPersistenceRef.current = null;
persistenceInFlightRef.current = true;
void client.setSidebarState(next)
.then((saved) => {
persistenceInFlightRef.current = false;
if (pendingPersistenceRef.current === null) {
if (rename) {
const title = normalizeSidebarState(saved).title_overrides[rename.key];
if (pendingPersistenceRef.current !== null) {
pendingPersistenceRef.current = withTitleOverride(
pendingPersistenceRef.current, rename.key, title,
);
}
const renamed = withTitleOverride(stateRef.current, rename.key, title);
stateRef.current = renamed;
setState(renamed);
rename.resolve();
} else if (pendingPersistenceRef.current === null) {
const canonical = normalizeSidebarState(saved);
stateRef.current = canonical;
setState(canonical);
}
flushPersistenceRef.current();
})
.catch(() => {
.catch((error: unknown) => {
persistenceInFlightRef.current = false;
if (pendingPersistenceRef.current === null) {
pendingPersistenceRef.current = next;
if (rename) {
rename.reject(error);
flushPersistenceRef.current();
} else {
if (pendingPersistenceRef.current === null) pendingPersistenceRef.current = next;
rejectPendingRenames(error);
}
});
}, [client]);
}, [client, rejectPendingRenames]);
flushPersistenceRef.current = flushPersistence;
const persist = useCallback((next: SidebarStatePayload) => {
@@ -218,7 +262,8 @@ export function useSidebarState(
useEffect(() => client.onStatus((status) => {
connectionOpenRef.current = status === "open";
if (status === "open") flushPersistence();
}), [client, flushPersistence]);
else rejectPendingRenames(new Error("WebUI connection is not open"));
}), [client, flushPersistence, rejectPendingRenames]);
useEffect(() => client.onSidebarStateUpdate((incoming) => {
if (
@@ -244,6 +289,17 @@ export function useSidebarState(
[persist],
);
const rename = useCallback((key: string, title: string): Promise<void> => {
if (!loadedRef.current) return Promise.reject(new Error("Sidebar state is not loaded"));
if (!connectionOpenRef.current) {
return Promise.reject(new Error("WebUI connection is not open"));
}
return new Promise<void>((resolve, reject) => {
pendingRenamesRef.current.push({ key: key.trim(), title, resolve, reject });
flushPersistence();
});
}, [flushPersistence]);
const pruned = useMemo(() => {
if (!sessionsLoaded || loading) return state;
return pruneMissingSessions(state, sessions);
@@ -254,5 +310,5 @@ export function useSidebarState(
void update(() => pruned);
}, [loading, pruned, sessionsLoaded, state, update]);
return { state, loading, update };
return { state, loading, update, rename };
}
+1
View File
@@ -1770,6 +1770,7 @@
"renameProjectDescription": "Change only this project's name in the WebUI sidebar.",
"renameProjectPlaceholder": "Project name",
"renameSave": "Save",
"renameFailed": "Couldn't save the name. Try again.",
"archive": "Archive",
"unarchive": "Unarchive",
"showArchived": "Show archived",
+1
View File
@@ -1571,6 +1571,7 @@
"renameProjectDescription": "Cambia solo el nombre del proyecto en la barra lateral WebUI.",
"renameProjectPlaceholder": "Nombre del proyecto",
"renameSave": "Guardar",
"renameFailed": "No se pudo guardar el nombre. Inténtalo de nuevo.",
"archive": "Archivar",
"unarchive": "Desarchivar",
"showArchived": "Mostrar archivados",
+1
View File
@@ -1570,6 +1570,7 @@
"renameProjectDescription": "Changez seulement le nom du projet dans la barre latérale WebUI.",
"renameProjectPlaceholder": "Nom du projet",
"renameSave": "Enregistrer",
"renameFailed": "Impossible d’enregistrer le nom. Réessayez.",
"archive": "Archiver",
"unarchive": "Désarchiver",
"showArchived": "Afficher les archives",
+1
View File
@@ -1570,6 +1570,7 @@
"renameProjectDescription": "Ubah hanya nama proyek di sidebar WebUI.",
"renameProjectPlaceholder": "Nama proyek",
"renameSave": "Simpan",
"renameFailed": "Nama tidak dapat disimpan. Coba lagi.",
"archive": "Arsipkan",
"unarchive": "Batalkan arsip",
"showArchived": "Tampilkan yang diarsipkan",
+1
View File
@@ -1570,6 +1570,7 @@
"renameProjectDescription": "WebUI のサイドバーに表示するプロジェクト名だけを変更します。",
"renameProjectPlaceholder": "プロジェクト名",
"renameSave": "保存",
"renameFailed": "名前を保存できませんでした。再試行してください。",
"archive": "アーカイブ",
"unarchive": "アーカイブを解除",
"showArchived": "アーカイブ済みを表示",
+1
View File
@@ -1570,6 +1570,7 @@
"renameProjectDescription": "WebUI 사이드바의 프로젝트 이름만 변경하세요.",
"renameProjectPlaceholder": "프로젝트 이름",
"renameSave": "저장",
"renameFailed": "이름을 저장하지 못했습니다. 다시 시도하세요.",
"archive": "보관",
"unarchive": "보관 해제",
"showArchived": "보관된 항목 표시",
+1
View File
@@ -1584,6 +1584,7 @@
"renameProjectDescription": "Altere apenas o nome do projeto na barra lateral WebUI.",
"renameProjectPlaceholder": "Nome do projeto",
"renameSave": "Salvar",
"renameFailed": "Não foi possível salvar o nome. Tente novamente.",
"archive": "Arquivar",
"unarchive": "Desarquivar",
"showArchived": "Mostrar arquivadas",
+1
View File
@@ -1570,6 +1570,7 @@
"renameProjectDescription": "Chỉ đổi tên dự án trong thanh bên WebUI.",
"renameProjectPlaceholder": "Tên dự án",
"renameSave": "Lưu",
"renameFailed": "Không thể lưu tên. Vui lòng thử lại.",
"archive": "Lưu trữ",
"unarchive": "Bỏ lưu trữ",
"showArchived": "Hiện mục đã lưu trữ",
+1
View File
@@ -1770,6 +1770,7 @@
"renameProjectDescription": "仅修改 WebUI 侧栏中的项目名称",
"renameProjectPlaceholder": "项目名称",
"renameSave": "保存",
"renameFailed": "名称保存失败,请重试。",
"archive": "归档",
"unarchive": "取消归档",
"showArchived": "显示归档",
+1
View File
@@ -1570,6 +1570,7 @@
"renameProjectDescription": "僅修改 WebUI 側欄中的專案名稱",
"renameProjectPlaceholder": "專案名稱",
"renameSave": "儲存",
"renameFailed": "名稱儲存失敗,請重試。",
"archive": "封存",
"unarchive": "取消封存",
"showArchived": "顯示封存",
+58
View File
@@ -2575,6 +2575,64 @@ describe("App layout", () => {
);
}, 15_000);
it("renames inline in the mobile drawer without dismissing it and reloads the saved title", async () => {
restoreBrowserFocus = mockBrowserFocus();
const user = userEvent.setup();
mockSessions = [{
key: "websocket:chat-a", channel: "websocket", chatId: "chat-a",
createdAt: null, updatedAt: null, title: "Existing chat", preview: "",
}];
vi.stubGlobal("matchMedia", vi.fn().mockImplementation((query: string) => ({
matches: !query.includes("1024px"), media: query, onchange: null,
addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(),
removeEventListener: vi.fn(), dispatchEvent: vi.fn(),
})));
let persisted: SidebarStatePayload | null = null;
mockFetchRoutes({ "/api/webui/sidebar-state": () => persisted ?? {} });
setSidebarStateSpy.mockImplementation(async (state: SidebarStatePayload) => {
persisted = state;
return state;
});
const firstRender = render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
act(() => statusHandlers.forEach((handler) => handler("open")));
const route = window.location.hash;
await user.click(await screen.findByRole("button", { name: "Toggle sidebar" }));
const sheet = await screen.findByRole("dialog");
const startRename = async () => {
await user.click(within(sheet).getByRole("button", { name: "Topic actions for Existing chat" }));
await user.click(await within(sheet).findByRole("menuitem", { name: "Rename", exact: true }));
return within(sheet).getByRole("textbox", { name: "Topic name" });
};
const firstInput = await startRename();
expect(screen.getAllByRole("dialog")).toHaveLength(1);
fireEvent.compositionStart(firstInput);
fireEvent.keyDown(firstInput, { key: "Escape" });
expect(firstInput).toBeInTheDocument();
expect(sheet).toBeInTheDocument();
fireEvent.compositionEnd(firstInput);
fireEvent.keyDown(firstInput, { key: "Escape" });
expect(within(sheet).queryByRole("textbox")).not.toBeInTheDocument();
expect(sheet).toBeInTheDocument();
const input = await startRename();
await user.clear(input);
await user.type(input, "Renamed topic");
setSidebarStateSpy.mockRejectedValueOnce(new Error("Disk full"));
await user.keyboard("{Enter}");
expect(await within(sheet).findByRole("alert")).toHaveTextContent("Couldn't save the name. Try again.");
expect(input).toHaveValue("Renamed topic");
expect(persisted?.title_overrides["websocket:chat-a"]).toBeUndefined();
await user.keyboard("{Enter}");
expect(await within(sheet).findByRole("button", { name: "Renamed topic", exact: true })).toBeInTheDocument();
expect(persisted?.title_overrides["websocket:chat-a"]).toBe("Renamed topic");
expect(window.location.hash).toBe(route);
expect(screen.getAllByRole("dialog")).toHaveLength(1);
firstRender.unmount();
render(<App />);
expect(await screen.findByRole("button", { name: "Renamed topic", exact: true })).toBeInTheDocument();
});
it("retries a failed sidebar read before enabling edits without losing saved state", async () => {
mockSessions = [
{
+5 -2
View File
@@ -43,7 +43,7 @@ function SidebarFocusCase() {
onTogglePin={vi.fn()}
onToggleArchive={vi.fn()}
onAttachPane={vi.fn()}
onRequestRename={(_key, title) => setRename(title)}
onRequestRename={vi.fn().mockResolvedValue(undefined)}
onRequestRenameTab={(_key, title) => setRename(title)}
onRequestRenameProject={(_key, title) => setRename(title)}
/>
@@ -94,7 +94,10 @@ describe("sidebar action focus", () => {
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
await waitFor(() => expect(input).toHaveFocus());
await user.keyboard("Updated");
expect(input).toHaveValue("ReviewUpdated");
expect(input).toHaveValue("Updated");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
await user.keyboard("{Escape}");
expect(screen.getByRole("button", { name: "Review", exact: true })).toHaveFocus();
});
it("keeps an outside click focused on its destination", async () => {
+178
View File
@@ -0,0 +1,178 @@
import { useState } from "react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ChatList } from "@/components/ChatList";
import type { ChatSummary } from "@/lib/types";
import { mockBrowserFocus } from "./browser-focus";
const topic: ChatSummary = {
key: "websocket:review", chatId: "review", channel: "websocket",
title: "Review", preview: "", createdAt: null, updatedAt: null,
};
function RenameCase({
save,
grouped = false,
onSelect = vi.fn(),
}: {
save: (key: string, title: string) => Promise<void>;
grouped?: boolean;
onSelect?: ReturnType<typeof vi.fn>;
}) {
const [titles, setTitles] = useState<Record<string, string>>({});
const title = titles[topic.key] ?? topic.title!;
return <ChatList
sessions={grouped ? [{ ...topic, key: "tab:group", title: "Group" }] : [
topic, { ...topic, key: "websocket:other", chatId: "other", title: "Other" },
]}
activeKey={null}
titleOverrides={titles}
paneGroups={grouped ? {
"tab:group": {
tabKey: "tab:group", title: "Group", activePaneKey: "websocket:other", visible: true,
panes: [{ key: topic.key, chatId: topic.chatId, title }],
},
} : {}}
onSelect={onSelect}
onSelectPane={onSelect}
onRequestDelete={vi.fn()}
onTogglePin={vi.fn()}
onToggleArchive={vi.fn()}
onRequestRename={async (key, nextTitle) => {
await save(key, nextTitle);
setTitles((current) => ({ ...current, [key]: nextTitle }));
}}
/>;
}
async function startRename(contextMenu = false, title = "Review") {
if (contextMenu) {
fireEvent.contextMenu(screen.getByRole("button", { name: title, exact: true }));
} else {
fireEvent.pointerDown(screen.getByRole("button", { name: `Topic actions for ${title}` }), {
button: 0, ctrlKey: false,
});
}
fireEvent.click(await screen.findByRole("menuitem", { name: "Rename", exact: true }));
return screen.getByRole("textbox", { name: "Topic name" });
}
describe("inline sidebar topic rename", () => {
let restoreFocus: () => void;
beforeEach(() => { restoreFocus = mockBrowserFocus(); });
afterEach(() => {
restoreFocus();
localStorage.removeItem("nanobot-webui.collapsed-pane-groups.v1");
});
it.each([false, true])("saves an inactive topic only after acknowledgement, grouped=%s", async (grouped) => {
let confirm!: () => void;
const save = vi.fn(() => new Promise<void>((resolve) => { confirm = resolve; }));
const onSelect = vi.fn();
render(<RenameCase save={save} grouped={grouped} onSelect={onSelect} />);
const input = await startRename(grouped);
expect(input).toHaveValue("Review");
await waitFor(() => expect(input).toHaveFocus());
expect(input.closest("button")).toBeNull();
expect(input).toHaveAttribute("maxlength", "160");
fireEvent.change(input, { target: { value: " Updated name " } });
fireEvent.click(input);
fireEvent.keyDown(input, { key: "Enter" });
fireEvent.keyDown(input, { key: "Enter" });
expect(save).toHaveBeenCalledTimes(1);
expect(save).toHaveBeenCalledWith(topic.key, "Updated name");
expect(input).toHaveAttribute("readonly");
expect(input.closest("form")).toHaveAttribute("aria-busy", "true");
expect(screen.queryByRole("button", { name: "Updated name", exact: true })).not.toBeInTheDocument();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(onSelect).not.toHaveBeenCalled();
await act(async () => { confirm(); });
expect(await screen.findByRole("button", { name: "Updated name", exact: true })).toHaveFocus();
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
expect(onSelect).not.toHaveBeenCalled();
});
it("does not let an older save close a newer edit of the same topic", async () => {
let confirm!: () => void;
const save = vi.fn(() => new Promise<void>((resolve) => { confirm = resolve; }));
render(<RenameCase save={save} />);
const first = await startRename();
fireEvent.change(first, { target: { value: "First saved title" } });
fireEvent.keyDown(first, { key: "Enter" });
await startRename(false, "Other");
const current = await startRename();
fireEvent.change(current, { target: { value: "Newer draft" } });
await act(async () => { confirm(); });
expect(current).toBeInTheDocument();
expect(current).toHaveValue("Newer draft");
fireEvent.keyDown(current, { key: "Escape" });
expect(screen.getByRole("button", { name: "First saved title", exact: true })).toBeInTheDocument();
});
it("retains a failed draft and allows retrying the same name", async () => {
const save = vi.fn().mockRejectedValueOnce(new Error("write failed")).mockResolvedValue(undefined);
render(<RenameCase save={save} />);
const input = await startRename();
fireEvent.change(input, { target: { value: " Keep this draft " } });
fireEvent.keyDown(input, { key: "Enter" });
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't save the name. Try again.");
expect(input).toHaveValue(" Keep this draft ");
expect(input).toHaveAttribute("aria-invalid", "true");
expect(input).toHaveFocus();
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
expect(await screen.findByRole("button", { name: "Keep this draft", exact: true })).toBeInTheDocument();
expect(save).toHaveBeenCalledTimes(2);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("cancels a failed edit with Escape without saving or switching topics", async () => {
const save = vi.fn().mockRejectedValue(new Error("write failed"));
const onSelect = vi.fn();
render(<RenameCase save={save} onSelect={onSelect} />);
const input = await startRename();
fireEvent.change(input, { target: { value: "Unconfirmed" } });
fireEvent.keyDown(input, { key: "Enter" });
await screen.findByRole("alert");
fireEvent.keyDown(input, { key: "Escape" });
expect(screen.getByRole("button", { name: "Review", exact: true })).toHaveFocus();
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
expect(save).toHaveBeenCalledTimes(1);
expect(onSelect).not.toHaveBeenCalled();
});
it("ignores blank names and IME confirmation keys, then saves once composition finishes", async () => {
const save = vi.fn().mockResolvedValue(undefined);
render(<RenameCase save={save} />);
const input = await startRename();
fireEvent.change(input, { target: { value: " " } });
fireEvent.keyDown(input, { key: "Enter" });
expect(screen.getByRole("button", { name: "Save", exact: true })).toBeDisabled();
expect(save).not.toHaveBeenCalled();
fireEvent.compositionStart(input);
fireEvent.change(input, { target: { value: "新的话题" } });
fireEvent.keyDown(input, { key: "Enter" });
fireEvent.keyDown(input, { key: "Escape" });
expect(input).toBeInTheDocument();
expect(save).not.toHaveBeenCalled();
fireEvent.compositionEnd(input);
fireEvent.keyDown(input, { key: "Enter", keyCode: 229 });
expect(save).not.toHaveBeenCalled();
fireEvent.keyDown(input, { key: "Enter" });
expect(await screen.findByRole("button", { name: "新的话题", exact: true })).toBeInTheDocument();
expect(save).toHaveBeenCalledTimes(1);
});
it("keeps keyboard activation of Cancel distinct from submitting the form", async () => {
const user = userEvent.setup();
const save = vi.fn().mockResolvedValue(undefined);
render(<RenameCase save={save} />);
await startRename();
const cancel = screen.getByRole("button", { name: "Cancel", exact: true });
cancel.focus();
await user.keyboard("{Enter}");
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
expect(save).not.toHaveBeenCalled();
});
});
+8 -2
View File
@@ -115,8 +115,11 @@ describe("ChatList", () => {
expect(trigger).toHaveClass("sidebar-action-trigger", "touch-target", "opacity-0");
fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Rename" }));
expect(onRequestRename).toHaveBeenCalledWith("websocket:review", "Review the patch");
const input = screen.getByRole("textbox", { name: "Topic name" });
expect(input).toHaveValue("Review the patch");
expect(onRequestRename).not.toHaveBeenCalled();
expect(onSelect).not.toHaveBeenCalled();
fireEvent.keyDown(input, { key: "Escape" });
fireEvent.click(screen.getByRole("button", { name: "Review the patch" }));
expect(onSelect).toHaveBeenCalledWith("websocket:review");
});
@@ -286,7 +289,10 @@ describe("ChatList", () => {
.closest("[data-sidebar-pane]")!;
fireEvent.contextMenu(paneRow);
fireEvent.click(await screen.findByRole("menuitem", { name: "Rename" }));
expect(onRequestRename).toHaveBeenCalledWith("websocket:child", "Research pane");
const input = screen.getByRole("textbox", { name: "Topic name" });
expect(input).toHaveValue("Research pane");
expect(onRequestRename).not.toHaveBeenCalled();
fireEvent.keyDown(input, { key: "Escape" });
const tabRow = screen.getByRole("button", { name: "Group: Root topic" })
.closest("[data-workbench-tab]")!;
+1 -1
View File
@@ -46,7 +46,7 @@ function LocalShell({ collapsed = false, initialRemote = false }) {
return <>
<Sidebar collapsed={collapsed} sessions={[]} activeKey={null} loading={false} newChatActive={false}
onNewChat={() => { if (connections?.managing) connections.selectLocal(); window.location.hash = "/new"; setRemotePage(false); }} onSelect={noop} onRequestDelete={noop} onTogglePin={noop}
onRequestRename={noop} onToggleArchive={noop} onToggleGroup={noop}
onRequestRename={async () => {}} onToggleArchive={noop} onToggleGroup={noop}
onRequestRenameProject={noop} onNewChatInProject={noop} onOpenSettings={noop}
onOpenApps={noop} onOpenSkills={noop} onOpenAutomations={noop} onOpenChannels={noop}
onOpenSearch={noop} onToggleArchived={noop} />
+233 -1
View File
@@ -4,9 +4,53 @@ import { describe, expect, it, vi } from "vitest";
import { useSidebarState } from "@/hooks/useSidebarState";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { SidebarStatePayload } from "@/lib/types";
import type { ConnectionStatus, SidebarStatePayload } from "@/lib/types";
import { ClientProvider } from "@/providers/ClientProvider";
type SidebarWrite = {
state: SidebarStatePayload;
resolve: (saved?: SidebarStatePayload) => void;
reject: (error: Error) => void;
};
async function renderLoadedSidebarState() {
const writes: SidebarWrite[] = [];
let status: ConnectionStatus = "open";
let onStatus: ((status: ConnectionStatus) => void) | undefined;
let onState: ((state: SidebarStatePayload) => void) | undefined;
const setSidebarState = vi.fn((state: SidebarStatePayload) => new Promise<SidebarStatePayload>(
(resolve, reject) => writes.push({ state, resolve: (saved = state) => resolve(saved), reject }),
));
const client = {
get status() { return status; },
onStatus: (handler: (status: ConnectionStatus) => void) => {
onStatus = handler;
handler(status);
return () => { onStatus = undefined; };
},
onSidebarStateUpdate: (handler: (state: SidebarStatePayload) => void) => {
onState = handler;
return () => { onState = undefined; };
},
setSidebarState,
} as unknown as NanobotClient;
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({
title_overrides: { "websocket:a": "Saved title", "websocket:b": "Other title" },
})));
const wrapper = ({ children }: { children: ReactNode }) => (
<ClientProvider client={client} token="token">{children}</ClientProvider>
);
const hook = renderHook(() => useSidebarState([], false), { wrapper });
await waitFor(() => expect(hook.result.current.loading).toBe(false));
return {
...hook,
writes,
setSidebarState,
setStatus: (next: ConnectionStatus) => { status = next; onStatus?.(next); },
receive: (state: SidebarStatePayload) => onState?.(state),
};
}
describe("useSidebarState", () => {
it("blocks writes after a failed read and retries before allowing edits", async () => {
const setSidebarState = vi.fn(async (state: SidebarStatePayload) => state);
@@ -34,6 +78,8 @@ describe("useSidebarState", () => {
await act(async () => {});
expect(fetch).toHaveBeenCalled();
await act(async () => {
await expect(result.current.rename("websocket:old", "New title"))
.rejects.toThrow("Sidebar state is not loaded");
await result.current.update((current) => ({ ...current, pinned_keys: ["websocket:new"] }));
});
expect(setSidebarState).not.toHaveBeenCalled();
@@ -138,6 +184,192 @@ describe("useSidebarState", () => {
}
});
it("keeps queued rename titles hidden until each acknowledgement", async () => {
const { result, writes, setSidebarState, receive } = await renderLoadedSidebarState();
let first!: Promise<void>;
let second!: Promise<void>;
const finished: string[] = [];
act(() => {
first = result.current.rename("websocket:a", "First requested").then(() => {
finished.push("a");
});
second = result.current.rename("websocket:b", "Second requested").then(() => {
finished.push("b");
});
});
expect(setSidebarState).toHaveBeenCalledTimes(1);
expect(writes[0].state.title_overrides["websocket:a"]).toBe("First requested");
act(() => receive(writes[0].state));
expect(result.current.state.title_overrides).toEqual({
"websocket:a": "Saved title", "websocket:b": "Other title",
});
expect(finished).toEqual([]);
await act(async () => {
writes[0].resolve({
...writes[0].state,
title_overrides: { "websocket:a": "First canonical", "websocket:b": "Other title" },
});
await first;
});
expect(finished).toEqual(["a"]);
expect(result.current.state.title_overrides).toEqual({
"websocket:a": "First canonical", "websocket:b": "Other title",
});
expect(setSidebarState).toHaveBeenCalledTimes(2);
expect(writes[1].state.title_overrides).toEqual({
"websocket:a": "First canonical", "websocket:b": "Second requested",
});
await act(async () => { writes[1].resolve(); await second; });
expect(finished).toEqual(["a", "b"]);
expect(result.current.state.title_overrides).toEqual({
"websocket:a": "First canonical", "websocket:b": "Second requested",
});
});
it("rejects a failed rename without retrying it until the user asks again", async () => {
const { result, writes, setSidebarState, setStatus } = await renderLoadedSidebarState();
let rename!: Promise<void>;
act(() => { rename = result.current.rename("websocket:a", "Requested title"); });
const rejected = expect(rename).rejects.toThrow("Rename failed");
act(() => {
void result.current.update((current) => ({ ...current, pinned_keys: ["websocket:b"] }));
});
expect(setSidebarState).toHaveBeenCalledTimes(1);
await act(async () => { writes[0].reject(new Error("Rename failed")); await rejected; });
expect(result.current.state.title_overrides["websocket:a"]).toBe("Saved title");
expect(result.current.state.pinned_keys).toEqual(["websocket:b"]);
expect(setSidebarState).toHaveBeenCalledTimes(2);
expect(writes[1].state).toEqual(result.current.state);
await act(async () => { writes[1].resolve(); });
act(() => { setStatus("closed"); setStatus("open"); });
expect(setSidebarState).toHaveBeenCalledTimes(2);
act(() => { rename = result.current.rename("websocket:a", "Requested title"); });
expect(setSidebarState).toHaveBeenCalledTimes(3);
expect(result.current.state.title_overrides["websocket:a"]).toBe("Saved title");
expect(writes[2].state.pinned_keys).toEqual(["websocket:b"]);
await act(async () => { writes[2].resolve(); await rename; });
expect(result.current.state.title_overrides["websocket:a"]).toBe("Requested title");
});
it("drains optimistic writes before renaming and preserves edits made during the rename", async () => {
const { result, writes, setSidebarState } = await renderLoadedSidebarState();
let rename!: Promise<void>;
act(() => {
void result.current.update((current) => ({ ...current, pinned_keys: ["websocket:a"] }));
rename = result.current.rename("websocket:a", "Requested title");
void result.current.update((current) => ({ ...current, archived_keys: ["websocket:b"] }));
void result.current.update((current) => ({
...current, view: { ...current.view, density: "compact" },
}));
});
expect(setSidebarState).toHaveBeenCalledTimes(1);
await act(async () => { writes[0].resolve(); });
expect(setSidebarState).toHaveBeenCalledTimes(2);
expect(writes[1].state).toEqual(expect.objectContaining({
pinned_keys: ["websocket:a"],
archived_keys: ["websocket:b"],
view: expect.objectContaining({ density: "compact" }),
}));
expect(writes[1].state.title_overrides["websocket:a"]).toBe("Saved title");
await act(async () => { writes[1].resolve(); });
expect(setSidebarState).toHaveBeenCalledTimes(3);
expect(writes[2].state).toEqual({
...writes[1].state,
title_overrides: { "websocket:a": "Requested title", "websocket:b": "Other title" },
});
expect(result.current.state.title_overrides["websocket:a"]).toBe("Saved title");
act(() => {
void result.current.update((current) => ({ ...current, pinned_keys: [] }));
void result.current.update((current) => ({
...current, tags_by_key: { "websocket:b": ["important"] },
}));
void result.current.update((current) => ({
...current, view: { ...current.view, density: "comfortable" },
}));
});
expect(setSidebarState).toHaveBeenCalledTimes(3);
expect(result.current.state.title_overrides["websocket:a"]).toBe("Saved title");
await act(async () => {
writes[2].resolve({
...writes[2].state,
title_overrides: { "websocket:a": "Canonical title", "websocket:b": "Other title" },
});
await rename;
});
expect(result.current.state).toEqual(expect.objectContaining({
pinned_keys: [],
archived_keys: ["websocket:b"],
tags_by_key: { "websocket:b": ["important"] },
view: expect.objectContaining({ density: "comfortable" }),
title_overrides: { "websocket:a": "Canonical title", "websocket:b": "Other title" },
}));
expect(setSidebarState).toHaveBeenCalledTimes(4);
expect(writes[3].state).toEqual(result.current.state);
await act(async () => { writes[3].resolve(); });
expect(result.current.state.title_overrides["websocket:a"]).toBe("Canonical title");
});
it("rejects waiting renames when an earlier optimistic write fails but retains its latest retry", async () => {
const { result, writes, setSidebarState, setStatus } = await renderLoadedSidebarState();
let first!: Promise<void>;
let second!: Promise<void>;
act(() => {
void result.current.update((current) => ({ ...current, pinned_keys: ["websocket:a"] }));
first = result.current.rename("websocket:a", "First requested");
second = result.current.rename("websocket:b", "Second requested");
void result.current.update((current) => ({
...current, tags_by_key: { "websocket:b": ["important"] },
}));
});
const firstRejected = expect(first).rejects.toThrow("Save failed");
const secondRejected = expect(second).rejects.toThrow("Save failed");
await act(async () => {
writes[0].reject(new Error("Save failed"));
await Promise.all([firstRejected, secondRejected]);
});
expect(setSidebarState).toHaveBeenCalledTimes(1);
expect(result.current.state.title_overrides).toEqual({
"websocket:a": "Saved title", "websocket:b": "Other title",
});
expect(result.current.state.tags_by_key).toEqual({ "websocket:b": ["important"] });
act(() => { setStatus("closed"); setStatus("open"); });
expect(setSidebarState).toHaveBeenCalledTimes(2);
expect(writes[1].state).toEqual(result.current.state);
expect(writes[1].state.pinned_keys).toEqual(["websocket:a"]);
await act(async () => { writes[1].resolve(); });
expect(setSidebarState).toHaveBeenCalledTimes(2);
});
it("rejects new and waiting renames on disconnect without replaying them on reconnect", async () => {
const { result, writes, setSidebarState, setStatus } = await renderLoadedSidebarState();
let rename!: Promise<void>;
act(() => {
void result.current.update((current) => ({ ...current, pinned_keys: ["websocket:a"] }));
rename = result.current.rename("websocket:a", "Requested title");
});
const rejected = expect(rename).rejects.toThrow("WebUI connection is not open");
await act(async () => { setStatus("closed"); await rejected; });
await act(async () => {
await expect(result.current.rename("websocket:b", "Offline title"))
.rejects.toThrow("WebUI connection is not open");
await result.current.update((current) => ({ ...current, archived_keys: ["websocket:b"] }));
writes[0].resolve();
});
expect(setSidebarState).toHaveBeenCalledTimes(1);
expect(result.current.state.title_overrides).toEqual({
"websocket:a": "Saved title", "websocket:b": "Other title",
});
expect(result.current.state.archived_keys).toEqual(["websocket:b"]);
act(() => setStatus("open"));
expect(setSidebarState).toHaveBeenCalledTimes(2);
expect(writes[1].state).toEqual(result.current.state);
await act(async () => { writes[1].resolve(); });
expect(setSidebarState).toHaveBeenCalledTimes(2);
});
it("serializes full-state writes so an older request cannot overwrite a newer update", async () => {
let resolveFirstWrite: (() => void) | null = null;
let sidebarStateUpdateHandler: ((state: SidebarStatePayload) => void) | null = null;