fix(webui): skip confirmation for undoable topic deletion (#6723)

* fix(webui): skip confirmation for undoable topic deletion

* refactor(webui): rely on gateway for linked automation confirmation
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 15:05:00 +08:00
1 parent f9052884ba
commit eb82ab84cc
19 files changed
+113 -233

No files matched your search

+3 -1
View File
@@ -95,7 +95,9 @@ If creating or forking a topic times out, it may already have succeeded; it is n
Drag topics within a sidebar group to reorder them. **Rename** edits a topic title in place; a failed save keeps the draft for retry.
Use **Select** in a topic's action menu to archive or delete several topics with one confirmation. Click outside the topic rows and toolbar, or press **Esc**, to leave selection mode. Cancelling a confirmation keeps your selection. Archiving removes pins and hides topics from the default list while keeping their conversations. Use **Show archived** to find them again; selecting only archived topics offers **Unarchive**.
Use **Select** in a topic's action menu to archive or delete several topics at once. Click outside the topic rows and toolbar, or press **Esc**, to leave selection mode. Archiving removes pins and hides topics from the default list while keeping their conversations. Use **Show archived** to find them again; selecting only archived topics offers **Unarchive**.
**Delete** hides topics and gives you 8 seconds to choose **Undo**. When that window ends, topics with linked automations reappear so you can confirm whether to delete them and their automations.
### Conversation groups and panes
+18 -50
View File
@@ -22,7 +22,7 @@ import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle";
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
import { invalidateToolsCatalog } from "@/lib/tools-catalog-cache";
import type { SidebarDeleteDecision, SidebarDeleteItem } from "@/components/ChatList";
import type { SidebarDeleteItem } from "@/components/ChatList";
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
import { StartupShell } from "@/components/StartupShell";
import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft";
@@ -831,8 +831,6 @@ type PendingDelete = {
id: number;
items: SidebarDeleteItem[];
automations: SessionAutomationJob[];
automationKeys: Set<string>;
onDecision?: SidebarDeleteDecision;
};
function restorePinOrder(pins: readonly string[], previous: readonly string[], restoring: ReadonlySet<string>) {
@@ -895,7 +893,6 @@ function Shell({
createChat,
forkChat,
deleteChat,
getSessionAutomations,
} = useSessions();
// Failed reads retain an empty list or partial reload cache, not proof of deletion.
const sessionsLoaded = !loading && sessionsError === null;
@@ -2085,21 +2082,18 @@ function Shell({
refresh,
);
const finishDeleteConfirmation = useCallback((request: PendingDelete, confirmed: boolean) => {
request.onDecision?.(confirmed);
setDeleteQueue((queue) => queue.filter((entry) => entry.id !== request.id));
const dismissDeleteConfirmation = useCallback((id: number) => {
setDeleteQueue((queue) => queue.filter((entry) => entry.id !== id));
}, []);
const onConfirmDelete = useCallback(() => {
if (!pendingDelete) return;
const { automationKeys } = pendingDelete;
const items = pendingDelete.items.filter((item) => topicSessions.some((session) => session.key === item.key));
finishDeleteConfirmation(pendingDelete, items.length > 0);
const stageDelete = useCallback((requested: SidebarDeleteItem[], deleteAutomations = false) => {
const items = requested.filter((item) => topicSessions.some((session) => session.key === item.key));
if (!items.length) return;
const batchKeys = new Set(items.map((item) => item.key));
setDeletingKeys((current) => new Set([...current, ...batchKeys]));
closeMobileSidebar();
if (activeKey && batchKeys.has(activeKey)) {
if (view === "chat" && activeKey && batchKeys.has(activeKey)) {
const currentIndex = topicSessions.findIndex((session) => session.key === activeKey);
const available = new Set(topicSessions.filter((session) => !batchKeys.has(session.key)).map((session) => session.key));
const fallbackKey = activeTabState?.paneKeys.find((key) => available.has(key))
@@ -2117,7 +2111,7 @@ function Shell({
try {
for (const item of items) {
try {
const result = await deleteChat(item.key, automationKeys.has(item.key) ? { deleteAutomations: true } : undefined);
const result = await deleteChat(item.key, deleteAutomations ? { deleteAutomations: true } : undefined);
if (result.deleted) {
filePreviewStore.delete(item.key);
draftStore.delete(item.key);
@@ -2140,7 +2134,6 @@ function Shell({
id: ++nextDeleteId.current,
items: blockedItems,
automations: blockedJobs,
automationKeys: new Set(blockedItems.map((item) => item.key)),
};
setDeleteQueue((queue) => [...queue, confirmation]);
}
@@ -2156,39 +2149,11 @@ function Shell({
action: { label: t("toast.undo"), run: reveal },
onExpire: () => { void commit(); },
});
}, [activeKey, activeTabState, deleteChat, draftStore, filePreviewStore, finishDeleteConfirmation, navigate, pendingDelete, showToast, t, topicSessions]);
}, [activeKey, activeTabState, closeMobileSidebar, deleteChat, draftStore, filePreviewStore, navigate, showToast, t, topicSessions, view]);
const onRequestDeleteMany = useCallback(async (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => {
const uniqueItems = Array.from(new Map(items.filter((item) => !deletingKeys.has(item.key)).map((item) => [item.key, item])).values());
if (uniqueItems.length === 0) {
onDecision?.(false);
return;
}
const automationResults = await Promise.allSettled(uniqueItems.map((item) => getSessionAutomations(item.key)));
const automationKeys = new Set<string>();
const automations = automationResults.flatMap((result, index) => {
if (result.status !== "fulfilled" || !result.value.length) return [];
automationKeys.add(uniqueItems[index].key);
return result.value;
});
let decision = onDecision;
const confirmation: PendingDelete = {
id: ++nextDeleteId.current,
items: uniqueItems,
automations,
automationKeys,
onDecision: (confirmed) => {
const notify = decision;
decision = undefined;
notify?.(confirmed);
},
};
setDeleteQueue((queue) => [...queue, confirmation]);
}, [deletingKeys, getSessionAutomations]);
const onRequestDelete = useCallback((key: string, label: string, onDecision?: SidebarDeleteDecision) => {
void onRequestDeleteMany([{ key, label }], onDecision);
}, [onRequestDeleteMany]);
const onRequestDelete = useCallback((key: string, label: string) => {
stageDelete([{ key, label }]);
}, [stageDelete]);
const automaticSidebarSort = sidebarState.view.sort === "manual"
? "updated_desc"
@@ -2460,7 +2425,7 @@ function Shell({
onSelect: onSelectSidebarItem,
onCloseTemporaryChat,
onRequestDelete,
onRequestDeleteMany,
onRequestDeleteMany: stageDelete,
onTogglePin,
onRequestRename,
onToggleArchive,
@@ -2858,8 +2823,11 @@ function Shell({
title={pendingDelete.items[0]?.label ?? ""}
count={pendingDelete.items.length}
automations={pendingDelete.automations}
onCancel={() => finishDeleteConfirmation(pendingDelete, false)}
onConfirm={onConfirmDelete}
onCancel={() => dismissDeleteConfirmation(pendingDelete.id)}
onConfirm={() => {
dismissDeleteConfirmation(pendingDelete.id);
stageDelete(pendingDelete.items, true);
}}
/>
</Suspense>
) : null}
+14 -25
View File
@@ -192,8 +192,6 @@ export interface SidebarDeleteItem {
label: string;
}
export type SidebarDeleteDecision = (confirmed: boolean) => void;
function droppablePaneKey(
dataTransfer: DataTransfer,
group: SidebarPaneGroup,
@@ -231,8 +229,8 @@ interface ChatListProps {
activeKey: string | null;
onSelect: (key: string) => void;
onCloseTemporaryChat?: (key: string) => void;
onRequestDelete: (key: string, label: string, onDecision?: SidebarDeleteDecision) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => void;
onRequestDelete: (key: string, label: string) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[]) => void;
onTogglePin: (key: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
onRequestRenameTab?: (key: string, label: string) => void;
@@ -352,7 +350,6 @@ export const ChatList = memo(function ChatList({
);
const [paneDropTarget, setPaneDropTarget] = useState<string | null>(null);
const [deleteSelectionMode, setDeleteSelectionMode] = useState(false);
const [deleteConfirmationPending, setDeleteConfirmationPending] = useState(false);
const [pendingArchive, setPendingArchive] = useState<{
keys: string[];
archive: boolean;
@@ -378,7 +375,7 @@ export const ChatList = memo(function ChatList({
() => new Set(),
);
const deleteSelectionAnchorRef = useRef<string | null>(null);
const selectionConfirmationPending = pendingArchive !== null || deleteConfirmationPending;
const selectionConfirmationPending = pendingArchive !== null;
const closeDeleteSelection = useCallback(() => {
setDeleteSelectionMode(false);
setSelectedDeleteKeys(new Set());
@@ -691,22 +688,12 @@ export const ChatList = memo(function ChatList({
});
if (!range) deleteSelectionAnchorRef.current = targetKey ?? null;
};
const requestDeleteItems = (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => {
const requestDeleteKeys = (keys: string[]) => {
const items = keys.map((key) => deleteItemsByKey.get(key))
.filter((item): item is SidebarDeleteItem => item !== undefined);
if (items.length === 0) return;
if (onRequestDeleteMany) onRequestDeleteMany(items, onDecision);
else if (items.length === 1) onRequestDelete(items[0].key, items[0].label, onDecision);
};
const requestDeleteKeys = (keys: string[], onDecision?: SidebarDeleteDecision) => {
requestDeleteItems(keys
.map((key) => deleteItemsByKey.get(key))
.filter((item): item is SidebarDeleteItem => item !== undefined), onDecision);
};
const confirmDeleteSelection = () => {
setDeleteConfirmationPending(true);
requestDeleteKeys(Array.from(selectedDeleteKeys), (confirmed) => {
setDeleteConfirmationPending(false);
if (confirmed) closeDeleteSelection();
});
if (onRequestDeleteMany) onRequestDeleteMany(items);
else if (items.length === 1) onRequestDelete(items[0].key, items[0].label);
};
const selectedArchiveKeys = Array.from(selectedDeleteKeys).filter((key) => archivableKeys.has(key));
const allSelectedArchived = selectedArchiveKeys.length > 0
@@ -1207,7 +1194,6 @@ export const ChatList = memo(function ChatList({
<div
ref={selectionBarRef}
data-testid="delete-selection-bar"
aria-busy={deleteConfirmationPending}
className="sticky bottom-2 z-30 mx-1 mt-3 flex min-h-11 items-center gap-1 rounded-floating border border-sidebar-border/80 bg-popover/95 p-1.5 pl-3 shadow-[0_10px_30px_rgba(15,23,42,0.14)] backdrop-blur-xl"
>
<span className="min-w-0 flex-1 truncate pr-2 text-[12.5px] font-medium text-foreground/85">
@@ -1221,7 +1207,7 @@ export const ChatList = memo(function ChatList({
<button
type="button"
aria-label={t(allSelectedArchived ? "chat.unarchive" : "chat.archive")}
disabled={selectedDeleteKeys.size === 0 || deleteConfirmationPending}
disabled={selectedDeleteKeys.size === 0}
onClick={() => setPendingArchive({
keys: selectedArchiveKeys,
archive: !allSelectedArchived,
@@ -1238,8 +1224,11 @@ export const ChatList = memo(function ChatList({
<button
type="button"
aria-label={t("chat.delete")}
disabled={selectedDeleteKeys.size === 0 || deleteConfirmationPending}
onClick={confirmDeleteSelection}
disabled={selectedDeleteKeys.size === 0}
onClick={() => {
requestDeleteKeys(Array.from(selectedDeleteKeys));
closeDeleteSelection();
}}
className="touch-target inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-destructive transition-colors media-hover:hover:bg-destructive/10 disabled:pointer-events-none disabled:opacity-40"
>
<Trash2 className="h-4 w-4" aria-hidden />
+28 -36
View File
@@ -8,7 +8,6 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { TOAST_ACTION_MS } from "@/components/ui/toast";
import type { TFunction } from "i18next";
import { Trash2 } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -20,7 +19,7 @@ interface DeleteConfirmProps {
open: boolean;
title: string;
count?: number;
automations?: SessionAutomationJob[];
automations: SessionAutomationJob[];
onCancel: () => void;
onConfirm: () => void;
}
@@ -29,13 +28,12 @@ export function DeleteConfirm({
open,
title,
count = 1,
automations = [],
automations,
onCancel,
onConfirm,
}: DeleteConfirmProps) {
const { t } = useTranslation();
const locale = currentLocale();
const hasAutomations = automations.length > 0;
const multiple = count > 1;
const visibleAutomations = automations.slice(0, 4);
const hiddenCount = Math.max(0, automations.length - visibleAutomations.length);
@@ -60,38 +58,34 @@ export function DeleteConfirm({
: t("deleteConfirm.title", { title })}
</AlertDialogTitle>
<AlertDialogDescription className="mt-3 max-w-[17rem] text-center text-[14px] leading-6 text-muted-foreground">
{hasAutomations
? multiple
? t("deleteConfirm.automationsDescriptionMany", {
defaultValue: "Linked automations will also be deleted.",
})
: t("deleteConfirm.automationsDescription")
: t("toast.deleteWindow", { seconds: TOAST_ACTION_MS / 1_000 })}
{multiple
? t("deleteConfirm.automationsDescriptionMany", {
defaultValue: "Linked automations will also be deleted.",
})
: t("deleteConfirm.automationsDescription")}
</AlertDialogDescription>
{hasAutomations ? (
<div className="mt-4 max-h-40 w-full overflow-y-auto rounded-2xl bg-muted/55 px-3 py-2 text-left">
{visibleAutomations.map((job) => (
<div key={job.id} className="min-w-0 py-1.5">
<div className="truncate text-[13px] font-medium leading-5 text-foreground">
{job.name || job.id}
</div>
<div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-[11.5px] leading-5 text-muted-foreground">
<span className="truncate">
{formatAutomationSchedule(job, t, locale)}
</span>
<span className="truncate">{formatAutomationNextRun(job, t, locale)}</span>
</div>
<div className="mt-4 max-h-40 w-full overflow-y-auto rounded-2xl bg-muted/55 px-3 py-2 text-left">
{visibleAutomations.map((job) => (
<div key={job.id} className="min-w-0 py-1.5">
<div className="truncate text-[13px] font-medium leading-5 text-foreground">
{job.name || job.id}
</div>
))}
{hiddenCount > 0 ? (
<div className="text-[13px] leading-6 text-muted-foreground">
{t("deleteConfirm.moreAutomations", {
count: hiddenCount,
})}
<div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-[11.5px] leading-5 text-muted-foreground">
<span className="truncate">
{formatAutomationSchedule(job, t, locale)}
</span>
<span className="truncate">{formatAutomationNextRun(job, t, locale)}</span>
</div>
) : null}
</div>
) : null}
</div>
))}
{hiddenCount > 0 ? (
<div className="text-[13px] leading-6 text-muted-foreground">
{t("deleteConfirm.moreAutomations", {
count: hiddenCount,
})}
</div>
) : null}
</div>
</AlertDialogHeader>
<AlertDialogFooter className="mt-6 !grid grid-cols-1 gap-2 sm:grid-cols-2">
<AlertDialogCancel
@@ -104,9 +98,7 @@ export function DeleteConfirm({
onClick={onConfirm}
className="w-full min-w-0 !whitespace-normal bg-destructive text-center text-destructive-foreground hover:bg-destructive/90"
>
{hasAutomations
? t("deleteConfirm.confirmWithAutomations")
: t("deleteConfirm.confirm")}
{t("deleteConfirm.confirm")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
+2 -3
View File
@@ -12,7 +12,6 @@ import { useTranslation } from "react-i18next";
import {
ChatList,
type SidebarDeleteDecision,
type SidebarDeleteItem,
type SidebarPaneGroup,
} from "@/components/ChatList";
@@ -42,8 +41,8 @@ interface SidebarProps {
onNewChat: () => void;
onSelect: (key: string) => void;
onCloseTemporaryChat?: (key: string) => void;
onRequestDelete: (key: string, label: string, onDecision?: SidebarDeleteDecision) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => void;
onRequestDelete: (key: string, label: string) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[]) => void;
onTogglePin: (key: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
onRequestRenameTab?: (key: string, label: string) => void;
+2 -6
View File
@@ -70,12 +70,8 @@ function ChatsPreview() {
activeKey={active} onSelect={setActive} pinnedKeys={pinned} archivedKeys={archived} showArchived={mode === "archived"}
loading={mode === "loading"}
onTogglePin={(key) => setPinned(toggle(pinned, key))} onToggleArchive={(key) => setArchived(toggle(archived, key))}
onRequestDelete={(key, _label, onDecision) => {
onDecision?.(true);
setSessions((items) => items.filter((item) => item.key !== key));
}}
onRequestDeleteMany={(items, onDecision) => {
onDecision?.(true);
onRequestDelete={(key) => setSessions((items) => items.filter((item) => item.key !== key))}
onRequestDeleteMany={(items) => {
const keys = new Set(items.map((item) => item.key));
setSessions((current) => current.filter((item) => !keys.has(item.key)));
}}
-9
View File
@@ -5,14 +5,12 @@ import { useNanobotStream } from "@/hooks/useNanobotStream";
import {
ApiError,
deleteSession as apiDeleteSession,
fetchSessionAutomations,
listSessions,
} from "@/lib/api";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
import type {
ChatSummary,
SessionAutomationJob,
SessionDeleteResult,
WorkspaceScopePayload,
} from "@/lib/types";
@@ -34,7 +32,6 @@ export function useSessions(): {
key: string,
options?: { deleteAutomations?: boolean },
) => Promise<SessionDeleteResult>;
getSessionAutomations: (key: string) => Promise<SessionAutomationJob[]>;
} {
const { client, token } = useClient();
const [sessions, setSessions] = useState<ChatSummary[]>(readReloadSessions);
@@ -187,11 +184,6 @@ export function useSessions(): {
[client],
);
const getSessionAutomations = useCallback(async (key: string) => {
const result = await fetchSessionAutomations(tokenRef.current, key);
return result.jobs;
}, []);
return {
sessions,
loading,
@@ -201,7 +193,6 @@ export function useSessions(): {
createChat,
forkChat,
deleteChat,
getSessionAutomations,
};
}
-2
View File
@@ -1955,7 +1955,6 @@
"automationsDescription": "Deleting this topic also deletes its linked automations.",
"automationsDescriptionMany": "Linked automations will also be deleted.",
"moreAutomations": "+ {{count}} more",
"confirmWithAutomations": "Delete",
"schedule": {
"at": "{{time}}",
"every": "Every {{duration}}",
@@ -2726,7 +2725,6 @@
"archiveFailed": "Could not change archive status.",
"unarchivedSingle": "Topic unarchived",
"deleteFailedSingle": "Could not delete the topic",
"deleteWindow": "You have {{seconds}} seconds to undo.",
"pendingDelete": "{{count}} topics will be deleted",
"archived": "{{count}} topics archived",
"unarchived": "{{count}} topics unarchived",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "Eliminar este tema también elimina sus tareas automáticas vinculadas.",
"automationsDescriptionMany": "También se eliminarán las automatizaciones vinculadas.",
"moreAutomations": "+ {{count}} más",
"confirmWithAutomations": "Eliminar",
"schedule": {
"at": "{{time}}",
"every": "Cada {{duration}}",
@@ -2544,7 +2543,6 @@
"archiveFailed": "No se pudo cambiar el estado de archivado.",
"unarchivedSingle": "Conversación desarchivada",
"deleteFailedSingle": "No se pudo eliminar la conversación",
"deleteWindow": "Tienes {{seconds}} segundos para deshacer la acción.",
"pendingDelete": "Se eliminarán {{count}} conversaciones",
"archived": "{{count}} conversaciones archivadas",
"unarchived": "{{count}} conversaciones desarchivadas",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "Supprimer ce sujet supprime aussi ses tâches automatiques liées.",
"automationsDescriptionMany": "Les automatisations liées seront également supprimées.",
"moreAutomations": "+ {{count}} autres",
"confirmWithAutomations": "Supprimer",
"schedule": {
"at": "{{time}}",
"every": "Tous les {{duration}}",
@@ -2544,7 +2543,6 @@
"archiveFailed": "Impossible de modifier le statut d’archivage.",
"unarchivedSingle": "Conversation désarchivée",
"deleteFailedSingle": "Impossible de supprimer la conversation",
"deleteWindow": "Vous avez {{seconds}} secondes pour annuler.",
"pendingDelete": "{{count}} conversations vont être supprimées",
"archived": "{{count}} conversations archivées",
"unarchived": "{{count}} conversations désarchivées",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "Menghapus topik ini juga menghapus tugas otomatis terkait.",
"automationsDescriptionMany": "Automasi terkait juga akan dihapus.",
"moreAutomations": "+ {{count}} lagi",
"confirmWithAutomations": "Hapus",
"schedule": {
"at": "{{time}}",
"every": "Setiap {{duration}}",
@@ -2544,7 +2543,6 @@
"archiveFailed": "Tidak dapat mengubah status arsip.",
"unarchivedSingle": "Percakapan dikeluarkan dari arsip",
"deleteFailedSingle": "Gagal menghapus percakapan",
"deleteWindow": "Anda punya {{seconds}} detik untuk mengurungkan tindakan.",
"pendingDelete": "{{count}} percakapan akan dihapus",
"archived": "{{count}} percakapan diarsipkan",
"unarchived": "{{count}} percakapan dikeluarkan dari arsip",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "このトピックを削除すると、関連する自動タスクも削除されます。",
"automationsDescriptionMany": "関連する自動タスクも削除されます。",
"moreAutomations": "他 {{count}} 件",
"confirmWithAutomations": "削除",
"schedule": {
"at": "{{time}}",
"every": "{{duration}} ごと",
@@ -2544,7 +2543,6 @@
"archiveFailed": "アーカイブ状態を変更できませんでした。",
"unarchivedSingle": "会話のアーカイブを解除しました",
"deleteFailedSingle": "会話を削除できませんでした",
"deleteWindow": "{{seconds}} 秒以内なら元に戻せます。",
"pendingDelete": "{{count}} 件の会話を削除します",
"archived": "{{count}} 件の会話をアーカイブしました",
"unarchived": "{{count}} 件の会話のアーカイブを解除しました",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "이 주제를 삭제하면 연결된 자동 작업도 삭제됩니다.",
"automationsDescriptionMany": "연결된 자동화도 함께 삭제됩니다.",
"moreAutomations": "+ {{count}}개 더",
"confirmWithAutomations": "삭제",
"schedule": {
"at": "{{time}}",
"every": "{{duration}}마다",
@@ -2544,7 +2543,6 @@
"archiveFailed": "보관 상태를 변경하지 못했습니다.",
"unarchivedSingle": "대화 보관을 해제했습니다",
"deleteFailedSingle": "대화를 삭제하지 못했습니다",
"deleteWindow": "{{seconds}}초 안에 삭제를 취소할 수 있습니다.",
"pendingDelete": "대화 {{count}}개가 곧 삭제됩니다",
"archived": "대화 {{count}}개를 보관했습니다",
"unarchived": "대화 {{count}}개의 보관을 해제했습니다",
-2
View File
@@ -1775,7 +1775,6 @@
"automationsDescription": "Excluir este tópico também exclui suas automações vinculadas.",
"automationsDescriptionMany": "As automações vinculadas também serão excluídas.",
"moreAutomations": "+ {{count}} a mais",
"confirmWithAutomations": "Excluir",
"schedule": {
"at": "{{time}}",
"every": "A cada {{duration}}",
@@ -2546,7 +2545,6 @@
"archiveFailed": "Não foi possível alterar o status de arquivamento.",
"unarchivedSingle": "Conversa desarquivada",
"deleteFailedSingle": "Não foi possível excluir a conversa",
"deleteWindow": "Você tem {{seconds}} segundos para desfazer a ação.",
"pendingDelete": "{{count}} conversas serão excluídas",
"archived": "{{count}} conversas arquivadas",
"unarchived": "{{count}} conversas desarquivadas",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "Xóa chủ đề này cũng xóa các tác vụ tự động liên quan.",
"automationsDescriptionMany": "Các tự động hóa liên kết cũng sẽ bị xóa.",
"moreAutomations": "+ {{count}} mục nữa",
"confirmWithAutomations": "Xóa",
"schedule": {
"at": "{{time}}",
"every": "Mỗi {{duration}}",
@@ -2544,7 +2543,6 @@
"archiveFailed": "Không thể thay đổi trạng thái lưu trữ.",
"unarchivedSingle": "Đã bỏ lưu trữ cuộc trò chuyện",
"deleteFailedSingle": "Không thể xóa cuộc trò chuyện",
"deleteWindow": "Bạn có {{seconds}} giây để hoàn tác.",
"pendingDelete": "Sắp xóa {{count}} cuộc trò chuyện",
"archived": "Đã lưu trữ {{count}} cuộc trò chuyện",
"unarchived": "Đã bỏ lưu trữ {{count}} cuộc trò chuyện",
-2
View File
@@ -1955,7 +1955,6 @@
"automationsDescription": "删除话题也会删除关联的自动任务",
"automationsDescriptionMany": "关联的自动任务也会一并删除。",
"moreAutomations": "另有 {{count}} 个",
"confirmWithAutomations": "删除",
"schedule": {
"at": "{{time}}",
"every": "每 {{duration}}",
@@ -2726,7 +2725,6 @@
"archiveFailed": "无法更改归档状态。",
"unarchivedSingle": "已取消归档",
"deleteFailedSingle": "删除会话失败",
"deleteWindow": "可在 {{seconds}} 秒内撤销。",
"pendingDelete": "即将删除 {{count}} 个会话",
"archived": "已归档 {{count}} 个会话",
"unarchived": "已取消归档 {{count}} 个会话",
-2
View File
@@ -1773,7 +1773,6 @@
"automationsDescription": "刪除話題也會刪除關聯的自動任務",
"automationsDescriptionMany": "關聯的自動任務也會一併刪除。",
"moreAutomations": "另有 {{count}} 個",
"confirmWithAutomations": "刪除",
"schedule": {
"at": "{{time}}",
"every": "每 {{duration}}",
@@ -2544,7 +2543,6 @@
"archiveFailed": "無法變更封存狀態。",
"unarchivedSingle": "已取消封存",
"deleteFailedSingle": "無法刪除對話",
"deleteWindow": "可在 {{seconds}} 秒內復原。",
"pendingDelete": "即將刪除 {{count}} 個對話",
"archived": "已封存 {{count}} 個對話",
"unarchived": "已取消封存 {{count}} 個對話",
+44 -72
View File
@@ -24,7 +24,6 @@ let clientOptions: NanobotClientOptions | undefined;
const refreshSpy = vi.fn();
const createChatSpy = vi.fn().mockResolvedValue("chat-1");
const deleteChatSpy = vi.fn();
const getSessionAutomationsSpy = vi.fn<(key: string) => Promise<SessionAutomationJob[]>>();
const toggleThemeSpy = vi.fn();
const updateUrlSpy = vi.fn();
const attachSpy = vi.fn();
@@ -50,10 +49,9 @@ const pairingChangeHandlers = new Set<() => void>();
const readyHandlers = new Set<() => void>();
let mockSessions: ChatSummary[] = [];
async function confirmTopicDeletion(button: HTMLElement) {
fireEvent.click(button);
// Happy DOM delivers the modal's aria-hidden removal on a timer. Start
// measuring the Undo window after the observer makes the toast reachable.
async function clickDeleteAction(action: HTMLElement) {
fireEvent.click(action);
// Flush menu dismissal and Happy DOM's aria-hidden observer before timing Undo.
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
}
@@ -211,7 +209,6 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => {
return chatId;
},
forkChat: async () => "fork-chat",
getSessionAutomations: getSessionAutomationsSpy,
deleteChat: async (key: string, options?: { deleteAutomations?: boolean }) => {
const result = options === undefined ? await deleteChatSpy(key) : await deleteChatSpy(key, options);
if (result && !result.deleted) return result;
@@ -349,7 +346,6 @@ describe("App layout", () => {
refreshSpy.mockReset();
createChatSpy.mockClear();
deleteChatSpy.mockReset();
getSessionAutomationsSpy.mockReset().mockResolvedValue([]);
toggleThemeSpy.mockReset();
attachSpy.mockReset();
setSidebarStateSpy.mockReset().mockImplementation(
@@ -2469,28 +2465,23 @@ describe("App layout", () => {
preview: "Second chat",
},
];
window.history.replaceState(null, "", "/#/chat/websocket%3Achat-a");
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
await waitFor(() =>
expect(
within(sidebar).getByRole("button", { name: /^First chat$/ }),
).toBeInTheDocument(),
);
expect(await within(sidebar).findByRole("button", { name: "First chat" }))
.toHaveAttribute("aria-current", "page");
fireEvent.pointerDown(screen.getByLabelText("Topic actions for First chat"), {
button: 0,
});
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
await waitFor(() =>
expect(screen.getByText("Delete this topic?")).toBeInTheDocument(),
);
const deleteFirst = await screen.findByRole("menuitem", { name: "Delete" });
vi.useFakeTimers();
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
await clickDeleteAction(deleteFirst);
expect(screen.getByText("Topic will be deleted")).toBeVisible();
expect(screen.getByRole("button", { name: "Undo" })).toBeVisible();
expect(window.location.hash).toBe("#/chat/websocket%3Achat-b");
expect(within(sidebar).queryByRole("button", { name: /^First chat$/ })).not.toBeInTheDocument();
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS - 1); });
expect(deleteChatSpy).not.toHaveBeenCalled();
@@ -2499,14 +2490,12 @@ describe("App layout", () => {
expect(deleteChatSpy).toHaveBeenCalledTimes(1);
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a");
expect(within(sidebar).getByRole("button", { name: /^Second chat$/ })).toBeInTheDocument();
expect(screen.queryByText("Delete this topic?")).not.toBeInTheDocument();
expect(document.body.style.pointerEvents).not.toBe("none");
fireEvent.pointerDown(screen.getByLabelText("Topic actions for Second chat"), { button: 0 });
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
const lastDelete = await screen.findByRole("alertdialog", { name: "Delete this topic?" });
const deleteLast = await screen.findByRole("menuitem", { name: "Delete" });
vi.useFakeTimers();
await confirmTopicDeletion(within(lastDelete).getByRole("button", { name: "Delete" }));
await clickDeleteAction(deleteLast);
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "56px" });
}, 15_000);
@@ -2609,7 +2598,7 @@ describe("App layout", () => {
expect(setSidebarStateSpy).toHaveBeenLastCalledWith(expect.objectContaining({ pinned_keys: keys, archived_keys: [] }));
});
it("deletes multiple selected topics through one confirmation", async () => {
it("offers one Undo for a bulk topic deletion", async () => {
mockSessions = [
{
key: "websocket:chat-a",
@@ -2648,23 +2637,8 @@ describe("App layout", () => {
fireEvent.click(within(sidebar).getByRole("button", { name: "Second chat" }));
expect(within(sidebar).getByText("2 selected")).toBeInTheDocument();
const automationReads: Array<(jobs: SessionAutomationJob[]) => void> = [];
getSessionAutomationsSpy.mockImplementation(() => new Promise((resolve) => automationReads.push(resolve)));
fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" }));
fireEvent.click(document.body);
expect(screen.getByTestId("delete-selection-bar")).toHaveTextContent("2 selected");
expect(deleteChatSpy).not.toHaveBeenCalled();
await act(async () => automationReads.forEach((resolve) => resolve([])));
expect(await screen.findByText("Delete 2 conversations?")).toBeInTheDocument();
fireEvent.keyDown(screen.getByRole("alertdialog"), { key: "Escape" });
expect(screen.getByTestId("delete-selection-bar")).toHaveTextContent("2 selected");
expect(deleteChatSpy).not.toHaveBeenCalled();
getSessionAutomationsSpy.mockResolvedValue([]);
fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" }));
expect(await screen.findByText("Delete 2 conversations?")).toBeInTheDocument();
vi.useFakeTimers();
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
await clickDeleteAction(within(sidebar).getByRole("button", { name: "Delete" }));
expect(screen.queryByTestId("delete-selection-bar")).not.toBeInTheDocument();
expect(screen.getByText("2 topics will be deleted")).toBeVisible();
expect(screen.getAllByRole("button", { name: "Undo" })).toHaveLength(1);
@@ -2675,8 +2649,6 @@ describe("App layout", () => {
"websocket:chat-a",
"websocket:chat-b",
]);
expect(getSessionAutomationsSpy).toHaveBeenCalledWith("websocket:chat-a");
expect(getSessionAutomationsSpy).toHaveBeenCalledWith("websocket:chat-b");
expect(within(sidebar).getByRole("button", { name: "Third chat" }))
.toBeInTheDocument();
}, 15_000);
@@ -2695,10 +2667,9 @@ describe("App layout", () => {
const { unmount } = render(<App />);
const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });
fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Review notes"), { button: 0 });
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
expect(await screen.findByRole("alertdialog", { name: "Delete this topic?" })).toBeVisible();
const deleteItem = await screen.findByRole("menuitem", { name: "Delete" });
vi.useFakeTimers();
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
await clickDeleteAction(deleteItem);
expect(within(sidebar).queryByRole("button", { name: "Review notes" })).not.toBeInTheDocument();
expect(screen.getByText("Topic will be deleted").closest('[role="status"]')).toHaveTextContent("Review notes");
expect(deleteChatSpy).not.toHaveBeenCalled();
@@ -2718,7 +2689,7 @@ describe("App layout", () => {
}
});
it("asks again only for the topic whose automations appeared during the delete window", async () => {
it("confirms only the topic whose deletion was blocked by linked automations", async () => {
mockSessions = ["a", "b"].map((id) => ({
key: `websocket:chat-${id}`, channel: "websocket", chatId: `chat-${id}`, title: `Topic ${id}`, preview: "",
createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z",
@@ -2734,21 +2705,22 @@ describe("App layout", () => {
fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Topic a"), { button: 0 });
fireEvent.click(await screen.findByRole("menuitem", { name: "Select" }));
fireEvent.click(within(sidebar).getByRole("button", { name: "Topic b" }));
fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" }));
const initial = await screen.findByRole("alertdialog", { name: "Delete 2 conversations?" });
vi.useFakeTimers();
await confirmTopicDeletion(within(initial).getByRole("button", { name: "Delete" }));
await clickDeleteAction(within(sidebar).getByRole("button", { name: "Delete" }));
expect(screen.getByText("2 topics will be deleted")).toBeVisible();
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
expect(deleteChatSpy.mock.calls).toEqual([["websocket:chat-a"], ["websocket:chat-b"]]);
const retry = screen.getByRole("alertdialog", { name: "Delete this topic?" });
vi.useRealTimers();
const retry = await screen.findByRole("alertdialog", { name: "Delete this topic?" });
expect(within(retry).getByText("Added during undo")).toBeVisible();
await confirmTopicDeletion(within(retry).getByRole("button", { name: "Delete" }));
vi.useFakeTimers();
await clickDeleteAction(within(retry).getByRole("button", { name: "Delete" }));
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
expect(deleteChatSpy).toHaveBeenCalledTimes(3);
expect(deleteChatSpy).toHaveBeenLastCalledWith("websocket:chat-b", { deleteAutomations: true });
}, 15_000);
it("shows localized bound automations in the first delete confirmation", async () => {
it("shows a localized automation warning and keeps the topic when cancelled", async () => {
mockSessions = [
{
key: "websocket:chat-a",
@@ -2767,16 +2739,18 @@ describe("App layout", () => {
preview: "Second chat",
},
];
getSessionAutomationsSpy.mockResolvedValue([
{
deleteChatSpy.mockResolvedValueOnce({
deleted: false,
blocked_by_automations: true,
automations: [{
id: "job-1",
name: "Daily repo check",
enabled: true,
schedule: { kind: "every", every_ms: 86_400_000 },
payload: { message: "Check the repo" },
state: { next_run_at_ms: Date.UTC(2026, 3, 17, 10, 0, 0) },
},
]);
}],
});
await i18n.changeLanguage("zh-CN");
render(<App />);
@@ -2792,12 +2766,14 @@ describe("App layout", () => {
fireEvent.pointerDown(screen.getByLabelText(/First chat.*话题操作/), {
button: 0,
});
fireEvent.click(await screen.findByRole("menuitem", { name: "删除" }));
const deleteItem = await screen.findByRole("menuitem", { name: "删除" });
vi.useFakeTimers();
await clickDeleteAction(deleteItem);
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
vi.useRealTimers();
await waitFor(() =>
expect(screen.getByText("Daily repo check")).toBeInTheDocument(),
);
expect(getSessionAutomationsSpy).toHaveBeenCalledWith("websocket:chat-a");
const dialog = await screen.findByRole("alertdialog", { name: "删除这个话题?" });
expect(within(dialog).getByText("Daily repo check")).toBeVisible();
expect(
screen.getByText("删除话题也会删除关联的自动任务"),
).toBeInTheDocument();
@@ -2806,12 +2782,10 @@ describe("App layout", () => {
).not.toBeInTheDocument();
vi.useFakeTimers();
await confirmTopicDeletion(screen.getByRole("button", { name: "删除" }));
expect(deleteChatSpy).not.toHaveBeenCalled();
await clickDeleteAction(within(dialog).getByRole("button", { name: "取消" }));
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a", { deleteAutomations: true });
expect(deleteChatSpy).toHaveBeenCalledTimes(1);
expect(screen.queryByText("Daily repo check")).not.toBeInTheDocument();
expect(deleteChatSpy.mock.calls).toEqual([["websocket:chat-a"]]);
expect(within(sidebar).getByRole("button", { name: "First chat" })).toBeVisible();
}, 15_000);
it("closes the mobile drawer when selecting a new or current topic without a search tooltip", async () => {
@@ -2902,9 +2876,8 @@ describe("App layout", () => {
expect(deleteItem).toBeInTheDocument();
fireEvent.click(deleteItem);
await waitFor(() =>
expect(screen.getByText("Delete this topic?")).toBeInTheDocument(),
);
expect(await screen.findByRole("button", { name: "Undo" })).toBeVisible();
expect(sheet).not.toBeInTheDocument();
}, 15_000);
it("renames inline in the mobile drawer without dismissing it and reloads the saved title", async () => {
@@ -4587,10 +4560,9 @@ describe("App layout", () => {
fireEvent.pointerDown(within(sidebar).getByRole("button", {
name: "New topic pane actions",
}), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
expect(await screen.findByText("Delete this topic?")).toBeInTheDocument();
const deletePane = await screen.findByRole("menuitem", { name: "Delete" });
vi.useFakeTimers();
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
await clickDeleteAction(deletePane);
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:new-pane");
+2 -11
View File
@@ -1,4 +1,4 @@
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChatList } from "@/components/ChatList";
@@ -94,7 +94,6 @@ describe("ChatList", () => {
{ archivedPaneKeys: [], projectLocked: undefined },
])("archives only persisted panes in a mixed selection ($archivedPaneKeys, draft=$projectLocked)", async ({ archivedPaneKeys, projectLocked }) => {
const onArchiveMany = vi.fn();
const onRequestDeleteMany = vi.fn();
render(<ChatList
sessions={[session({ chatId: "draft", title: "Draft", projectLocked: false })]}
paneGroups={{
@@ -110,7 +109,6 @@ describe("ChatList", () => {
activeKey="websocket:draft"
onSelect={vi.fn()}
onRequestDelete={vi.fn()}
onRequestDeleteMany={onRequestDeleteMany}
onTogglePin={vi.fn()}
onRequestRename={vi.fn()}
onToggleArchive={vi.fn()}
@@ -122,11 +120,6 @@ describe("ChatList", () => {
fireEvent.click(screen.getByRole("menuitem", { name: "Select" }));
const bar = screen.getByTestId("delete-selection-bar");
expect(within(bar).queryByRole("button", { name: "Archive" })).not.toBeInTheDocument();
fireEvent.click(within(bar).getByRole("button", { name: "Delete" }));
expect(onRequestDeleteMany).toHaveBeenCalledWith([
{ key: "websocket:draft", label: "Draft" },
], expect.any(Function));
act(() => onRequestDeleteMany.mock.calls[0][1](false));
fireEvent.click(screen.getByRole("button", { name: "Empty fork" }));
const action = archivedPaneKeys.length ? "Unarchive" : "Archive";
fireEvent.click(within(bar).getByRole("button", { name: action }));
@@ -875,9 +868,7 @@ describe("ChatList", () => {
{ key: "websocket:root", label: "Root topic" },
{ key: "websocket:child", label: "Research pane" },
{ key: "websocket:target", label: "Target tab" },
], expect.any(Function));
expect(screen.getByText("3 selected")).toBeInTheDocument();
act(() => onRequestDeleteMany.mock.calls[0][1](true));
]);
expect(screen.queryByTestId("delete-selection-bar")).not.toBeInTheDocument();
});