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
This commit is contained in:
1 parent
7935176eb7
commit
cb95277098
31 files changed
+652
-668
No files matched your search
+1
-1
@@ -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
|
||||
|
||||
+148
-56
@@ -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<string>) {
|
||||
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<Set<string>>(() => new Set());
|
||||
const topicSessions = useMemo(() => deletingKeys.size === 0 ? sessions
|
||||
: sessions.filter((session) => !deletingKeys.has(session.key)), [deletingKeys, sessions]);
|
||||
const [deleteQueue, setDeleteQueue] = useState<PendingDelete[]>([]);
|
||||
const [pendingDelete] = deleteQueue;
|
||||
const nextDeleteId = useRef(0);
|
||||
const archiveUndoOwners = useRef(new Map<string, { operation: symbol; pinOrder?: string[] }>());
|
||||
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<Set<string>>(new Set());
|
||||
const showAutomationConfirmRef = useRef<(
|
||||
items: SidebarDeleteItem[],
|
||||
jobsByKey: ReadonlyMap<string, SessionAutomationJob[]>,
|
||||
) => 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<string>,
|
||||
): 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<string, SessionAutomationJob[]>();
|
||||
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<string, SessionAutomationJob[]>,
|
||||
): 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) => (
|
||||
<AutomationDeleteToastDetails
|
||||
groups={groups}
|
||||
onExcludeSession={(excludedKey) => {
|
||||
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<string, SessionAutomationJob[]>,
|
||||
) => {
|
||||
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<string, SessionAutomationJob[]>();
|
||||
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({
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{pendingDelete && localActive && !managingConnections ? (
|
||||
<Suspense fallback={null}>
|
||||
<DeleteConfirm
|
||||
key={pendingDelete.id}
|
||||
open
|
||||
title={pendingDelete.items[0]?.label ?? ""}
|
||||
count={pendingDelete.items.length}
|
||||
automations={pendingDelete.automations}
|
||||
onCancel={() => dismissDeleteConfirmation(pendingDelete.id)}
|
||||
onConfirm={() => {
|
||||
dismissDeleteConfirmation(pendingDelete.id);
|
||||
stageDelete(pendingDelete.items, true);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
{pendingTabRename ? (
|
||||
<Suspense fallback={null}>
|
||||
<RenameDialog
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { MessageSquare } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { currentLocale } from "@/i18n";
|
||||
import { fmtDateTime } from "@/lib/format-time";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { SidebarDeleteItem } from "@/components/ChatList";
|
||||
|
||||
export interface AutomationDeleteSessionGroup {
|
||||
item: SidebarDeleteItem;
|
||||
jobs: SessionAutomationJob[];
|
||||
}
|
||||
|
||||
export function AutomationDeleteToastDetails({
|
||||
groups,
|
||||
onExcludeSession,
|
||||
}: {
|
||||
groups: AutomationDeleteSessionGroup[];
|
||||
onExcludeSession: (key: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const locale = currentLocale();
|
||||
|
||||
return (
|
||||
<div className="max-h-64 divide-y divide-border/60 overflow-y-auto overscroll-contain">
|
||||
{groups.map(({ item, jobs }) => (
|
||||
<section key={item.key} className="px-3.5 py-2.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<MessageSquare
|
||||
aria-hidden="true"
|
||||
className="h-3.5 w-3.5 shrink-0 text-muted-foreground/80"
|
||||
strokeWidth={1.8}
|
||||
/>
|
||||
<span className="min-w-0 truncate text-[13px] font-medium leading-5 text-foreground">
|
||||
{item.label}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={t("toast.excludeSessionAria", { title: item.label })}
|
||||
onClick={() => onExcludeSession(item.key)}
|
||||
className="h-6 shrink-0 rounded-full border border-border/70 bg-background/70 px-2.5 text-[11.5px] font-medium leading-4 text-muted-foreground transition-colors hover:border-border hover:bg-muted/75 hover:text-foreground"
|
||||
>
|
||||
{t("toast.excludeSession")}
|
||||
</Button>
|
||||
</div>
|
||||
<ul className="mt-1.5 space-y-0.5 pl-[1.375rem]">
|
||||
{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 (
|
||||
<li
|
||||
key={job.id}
|
||||
className="flex items-center justify-between gap-3 rounded-lg px-2 py-1 text-[12.5px] leading-5 transition-colors hover:bg-muted/45"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn("h-1.5 w-1.5 shrink-0 rounded-full", statusDotClass)}
|
||||
/>
|
||||
<span className="min-w-0 truncate text-foreground/90">
|
||||
{job.name || job.id}
|
||||
</span>
|
||||
</div>
|
||||
{!job.enabled ? (
|
||||
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium leading-4 text-muted-foreground">
|
||||
{t("settings.automations.status.paused")}
|
||||
</span>
|
||||
) : (
|
||||
<span className="shrink-0 text-[11.5px] leading-4 tabular-nums text-muted-foreground">
|
||||
{formatCompactSchedule(job, locale, t)}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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 (
|
||||
<AlertDialog open={open} onOpenChange={(o) => (!o ? onCancel() : undefined)}>
|
||||
<AlertDialogContent
|
||||
className="w-[min(calc(100vw-2rem),24rem)] gap-0 p-5 text-center"
|
||||
onEscapeKeyDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<AlertDialogHeader className="items-center space-y-0 text-center">
|
||||
<Trash2
|
||||
className="mb-4 h-6 w-6 text-destructive"
|
||||
strokeWidth={1.8}
|
||||
aria-hidden
|
||||
/>
|
||||
<AlertDialogTitle className="text-center text-[20px] font-semibold leading-tight tracking-[-0.02em] text-foreground">
|
||||
{multiple
|
||||
? t("deleteConfirm.titleMany", {
|
||||
defaultValue: "Delete {{count}} conversations?",
|
||||
count,
|
||||
})
|
||||
: t("deleteConfirm.title", { title })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="mt-3 max-w-[17rem] text-center text-[14px] leading-6 text-muted-foreground">
|
||||
{multiple
|
||||
? t("deleteConfirm.automationsDescriptionMany", {
|
||||
defaultValue: "Linked automations will also be deleted.",
|
||||
})
|
||||
: t("deleteConfirm.automationsDescription")}
|
||||
</AlertDialogDescription>
|
||||
<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>
|
||||
))}
|
||||
{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
|
||||
onClick={onCancel}
|
||||
className="mt-0 w-full min-w-0"
|
||||
>
|
||||
{t("deleteConfirm.cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={onConfirm}
|
||||
className="w-full min-w-0 !whitespace-normal bg-destructive text-center text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{t("deleteConfirm.confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ export function RenameDialog({
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
>
|
||||
{t("deleteConfirm.cancel")}
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button className="min-w-20" type="submit" disabled={!trimmed}>
|
||||
{t("chat.renameSave")}
|
||||
|
||||
@@ -97,7 +97,7 @@ export function SidebarTopicRename({ title, onSave, onClose }: SidebarTopicRenam
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("deleteConfirm.cancel")}
|
||||
aria-label={t("common.cancel")}
|
||||
disabled={saving}
|
||||
onClick={onClose}
|
||||
className="touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground disabled:opacity-40"
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.18), 0 8px 24px -8px rgb(0 0 0 / 0.45);
|
||||
}
|
||||
|
||||
.toast-card::before {
|
||||
.toast-card[data-toast-timed="true"]::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
@@ -26,7 +26,7 @@
|
||||
animation-play-state: var(--toast-play-state);
|
||||
}
|
||||
|
||||
.toast-card:dir(rtl)::before {
|
||||
.toast-card[data-toast-timed="true"]:dir(rtl)::before {
|
||||
--toast-sweep-direction: to left;
|
||||
animation-direction: reverse;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
import { Check, Trash2, TriangleAlert } from "lucide-react";
|
||||
import { createContext, useCallback, useContext, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
|
||||
import { Check, ChevronDown, Trash2, TriangleAlert } from "lucide-react";
|
||||
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import "./toast.css";
|
||||
|
||||
const TOAST_NOTICE_MS = 3_000;
|
||||
export const TOAST_ACTION_MS = 8_000;
|
||||
|
||||
type ToastNotice = {
|
||||
export type ToastController = {
|
||||
update: (next: ToastNotice) => void;
|
||||
dismiss: () => void;
|
||||
};
|
||||
|
||||
type ToastAction = {
|
||||
label: string;
|
||||
run: () => void | ToastNotice;
|
||||
tone?: "default" | "destructive";
|
||||
};
|
||||
|
||||
export type ToastNotice = {
|
||||
message: string;
|
||||
detail?: string;
|
||||
tone: "success" | "error" | "pending";
|
||||
dedupeKey?: string;
|
||||
action?: { label: string; run: () => void };
|
||||
persistent?: boolean;
|
||||
details?: {
|
||||
label: string;
|
||||
render: (controller: ToastController) => ReactNode;
|
||||
};
|
||||
action?: ToastAction;
|
||||
secondaryAction?: { label: string; run?: () => void };
|
||||
onExpire?: () => void;
|
||||
};
|
||||
|
||||
@@ -20,63 +38,145 @@ function toastDurationMs(notice: ToastNotice) {
|
||||
return notice.action ? TOAST_ACTION_MS : TOAST_NOTICE_MS;
|
||||
}
|
||||
|
||||
type ToastEntry = ToastNotice & { id: number };
|
||||
type ToastEntry = ToastNotice & { id: number; step: number };
|
||||
const ToastContext = createContext<((notice: ToastNotice) => void) | null>(null);
|
||||
export const useToast = () => useContext(ToastContext);
|
||||
|
||||
function ToastViewport({ children, viewportRef, hidden }: { children: ReactNode; viewportRef: Ref<HTMLDivElement>; hidden: boolean }) {
|
||||
return <div ref={viewportRef} className="pointer-events-none fixed inset-x-3 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 mx-auto flex max-w-[22rem] flex-col items-center gap-2 [.native-host_&]:top-12" style={hidden ? { visibility: "hidden" } : undefined}>
|
||||
return <div ref={viewportRef} className="pointer-events-none fixed inset-x-3 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 mx-auto flex max-w-[min(calc(100vw-1.5rem),36rem)] flex-col items-center gap-2 [.native-host_&]:top-12" style={hidden ? { visibility: "hidden" } : undefined}>
|
||||
{children}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ToastCard({ notice, paused, onAction, onHoverChange, onFocusChange }: {
|
||||
function ToastCard({ notice, step, paused, unavailable, controller, onAction, onSecondaryAction, onHoverChange, onFocusChange }: {
|
||||
notice: ToastNotice;
|
||||
step: number;
|
||||
paused: boolean;
|
||||
unavailable: boolean;
|
||||
controller: ToastController;
|
||||
onAction: () => void;
|
||||
onSecondaryAction: () => void;
|
||||
onHoverChange?: (hovered: boolean) => void;
|
||||
onFocusChange?: (focused: boolean) => void;
|
||||
}) {
|
||||
const { message, detail, tone, action } = notice;
|
||||
const { message, detail, tone, persistent, details, action, secondaryAction } = notice;
|
||||
const [detailsOpen, setDetailsOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!details || unavailable) setDetailsOpen(false);
|
||||
}, [details, unavailable]);
|
||||
const Icon = tone === "error" ? TriangleAlert : tone === "pending" ? Trash2 : Check;
|
||||
return <div
|
||||
className={`toast-card isolate relative flex min-h-10 max-w-full items-center gap-2 px-3 py-0.5${action ? " pointer-events-auto" : ""}`}
|
||||
style={{
|
||||
"--toast-duration": `${toastDurationMs(notice)}ms`,
|
||||
"--toast-play-state": paused ? "paused" : "running",
|
||||
} as CSSProperties}
|
||||
onPointerEnter={(event) => { 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}
|
||||
>
|
||||
<Icon aria-hidden="true" size={15} strokeWidth={2} className="shrink-0" />
|
||||
<div role={tone === "error" ? "alert" : "status"} className="min-w-0 truncate text-sm leading-5"
|
||||
title={detail ? `${message} ${detail}` : message}>
|
||||
<span className={detail ? "text-muted-foreground" : "font-medium"}>{message}</span>
|
||||
{detail && <> <span className="font-medium">{detail}</span></>}
|
||||
</div>
|
||||
{action && <Button type="button" variant="ghost" size="sm" onClick={onAction} className="h-8 shrink-0 px-2">{action.label}</Button>}
|
||||
</div>;
|
||||
const hasActions = Boolean(action || secondaryAction);
|
||||
const interactive = Boolean(hasActions || details);
|
||||
return (
|
||||
<Popover open={Boolean(details) && detailsOpen} onOpenChange={setDetailsOpen}>
|
||||
<PopoverAnchor asChild>
|
||||
<div
|
||||
className={`toast-card isolate relative flex min-h-10 max-w-full items-center gap-2 ${interactive ? "py-1 pl-3.5 pr-1.5" : "px-3.5 py-1"}${interactive ? " pointer-events-auto" : ""}`}
|
||||
style={{
|
||||
"--toast-duration": `${toastDurationMs(notice)}ms`,
|
||||
"--toast-play-state": paused ? "paused" : "running",
|
||||
} as CSSProperties}
|
||||
onPointerEnter={(event) => { 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"}
|
||||
>
|
||||
<Icon aria-hidden="true" size={15} strokeWidth={2} className="shrink-0" />
|
||||
<div role={tone === "error" ? "alert" : "status"} className="min-w-0 truncate text-sm leading-5">
|
||||
<span className={detail ? "text-muted-foreground" : "font-medium"}>{message}</span>
|
||||
{detail && <> <span className="font-medium">{detail}</span></>}
|
||||
</div>
|
||||
{details && (
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 shrink-0 gap-1 rounded-full bg-muted/65 px-2.5 text-sm font-medium leading-5 tabular-nums text-foreground/85 hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground"
|
||||
>
|
||||
<span>{details.label}</span>
|
||||
<ChevronDown
|
||||
className={`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ${detailsOpen ? "rotate-180" : ""}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
)}
|
||||
{details && hasActions && (
|
||||
<span aria-hidden="true" className="mx-0.5 h-4 w-px shrink-0 bg-border/80" />
|
||||
)}
|
||||
{hasActions && (
|
||||
<div className="flex shrink-0 items-center gap-0.5">
|
||||
{secondaryAction && (
|
||||
<Button
|
||||
key={`secondary-${step}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onSecondaryAction}
|
||||
className="h-7 shrink-0 rounded-full px-2.5 text-sm leading-5 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{secondaryAction.label}
|
||||
</Button>
|
||||
)}
|
||||
{action && (
|
||||
<Button
|
||||
key={`action-${step}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onAction}
|
||||
className={action.tone === "destructive"
|
||||
? "h-7 shrink-0 rounded-full px-2.5 text-sm font-medium leading-5 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
: "h-7 shrink-0 rounded-full px-2.5 text-sm font-medium leading-5"}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverAnchor>
|
||||
{details && (
|
||||
<PopoverContent
|
||||
align="center"
|
||||
side="bottom"
|
||||
sideOffset={8}
|
||||
className="w-[var(--radix-popover-trigger-width)] min-w-[min(calc(100vw-1.5rem),21rem)] max-w-[calc(100vw-1.5rem)] rounded-panel border border-border bg-popover p-0 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_12px_32px_-10px_rgb(0_0_0/0.18)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.2),0_14px_34px_-8px_rgb(0_0_0/0.48)]"
|
||||
>
|
||||
{details.render(controller)}
|
||||
</PopoverContent>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
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<ToastController>(() => ({
|
||||
update: (next) => update(entry, next),
|
||||
dismiss: () => dismiss(entry),
|
||||
}), [dismiss, entry, update]);
|
||||
|
||||
return <ToastCard notice={entry} paused={paused} onAction={() => finish(entry, "action")}
|
||||
onHoverChange={entry.action ? setHovered : undefined} onFocusChange={entry.action ? setFocused : undefined} />;
|
||||
return <ToastCard notice={entry} step={entry.step} paused={paused} unavailable={unavailable}
|
||||
controller={controller}
|
||||
onAction={() => 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<number, ToastEntry>());
|
||||
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 <ToastContext.Provider value={show}>
|
||||
{children}
|
||||
<ToastViewport viewportRef={viewportRef} hidden={unavailable}>
|
||||
{entries.map((entry) => <TimedToast key={entry.id} entry={entry} finish={finish} unavailable={unavailable} />)}
|
||||
{entries.map((entry) => (
|
||||
<TimedToast
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
finish={finish}
|
||||
update={update}
|
||||
dismiss={dismiss}
|
||||
unavailable={unavailable}
|
||||
/>
|
||||
))}
|
||||
</ToastViewport>
|
||||
</ToastContext.Provider>;
|
||||
}
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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": "コマンドや識別子を編集して、強調表示とセッション固有の色を確認できます。",
|
||||
|
||||
@@ -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": "명령과 식별자를 편집하여 강조 표시와 일관된 세션 색상을 확인합니다.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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": "编辑命令与标识,查看高亮和会话颜色。",
|
||||
|
||||
@@ -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": "編輯指令與識別碼,查看醒目樣式與色彩。",
|
||||
|
||||
@@ -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() {
|
||||
</div>;
|
||||
}
|
||||
|
||||
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 <>
|
||||
<StatePicker label={t("previews.delete.scenario")} value={scenario} options={["single", "multiple", "automations"]}
|
||||
onChange={(next) => { setScenario(next); setDeleted(false); }} />
|
||||
<Button variant="outline" onClick={() => { setDeleted(false); setOpen(true); }}>{t("previews.delete.open")}</Button>
|
||||
<DeleteConfirm open={open} title="组件设计" count={scenario === "multiple" ? 3 : 1}
|
||||
automations={scenario === "automations" ? automations : []} onCancel={() => setOpen(false)}
|
||||
onConfirm={() => { setDeleted(true); setOpen(false); }} />
|
||||
<p role="status" className="mt-4 text-xs text-muted-foreground">{t(deleted ? "previews.delete.confirmed" : "previews.delete.hint")}</p>
|
||||
</>;
|
||||
}
|
||||
|
||||
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: '<RenameDialog open={open} title={title} dialogTitle="Rename group" description="Give this group a name." placeholder="Group name" onCancel={close} onConfirm={rename} />' },
|
||||
{ title: "previews.delete.title", files: ["DeleteConfirm"], Preview: DeletePreview,
|
||||
description: "previews.delete.description", options: "previews.delete.options",
|
||||
code: '<DeleteConfirm open={open} title="组件设计" count={1} automations={jobs} onCancel={close} onConfirm={remove} />' },
|
||||
{ title: "previews.inlineTokens.title", files: ["SlashCommandText", "InlineTokenHighlight", "SessionHandleLabel"], Preview: InlineTokensPreview,
|
||||
description: "previews.inlineTokens.description", options: "previews.inlineTokens.options",
|
||||
code: '<SlashCommandText command="/status" />\n<SessionHandleLabel id={session.id}>@design</SessionHandleLabel>\n<InlineTokenHighlight color="var(--inline-token-highlight)">review</InlineTokenHighlight>' },
|
||||
|
||||
@@ -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<SessionDeleteResult>;
|
||||
getSessionAutomations: (key: string) => Promise<SessionAutomationJob[]>;
|
||||
} {
|
||||
const { client, token } = useClient();
|
||||
const [sessions, setSessions] = useState<ChatSummary[]>(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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "再試行",
|
||||
|
||||
@@ -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": "다시 시도",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "重试",
|
||||
|
||||
@@ -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": "重試",
|
||||
|
||||
@@ -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<SessionAutomationJob[]>>().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<HTMLElement>("[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(<App />);
|
||||
@@ -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<HTMLElement>("[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<HTMLElement>("[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<HTMLElement>("[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 () => {
|
||||
|
||||
Reference in new issue
Block a user