From cb95277098d24404ac72414373360a71676044c3 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:05:23 +0800 Subject: [PATCH] fix(webui): confirm linked automation deletion in untimed toast (#6731) * fix(webui): confirm linked automation deletion in untimed toast * feat(webui): add linked automation dropdown and session exclude in delete toast * style(webui): align toast automation dropdown and refine visual polish --- docs/webui.md | 2 +- webui/src/App.tsx | 204 +++++++++++----- .../AutomationDeleteToastDetails.tsx | 139 +++++++++++ webui/src/components/DeleteConfirm.tsx | 173 -------------- webui/src/components/RenameDialog.tsx | 2 +- webui/src/components/SidebarTopicRename.tsx | 2 +- webui/src/components/ui/toast.css | 4 +- webui/src/components/ui/toast.tsx | 225 ++++++++++++++---- .../src/dev/gallery/locales/previews/en.json | 9 - .../src/dev/gallery/locales/previews/es.json | 9 - .../src/dev/gallery/locales/previews/fr.json | 9 - .../src/dev/gallery/locales/previews/id.json | 9 - .../src/dev/gallery/locales/previews/ja.json | 9 - .../src/dev/gallery/locales/previews/ko.json | 9 - .../dev/gallery/locales/previews/pt-BR.json | 9 - .../src/dev/gallery/locales/previews/vi.json | 9 - .../dev/gallery/locales/previews/zh-CN.json | 9 - .../dev/gallery/locales/previews/zh-TW.json | 9 - webui/src/dev/gallery/shell.tsx | 30 +-- webui/src/hooks/useSessions.ts | 9 + webui/src/i18n/locales/en/common.json | 31 +-- webui/src/i18n/locales/es/common.json | 31 +-- webui/src/i18n/locales/fr/common.json | 31 +-- webui/src/i18n/locales/id/common.json | 31 +-- webui/src/i18n/locales/ja/common.json | 31 +-- webui/src/i18n/locales/ko/common.json | 31 +-- webui/src/i18n/locales/pt-BR/common.json | 31 +-- webui/src/i18n/locales/vi/common.json | 31 +-- webui/src/i18n/locales/zh-CN/common.json | 31 +-- webui/src/i18n/locales/zh-TW/common.json | 31 +-- webui/src/tests/app-layout.test.tsx | 130 +++++++--- 31 files changed, 652 insertions(+), 668 deletions(-) create mode 100644 webui/src/components/AutomationDeleteToastDetails.tsx delete mode 100644 webui/src/components/DeleteConfirm.tsx diff --git a/docs/webui.md b/docs/webui.md index 6b00b1b03..680974d0b 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -63,7 +63,7 @@ Each topic in the sidebar keeps its own history, title, project folder, and link - **Organize:** Drag topics to reorder them, or use **Rename** to edit a title inline. - **Bulk actions:** Choose **Select** in a topic's menu to archive or delete multiple topics at once (press `Esc` to exit selection mode). Archived topics stay saved and can be restored from **Show archived**. -- **Delete with undo:** Deleting a topic hides it with an 8-second **Undo** window. Topics with linked automations ask for confirmation before removing their automations. +- **Delete with undo:** Deleting a topic hides it with an 8-second **Undo** window. Topics with linked automations pause for confirmation in the toast before starting the undo countdown. - **Navigate long conversations:** Use the message rail on wide screens or prompt-summary search in the header to jump directly to earlier messages. Scroll past the top (or pull down on touch devices) to load older history. ### Conversation groups and panes diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 907f8ef21..8eed6e9e9 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -59,7 +59,11 @@ import { workbenchTabForPane, type WorkbenchState, } from "@/components/workbench/workbench-model"; -import { ToastProvider, useToast } from "@/components/ui/toast"; +import { ToastProvider, useToast, type ToastNotice } from "@/components/ui/toast"; +import { + AutomationDeleteToastDetails, + type AutomationDeleteSessionGroup, +} from "@/components/AutomationDeleteToastDetails"; import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"; import { useLocalGateway } from "@/hooks/useLocalGateway"; @@ -124,10 +128,6 @@ const SessionSearchDialog = lazy(async () => { const module = await import("@/components/SessionSearchDialog"); return { default: module.SessionSearchDialog }; }); -const DeleteConfirm = lazy(async () => { - const module = await import("@/components/DeleteConfirm"); - return { default: module.DeleteConfirm }; -}); const RenameDialog = lazy(async () => { const module = await import("@/components/RenameDialog"); return { default: module.RenameDialog }; @@ -412,12 +412,6 @@ export default function App() { ); } -type PendingDelete = { - id: number; - items: SidebarDeleteItem[]; - automations: SessionAutomationJob[]; -}; - function restorePinOrder(pins: readonly string[], previous: readonly string[], restoring: ReadonlySet) { const next = [...pins]; previous.forEach((key, index) => { @@ -478,6 +472,7 @@ 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; @@ -535,9 +530,6 @@ function Shell({ const [deletingKeys, setDeletingKeys] = useState>(() => new Set()); const topicSessions = useMemo(() => deletingKeys.size === 0 ? sessions : sessions.filter((session) => !deletingKeys.has(session.key)), [deletingKeys, sessions]); - const [deleteQueue, setDeleteQueue] = useState([]); - const [pendingDelete] = deleteQueue; - const nextDeleteId = useRef(0); const archiveUndoOwners = useRef(new Map()); const canNavigateArchiveRef = useRef(false); useEffect(() => { @@ -1672,23 +1664,36 @@ function Shell({ refresh, ); - const dismissDeleteConfirmation = useCallback((id: number) => { - setDeleteQueue((queue) => queue.filter((entry) => entry.id !== id)); - }, []); + const deleteContextRef = useRef({ topicSessions, activeKey, activeTabState, view }); + deleteContextRef.current = { topicSessions, activeKey, activeTabState, view }; + const checkingDeleteKeysRef = useRef>(new Set()); + const showAutomationConfirmRef = useRef<( + items: SidebarDeleteItem[], + jobsByKey: ReadonlyMap, + ) => void>(() => {}); - const stageDelete = useCallback((requested: SidebarDeleteItem[], deleteAutomations = false) => { - const items = requested.filter((item) => topicSessions.some((session) => session.key === item.key)); - if (!items.length) return; + const prepareStagedDelete = useCallback(( + requested: SidebarDeleteItem[], + automationKeys?: ReadonlySet, + ): ToastNotice | null => { + const { + topicSessions: liveSessions, + activeKey: currentActiveKey, + activeTabState: currentActiveTabState, + view: currentView, + } = deleteContextRef.current; + const items = requested.filter((item) => liveSessions.some((session) => session.key === item.key)); + if (!items.length) return null; const batchKeys = new Set(items.map((item) => item.key)); setDeletingKeys((current) => new Set([...current, ...batchKeys])); closeMobileSidebar(); - 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)) - ?? topicSessions.slice(currentIndex + 1).find((session) => available.has(session.key))?.key - ?? topicSessions.slice(0, Math.max(0, currentIndex)).reverse().find((session) => available.has(session.key))?.key + if (currentView === "chat" && currentActiveKey && batchKeys.has(currentActiveKey)) { + const currentIndex = liveSessions.findIndex((session) => session.key === currentActiveKey); + const available = new Set(liveSessions.filter((session) => !batchKeys.has(session.key)).map((session) => session.key)); + const fallbackKey = currentActiveTabState?.paneKeys.find((key) => available.has(key)) + ?? liveSessions.slice(currentIndex + 1).find((session) => available.has(session.key))?.key + ?? liveSessions.slice(0, Math.max(0, currentIndex)).reverse().find((session) => available.has(session.key))?.key ?? null; navigate({ view: "chat", activeKey: fallbackKey, settingsSection: "overview" }, { replace: true }); } @@ -1697,17 +1702,20 @@ function Shell({ const commit = async () => { let failed = 0; const blockedItems: SidebarDeleteItem[] = []; - const blockedJobs: SessionAutomationJob[] = []; + const blockedJobsByKey = new Map(); try { for (const item of items) { try { - const result = await deleteChat(item.key, deleteAutomations ? { deleteAutomations: true } : undefined); + const result = await deleteChat( + item.key, + automationKeys?.has(item.key) ? { deleteAutomations: true } : undefined, + ); if (result.deleted) { filePreviewStore.delete(item.key); draftStore.delete(item.key); } else if (result.blocked_by_automations && result.automations?.length) { blockedItems.push(item); - blockedJobs.push(...result.automations); + blockedJobsByKey.set(item.key, result.automations); } else { failed++; } @@ -1720,30 +1728,130 @@ function Shell({ reveal(); } if (blockedItems.length) { - const confirmation: PendingDelete = { - id: ++nextDeleteId.current, - items: blockedItems, - automations: blockedJobs, - }; - setDeleteQueue((queue) => [...queue, confirmation]); + showAutomationConfirmRef.current(blockedItems, blockedJobsByKey); } if (failed) showToast({ message: t(failed === 1 ? "toast.deleteFailedSingle" : "toast.deleteFailed", { count: failed }), tone: "error", }); }; - showToast({ + return { message: t(items.length === 1 ? "toast.pendingDeleteSingle" : "toast.pendingDelete", { count: items.length }), detail: items.length === 1 ? items[0].label : undefined, tone: "pending", action: { label: t("toast.undo"), run: reveal }, onExpire: () => { void commit(); }, + }; + }, [closeMobileSidebar, deleteChat, draftStore, filePreviewStore, navigate, showToast, t]); + + const buildAutomationDeleteConfirmNotice = useCallback(( + items: SidebarDeleteItem[], + jobsByKey: ReadonlyMap, + ): ToastNotice => { + const groups: AutomationDeleteSessionGroup[] = items.flatMap((item) => { + const jobs = jobsByKey.get(item.key); + return jobs?.length ? [{ item, jobs }] : []; }); - }, [activeKey, activeTabState, closeMobileSidebar, deleteChat, draftStore, filePreviewStore, navigate, showToast, t, topicSessions, view]); + const automationKeys = new Set(groups.map((group) => group.item.key)); + const totalAutomations = groups.reduce((sum, group) => sum + group.jobs.length, 0); + const detailsLabel = totalAutomations === 1 + ? t("toast.automationCountSingle") + : t("toast.automationCount", { count: totalAutomations }); + return { + message: items.length === 1 + ? t("toast.confirmDeleteAutomationsSingle") + : t("toast.confirmDeleteAutomations", { count: items.length }), + tone: "pending", + persistent: true, + dedupeKey: `delete-confirm:${items.map((item) => item.key).sort().join(",")}`, + details: { + label: detailsLabel, + render: (controller) => ( + { + const remainingItems = items.filter((item) => item.key !== excludedKey); + if (!remainingItems.length) { + controller.dismiss(); + return; + } + const nextJobsByKey = new Map( + Array.from(jobsByKey.entries()).filter(([key]) => key !== excludedKey), + ); + const stillHasAutomations = remainingItems.some( + (item) => (nextJobsByKey.get(item.key)?.length ?? 0) > 0, + ); + if (stillHasAutomations) { + controller.update(buildAutomationDeleteConfirmNotice(remainingItems, nextJobsByKey)); + return; + } + const staged = prepareStagedDelete(remainingItems); + if (staged) controller.update(staged); + else controller.dismiss(); + }} + /> + ), + }, + secondaryAction: { label: t("common.cancel") }, + action: { + label: t("chat.delete"), + tone: "destructive", + run: () => prepareStagedDelete(items, automationKeys) ?? undefined, + }, + }; + }, [prepareStagedDelete, t]); + + const showAutomationDeleteConfirmToast = useCallback(( + items: SidebarDeleteItem[], + jobsByKey: ReadonlyMap, + ) => { + closeMobileSidebar(); + showToast(buildAutomationDeleteConfirmNotice(items, jobsByKey)); + }, [buildAutomationDeleteConfirmNotice, closeMobileSidebar, showToast]); + showAutomationConfirmRef.current = showAutomationDeleteConfirmToast; + + const onRequestDeleteMany = useCallback(async (requested: SidebarDeleteItem[]) => { + const liveKeys = new Set(deleteContextRef.current.topicSessions.map((session) => session.key)); + const uniqueItems = Array.from(new Map( + requested + .filter((item) => liveKeys.has(item.key) && !checkingDeleteKeysRef.current.has(item.key)) + .map((item) => [item.key, item]), + ).values()); + if (!uniqueItems.length) return; + for (const item of uniqueItems) checkingDeleteKeysRef.current.add(item.key); + const jobsByKey = new Map(); + try { + const results = await Promise.allSettled( + uniqueItems.map((item) => getSessionAutomations(item.key)), + ); + results.forEach((result, index) => { + if (result.status === "fulfilled" && result.value.length) { + jobsByKey.set(uniqueItems[index].key, result.value); + } + }); + } finally { + for (const item of uniqueItems) checkingDeleteKeysRef.current.delete(item.key); + } + const stillLiveKeys = new Set(deleteContextRef.current.topicSessions.map((session) => session.key)); + const items = uniqueItems.filter((item) => stillLiveKeys.has(item.key)); + if (!items.length) return; + const liveJobsByKey = new Map( + items.flatMap((item) => { + const jobs = jobsByKey.get(item.key); + return jobs?.length ? [[item.key, jobs] as const] : []; + }), + ); + if (liveJobsByKey.size > 0) { + showAutomationDeleteConfirmToast(items, liveJobsByKey); + return; + } + const notice = prepareStagedDelete(items); + if (notice) showToast(notice); + }, [getSessionAutomations, prepareStagedDelete, showAutomationDeleteConfirmToast, showToast]); const onRequestDelete = useCallback((key: string, label: string) => { - stageDelete([{ key, label }]); - }, [stageDelete]); + void onRequestDeleteMany([{ key, label }]); + }, [onRequestDeleteMany]); const automaticSidebarSort = sidebarState.view.sort === "manual" ? "updated_desc" @@ -2015,7 +2123,7 @@ function Shell({ onSelect: onSelectSidebarItem, onCloseTemporaryChat, onRequestDelete, - onRequestDeleteMany: stageDelete, + onRequestDeleteMany: (items: SidebarDeleteItem[]) => { void onRequestDeleteMany(items); }, onTogglePin, onRequestRename, onToggleArchive, @@ -2407,22 +2515,6 @@ function Shell({ - {pendingDelete && localActive && !managingConnections ? ( - - dismissDeleteConfirmation(pendingDelete.id)} - onConfirm={() => { - dismissDeleteConfirmation(pendingDelete.id); - stageDelete(pendingDelete.items, true); - }} - /> - - ) : null} {pendingTabRename ? ( void; +}) { + const { t } = useTranslation(); + const locale = currentLocale(); + + return ( +
+ {groups.map(({ item, jobs }) => ( +
+
+
+
+ +
+
    + {jobs.map((job) => { + const needsAttention = job.state.last_status === "error" || Boolean(job.state.last_error); + const statusDotClass = job.enabled + ? needsAttention + ? "bg-destructive" + : "bg-emerald-500" + : "bg-muted-foreground/35"; + return ( +
  • +
    +
    + {!job.enabled ? ( + + {t("settings.automations.status.paused")} + + ) : ( + + {formatCompactSchedule(job, locale, t)} + + )} +
  • + ); + })} +
+
+ ))} +
+ ); +} + +function formatCompactSchedule( + job: SessionAutomationJob, + locale: string, + t: TFunction, +): string { + if (job.schedule.kind === "at" && job.schedule.at_ms) { + return t("settings.automations.schedule.at", { time: fmtDateTime(job.schedule.at_ms, locale) }); + } + if (job.schedule.kind === "every" && job.schedule.every_ms) { + return t("settings.automations.schedule.every", { + duration: formatDuration(job.schedule.every_ms, locale), + }); + } + if (job.schedule.kind === "cron" && job.schedule.expr) { + return job.schedule.expr; + } + if (job.kind === "local_trigger" || job.schedule.kind === "local" || job.payload.kind === "local_trigger") { + return t("settings.automations.commandCondition"); + } + return t("settings.automations.schedule.custom"); +} + +function formatDuration(ms: number, locale: string): string { + const units: Array<[Intl.NumberFormatOptions["unit"], number]> = [ + ["day", 86_400_000], + ["hour", 3_600_000], + ["minute", 60_000], + ["second", 1000], + ]; + for (const [unit, size] of units) { + if (ms >= size && ms % size === 0) { + return new Intl.NumberFormat(locale, { + style: "unit", + unit, + unitDisplay: "long", + maximumFractionDigits: 0, + }).format(ms / size); + } + } + return new Intl.NumberFormat(locale, { + style: "unit", + unit: "minute", + unitDisplay: "long", + maximumFractionDigits: 1, + }).format(ms / 60_000); +} diff --git a/webui/src/components/DeleteConfirm.tsx b/webui/src/components/DeleteConfirm.tsx deleted file mode 100644 index 338058605..000000000 --- a/webui/src/components/DeleteConfirm.tsx +++ /dev/null @@ -1,173 +0,0 @@ -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; -import type { TFunction } from "i18next"; -import { Trash2 } from "lucide-react"; -import { useTranslation } from "react-i18next"; -import { currentLocale } from "@/i18n"; -import { fmtDateTime } from "@/lib/format-time"; -import type { SessionAutomationJob } from "@/lib/types"; - -interface DeleteConfirmProps { - open: boolean; - title: string; - count?: number; - automations: SessionAutomationJob[]; - onCancel: () => void; - onConfirm: () => void; -} - -export function DeleteConfirm({ - open, - title, - count = 1, - automations, - onCancel, - onConfirm, -}: DeleteConfirmProps) { - const { t } = useTranslation(); - const locale = currentLocale(); - const multiple = count > 1; - const visibleAutomations = automations.slice(0, 4); - const hiddenCount = Math.max(0, automations.length - visibleAutomations.length); - return ( - (!o ? onCancel() : undefined)}> - event.stopPropagation()} - > - - - - {multiple - ? t("deleteConfirm.titleMany", { - defaultValue: "Delete {{count}} conversations?", - count, - }) - : t("deleteConfirm.title", { title })} - - - {multiple - ? t("deleteConfirm.automationsDescriptionMany", { - defaultValue: "Linked automations will also be deleted.", - }) - : t("deleteConfirm.automationsDescription")} - -
- {visibleAutomations.map((job) => ( -
-
- {job.name || job.id} -
-
- - {formatAutomationSchedule(job, t, locale)} - - {formatAutomationNextRun(job, t, locale)} -
-
- ))} - {hiddenCount > 0 ? ( -
- {t("deleteConfirm.moreAutomations", { - count: hiddenCount, - })} -
- ) : null} -
-
- - - {t("deleteConfirm.cancel")} - - - {t("deleteConfirm.confirm")} - - -
-
- ); -} - -function formatAutomationSchedule( - job: SessionAutomationJob, - t: TFunction, - locale: string, -): string { - if (job.schedule.kind === "at" && job.schedule.at_ms) { - return t("deleteConfirm.schedule.at", { time: fmtDateTime(job.schedule.at_ms, locale) }); - } - if (job.schedule.kind === "every" && job.schedule.every_ms) { - return t("deleteConfirm.schedule.every", { - duration: formatDuration(job.schedule.every_ms, locale), - }); - } - if (job.schedule.kind === "cron" && job.schedule.expr) { - return job.schedule.tz - ? t("deleteConfirm.schedule.cronWithTz", { - expr: job.schedule.expr, - tz: job.schedule.tz, - }) - : t("deleteConfirm.schedule.cron", { expr: job.schedule.expr }); - } - if (job.schedule.kind === "local" || job.payload.kind === "local_trigger") { - return t("deleteConfirm.schedule.local", { defaultValue: "Local trigger" }); - } - return t("deleteConfirm.schedule.unknown"); -} - -function formatAutomationNextRun( - job: SessionAutomationJob, - t: TFunction, - locale: string, -): string { - if (!job.enabled) return t("deleteConfirm.next.disabled"); - if (job.schedule.kind === "local" || job.payload.kind === "local_trigger") { - return t("deleteConfirm.next.local", { defaultValue: "Waiting for trigger" }); - } - const next = job.state.next_run_at_ms; - if (!next) return t("deleteConfirm.next.none"); - return t("deleteConfirm.next.label", { time: fmtDateTime(next, locale) }); -} - -function formatDuration(ms: number, locale: string): string { - const units: Array<[Intl.NumberFormatOptions["unit"], number]> = [ - ["day", 86_400_000], - ["hour", 3_600_000], - ["minute", 60_000], - ["second", 1000], - ]; - for (const [unit, size] of units) { - if (ms >= size && ms % size === 0) { - return new Intl.NumberFormat(locale, { - style: "unit", - unit, - unitDisplay: "long", - maximumFractionDigits: 0, - }).format(ms / size); - } - } - return new Intl.NumberFormat(locale, { - style: "unit", - unit: "minute", - unitDisplay: "long", - maximumFractionDigits: 1, - }).format(ms / 60_000); -} diff --git a/webui/src/components/RenameDialog.tsx b/webui/src/components/RenameDialog.tsx index aa921533c..b858e1fec 100644 --- a/webui/src/components/RenameDialog.tsx +++ b/webui/src/components/RenameDialog.tsx @@ -71,7 +71,7 @@ export function RenameDialog({ variant="outline" onClick={onCancel} > - {t("deleteConfirm.cancel")} + {t("common.cancel")} } - ; + const hasActions = Boolean(action || secondaryAction); + const interactive = Boolean(hasActions || details); + return ( + + +
{ if (event.pointerType !== "touch") onHoverChange?.(true); }} + onPointerLeave={() => onHoverChange?.(false)} + onFocus={() => onFocusChange?.(true)} + onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) onFocusChange?.(false); }} + data-toast-tone={tone} + data-toast-timed={persistent ? "false" : "true"} + > +
+
+ {details && ( + + {details.render(controller)} + + )} +
+ ); } -type ToastFinishReason = "action" | "expired"; +type ToastFinishReason = "action" | "secondary" | "expired"; -function TimedToast({ entry, finish, unavailable }: { +function TimedToast({ entry, finish, update, dismiss, unavailable }: { entry: ToastEntry; finish: (entry: ToastEntry, reason: ToastFinishReason) => void; + update: (entry: ToastEntry, next: ToastNotice) => void; + dismiss: (entry: ToastEntry) => void; unavailable: boolean; }) { const [hovered, setHovered] = useState(false); const [focused, setFocused] = useState(false); - const paused = unavailable || hovered || focused; + const persistent = Boolean(entry.persistent); + const paused = persistent || unavailable || hovered || focused; + const remaining = useRef(toastDurationMs(entry)); + useLayoutEffect(() => { + setHovered(false); + setFocused(false); + remaining.current = toastDurationMs(entry); + }, [entry.step]); useLayoutEffect(() => { if (!unavailable) return; setHovered(false); setFocused(false); }, [unavailable]); - const remaining = useRef(toastDurationMs(entry)); useLayoutEffect(() => { if (paused) return; const start = performance.now(); @@ -86,9 +186,17 @@ function TimedToast({ entry, finish, unavailable }: { remaining.current = Math.max(0, remaining.current - (performance.now() - start)); }; }, [entry, finish, paused]); + const controller = useMemo(() => ({ + update: (next) => update(entry, next), + dismiss: () => dismiss(entry), + }), [dismiss, entry, update]); - return finish(entry, "action")} - onHoverChange={entry.action ? setHovered : undefined} onFocusChange={entry.action ? setFocused : undefined} />; + return finish(entry, "action")} + onSecondaryAction={() => finish(entry, "secondary")} + onHoverChange={!persistent && entry.action ? setHovered : undefined} + onFocusChange={!persistent && entry.action ? setFocused : undefined} />; } export function ToastProvider({ children }: { children: ReactNode }) { @@ -115,25 +223,58 @@ export function ToastProvider({ children }: { children: ReactNode }) { const live = useRef(new Map()); const publish = useCallback(() => setEntries([...live.current.values()]), []); const show = useCallback((notice: ToastNotice) => { - if (notice.dedupeKey && !notice.action && !notice.onExpire) { + if (notice.dedupeKey && !notice.onExpire && (!notice.action || notice.persistent)) { for (const [id, entry] of live.current) { - if (entry.dedupeKey === notice.dedupeKey && !entry.action && !entry.onExpire) live.current.delete(id); + if (entry.dedupeKey === notice.dedupeKey && !entry.onExpire && (!entry.action || entry.persistent)) { + live.current.delete(id); + } } } - const entry = { ...notice, id: ++nextId.current }; + const entry = { ...notice, id: ++nextId.current, step: 0 }; live.current.set(entry.id, entry); publish(); }, [publish]); - const finish = useCallback((entry: ToastEntry, reason: ToastFinishReason) => { - if (!live.current.delete(entry.id)) return; + const update = useCallback((entry: ToastEntry, next: ToastNotice) => { + const current = live.current.get(entry.id); + if (!current || current.step !== entry.step) return; + live.current.set(entry.id, { ...next, id: entry.id, step: current.step + 1 }); publish(); - if (reason === "action") entry.action?.run(); - else entry.onExpire?.(); + }, [publish]); + const dismiss = useCallback((entry: ToastEntry) => { + const current = live.current.get(entry.id); + if (!current || current.step !== entry.step) return; + live.current.delete(entry.id); + publish(); + }, [publish]); + const finish = useCallback((entry: ToastEntry, reason: ToastFinishReason) => { + const current = live.current.get(entry.id); + if (!current || current.step !== entry.step) return; + if (reason === "action") { + const next = current.action?.run(); + if (next) { + live.current.set(entry.id, { ...next, id: entry.id, step: current.step + 1 }); + publish(); + return; + } + } + live.current.delete(entry.id); + publish(); + if (reason === "secondary") current.secondaryAction?.run?.(); + else if (reason === "expired") current.onExpire?.(); }, [publish]); return {children} ; } diff --git a/webui/src/dev/gallery/locales/previews/en.json b/webui/src/dev/gallery/locales/previews/en.json index 9fd7e1d81..7ee5250ff 100644 --- a/webui/src/dev/gallery/locales/previews/en.json +++ b/webui/src/dev/gallery/locales/previews/en.json @@ -14,15 +14,6 @@ "options": "The caller supplies dialogTitle, description and placeholder. title sets the initial value; onConfirm receives the trimmed title. Empty titles cannot be saved.", "hint": "Saving updates the title above." }, - "delete": { - "title": "DeleteConfirm · Delete confirmation", - "description": "Compare deletion of one chat, multiple chats, or a chat with automations.", - "options": "count controls bulk deletion copy. automations shows linked jobs, schedules and next runs. Confirm calls onConfirm.", - "scenario": "Deletion scenario", - "open": "Open delete confirmation", - "confirmed": "Example deletion confirmed.", - "hint": "Choose a single chat, multiple chats, or a chat with automations." - }, "inlineTokens": { "title": "Inline tokens · Commands and session handles", "description": "Edit commands and handles to see highlighting and stable session colors.", diff --git a/webui/src/dev/gallery/locales/previews/es.json b/webui/src/dev/gallery/locales/previews/es.json index 1c2857f51..ff7161184 100644 --- a/webui/src/dev/gallery/locales/previews/es.json +++ b/webui/src/dev/gallery/locales/previews/es.json @@ -14,15 +14,6 @@ "options": "El componente padre aporta dialogTitle, description y placeholder. title fija el valor inicial; onConfirm recibe el título sin espacios en los extremos. No se pueden guardar títulos vacíos.", "hint": "Al guardar se actualiza el título de arriba." }, - "delete": { - "title": "DeleteConfirm · Confirmación de eliminación", - "description": "Compara la eliminación de un chat, varios chats o un chat con automatizaciones.", - "options": "count controla el texto de eliminación múltiple. automations muestra tareas vinculadas, horarios y próximas ejecuciones. Confirmar llama a onConfirm.", - "scenario": "Escenario de eliminación", - "open": "Abrir confirmación de eliminación", - "confirmed": "Eliminación de ejemplo confirmada.", - "hint": "Elige un chat, varios chats o un chat con automatizaciones." - }, "inlineTokens": { "title": "Inline tokens · Comandos e identificadores de sesión", "description": "Edita comandos e identificadores para ver el resaltado y los colores estables de sesión.", diff --git a/webui/src/dev/gallery/locales/previews/fr.json b/webui/src/dev/gallery/locales/previews/fr.json index c3d66d7bd..840c5f38d 100644 --- a/webui/src/dev/gallery/locales/previews/fr.json +++ b/webui/src/dev/gallery/locales/previews/fr.json @@ -14,15 +14,6 @@ "options": "L’appelant fournit dialogTitle, description et placeholder. title définit la valeur initiale ; onConfirm reçoit le titre sans espaces aux extrémités. Un titre vide ne peut pas être enregistré.", "hint": "L’enregistrement met à jour le titre ci-dessus." }, - "delete": { - "title": "DeleteConfirm · Confirmation de suppression", - "description": "Comparez la suppression d’une discussion, de plusieurs discussions ou d’une discussion avec automatisations.", - "options": "count détermine le texte de suppression groupée. automations affiche les tâches liées, leur planification et leur prochaine exécution. La confirmation appelle onConfirm.", - "scenario": "Scénario de suppression", - "open": "Ouvrir la confirmation de suppression", - "confirmed": "Suppression d’exemple confirmée.", - "hint": "Choisissez une discussion, plusieurs discussions ou une discussion avec automatisations." - }, "inlineTokens": { "title": "Inline tokens · Commandes et identifiants de session", "description": "Modifiez les commandes et identifiants pour observer la mise en évidence et les couleurs stables.", diff --git a/webui/src/dev/gallery/locales/previews/id.json b/webui/src/dev/gallery/locales/previews/id.json index e49deeb7d..d3f188d25 100644 --- a/webui/src/dev/gallery/locales/previews/id.json +++ b/webui/src/dev/gallery/locales/previews/id.json @@ -14,15 +14,6 @@ "options": "Pemanggil menyediakan dialogTitle, description, dan placeholder. title menentukan nilai awal; onConfirm menerima judul tanpa spasi di kedua ujung. Judul kosong tidak dapat disimpan.", "hint": "Menyimpan akan memperbarui judul di atas." }, - "delete": { - "title": "DeleteConfirm · Konfirmasi penghapusan", - "description": "Bandingkan penghapusan satu percakapan, beberapa percakapan, atau percakapan dengan otomatisasi.", - "options": "count mengatur teks penghapusan massal. automations menampilkan tugas terkait, jadwal, dan waktu eksekusi berikutnya. Konfirmasi memanggil onConfirm.", - "scenario": "Skenario penghapusan", - "open": "Buka konfirmasi penghapusan", - "confirmed": "Penghapusan contoh dikonfirmasi.", - "hint": "Pilih satu percakapan, beberapa percakapan, atau percakapan dengan otomatisasi." - }, "inlineTokens": { "title": "Inline tokens · Perintah dan pengenal sesi", "description": "Edit perintah dan pengenal untuk melihat sorotan serta warna sesi yang konsisten.", diff --git a/webui/src/dev/gallery/locales/previews/ja.json b/webui/src/dev/gallery/locales/previews/ja.json index b56bbc7e3..2c240c060 100644 --- a/webui/src/dev/gallery/locales/previews/ja.json +++ b/webui/src/dev/gallery/locales/previews/ja.json @@ -14,15 +14,6 @@ "options": "呼び出し元が dialogTitle、description、placeholder を渡します。title が初期値になり、onConfirm は前後の空白を除いた名前を受け取ります。空の名前は保存できません。", "hint": "保存すると上の名前が更新されます。" }, - "delete": { - "title": "DeleteConfirm · 削除の確認", - "description": "単一、複数、自動化タスク付きチャットの削除確認を比較できます。", - "options": "count が一括削除の文言を制御します。automations は関連タスク、スケジュール、次回実行日時を表示します。確認すると onConfirm を呼び出します。", - "scenario": "削除のシナリオ", - "open": "削除確認を開く", - "confirmed": "サンプルの削除を確認しました。", - "hint": "単一、複数、または自動化タスク付きのチャットを選択してください。" - }, "inlineTokens": { "title": "Inline tokens · コマンドとセッション識別子", "description": "コマンドや識別子を編集して、強調表示とセッション固有の色を確認できます。", diff --git a/webui/src/dev/gallery/locales/previews/ko.json b/webui/src/dev/gallery/locales/previews/ko.json index d7776d2f5..0fe494a41 100644 --- a/webui/src/dev/gallery/locales/previews/ko.json +++ b/webui/src/dev/gallery/locales/previews/ko.json @@ -14,15 +14,6 @@ "options": "호출자가 dialogTitle, description, placeholder를 제공합니다. title은 초기값이며 onConfirm은 양끝 공백을 제거한 이름을 받습니다. 빈 이름은 저장할 수 없습니다.", "hint": "저장하면 위의 제목이 바뀝니다." }, - "delete": { - "title": "DeleteConfirm · 삭제 확인", - "description": "단일 채팅, 여러 채팅, 자동화가 연결된 채팅의 삭제를 비교합니다.", - "options": "count는 일괄 삭제 문구를 제어합니다. automations는 연결된 작업, 일정, 다음 실행 시간을 표시합니다. 확인하면 onConfirm을 호출합니다.", - "scenario": "삭제 시나리오", - "open": "삭제 확인 열기", - "confirmed": "예제 삭제를 확인했습니다.", - "hint": "단일 채팅, 여러 채팅 또는 자동화가 있는 채팅을 선택하세요." - }, "inlineTokens": { "title": "Inline tokens · 명령과 세션 식별자", "description": "명령과 식별자를 편집하여 강조 표시와 일관된 세션 색상을 확인합니다.", diff --git a/webui/src/dev/gallery/locales/previews/pt-BR.json b/webui/src/dev/gallery/locales/previews/pt-BR.json index 184a75b36..10055538b 100644 --- a/webui/src/dev/gallery/locales/previews/pt-BR.json +++ b/webui/src/dev/gallery/locales/previews/pt-BR.json @@ -14,15 +14,6 @@ "options": "O chamador fornece dialogTitle, description e placeholder. title define o valor inicial; onConfirm recebe o título sem espaços nas extremidades. Títulos vazios não podem ser salvos.", "hint": "Ao salvar, o título acima é atualizado." }, - "delete": { - "title": "DeleteConfirm · Confirmação de exclusão", - "description": "Compare a exclusão de uma conversa, várias conversas ou uma conversa com automações.", - "options": "count controla o texto de exclusão em lote. automations mostra tarefas vinculadas, agendamentos e próximas execuções. Confirmar chama onConfirm.", - "scenario": "Cenário de exclusão", - "open": "Abrir confirmação de exclusão", - "confirmed": "Exclusão de exemplo confirmada.", - "hint": "Escolha uma conversa, várias conversas ou uma conversa com automações." - }, "inlineTokens": { "title": "Inline tokens · Comandos e identificadores de sessão", "description": "Edite comandos e identificadores para ver o destaque e as cores estáveis das sessões.", diff --git a/webui/src/dev/gallery/locales/previews/vi.json b/webui/src/dev/gallery/locales/previews/vi.json index 8ecf34955..cbcd41ade 100644 --- a/webui/src/dev/gallery/locales/previews/vi.json +++ b/webui/src/dev/gallery/locales/previews/vi.json @@ -14,15 +14,6 @@ "options": "Bên gọi cung cấp dialogTitle, description và placeholder. title đặt giá trị ban đầu; onConfirm nhận tên đã bỏ khoảng trắng ở hai đầu. Không thể lưu tên trống.", "hint": "Khi lưu, tiêu đề phía trên sẽ được cập nhật." }, - "delete": { - "title": "DeleteConfirm · Xác nhận xóa", - "description": "So sánh việc xóa một cuộc trò chuyện, nhiều cuộc trò chuyện hoặc cuộc trò chuyện có tác vụ tự động.", - "options": "count điều khiển nội dung xóa hàng loạt. automations hiển thị tác vụ liên kết, lịch và lần chạy tiếp theo. Xác nhận sẽ gọi onConfirm.", - "scenario": "Tình huống xóa", - "open": "Mở xác nhận xóa", - "confirmed": "Đã xác nhận xóa ví dụ.", - "hint": "Chọn một, nhiều hoặc cuộc trò chuyện có tác vụ tự động." - }, "inlineTokens": { "title": "Inline tokens · Lệnh và định danh phiên", "description": "Sửa lệnh và định danh để xem phần tô sáng và màu ổn định của phiên.", diff --git a/webui/src/dev/gallery/locales/previews/zh-CN.json b/webui/src/dev/gallery/locales/previews/zh-CN.json index 958f41e69..8d65b0cca 100644 --- a/webui/src/dev/gallery/locales/previews/zh-CN.json +++ b/webui/src/dev/gallery/locales/previews/zh-CN.json @@ -14,15 +14,6 @@ "options": "调用方提供 dialogTitle、description 和 placeholder。title 设置初值,onConfirm 接收去除两端空白的标题。空标题无法保存。", "hint": "保存后更新上方标题。" }, - "delete": { - "title": "DeleteConfirm · 删除确认", - "description": "比较单个、批量和带自动任务的删除确认。", - "options": "count 控制批量文案;automations 展示关联任务、计划和下次运行时间。确认按钮调用 onConfirm。", - "scenario": "删除场景", - "open": "打开删除确认", - "confirmed": "已确认删除示例。", - "hint": "选择单个、批量或带自动任务的会话。" - }, "inlineTokens": { "title": "Inline tokens · 命令与会话标识", "description": "编辑命令与标识,查看高亮和会话颜色。", diff --git a/webui/src/dev/gallery/locales/previews/zh-TW.json b/webui/src/dev/gallery/locales/previews/zh-TW.json index bf7a07326..a6531fac6 100644 --- a/webui/src/dev/gallery/locales/previews/zh-TW.json +++ b/webui/src/dev/gallery/locales/previews/zh-TW.json @@ -14,15 +14,6 @@ "options": "呼叫端提供 dialogTitle、description 與 placeholder。title 設定初始值,onConfirm 接收去除頭尾空白的標題。空標題無法儲存。", "hint": "儲存後更新上方標題。" }, - "delete": { - "title": "DeleteConfirm · 刪除確認", - "description": "比較單筆、多筆與含自動任務的刪除確認。", - "options": "count 控制批次刪除文案;automations 顯示關聯任務、排程與下次執行時間。確認按鈕呼叫 onConfirm。", - "scenario": "刪除情境", - "open": "開啟刪除確認", - "confirmed": "已確認刪除範例。", - "hint": "選擇單一、多個或含自動任務的對話。" - }, "inlineTokens": { "title": "Inline tokens · 指令與對話識別", "description": "編輯指令與識別碼,查看醒目樣式與色彩。", diff --git a/webui/src/dev/gallery/shell.tsx b/webui/src/dev/gallery/shell.tsx index 5f5116f8c..8dcb42514 100644 --- a/webui/src/dev/gallery/shell.tsx +++ b/webui/src/dev/gallery/shell.tsx @@ -4,7 +4,6 @@ import { Trans, useTranslation } from "react-i18next"; import { CapabilityMentionToken } from "@/components/CliAppMentionText"; import type { CapabilityMentionSegment } from "@/lib/composer-mention-text"; -import { DeleteConfirm } from "@/components/DeleteConfirm"; import { FileActions } from "@/components/FileActions"; import { InlineTokenHighlight, INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight"; import { RenameDialog } from "@/components/RenameDialog"; @@ -21,7 +20,7 @@ import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { PaneWorkbench, type WorkbenchPane } from "@/components/workbench/PaneWorkbench"; import type { HostCompatibility, RemoteProfile } from "@/lib/remote-instances"; -import type { CliAppInfo, McpPresetInfo, SessionAutomationJob, SessionMention, WorkbenchLayout } from "@/lib/types"; +import type { CliAppInfo, McpPresetInfo, SessionMention, WorkbenchLayout } from "@/lib/types"; import { cn } from "@/lib/utils"; import { Sample, StatePicker, type ComponentExample } from "./example"; import { useGalleryTranslation } from "./i18n"; @@ -60,30 +59,6 @@ function RenamePreview() { ; } -const automations: SessionAutomationJob[] = [ - { id: "gallery-daily", name: "每日项目摘要", enabled: true, schedule: { kind: "cron", expr: "0 9 * * *", tz: "Asia/Shanghai" }, payload: { message: "Summarize project updates" }, state: { next_run_at_ms: Date.UTC(2026, 9, 14, 1) } }, - { id: "gallery-hourly", name: "每小时检查", enabled: false, schedule: { kind: "every", every_ms: 3_600_000 }, payload: { message: "Check updates" }, state: {} }, - { id: "gallery-trigger", name: "发布后检查", enabled: true, schedule: { kind: "local" }, payload: { message: "Check the release", kind: "local_trigger" }, state: {} }, - { id: "gallery-once", name: "一次性提醒", enabled: true, schedule: { kind: "at", at_ms: Date.UTC(2026, 9, 15, 2) }, payload: { message: "Review the result" }, state: { next_run_at_ms: Date.UTC(2026, 9, 15, 2) } }, - { id: "gallery-weekly", name: "每周回顾", enabled: true, schedule: { kind: "every", every_ms: 604_800_000 }, payload: { message: "Review the week" }, state: {} }, -]; - -function DeletePreview() { - const { t } = useGalleryTranslation(); - const [scenario, setScenario] = useState<"single" | "multiple" | "automations">("single"); - const [open, setOpen] = useState(false); - const [deleted, setDeleted] = useState(false); - return <> - { setScenario(next); setDeleted(false); }} /> - - setOpen(false)} - onConfirm={() => { setDeleted(true); setOpen(false); }} /> -

{t(deleted ? "previews.delete.confirmed" : "previews.delete.hint")}

- ; -} - function InlineTokensPreview() { const { t } = useGalleryTranslation(); const [command, setCommand] = useState("/status"); @@ -244,9 +219,6 @@ export const shellExamples: ComponentExample[] = [ { title: "previews.rename.title", files: ["RenameDialog"], Preview: RenamePreview, description: "previews.rename.description", options: "previews.rename.options", code: '' }, - { title: "previews.delete.title", files: ["DeleteConfirm"], Preview: DeletePreview, - description: "previews.delete.description", options: "previews.delete.options", - code: '' }, { title: "previews.inlineTokens.title", files: ["SlashCommandText", "InlineTokenHighlight", "SessionHandleLabel"], Preview: InlineTokensPreview, description: "previews.inlineTokens.description", options: "previews.inlineTokens.options", code: '\n@design\nreview' }, diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.ts index d8421f8f0..78f8c2ba5 100644 --- a/webui/src/hooks/useSessions.ts +++ b/webui/src/hooks/useSessions.ts @@ -5,12 +5,14 @@ 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"; @@ -32,6 +34,7 @@ export function useSessions(): { key: string, options?: { deleteAutomations?: boolean }, ) => Promise; + getSessionAutomations: (key: string) => Promise; } { const { client, token } = useClient(); const [sessions, setSessions] = useState(readReloadSessions); @@ -184,6 +187,11 @@ export function useSessions(): { [client], ); + const getSessionAutomations = useCallback(async (key: string) => { + const result = await fetchSessionAutomations(tokenRef.current, key); + return result.jobs; + }, []); + return { sessions, loading, @@ -193,6 +201,7 @@ export function useSessions(): { createChat, forkChat, deleteChat, + getSessionAutomations, }; } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index d19a55f59..5b60ca68e 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1948,29 +1948,6 @@ "description": "Conversations are kept. You can unarchive them at any time.", "unarchiveDescription": "These topics will return to the sidebar." }, - "deleteConfirm": { - "title": "Delete this topic?", - "titleMany": "Delete {{count}} conversations?", - "cancel": "Cancel", - "confirm": "Delete", - "automationsDescription": "Deleting this topic also deletes its linked automations.", - "automationsDescriptionMany": "Linked automations will also be deleted.", - "moreAutomations": "+ {{count}} more", - "schedule": { - "at": "{{time}}", - "every": "Every {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "Local trigger", - "unknown": "Custom schedule" - }, - "next": { - "label": "Next: {{time}}", - "disabled": "Paused", - "local": "Waiting for trigger", - "none": "No next run" - } - }, "connection": { "idle": "Idle", "connecting": "Connecting…", @@ -2730,7 +2707,13 @@ "pendingDelete": "{{count}} topics will be deleted", "archived": "{{count}} topics archived", "unarchived": "{{count}} topics unarchived", - "deleteFailed": "Could not delete {{count}} topics" + "deleteFailed": "Could not delete {{count}} topics", + "confirmDeleteAutomationsSingle": "Delete topic and linked automations?", + "confirmDeleteAutomations": "Delete {{count}} topics and linked automations?", + "automationCountSingle": "1 automation", + "automationCount": "{{count}} automations", + "excludeSession": "Keep", + "excludeSessionAria": "Exclude {{title}} from deletion" }, "common": { "retry": "Retry", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 0812006c2..847ecee04 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -1766,29 +1766,6 @@ "description": "Las conversaciones se conservan. Puedes desarchivarlas en cualquier momento.", "unarchiveDescription": "Estos temas volverán a la barra lateral." }, - "deleteConfirm": { - "title": "¿Eliminar este chat?", - "titleMany": "¿Eliminar {{count}} conversaciones?", - "cancel": "Cancelar", - "confirm": "Eliminar", - "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", - "schedule": { - "at": "{{time}}", - "every": "Cada {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "Activador local", - "unknown": "Programación personalizada" - }, - "next": { - "label": "Siguiente: {{time}}", - "disabled": "Pausada", - "local": "Esperando activador", - "none": "Sin próxima ejecución" - } - }, "connection": { "idle": "Inactivo", "connecting": "Conectando…", @@ -2548,7 +2525,13 @@ "pendingDelete": "Se eliminarán {{count}} conversaciones", "archived": "{{count}} conversaciones archivadas", "unarchived": "{{count}} conversaciones desarchivadas", - "deleteFailed": "No se pudieron eliminar {{count}} conversaciones" + "deleteFailed": "No se pudieron eliminar {{count}} conversaciones", + "confirmDeleteAutomationsSingle": "¿Eliminar la conversación y sus automatizaciones?", + "confirmDeleteAutomations": "¿Eliminar {{count}} conversaciones y sus automatizaciones?", + "automationCountSingle": "1 automatización", + "automationCount": "{{count}} automatizaciones", + "excludeSession": "Conservar", + "excludeSessionAria": "Quitar {{title}} de esta eliminación" }, "common": { "retry": "Reintentar", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index e17b35110..84f5208d7 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -1766,29 +1766,6 @@ "description": "Les conversations sont conservées. Vous pouvez les désarchiver à tout moment.", "unarchiveDescription": "Ces sujets réapparaîtront dans la barre latérale." }, - "deleteConfirm": { - "title": "Supprimer cette discussion ?", - "titleMany": "Supprimer {{count}} conversations ?", - "cancel": "Annuler", - "confirm": "Supprimer", - "automationsDescription": "Supprimer ce sujet supprime aussi ses tâches automatiques liées.", - "automationsDescriptionMany": "Les automatisations liées seront également supprimées.", - "moreAutomations": "+ {{count}} autres", - "schedule": { - "at": "{{time}}", - "every": "Tous les {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "Déclencheur local", - "unknown": "Planification personnalisée" - }, - "next": { - "label": "Prochaine exécution : {{time}}", - "disabled": "En pause", - "local": "En attente du déclencheur", - "none": "Aucune prochaine exécution" - } - }, "connection": { "idle": "Inactif", "connecting": "Connexion…", @@ -2548,7 +2525,13 @@ "pendingDelete": "{{count}} conversations vont être supprimées", "archived": "{{count}} conversations archivées", "unarchived": "{{count}} conversations désarchivées", - "deleteFailed": "Impossible de supprimer {{count}} conversations" + "deleteFailed": "Impossible de supprimer {{count}} conversations", + "confirmDeleteAutomationsSingle": "Supprimer la conversation et ses automatisations ?", + "confirmDeleteAutomations": "Supprimer {{count}} conversations et leurs automatisations ?", + "automationCountSingle": "1 automatisation", + "automationCount": "{{count}} automatisations", + "excludeSession": "Conserver", + "excludeSessionAria": "Retirer {{title}} de cette suppression" }, "common": { "retry": "Réessayer", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 0f148c3a1..269c6db75 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -1766,29 +1766,6 @@ "description": "Percakapan tetap tersimpan. Anda dapat membatalkan arsipnya kapan saja.", "unarchiveDescription": "Topik ini akan kembali muncul di bilah samping." }, - "deleteConfirm": { - "title": "Hapus obrolan ini?", - "titleMany": "Hapus {{count}} percakapan?", - "cancel": "Batal", - "confirm": "Hapus", - "automationsDescription": "Menghapus topik ini juga menghapus tugas otomatis terkait.", - "automationsDescriptionMany": "Automasi terkait juga akan dihapus.", - "moreAutomations": "+ {{count}} lagi", - "schedule": { - "at": "{{time}}", - "every": "Setiap {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "Pemicu lokal", - "unknown": "Jadwal khusus" - }, - "next": { - "label": "Berikutnya: {{time}}", - "disabled": "Dijeda", - "local": "Menunggu pemicu", - "none": "Tidak ada jadwal berikutnya" - } - }, "connection": { "idle": "Tidak aktif", "connecting": "Menghubungkan…", @@ -2548,7 +2525,13 @@ "pendingDelete": "{{count}} percakapan akan dihapus", "archived": "{{count}} percakapan diarsipkan", "unarchived": "{{count}} percakapan dikeluarkan dari arsip", - "deleteFailed": "Gagal menghapus {{count}} percakapan" + "deleteFailed": "Gagal menghapus {{count}} percakapan", + "confirmDeleteAutomationsSingle": "Hapus percakapan dan otomatisasi terkait?", + "confirmDeleteAutomations": "Hapus {{count}} percakapan dan otomatisasi terkait?", + "automationCountSingle": "1 otomatisasi", + "automationCount": "{{count}} otomatisasi", + "excludeSession": "Simpan", + "excludeSessionAria": "Keluarkan {{title}} dari penghapusan ini" }, "common": { "retry": "Coba lagi", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index b05fbc585..acf74b047 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1766,29 +1766,6 @@ "description": "会話履歴は保持され、いつでもアーカイブを解除できます。", "unarchiveDescription": "これらのトピックがサイドバーに再表示されます。" }, - "deleteConfirm": { - "title": "このチャットを削除しますか?", - "titleMany": "{{count}} 件の会話を削除しますか?", - "cancel": "キャンセル", - "confirm": "削除", - "automationsDescription": "このトピックを削除すると、関連する自動タスクも削除されます。", - "automationsDescriptionMany": "関連する自動タスクも削除されます。", - "moreAutomations": "他 {{count}} 件", - "schedule": { - "at": "{{time}}", - "every": "{{duration}} ごと", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}}({{tz}})", - "local": "ローカルトリガー", - "unknown": "カスタムスケジュール" - }, - "next": { - "label": "次回: {{time}}", - "disabled": "一時停止中", - "local": "トリガー待ち", - "none": "次回実行なし" - } - }, "connection": { "idle": "待機中", "connecting": "接続中…", @@ -2548,7 +2525,13 @@ "pendingDelete": "{{count}} 件の会話を削除します", "archived": "{{count}} 件の会話をアーカイブしました", "unarchived": "{{count}} 件の会話のアーカイブを解除しました", - "deleteFailed": "{{count}} 件の会話を削除できませんでした" + "deleteFailed": "{{count}} 件の会話を削除できませんでした", + "confirmDeleteAutomationsSingle": "会話と関連する自動タスクを削除しますか?", + "confirmDeleteAutomations": "{{count}} 件の会話と関連する自動タスクを削除しますか?", + "automationCountSingle": "タスク 1 件", + "automationCount": "タスク {{count}} 件", + "excludeSession": "残す", + "excludeSessionAria": "「{{title}}」を削除対象から外す" }, "common": { "retry": "再試行", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 8a1243628..01a707111 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1766,29 +1766,6 @@ "description": "대화 기록은 유지되며 언제든지 보관을 해제할 수 있습니다.", "unarchiveDescription": "이 주제들이 사이드바에 다시 표시됩니다." }, - "deleteConfirm": { - "title": "이 채팅을 삭제할까요?", - "titleMany": "대화 {{count}}개를 삭제할까요?", - "cancel": "취소", - "confirm": "삭제", - "automationsDescription": "이 주제를 삭제하면 연결된 자동 작업도 삭제됩니다.", - "automationsDescriptionMany": "연결된 자동화도 함께 삭제됩니다.", - "moreAutomations": "+ {{count}}개 더", - "schedule": { - "at": "{{time}}", - "every": "{{duration}}마다", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "로컬 트리거", - "unknown": "사용자 지정 일정" - }, - "next": { - "label": "다음: {{time}}", - "disabled": "일시 중지됨", - "local": "트리거 대기 중", - "none": "다음 실행 없음" - } - }, "connection": { "idle": "대기 중", "connecting": "연결 중…", @@ -2548,7 +2525,13 @@ "pendingDelete": "대화 {{count}}개가 곧 삭제됩니다", "archived": "대화 {{count}}개를 보관했습니다", "unarchived": "대화 {{count}}개의 보관을 해제했습니다", - "deleteFailed": "대화 {{count}}개를 삭제하지 못했습니다" + "deleteFailed": "대화 {{count}}개를 삭제하지 못했습니다", + "confirmDeleteAutomationsSingle": "대화와 연결된 자동 작업을 삭제할까요?", + "confirmDeleteAutomations": "대화 {{count}}개와 연결된 자동 작업을 삭제할까요?", + "automationCountSingle": "작업 1개", + "automationCount": "작업 {{count}}개", + "excludeSession": "유지", + "excludeSessionAria": "{{title}}을(를) 삭제 대상에서 제외" }, "common": { "retry": "다시 시도", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index ef2312fce..4c5c2a80c 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1768,29 +1768,6 @@ "description": "As conversas são mantidas. Você pode desarquivá-las a qualquer momento.", "unarchiveDescription": "Estes tópicos voltarão à barra lateral." }, - "deleteConfirm": { - "title": "Excluir esta conversa?", - "titleMany": "Excluir {{count}} conversas?", - "cancel": "Cancelar", - "confirm": "Excluir", - "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", - "schedule": { - "at": "{{time}}", - "every": "A cada {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "Gatilho local", - "unknown": "Agendamento personalizado" - }, - "next": { - "label": "Próxima: {{time}}", - "disabled": "Pausada", - "local": "Aguardando gatilho", - "none": "Sem próxima execução" - } - }, "connection": { "idle": "Ocioso", "connecting": "Conectando…", @@ -2550,7 +2527,13 @@ "pendingDelete": "{{count}} conversas serão excluídas", "archived": "{{count}} conversas arquivadas", "unarchived": "{{count}} conversas desarquivadas", - "deleteFailed": "Não foi possível excluir {{count}} conversas" + "deleteFailed": "Não foi possível excluir {{count}} conversas", + "confirmDeleteAutomationsSingle": "Excluir a conversa e as automações vinculadas?", + "confirmDeleteAutomations": "Excluir {{count}} conversas e as automações vinculadas?", + "automationCountSingle": "1 automação", + "automationCount": "{{count}} automações", + "excludeSession": "Manter", + "excludeSessionAria": "Remover {{title}} desta exclusão" }, "common": { "retry": "Tentar novamente", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 1b68ae182..de96c7b0f 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -1766,29 +1766,6 @@ "description": "Lịch sử trò chuyện vẫn được giữ lại. Bạn có thể bỏ lưu trữ bất cứ lúc nào.", "unarchiveDescription": "Các chủ đề này sẽ xuất hiện lại trên thanh bên." }, - "deleteConfirm": { - "title": "Xóa cuộc trò chuyện này?", - "titleMany": "Xóa {{count}} cuộc trò chuyện?", - "cancel": "Hủy", - "confirm": "Xóa", - "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", - "schedule": { - "at": "{{time}}", - "every": "Mỗi {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}} ({{tz}})", - "local": "Trình kích hoạt cục bộ", - "unknown": "Lịch tùy chỉnh" - }, - "next": { - "label": "Tiếp theo: {{time}}", - "disabled": "Đã tạm dừng", - "local": "Đang chờ kích hoạt", - "none": "Không có lần chạy tiếp theo" - } - }, "connection": { "idle": "Rảnh", "connecting": "Đang kết nối…", @@ -2548,7 +2525,13 @@ "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", - "deleteFailed": "Không thể xóa {{count}} cuộc trò chuyện" + "deleteFailed": "Không thể xóa {{count}} cuộc trò chuyện", + "confirmDeleteAutomationsSingle": "Xóa cuộc trò chuyện và các tác vụ tự động?", + "confirmDeleteAutomations": "Xóa {{count}} cuộc trò chuyện và các tác vụ tự động?", + "automationCountSingle": "1 tác vụ", + "automationCount": "{{count}} tác vụ", + "excludeSession": "Giữ lại", + "excludeSessionAria": "Bỏ {{title}} khỏi lần xóa này" }, "common": { "retry": "Thử lại", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index ff7ef219e..d8134609a 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1948,29 +1948,6 @@ "description": "聊天记录会保留,可随时取消归档。", "unarchiveDescription": "这些话题将重新显示在侧栏中。" }, - "deleteConfirm": { - "title": "删除这个话题?", - "titleMany": "删除这 {{count}} 个对话?", - "cancel": "取消", - "confirm": "删除", - "automationsDescription": "删除话题也会删除关联的自动任务", - "automationsDescriptionMany": "关联的自动任务也会一并删除。", - "moreAutomations": "另有 {{count}} 个", - "schedule": { - "at": "{{time}}", - "every": "每 {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}}({{tz}})", - "local": "本地触发器", - "unknown": "自定义计划" - }, - "next": { - "label": "下次:{{time}}", - "disabled": "已暂停", - "local": "等待触发", - "none": "没有下次运行" - } - }, "connection": { "idle": "空闲", "connecting": "连接中…", @@ -2730,7 +2707,13 @@ "pendingDelete": "即将删除 {{count}} 个会话", "archived": "已归档 {{count}} 个会话", "unarchived": "已取消归档 {{count}} 个会话", - "deleteFailed": "{{count}} 个会话删除失败" + "deleteFailed": "{{count}} 个会话删除失败", + "confirmDeleteAutomationsSingle": "删除会话及关联自动任务?", + "confirmDeleteAutomations": "删除 {{count}} 个会话及关联自动任务?", + "automationCountSingle": "1 个任务", + "automationCount": "{{count}} 个任务", + "excludeSession": "保留", + "excludeSessionAria": "从本次删除中移除「{{title}}」" }, "common": { "retry": "重试", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index cb98b4742..f8ff1ead6 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1766,29 +1766,6 @@ "description": "聊天記錄會保留,可隨時取消封存。", "unarchiveDescription": "這些話題將重新顯示在側欄中。" }, - "deleteConfirm": { - "title": "刪除這個話題?", - "titleMany": "刪除這 {{count}} 個對話?", - "cancel": "取消", - "confirm": "刪除", - "automationsDescription": "刪除話題也會刪除關聯的自動任務", - "automationsDescriptionMany": "關聯的自動任務也會一併刪除。", - "moreAutomations": "另有 {{count}} 個", - "schedule": { - "at": "{{time}}", - "every": "每 {{duration}}", - "cron": "Cron {{expr}}", - "cronWithTz": "Cron {{expr}}({{tz}})", - "local": "本機觸發器", - "unknown": "自訂排程" - }, - "next": { - "label": "下次:{{time}}", - "disabled": "已暫停", - "local": "等待觸發", - "none": "沒有下次執行" - } - }, "connection": { "idle": "閒置", "connecting": "連線中…", @@ -2548,7 +2525,13 @@ "pendingDelete": "即將刪除 {{count}} 個對話", "archived": "已封存 {{count}} 個對話", "unarchived": "已取消封存 {{count}} 個對話", - "deleteFailed": "無法刪除 {{count}} 個對話" + "deleteFailed": "無法刪除 {{count}} 個對話", + "confirmDeleteAutomationsSingle": "刪除對話及關聯自動任務?", + "confirmDeleteAutomations": "刪除 {{count}} 個對話及關聯自動任務?", + "automationCountSingle": "1 個任務", + "automationCount": "{{count}} 個任務", + "excludeSession": "保留", + "excludeSessionAria": "從本次刪除中移除「{{title}}」" }, "common": { "retry": "重試", diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 44c85d230..8fa422cdf 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -24,6 +24,7 @@ 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>().mockResolvedValue([]); const toggleThemeSpy = vi.fn(); const updateUrlSpy = vi.fn(); const attachSpy = vi.fn(); @@ -215,6 +216,7 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => { setSessions((prev: ChatSummary[]) => prev.filter((s) => s.key !== key)); return { deleted: true }; }, + getSessionAutomations: (key: string) => getSessionAutomationsSpy(key), }; }), }; @@ -346,6 +348,7 @@ describe("App layout", () => { refreshSpy.mockReset(); createChatSpy.mockClear(); deleteChatSpy.mockReset(); + getSessionAutomationsSpy.mockReset().mockResolvedValue([]); toggleThemeSpy.mockReset(); attachSpy.mockReset(); setSidebarStateSpy.mockReset().mockImplementation( @@ -2708,17 +2711,27 @@ describe("App layout", () => { 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"]]); - vi.useRealTimers(); - const retry = await screen.findByRole("alertdialog", { name: "Delete this topic?" }); - expect(within(retry).getByText("Added during undo")).toBeVisible(); - vi.useFakeTimers(); - await clickDeleteAction(within(retry).getByRole("button", { name: "Delete" })); + expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument(); + + const confirmToast = screen.getByText("Delete topic and linked automations?").closest("[data-toast-tone]")!; + expect(confirmToast).toHaveAttribute("data-toast-timed", "false"); + expect(within(confirmToast).getByRole("status")).not.toHaveAttribute("title"); + await clickDeleteAction(within(confirmToast).getByRole("button", { name: "1 automation" })); + const popover = screen.getByRole("dialog"); + expect(within(popover).getByText("Topic b")).toBeVisible(); + expect(within(popover).getByText("Added during undo")).toBeVisible(); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS * 3); }); + expect(deleteChatSpy).toHaveBeenCalledTimes(2); + + await clickDeleteAction(within(confirmToast).getByRole("button", { name: "Delete" })); + expect(confirmToast).toHaveAttribute("data-toast-timed", "true"); + expect(within(confirmToast).getByText("Topic will be deleted")).toBeVisible(); 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 a localized automation warning and keeps the topic when cancelled", async () => { + it("lists linked automations by session in a toast dropdown and lets the user exclude a session from deletion", async () => { mockSessions = [ { key: "websocket:chat-a", @@ -2737,18 +2750,18 @@ describe("App layout", () => { preview: "Second chat", }, ]; - 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) }, - }], - }); + getSessionAutomationsSpy.mockImplementation(async (key: string) => ( + key === "websocket:chat-a" + ? [{ + 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(); @@ -2767,23 +2780,74 @@ describe("App layout", () => { const deleteItem = await screen.findByRole("menuitem", { name: "删除" }); vi.useFakeTimers(); await clickDeleteAction(deleteItem); - await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); - vi.useRealTimers(); - const dialog = await screen.findByRole("alertdialog", { name: "删除这个话题?" }); - expect(within(dialog).getByText("Daily repo check")).toBeVisible(); - expect( - screen.getByText("删除话题也会删除关联的自动任务"), - ).toBeInTheDocument(); - expect( - screen.queryByText("Deleting this topic also deletes its linked automations."), - ).not.toBeInTheDocument(); - - vi.useFakeTimers(); - await clickDeleteAction(within(dialog).getByRole("button", { name: "取消" })); - await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); - expect(deleteChatSpy.mock.calls).toEqual([["websocket:chat-a"]]); + expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument(); expect(within(sidebar).getByRole("button", { name: "First chat" })).toBeVisible(); + const toast = screen.getByText("删除会话及关联自动任务?").closest("[data-toast-tone]")!; + expect(toast).toHaveAttribute("data-toast-timed", "false"); + expect(within(toast).getByRole("status")).not.toHaveAttribute("title"); + expect(toast.textContent).not.toContain("·"); + + await clickDeleteAction(within(toast).getByRole("button", { name: "1 个任务" })); + const details = screen.getByRole("dialog"); + expect(within(details).getByText("First chat")).toBeVisible(); + expect(within(details).getByText("Daily repo check")).toBeVisible(); + expect(details.textContent).not.toContain("·"); + + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS * 3); }); + expect(deleteChatSpy).not.toHaveBeenCalled(); + expect(within(sidebar).getByRole("button", { name: "First chat" })).toBeVisible(); + + await clickDeleteAction(within(details).getByRole("button", { name: "从本次删除中移除「First chat」" })); + expect(screen.queryByText("删除会话及关联自动任务?")).not.toBeInTheDocument(); + expect(deleteChatSpy).not.toHaveBeenCalled(); + expect(within(sidebar).getByRole("button", { name: "First chat" })).toBeVisible(); + + vi.useRealTimers(); + fireEvent.pointerDown(within(sidebar).getByLabelText(/First chat.*话题操作/), { button: 0 }); + fireEvent.click(await screen.findByRole("menuitem", { name: "选择" })); + fireEvent.click(within(sidebar).getByRole("button", { name: "Second chat" })); + vi.useFakeTimers(); + await clickDeleteAction(within(sidebar).getByRole("button", { name: "删除" })); + + const bulkToast = screen.getByText("删除 2 个会话及关联自动任务?").closest("[data-toast-tone]")!; + expect(bulkToast).toHaveAttribute("data-toast-timed", "false"); + await clickDeleteAction(within(bulkToast).getByRole("button", { name: "1 个任务" })); + const bulkDetails = screen.getByRole("dialog"); + await clickDeleteAction(within(bulkDetails).getByRole("button", { name: "从本次删除中移除「First chat」" })); + + expect(document.querySelectorAll("[data-toast-tone]")).toHaveLength(1); + expect(bulkToast).toHaveAttribute("data-toast-timed", "true"); + expect(within(bulkToast).getByText("即将删除会话")).toBeVisible(); + expect(within(bulkToast).getByText("Second chat")).toBeVisible(); + expect(within(sidebar).getByRole("button", { name: "First chat" })).toBeVisible(); + expect(within(sidebar).queryByRole("button", { name: "Second chat" })).not.toBeInTheDocument(); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(deleteChatSpy).toHaveBeenCalledTimes(1); + expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-b"); + + vi.useRealTimers(); + fireEvent.pointerDown(within(sidebar).getByLabelText(/First chat.*话题操作/), { button: 0 }); + const deleteAgain = await screen.findByRole("menuitem", { name: "删除" }); + vi.useFakeTimers(); + await clickDeleteAction(deleteAgain); + + const confirmToast = screen.getByText("删除会话及关联自动任务?").closest("[data-toast-tone]")!; + expect(document.querySelectorAll("[data-toast-tone]")).toHaveLength(1); + await clickDeleteAction(within(confirmToast).getByRole("button", { name: "删除" })); + + expect(document.querySelectorAll("[data-toast-tone]")).toHaveLength(1); + expect(confirmToast).toHaveAttribute("data-toast-timed", "true"); + expect(within(confirmToast).getByText("即将删除会话")).toBeVisible(); + expect(within(confirmToast).getByRole("button", { name: "撤销" })).toBeVisible(); + expect(within(sidebar).queryByRole("button", { name: "First chat" })).not.toBeInTheDocument(); + expect(deleteChatSpy).toHaveBeenCalledTimes(1); + + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS - 1); }); + expect(deleteChatSpy).toHaveBeenCalledTimes(1); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + expect(deleteChatSpy).toHaveBeenCalledTimes(2); + expect(deleteChatSpy).toHaveBeenLastCalledWith("websocket:chat-a", { deleteAutomations: true }); }, 15_000); it("closes the mobile drawer when selecting a new or current topic without a search tooltip", async () => {