diff --git a/webui/browser/composer-action-fixture.tsx b/webui/browser/composer-action-fixture.tsx index 00b198509..a18a4f137 100644 --- a/webui/browser/composer-action-fixture.tsx +++ b/webui/browser/composer-action-fixture.tsx @@ -1,10 +1,17 @@ import { useState } from "react"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; +import { ToastProvider } from "@/components/ui/toast"; + +export function installMissingMicrophonePreview() { + Object.defineProperty(navigator.mediaDevices, "getUserMedia", { + value: async () => { throw new DOMException("No microphone", "NotFoundError"); }, + }); +} export function ComposerActionFixture({ parameters }: { parameters: URLSearchParams }) { const [running, setRunning] = useState(false); const [stopRequested, setStopRequested] = useState(false); - return
+ return
{ setRunning(false); setStopRequested(false); }}>Finish response -
; +
; } diff --git a/webui/browser/composer-action.spec.ts b/webui/browser/composer-action.spec.ts index bc67b6e1f..764786152 100644 --- a/webui/browser/composer-action.spec.ts +++ b/webui/browser/composer-action.spec.ts @@ -1,5 +1,29 @@ import { expect, test } from "@playwright/test"; +test("missing microphone uses a short toast without resizing the mobile composer", async ({ page }) => { + await page.setViewportSize({ width: 320, height: 720 }); + await page.goto("/browser/fixture.html?case=composer-action&voiceError=noDevice"); + const voice = page.getByRole("button", { name: "Voice input" }); + const composer = page.locator(".thread-composer-form"); + await expect(voice).toBeVisible(); + await page.evaluate(async () => { await document.fonts.ready; }); + await voice.hover(); + // Compact controls can be visible before the footer's padding finishes transitioning. + await expect(composer).toHaveAttribute("data-compact-controls", "true"); + const footer = composer.locator(".thread-composer-footer"); + await expect.poll(() => footer.evaluate((element) => element.getAnimations().some((animation) => + animation instanceof CSSTransition && animation.transitionProperty === "padding-bottom", + ))).toBe(false); + const bounds = await composer.boundingBox(); + await voice.click(); + const alert = page.locator('[data-toast-tone="error"]').getByRole("alert"); + await expect(alert).toHaveText("Connect a microphone to record."); + expect(await alert.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true); + expect(await composer.boundingBox()).toEqual(bounds); + await expect(alert).toBeHidden(); + await expect(voice).toBeEnabled(); +}); + for (const width of [1280, 390]) { for (const variant of ["hero", "thread"]) { test(`composer edge presses send and stop without losing the click (${width}px, ${variant})`, async ({ page }) => { diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 0b0ac2fc5..b52d88739 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -3,7 +3,7 @@ import { createRoot } from "react-dom/client"; import { TooltipProvider } from "@/components/ui/tooltip"; import { initializeI18n, setAppLanguage } from "@/i18n"; -import { normalizeLocale } from "@/i18n/config"; +import { LOCALE_STORAGE_KEY, normalizeLocale } from "@/i18n/config"; import "../src/globals.css"; const parameters = new URLSearchParams(location.search); @@ -27,6 +27,10 @@ async function loadFixture() { installModelOptionsPreviewApi(); return ; } + case "toast": { + const { ToastFixture } = await import("./toast-fixture"); + return ; + } case "session-transition": { const { installSessionTransitionPreviewApi, SessionTransitionFixture } = await import("./session-transition-fixture"); if (parameters.has("preview")) installSessionTransitionPreviewApi(); @@ -67,7 +71,8 @@ async function loadFixture() { return withClient(); } case "composer-action": { - const { ComposerActionFixture } = await import("./composer-action-fixture"); + const { ComposerActionFixture, installMissingMicrophonePreview } = await import("./composer-action-fixture"); + if (parameters.get("voiceError") === "noDevice") installMissingMicrophonePreview(); return ; } case "workspace-alignment": { @@ -214,6 +219,12 @@ async function loadFixture() { const fixture = await loadFixture(); await initializeI18n(); if (fixtureCase === "activity-wheel") await setAppLanguage("zh-CN"); +if (fixtureCase === "toast" && parameters.has("lang")) { + const previous = localStorage.getItem(LOCALE_STORAGE_KEY); + await setAppLanguage(normalizeLocale(parameters.get("lang"))); + if (previous === null) localStorage.removeItem(LOCALE_STORAGE_KEY); + else localStorage.setItem(LOCALE_STORAGE_KEY, previous); +} if ((["appearance", "session-transition", "tools-catalog"].includes(fixtureCase ?? "") || historyPreview) && parameters.has("lang")) { await setAppLanguage(normalizeLocale(parameters.get("lang"))); } diff --git a/webui/browser/toast-fixture.tsx b/webui/browser/toast-fixture.tsx new file mode 100644 index 000000000..6f3336be2 --- /dev/null +++ b/webui/browser/toast-fixture.tsx @@ -0,0 +1,51 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Button } from "@/components/ui/button"; +import { Sheet, SheetContent, SheetDescription, SheetTitle, SheetTrigger } from "@/components/ui/sheet"; +import { ToastProvider, useToast } from "@/components/ui/toast"; + +function ToastActions({ stack, longTitle, modal }: { stack: boolean; longTitle: boolean; modal: boolean }) { + const { t } = useTranslation(); + const show = useToast(); + const [result, setResult] = useState<"undone" | "committed" | null>(null); + + const play = () => { + setResult(null); + show?.({ + message: t("toast.pendingDeleteSingle"), + detail: longTitle ? "Research notes: cross-platform layout and keyboard accessibility verification" : "Research notes", + tone: "pending", + action: { label: t("toast.undo"), run: () => setResult("undone") }, + onExpire: () => setResult("committed"), + }); + if (stack) show?.({ message: t("fileActions.copied"), tone: "success" }); + }; + + return
+

Toast fixtures

+
+ + {modal && <> + {/* The app also has a live region outside the modal; Radix then hides the toast viewport itself. */} + + + + + Navigation sheet + Toast actions are not reachable while this sheet is open. + + + } +
+ {result === "undone" &&

Undo applied

} + {result === "committed" &&

Simulated delete committed

} +
; +} + +export function ToastFixture({ parameters }: { parameters: URLSearchParams }) { + document.documentElement.classList.toggle("dark", parameters.has("dark")); + return + + ; +} diff --git a/webui/browser/toast.spec.ts b/webui/browser/toast.spec.ts new file mode 100644 index 000000000..af3fcda1f --- /dev/null +++ b/webui/browser/toast.spec.ts @@ -0,0 +1,104 @@ +import { expect, test, type Locator } from "@playwright/test"; + +const fixture = "/browser/fixture.html?case=toast&lang=en&scene="; +const shadowStyle = (card: Locator, property: string) => card.evaluate( + (element, key) => getComputedStyle(element, "::before").getPropertyValue(key), + property, +); + +test("plain feedback expires in the short tier while the pending delete stays available", async ({ page }) => { + await page.clock.install(); + await page.goto(`${fixture}stack`); + await page.getByRole("button", { name: "Play timing" }).click(); + + const copied = page.locator('[data-toast-tone="success"]'); + const deletion = page.locator('[data-toast-tone="pending"]'); + await expect(copied.getByRole("status")).toHaveText("Copied"); + await expect(deletion.getByText("Research notes")).toBeVisible(); + expect(await shadowStyle(copied, "animation-duration")).toBe("3s"); + expect(await shadowStyle(deletion, "animation-duration")).toBe("8s"); + await page.clock.runFor(2_000); + await expect(copied).toBeVisible(); + await page.clock.runFor(1_001); + await expect(copied).toHaveCount(0); + await deletion.getByRole("button", { name: "Undo" }).click(); + await expect(page.getByText("Undo applied")).toBeVisible(); + await page.clock.runFor(8_001); + await expect(page.getByText("Simulated delete committed")).toHaveCount(0); +}); + +test("a long title is clipped on one line without crowding keyboard undo on a narrow screen", async ({ page }) => { + await page.setViewportSize({ width: 320, height: 650 }); + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.clock.install(); + await page.goto(`${fixture}delete&dark&long-title`); + await page.getByRole("button", { name: "Play timing" }).click(); + + const card = page.locator('[data-toast-tone="pending"]'); + const status = card.getByRole("status"); + const undo = card.getByRole("button", { name: "Undo" }); + await expect(status).toContainText("Research notes: cross-platform layout and keyboard accessibility verification"); + await expect(undo).toBeInViewport(); + const bounds = (await card.boundingBox())!; + const content = (await status.boundingBox())!; + const button = (await undo.boundingBox())!; + expect(bounds.x).toBeGreaterThanOrEqual(12); + expect(bounds.x + bounds.width).toBeLessThanOrEqual(308); + expect(bounds.height).toBeLessThanOrEqual(44); + expect(button.x).toBeGreaterThan(content.x + content.width); + expect(content.y + content.height / 2).toBeCloseTo(button.y + button.height / 2); + expect(await status.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(true); + + await undo.focus(); + await expect(undo).toBeFocused(); + await page.clock.runFor(8_001); + await undo.press("Enter"); + await expect(page.getByText("Undo applied")).toBeVisible(); +}); + +test("a pending delete waits while hovered and commits after leaving the card", async ({ page }) => { + await page.clock.install(); + await page.goto(`${fixture}delete`); + await page.getByRole("button", { name: "Play timing" }).click(); + + const undo = page.getByRole("button", { name: "Undo" }); + const committed = page.getByText("Simulated delete committed"); + const card = page.locator('[data-toast-tone="pending"]'); + await undo.hover(); + await expect.poll(() => shadowStyle(card, "animation-play-state")).toBe("paused"); + await page.clock.runFor(8_001); + await expect(undo).toBeVisible(); + await expect(committed).toHaveCount(0); + + await page.getByRole("heading", { name: "Toast fixtures" }).hover(); + await expect.poll(() => shadowStyle(card, "animation-play-state")).toBe("running"); + await page.clock.runFor(8_001); + await expect(committed).toBeVisible(); + await expect(undo).toHaveCount(0); +}); + +test("a modal sheet pauses an unreachable Undo and preserves the remaining time", async ({ page }) => { + await page.clock.install(); + await page.goto(`${fixture}delete&modal`); + await page.getByRole("button", { name: "Play timing" }).click(); + const undo = page.getByRole("button", { name: "Undo" }); + const card = page.locator('[data-toast-tone="pending"]'); + const committed = page.getByText("Simulated delete committed"); + await expect(undo).toBeVisible(); + await page.clock.runFor(3_000); + await page.getByRole("button", { name: "Open sheet" }).click(); + await expect(page.getByRole("dialog", { name: "Navigation sheet" })).toBeVisible(); + await expect(undo).toHaveCount(0); + await expect.poll(() => shadowStyle(card, "animation-play-state")).toBe("paused"); + await page.clock.runFor(8_001); + await expect(card).toBeAttached(); + await expect(committed).toHaveCount(0); + + await page.keyboard.press("Escape"); + await expect(undo).toBeVisible(); + await page.clock.runFor(4_000); + await expect(undo).toBeVisible(); + await page.clock.runFor(1_100); + await expect(committed).toBeVisible(); + await expect(undo).toHaveCount(0); +}); diff --git a/webui/src/App.tsx b/webui/src/App.tsx index caef70008..37890f687 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -9,7 +9,7 @@ import { type CSSProperties, type ReactNode, } from "react"; -import { ArrowRight, ChevronDown, Eye, EyeOff } from "lucide-react"; +import { ArrowRight, CircleHelp, Eye, EyeOff, Loader2 } from "lucide-react"; import { ThemeToggleIcon } from "@/components/icons/ThemeToggleIcon"; import { Trans, useTranslation } from "react-i18next"; import { ChannelPairing } from "@/components/pairing/ChannelPairing"; @@ -49,7 +49,7 @@ import { workbenchTabForPane, type WorkbenchState, } from "@/components/workbench/workbench-model"; -import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; +import { ToastProvider, useToast } from "@/components/ui/toast"; import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"; import { useSessions } from "@/hooks/useSessions"; @@ -88,12 +88,14 @@ import type { RuntimeSurface, SessionAutomationJob, SettingsPayload, + SidebarStatePayload, WorkspaceScopePayload, WorkspacesPayload, } from "@/lib/types"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { Disclosure } from "@/components/ui/disclosure"; +import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; +import { HoverHint } from "@/components/ui/hover-hint"; import { fetchSettings, fetchWorkspaces } from "@/lib/api"; import { createRuntimeHost, @@ -109,7 +111,7 @@ import { type BootState = | { status: "loading" } | { status: "error"; message: string } - | { status: "auth"; failed?: boolean } + | { status: "auth" } | { status: "ready"; client: NanobotClient; @@ -372,31 +374,25 @@ function tokenRefreshDelayMs(expiresAt: number): number { return Math.max(TOKEN_REFRESH_MIN_DELAY_MS, remaining - margin); } -function AuthForm({ - failed, - onSecret, -}: { - failed: boolean; - onSecret: (secret: string) => void; +function AuthForm({ onSecret }: { + onSecret: (secret: string, onAuthRejected: () => void) => void; }) { const { t } = useTranslation(); const inputRef = useRef(null); const [value, setValue] = useState(""); const [passwordVisible, setPasswordVisible] = useState(false); const [submitting, setSubmitting] = useState(false); - const [validationError, setValidationError] = useState<"required" | "invalid" | null>( - failed ? "invalid" : null, - ); - const errorMessage = validationError ? t(`app.auth.${validationError}`) : null; - - useEffect(() => { - if (!validationError) return; - const timeout = window.setTimeout(() => setValidationError(null), 3_000); - return () => window.clearTimeout(timeout); - }, [validationError]); + const [validationError, setValidationError] = useState<"required" | "invalid" | null>(null); + const helpTitle = t("app.auth.helpTitle"); + const passwordLabel = t("app.auth.label"); + const requiredMessage = t("app.auth.required"); + const invalidMessage = t("app.auth.invalid"); + const errorMessage = validationError === "required" ? requiredMessage + : validationError === "invalid" ? invalidMessage : null; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); + if (submitting) return; const secret = value.trim(); if (!secret) { setValue(""); @@ -405,54 +401,91 @@ function AuthForm({ return; } setSubmitting(true); - onSecret(secret); + onSecret(secret, () => { + setValue(""); + setPasswordVisible(false); + setSubmitting(false); + setValidationError("invalid"); + inputRef.current?.focus(); + }); }; return (
-
+
+ + + + + + + + {helpTitle} +
+
+ {t("app.auth.helpConfig")} + + ~/.nanobot/config.json + +
+
+

{t("app.auth.helpSecret")}

+ + channels.websocket.tokenIssueSecret + +
+

+ }} + /> +

+
+
+
-
+
- -

+
+ +
+

{t("app.auth.title")}

+
{ setValue(e.target.value); setValidationError(null); }} - disabled={submitting} + readOnly={submitting} aria-invalid={validationError ? true : undefined} aria-describedby={validationError ? "webui-auth-error" : undefined} - placeholder={errorMessage ?? undefined} - className={cn( - "h-12 rounded-full border-foreground/15 bg-muted/30 px-4 pr-24 text-base", - validationError && "placeholder:text-[13px] placeholder:text-red-600 dark:placeholder:text-red-400", - )} + className="h-12 rounded-full border-border bg-background/85 ps-4 pe-14 text-base" autoFocus /> -
- {errorMessage ? ( - - ) : null} +
+ + + {errorMessage ? ( + + ) : null} +
+
- - {t("app.auth.helpTitle")} - - - )} - > -

{t("app.auth.helpConfig")}

- - ~/.nanobot/config.json - -

{t("app.auth.helpSecret")}

- - channels.websocket.tokenIssueSecret - -

- }} - /> -

-
@@ -652,11 +659,11 @@ export default function App() { ); const bootstrapWithSecret = useCallback( - (secret: string) => { + (secret: string, onAuthRejected?: () => void) => { let cancelled = false; if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {}); (async () => { - setState({ status: "loading" }); + if (!onAuthRejected) setState({ status: "loading" }); try { const boot = await fetchBootstrap("", secret); if (cancelled) return; @@ -698,7 +705,8 @@ export default function App() { clearReloadCache(); clearStoredComposerDrafts(); webuiThreadCache.clear(); - setState({ status: "auth", failed: !!secret }); + if (onAuthRejected) onAuthRejected(); + else setState({ status: "auth" }); } else { setState({ status: "error", @@ -725,7 +733,7 @@ export default function App() { clearReloadCache(); clearStoredComposerDrafts(); webuiThreadCache.clear(); - setState({ status: "auth", failed: !!bootstrapSecretRef.current }); + setState({ status: "auth" }); } } }, tokenRefreshDelayMs(state.tokenExpiresAt)); @@ -741,12 +749,7 @@ export default function App() { return ; } if (state.status === "auth") { - return ( - bootstrapWithSecret(s)} - /> - ); + return ; } if (state.status === "error") { return ( @@ -814,16 +817,37 @@ export default function App() { allowUpdateFlow={state.runtimeSurface !== "native"} > - + /> ); } +type PendingDelete = { + id: number; + items: SidebarDeleteItem[]; + automations: SessionAutomationJob[]; + automationKeys: Set; + onDecision?: SidebarDeleteDecision; +}; + +function restorePinOrder(pins: readonly string[], previous: readonly string[], restoring: ReadonlySet) { + const next = [...pins]; + previous.forEach((key, index) => { + if (!restoring.has(key) || next.includes(key)) return; + const successor = previous.slice(index + 1).find((candidate) => next.includes(candidate)); + const predecessor = previous.slice(0, index).reverse().find((candidate) => next.includes(candidate)); + const offset = successor !== undefined ? next.indexOf(successor) + : predecessor !== undefined ? next.indexOf(predecessor) + 1 : next.length; + next.splice(offset, 0, key); + }); + return next; +} + function Shell({ runtimeSurface, onModelNameChange, @@ -836,6 +860,7 @@ function Shell({ onNativeEngineRestart: () => Promise; }) { const { t, i18n } = useTranslation(); + const showToast = useToast()!; // App always renders Shell inside ToastProvider. const remoteConnections = useRemoteConnections(); const versionCheck = useVersionCheck(); const updateFlow = useUpdateFlow(); @@ -878,6 +903,7 @@ function Shell({ state: sidebarState, loading: sidebarStateLoading, update: updateSidebarState, + save: saveSidebarState, rename: onRequestRename, } = useSidebarState(sessions, sessionsLoaded); @@ -924,12 +950,18 @@ function Shell({ }, [updateSidebarState]); const lastActivePaneByTabRef = useRef(new Map()); const [creatingPane, setCreatingPane] = useState(false); - const topicSessions = sessions; - const [pendingDelete, setPendingDelete] = useState<{ - items: SidebarDeleteItem[]; - automations?: SessionAutomationJob[]; - onDecision?: SidebarDeleteDecision; - } | null>(null); + 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(() => { + canNavigateArchiveRef.current = localActive && !managingConnections; + return () => { canNavigateArchiveRef.current = false; }; + }, [localActive, managingConnections]); const [pendingTabRename, setPendingTabRename] = useState<{ key: string; label: string; @@ -940,7 +972,6 @@ function Shell({ } | null>(null); const restartSawDisconnectRef = useRef(false); const restartStartedAtRef = useRef(0); - const [restartToast, setRestartToast] = useState(null); const [isRestarting, setIsRestarting] = useState(false); const [runningChatIds, setRunningChatIds] = useState>(() => new Set()); const [updatedChatIds, setUpdatedChatIds] = useState>(readSessionUpdateChatIds); @@ -1161,8 +1192,8 @@ function Shell({ const activeSession = useMemo(() => { if (!activeKey) return null; if (temporarySessions[activeKey]) return temporarySessions[activeKey]; - return sessions.find((s) => s.key === activeKey) ?? null; - }, [sessions, activeKey, temporarySessions]); + return topicSessions.find((s) => s.key === activeKey) ?? null; + }, [topicSessions, activeKey, temporarySessions]); const activeTabMatch = useMemo(() => ( activeKey && !temporarySessions[activeKey] ? workbenchTabForPane(workbenchState, activeKey) @@ -1276,7 +1307,7 @@ function Shell({ }, { replace: true }); return; } - if (sessions.some((session) => session.key === activeKey)) return; + if (topicSessions.some((session) => session.key === activeKey)) return; // WebKit can commit the route before useSessions' optimistic insert. // Keep that just-created destination valid until the session list catches up. if (pendingCreatedKey === activeKey) return; @@ -1289,7 +1320,7 @@ function Shell({ }, { replace: true }, ); - }, [activeKey, loading, navigate, sessions, temporarySessions]); + }, [activeKey, loading, navigate, sessions, temporarySessions, topicSessions]); useEffect(() => { return client.onSessionUpdate((chatId, scope, workspaceScope) => { @@ -1547,6 +1578,7 @@ function Shell({ const onSelectChat = useCallback( (key: string) => { + if (deletingKeys.has(key)) return; const selectedTemporary = temporarySessionsRef.current[key]; const selected = selectedTemporary ?? sessions.find((session) => session.key === key); @@ -1573,7 +1605,7 @@ function Shell({ }); setMobileSidebarOpen(false); }, - [navigate, sessions], + [deletingKeys, navigate, sessions], ); const onCloseTemporaryChat = useCallback((key: string) => { @@ -1685,36 +1717,89 @@ function Shell({ [pendingProjectRename, updateSidebarState], ); + const titleForSession = useCallback((session: ChatSummary) => ( + sidebarState.title_overrides[session.key] + || session.title + || deriveTitle(session.preview, t("chat.newChat")) + ), [sidebarState.title_overrides, t]); + const onArchiveMany = useCallback( (keys: string[], archive: boolean) => { - const persistedKeys = new Set(sessions + if (sidebarStateLoading) return; + const persistedSessions = new Map(topicSessions .filter((session) => session.projectLocked !== false) - .map((session) => session.key)); - const selected = new Set(keys.filter((key) => persistedKeys.has(key))); - if (selected.size === 0) return; - void updateSidebarState((current) => { - const archived = new Set(current.archived_keys); - for (const key of selected) { - if (archive) archived.add(key); - else archived.delete(key); - } - return { - ...current, - pinned_keys: current.pinned_keys.filter((key) => !selected.has(key)), - archived_keys: Array.from(archived), - }; + .map((session) => [session.key, session])); + const operation = Symbol(); + const selected = new Set(); + let pinOrder: string[] = []; + let removedPins = new Set(); + let archivedAfterSave: string[] = []; + const reportFailure = () => showToast({ + message: t("toast.archiveFailed"), tone: "error", dedupeKey: "archive-failed", }); - if (archive && activeKey && selected.has(activeKey)) { - const archived = new Set([...sidebarState.archived_keys, ...selected]); - const next = topicSessions.find((session) => !archived.has(session.key)); - navigate({ - view: "chat", - activeKey: next?.key ?? null, - settingsSection: "overview", + const owned = (key: string) => archiveUndoOwners.current.get(key)?.operation === operation; + const release = () => { + for (const key of selected) if (owned(key)) archiveUndoOwners.current.delete(key); + }; + const changeArchive = (current: SidebarStatePayload, affected: ReadonlySet, archived: boolean) => ({ + ...current, + archived_keys: archived + ? [...new Set([...current.archived_keys, ...affected])] + : current.archived_keys.filter((key) => !affected.has(key)), + }); + setMobileSidebarOpen(false); + void saveSidebarState((current) => { + for (const key of keys) { + if (persistedSessions.has(key) && current.archived_keys.includes(key) !== archive) selected.add(key); + } + if (!selected.size) return null; + // Include pins removed by earlier, still-undoable operations so either undo order works. + removedPins = new Set(current.pinned_keys.filter((key) => selected.has(key))); + pinOrder = current.pinned_keys; + for (const [key, previous] of archiveUndoOwners.current) { + if (previous.pinOrder) pinOrder = restorePinOrder(pinOrder, previous.pinOrder, new Set([key])); + } + const apply = (state: SidebarStatePayload) => ({ + ...changeArchive(state, selected, archive), + pinned_keys: state.pinned_keys.filter((key) => !selected.has(key)), }); - } + archivedAfterSave = apply(current).archived_keys; + return apply; + }).then(() => { + if (!selected.size) return; + for (const key of selected) { + archiveUndoOwners.current.set(key, { operation, pinOrder: removedPins.has(key) ? pinOrder : undefined }); + } + const singleTopic = selected.size === 1 ? persistedSessions.get([...selected][0]) : undefined; + showToast({ + tone: "success", + detail: singleTopic ? titleForSession(singleTopic) : undefined, + message: archive + ? t(selected.size === 1 ? "toast.archivedSingle" : "toast.archived", { count: selected.size }) + : t(selected.size === 1 ? "toast.unarchivedSingle" : "toast.unarchived", { count: selected.size }), + onExpire: release, + action: { label: t("toast.undo"), run: () => { + void saveSidebarState((current) => { + const restoring = new Set([...selected].filter((key) => ( + owned(key) && current.archived_keys.includes(key) === archive + ))); + if (!restoring.size) return null; + const restoringPins = new Set([...restoring].filter((key) => removedPins.has(key))); + return (state) => ({ + ...changeArchive(state, restoring, !archive), + pinned_keys: restorePinOrder(state.pinned_keys, pinOrder, restoringPins), + }); + }).then(release, () => { release(); reportFailure(); }); + } }, + }); + const route = currentShellRouteRef.current; + if (archive && canNavigateArchiveRef.current && route.view === "chat" && route.activeKey && selected.has(route.activeKey)) { + const next = topicSessions.find((session) => !archivedAfterSave.includes(session.key)); + navigate({ view: "chat", activeKey: next?.key ?? null, settingsSection: "overview" }); + } + }, reportFailure); }, - [activeKey, navigate, sessions, sidebarState.archived_keys, topicSessions, updateSidebarState], + [navigate, saveSidebarState, showToast, sidebarStateLoading, t, titleForSession, topicSessions], ); const onToggleArchive = useCallback((key: string) => { @@ -1985,8 +2070,7 @@ function Shell({ const refreshGeneration = ++settingsRefreshGenerationRef.current; restartStartedAtRef.current = 0; setIsRestarting(false); - setRestartToast(t("app.restart.completed", { seconds: (elapsedMs / 1000).toFixed(1) })); - window.setTimeout(() => setRestartToast(null), 3_500); + showToast({ message: t("app.restart.completed", { seconds: (elapsedMs / 1000).toFixed(1) }), tone: "success", dedupeKey: "restart-completed" }); refreshSettings(refreshGeneration); }); return () => { @@ -1994,111 +2078,129 @@ function Shell({ unsubscribe(); if (retryTimer !== undefined) window.clearTimeout(retryTimer); }; - }, [client, getToken, t]); + }, [client, getToken, showToast, t]); const onTurnEnd = useDeferredTitleRefresh( temporaryChatActive ? null : activePaneSession, refresh, ); - const onConfirmDelete = useCallback(async () => { + const finishDeleteConfirmation = useCallback((request: PendingDelete, confirmed: boolean) => { + request.onDecision?.(confirmed); + setDeleteQueue((queue) => queue.filter((entry) => entry.id !== request.id)); + }, []); + + const onConfirmDelete = useCallback(() => { if (!pendingDelete) return; - pendingDelete.onDecision?.(true); - const items = pendingDelete.items; - const deletingKeys = new Set(items.map((item) => item.key)); - const hasAutomations = (pendingDelete.automations?.length ?? 0) > 0; - const deletingActive = activeKey !== null && deletingKeys.has(activeKey); - const currentIndex = topicSessions.findIndex((s) => s.key === activeKey); - const availableKeys = new Set(topicSessions.map((session) => session.key)); - const siblingFallbackKey = deletingActive - ? activeTabState?.paneKeys.find((key) => ( - !deletingKeys.has(key) && availableKeys.has(key) - )) ?? null - : null; - const fallbackKey = deletingActive - ? ( - siblingFallbackKey - ?? topicSessions.slice(currentIndex + 1).find((session) => ( - !deletingKeys.has(session.key) - ))?.key - ?? topicSessions.slice(0, Math.max(0, currentIndex)).reverse().find((session) => ( - !deletingKeys.has(session.key) - ))?.key - ?? null - ) - : activeKey; - try { - for (let index = 0; index < items.length; index += 1) { - const item = items[index]; - const result = await deleteChat( - item.key, - hasAutomations ? { deleteAutomations: true } : undefined, - ); - if (result.blocked_by_automations) { - setPendingDelete({ - items: items.slice(index), - automations: result.automations ?? [], - }); - return; - } - filePreviewStore.delete(item.key); - draftStore.delete(item.key); - } - setPendingDelete(null); - if (deletingActive) { - navigate({ - view: "chat", - activeKey: fallbackKey, - settingsSection: "overview", - }, { replace: true }); - } - } catch (e) { - console.error("Failed to delete session", e); + const { automationKeys } = pendingDelete; + const items = pendingDelete.items.filter((item) => topicSessions.some((session) => session.key === item.key)); + finishDeleteConfirmation(pendingDelete, items.length > 0); + if (!items.length) return; + const batchKeys = new Set(items.map((item) => item.key)); + setDeletingKeys((current) => new Set([...current, ...batchKeys])); + + if (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 + ?? null; + navigate({ view: "chat", activeKey: fallbackKey, settingsSection: "overview" }, { replace: true }); } - }, [pendingDelete, deleteChat, activeKey, activeTabState, navigate, topicSessions, filePreviewStore, draftStore]); + + const reveal = () => setDeletingKeys((current) => new Set([...current].filter((key) => !batchKeys.has(key)))); + const commit = async () => { + let failed = 0; + const blockedItems: SidebarDeleteItem[] = []; + const blockedJobs: SessionAutomationJob[] = []; + try { + for (const item of items) { + try { + 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); + } else { + failed++; + } + } catch (error) { + console.error("Failed to delete session", error); + failed++; + } + } + } finally { + reveal(); + } + if (blockedItems.length) { + const confirmation: PendingDelete = { + id: ++nextDeleteId.current, + items: blockedItems, + automations: blockedJobs, + automationKeys: new Set(blockedItems.map((item) => item.key)), + }; + setDeleteQueue((queue) => [...queue, confirmation]); + } + if (failed) showToast({ + message: t(failed === 1 ? "toast.deleteFailedSingle" : "toast.deleteFailed", { count: failed }), + tone: "error", + }); + }; + showToast({ + 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(); }, + }); + }, [activeKey, activeTabState, deleteChat, draftStore, filePreviewStore, finishDeleteConfirmation, navigate, pendingDelete, showToast, t, topicSessions]); const onRequestDeleteMany = useCallback(async (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => { - const uniqueItems = Array.from(new Map(items.map((item) => [item.key, item])).values()); - if (uniqueItems.length === 0) return; - const automationResults = await Promise.allSettled( - uniqueItems.map((item) => getSessionAutomations(item.key)), - ); - const automations = automationResults.flatMap((result) => ( - result.status === "fulfilled" ? result.value : [] - )); + const uniqueItems = Array.from(new Map(items.filter((item) => !deletingKeys.has(item.key)).map((item) => [item.key, item])).values()); + if (uniqueItems.length === 0) { + onDecision?.(false); + return; + } + const automationResults = await Promise.allSettled(uniqueItems.map((item) => getSessionAutomations(item.key))); + const automationKeys = new Set(); + const automations = automationResults.flatMap((result, index) => { + if (result.status !== "fulfilled" || !result.value.length) return []; + automationKeys.add(uniqueItems[index].key); + return result.value; + }); let decision = onDecision; - setPendingDelete({ + const confirmation: PendingDelete = { + id: ++nextDeleteId.current, items: uniqueItems, automations, + automationKeys, onDecision: (confirmed) => { const notify = decision; decision = undefined; notify?.(confirmed); }, - }); - }, [getSessionAutomations]); + }; + setDeleteQueue((queue) => [...queue, confirmation]); + }, [deletingKeys, getSessionAutomations]); const onRequestDelete = useCallback((key: string, label: string, onDecision?: SidebarDeleteDecision) => { void onRequestDeleteMany([{ key, label }], onDecision); }, [onRequestDeleteMany]); - const titleForSession = useCallback((session: ChatSummary) => ( - sidebarState.title_overrides[session.key] - || session.title - || deriveTitle(session.preview, t("chat.newChat")) - ), [sidebarState.title_overrides, t]); - const automaticSidebarSort = sidebarState.view.sort === "manual" ? "updated_desc" : sidebarState.view.sort; const orderedWorkbenchTabs = useMemo(() => { const orderedSessions = sortSessions( - sessions, + topicSessions, automaticSidebarSort, sidebarState.title_overrides, sidebarState.session_order, ); - const updatedAtByKey = new Map(sessions.map((session) => [ + const updatedAtByKey = new Map(topicSessions.map((session) => [ session.key, session.updatedAt ?? session.createdAt, ])); @@ -2109,7 +2211,7 @@ function Shell({ ); }, [ automaticSidebarSort, - sessions, + topicSessions, sidebarState.session_order, sidebarState.title_overrides, workbenchState, @@ -2119,7 +2221,7 @@ function Shell({ [orderedWorkbenchTabs], ); const sidebarTabPresentations = useMemo(() => { - const sessionsByKey = new Map(sessions.map((session) => [session.key, session])); + const sessionsByKey = new Map(topicSessions.map((session) => [session.key, session])); return orderedWorkbenchTabs.flatMap((tab) => { const anchorKey = tab.tab.paneKeys.find((key) => sessionsByKey.has(key)) ?? tab.paneKeys[0]; @@ -2144,7 +2246,7 @@ function Shell({ : anchor, }]; }); - }, [orderedWorkbenchTabs, sessions, titleForSession]); + }, [orderedWorkbenchTabs, topicSessions, titleForSession]); const sidebarTopicSessions = useMemo( () => sidebarTabPresentations.map((presentation) => presentation.session), [sidebarTabPresentations], @@ -2157,7 +2259,7 @@ function Shell({ : t("app.brand"); const workbenchPaneSessions = useMemo(() => { if (!activeTabState) return []; - const byKey = new Map(sessions.map((session) => [session.key, session])); + const byKey = new Map(topicSessions.map((session) => [session.key, session])); const sortedPaneKeys = activeTabKey ? orderedWorkbenchTabsByKey.get(activeTabKey)?.paneKeys ?? activeTabState.paneKeys : activeTabState.paneKeys; @@ -2168,7 +2270,7 @@ function Shell({ return paneKeys .map((key) => byKey.get(key)) .filter((session): session is ChatSummary => session !== undefined); - }, [activeTabKey, activeTabState, orderedWorkbenchTabsByKey, sessions]); + }, [activeTabKey, activeTabState, orderedWorkbenchTabsByKey, topicSessions]); const paneChromeEnabled = Boolean( activeKey && activeSession && !temporaryChatActive && activeTabState, ); @@ -2247,13 +2349,13 @@ function Shell({ const onSelectSidebarTab = useCallback((tabKey: string) => { const tab = workbenchTab(workbenchState, tabKey); if (!tab) return; + const visiblePaneKeys = tab.paneKeys.filter((key) => !deletingKeys.has(key)); const rememberedPaneKey = lastActivePaneByTabRef.current.get(tabKey); - onSelectChat( - rememberedPaneKey && tab.paneKeys.includes(rememberedPaneKey) - ? rememberedPaneKey - : tab.paneKeys[0], - ); - }, [onSelectChat, workbenchState]); + const paneKey = rememberedPaneKey && visiblePaneKeys.includes(rememberedPaneKey) + ? rememberedPaneKey + : visiblePaneKeys[0]; + if (paneKey) onSelectChat(paneKey); + }, [deletingKeys, onSelectChat, workbenchState]); const onSelectSidebarItem = useCallback((key: string) => { if ( @@ -2593,7 +2695,7 @@ function Shell({ return ( - {pendingDelete ? ( + {pendingDelete && localActive && !managingConnections ? ( { - pendingDelete.onDecision?.(false); - setPendingDelete(null); - }} + onCancel={() => finishDeleteConfirmation(pendingDelete, false)} onConfirm={onConfirmDelete} /> @@ -2789,19 +2889,6 @@ function Shell({ /> ) : null} - {restartToast ? ( -
-
- {restartToast} -
-
- ) : null} diff --git a/webui/src/components/CodeBlock.tsx b/webui/src/components/CodeBlock.tsx index fff3bd712..17ea51791 100644 --- a/webui/src/components/CodeBlock.tsx +++ b/webui/src/components/CodeBlock.tsx @@ -2,6 +2,7 @@ import { Component, Suspense, lazy, memo, startTransition, useCallback, useEffec import { Check, Copy } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { useToast } from "@/components/ui/toast"; import { useThemeValue } from "@/hooks/useTheme"; import { hasAnsi, parseAnsiSegments, stripAnsi } from "@/lib/ansi"; import { copyTextToClipboard } from "@/lib/clipboard"; @@ -139,6 +140,7 @@ export const CodeBlock = memo(function CodeBlock({ viewportHighlight = false, }: CodeBlockProps) { const { t } = useTranslation(); + const showToast = useToast(); const rootRef = useRef(null); const [copied, setCopied] = useState(false); const [highlightedSource, setHighlightedSource] = useState(null); @@ -191,11 +193,14 @@ export const CodeBlock = memo(function CodeBlock({ const onCopy = useCallback(() => { void copyTextToClipboard(plainCode).then((ok) => { - if (!ok) return; + if (!ok) { + showToast?.({ message: t("fileActions.failed"), tone: "error", dedupeKey: "copy-failed" }); + return; + } setCopied(true); setTimeout(() => setCopied(false), 1_500); }); - }, [plainCode]); + }, [plainCode, showToast, t]); return (
{hasAutomations ? (
diff --git a/webui/src/components/FileActions.tsx b/webui/src/components/FileActions.tsx index b228fec67..7dea85e91 100644 --- a/webui/src/components/FileActions.tsx +++ b/webui/src/components/FileActions.tsx @@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next"; import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface"; import { useFloatingPortal } from "@/components/ui/floating-portal"; +import { useToast } from "@/components/ui/toast"; import { copyTextToClipboard } from "@/lib/clipboard"; import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -33,6 +34,7 @@ export function FileActions({ }) { const context = useContext(FileActionsContext); const { t } = useTranslation(); + const showToast = useToast(); const [open, setOpen] = useState(false); const [resolved, setResolved] = useState(null); const [loadFailed, setLoadFailed] = useState(false); @@ -71,8 +73,14 @@ export function FileActions({ const success = await copyTextToClipboard(value); // A dismissed/reopened menu or another reference owns its own feedback. if (generation !== copyGeneration.current) return; - setCopyStatus(success ? "copied" : "failed"); - if (success) changeOpen(false); + if (showToast) { + showToast({ message: t(success ? "fileActions.copied" : "fileActions.failed"), tone: success ? "success" : "error", + dedupeKey: success ? "copied" : "copy-failed" }); + } else { + setCopyStatus(success ? "copied" : "failed"); + } + // A modal menu hides the rest of the app, including the toast, from assistive technology. + if (success || showToast) changeOpen(false); }; const openMenu = (target: EventTarget, x: number, y: number) => { point.current = { x, y }; diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index ac8944068..372ffd743 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -25,6 +25,7 @@ import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen"; import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice"; import { UserMessageText } from "@/components/UserMessageText"; import { HoverHint } from "@/components/ui/tooltip"; +import { useToast } from "@/components/ui/toast"; import { cn } from "@/lib/utils"; import { copyTextToClipboard } from "@/lib/clipboard"; import { formatMessageEndTime } from "@/lib/format-time"; @@ -76,6 +77,7 @@ function ForkArrowIcon({ className }: { className?: string }) { function useMessageCopy(content: string) { const { t } = useTranslation(); + const showToast = useToast(); const [copied, setCopied] = useState(false); const copyResetRef = useRef(null); @@ -89,7 +91,10 @@ function useMessageCopy(content: string) { const onCopy = useCallback(() => { void copyTextToClipboard(content).then((ok) => { - if (!ok) return; + if (!ok) { + showToast?.({ message: t("fileActions.failed"), tone: "error", dedupeKey: "copy-failed" }); + return; + } setCopied(true); if (copyResetRef.current !== null) { window.clearTimeout(copyResetRef.current); @@ -99,7 +104,7 @@ function useMessageCopy(content: string) { copyResetRef.current = null; }, 1_500); }); - }, [content]); + }, [content, showToast, t]); const label = copied ? t("message.copiedReply") : t("message.copyReply"); return { copied, label, onCopy }; diff --git a/webui/src/components/markdown-diagrams/MermaidBlock.tsx b/webui/src/components/markdown-diagrams/MermaidBlock.tsx index b79ff922d..069db6f71 100644 --- a/webui/src/components/markdown-diagrams/MermaidBlock.tsx +++ b/webui/src/components/markdown-diagrams/MermaidBlock.tsx @@ -6,6 +6,7 @@ import { CodeBlock } from "@/components/CodeBlock"; import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { HoverHint } from "@/components/ui/hover-hint"; import { ImageViewport } from "@/components/ui/image-viewport"; +import { useToast } from "@/components/ui/toast"; import { copyTextToClipboard } from "@/lib/clipboard"; import { cn } from "@/lib/utils"; import { useDiagramScope } from "./context"; @@ -26,6 +27,7 @@ function readPalette(element: HTMLElement): DiagramPalette { export default function MermaidBlock({ source }: { source: string }) { const { t } = useTranslation(); + const showToast = useToast(); const scope = useDiagramScope(); const container = useRef(null); const mono = useRef(null); @@ -104,7 +106,10 @@ export default function MermaidBlock({ source }: { source: string }) { useEffect(() => () => clearTimeout(copyTimer.current), []); const copy = async () => { - if (!await copyTextToClipboard(source)) return; + if (!await copyTextToClipboard(source)) { + showToast?.({ message: t("fileActions.failed"), tone: "error", dedupeKey: "copy-failed" }); + return; + } setCopied(true); clearTimeout(copyTimer.current); copyTimer.current = setTimeout(() => setCopied(false), 2000); diff --git a/webui/src/components/remote/RemoteConnectionsPage.tsx b/webui/src/components/remote/RemoteConnectionsPage.tsx index a28457b15..b05193421 100644 --- a/webui/src/components/remote/RemoteConnectionsPage.tsx +++ b/webui/src/components/remote/RemoteConnectionsPage.tsx @@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input"; import { DisclosureContent } from "@/components/ui/disclosure"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; +import { useToast } from "@/components/ui/toast"; import { useClient } from "@/providers/ClientProvider"; import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances"; import { cn } from "@/lib/utils"; @@ -34,6 +35,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro const { t } = useTranslation(); const { client } = useClient(); const connections = useRemoteConnections(); + const showToast = useToast(); const [form, setForm] = useState(emptyProfile); const [editorOpen, setEditorOpen] = useState(false); const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn); @@ -190,6 +192,15 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro if (wanted(attempt)) setFingerprint({ id, ...result, inspect }); } catch (scanError) { if (wanted(attempt)) showError(scanError); } } else { + // Opening an alias of the local gateway needs no recovery. A dialog + // (including the pairing popup) can hide the shell's toast viewport. + if (reason instanceof Error && reason.message === "same_instance" && showToast + && !editorOpen && !fingerprint && !detailsOpen && page.current + && !page.current.closest("[hidden], [inert], [aria-hidden='true']") + && !document.querySelector(":is([role='dialog'], [role='alertdialog']):not([data-state='closed'])")) { + showToast({ message: t("remote.errors.same_instance"), tone: "error", dedupeKey: "remote-same-instance" }); + return; + } if (!editorOpen) { const profile = directory?.profiles.find((item) => item.id === id); if (profile && !profile.paired) { diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index cde055491..f17ec1049 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -332,6 +332,7 @@ export function SettingsPage({ }} onDeleteConfiguration={(preset, onDeleted) => { presetDeletedCallback.current = onDeleted; + modelState.setModelPresetDeleteError(null); modelState.setModelPresetPendingDelete(preset); }} /> @@ -604,9 +605,13 @@ export function SettingsPage({ onAction={systemActions.handleAutomationAction} onRequestEdit={(job) => { setAutomationDetailReturn(null); + systemState.setAutomationDialogError(null); systemState.setAutomationPendingEdit(job); }} - onRequestDelete={systemState.setAutomationPendingDelete} + onRequestDelete={(job) => { + systemState.setAutomationDialogError(null); + systemState.setAutomationPendingDelete(job); + }} onChangeChat={systemActions.handleAutomationChat} onManageModels={() => selectSection("models")} returnToDetailJob={automationDetailReturn} @@ -669,6 +674,7 @@ export function SettingsPage({ { if (!open) { modelState.setModelPresetPendingDelete(null); @@ -728,6 +734,7 @@ export function SettingsPage({ { if (!open) systemState.setAutomationPendingDelete(null); }} @@ -737,6 +744,7 @@ export function SettingsPage({ { if (!open) systemState.setAutomationPendingEdit(null); }} diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsx index 7ae57ca69..2ebef6d1b 100644 --- a/webui/src/components/settings/models/ModelsSettings.tsx +++ b/webui/src/components/settings/models/ModelsSettings.tsx @@ -149,11 +149,13 @@ export function agentDraftFromPayload( export function ModelPresetDeleteDialog({ preset, deleting, + error, onOpenChange, onConfirm, }: { preset: SettingsPayload["model_presets"][number] | null; deleting: boolean; + error?: string | null; onOpenChange: (open: boolean) => void; onConfirm: () => void; }) { @@ -161,8 +163,8 @@ export function ModelPresetDeleteDialog({ const tx = (key: string, fallback: string, values?: Record) => t(key, { defaultValue: fallback, ...(values ?? {}) }); return ( - - + { if (open || !deleting) onOpenChange(open); }}> + {tx("settings.models.deletePresetTitle", "Delete model preset?")} @@ -175,6 +177,7 @@ export function ModelPresetDeleteDialog({ )} + {error ?

{error}

: null} } +
; +} + +type ToastFinishReason = "action" | "expired"; + +function TimedToast({ entry, finish, unavailable }: { + entry: ToastEntry; + finish: (entry: ToastEntry, reason: ToastFinishReason) => void; + unavailable: boolean; +}) { + const [hovered, setHovered] = useState(false); + const [focused, setFocused] = useState(false); + const paused = unavailable || hovered || focused; + useLayoutEffect(() => { + if (!unavailable) return; + setHovered(false); + setFocused(false); + }, [unavailable]); + const remaining = useRef(toastDurationMs(entry)); + useLayoutEffect(() => { + if (paused) return; + const start = performance.now(); + const timer = window.setTimeout(() => finish(entry, "expired"), remaining.current); + return () => { + window.clearTimeout(timer); + remaining.current = Math.max(0, remaining.current - (performance.now() - start)); + }; + }, [entry, finish, paused]); + + return finish(entry, "action")} + onHoverChange={entry.action ? setHovered : undefined} onFocusChange={entry.action ? setFocused : undefined} />; +} + +export function ToastProvider({ children }: { children: ReactNode }) { + const [entries, setEntries] = useState([]); + const [unavailable, setUnavailable] = useState(false); + const viewportRef = useRef(null); + useLayoutEffect(() => { + const visibilityTree: HTMLElement[] = []; + for (let node: HTMLElement | null = viewportRef.current; node; node = node.parentElement) visibilityTree.push(node); + // Radix dialogs/sheets hide the surrounding tree; inactive remote hosts are inert. + const update = () => setUnavailable(document.visibilityState === "hidden" || visibilityTree.some((node) => ( + node.getAttribute("aria-hidden") === "true" || node.hasAttribute("inert") + ))); + const observer = new MutationObserver(update); + for (const node of visibilityTree) observer.observe(node, { attributeFilter: ["aria-hidden", "inert"] }); + document.addEventListener("visibilitychange", update); + update(); + return () => { + observer.disconnect(); + document.removeEventListener("visibilitychange", update); + }; + }, []); + const nextId = useRef(0); + const live = useRef(new Map()); + const publish = useCallback(() => setEntries([...live.current.values()]), []); + const show = useCallback((notice: ToastNotice) => { + if (notice.dedupeKey && !notice.action && !notice.onExpire) { + for (const [id, entry] of live.current) { + if (entry.dedupeKey === notice.dedupeKey && !entry.action && !entry.onExpire) live.current.delete(id); + } + } + const entry = { ...notice, id: ++nextId.current }; + live.current.set(entry.id, entry); + publish(); + }, [publish]); + const finish = useCallback((entry: ToastEntry, reason: ToastFinishReason) => { + if (!live.current.delete(entry.id)) return; + publish(); + if (reason === "action") entry.action?.run(); + else entry.onExpire?.(); + }, [publish]); + return + {children} + + ; +} diff --git a/webui/src/dev/gallery/foundations.tsx b/webui/src/dev/gallery/foundations.tsx index 176bc3814..aebbfffdf 100644 --- a/webui/src/dev/gallery/foundations.tsx +++ b/webui/src/dev/gallery/foundations.tsx @@ -22,6 +22,7 @@ import { ExpandableText } from "@/components/ui/expandable-text"; import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen"; import { LoadingRing } from "@/components/ui/loading-ring"; import { ImageViewport } from "@/components/ui/image-viewport"; +import { ToastProvider, useToast } from "@/components/ui/toast"; import type { CodexFastMode } from "@/lib/types"; import { Sample, type ComponentExample } from "./example"; import { useGalleryTranslation } from "./i18n"; @@ -168,6 +169,33 @@ function Alerts() {
; } +function ToastActions() { + const { t } = useGalleryTranslation(); + const show = useToast(); + const [removed, setRemoved] = useState(false); + const remove = () => { + setRemoved(true); + show?.({ + tone: "pending", + message: t("controls.toast.pending"), + action: { + label: t("toast.undo", { ns: "common" }), + run: () => { + setRemoved(false); + show?.({ tone: "success", message: t("controls.toast.restored") }); + }, + }, + onExpire: () => setRemoved(false), + }); + }; + return
+ + +
; +} + function Sheets() { const { t } = useGalleryTranslation(); return @@ -306,6 +334,9 @@ export const foundationExamples: ComponentExample[] = [ { title: "controls.alert.title", files: ["alert-dialog"], Preview: Alerts, description: "controls.alert.description", options: "controls.alert.options", code: '\n\n Remove item?This removes the item.CancelRemove\n' }, + { title: "controls.toast.title", files: ["toast"], Preview: () => , + description: "controls.toast.description", options: "controls.toast.options", + code: '\n\n// Inside ExampleActions\nconst show = useToast();\nshow?.({ tone: "pending", message: "Example will be removed.",\n action: { label: "Undo", run: restoreExample }, onExpire: removeExample });' }, { title: "controls.sheet.title", files: ["sheet"], Preview: Sheets, description: "controls.sheet.description", options: "controls.sheet.options", code: 'DetailsAdditional information.{content}' }, diff --git a/webui/src/dev/gallery/locales/controls/en.json b/webui/src/dev/gallery/locales/controls/en.json index e289094bd..913955fd4 100644 --- a/webui/src/dev/gallery/locales/controls/en.json +++ b/webui/src/dev/gallery/locales/controls/en.json @@ -106,6 +106,15 @@ "removed": "Example removed.", "available": "Example available." }, + "toast": { + "title": "Toasts", + "description": "Short notices for errors, success, and actions you can undo.", + "options": "Mount ToastProvider and call useToast to show a notice. An optional action gives the user more time to respond.", + "showError": "Show error", + "error": "Could not save the example.", + "pending": "Example will be removed.", + "restored": "Example restored." + }, "sheet": { "title": "Side panels", "description": "A modal panel attached to an edge of the viewport.", diff --git a/webui/src/dev/gallery/locales/controls/es.json b/webui/src/dev/gallery/locales/controls/es.json index bb36d6cc1..909bb6017 100644 --- a/webui/src/dev/gallery/locales/controls/es.json +++ b/webui/src/dev/gallery/locales/controls/es.json @@ -106,6 +106,15 @@ "removed": "Ejemplo eliminado.", "available": "Ejemplo disponible." }, + "toast": { + "title": "Avisos temporales", + "description": "Avisos breves de errores, acciones completadas y acciones que se pueden deshacer.", + "options": "Monta ToastProvider y usa useToast para mostrar un aviso. Una acción opcional da más tiempo para responder.", + "showError": "Mostrar error", + "error": "No se pudo guardar el ejemplo.", + "pending": "Se eliminará el ejemplo.", + "restored": "Ejemplo restaurado." + }, "sheet": { "title": "Paneles laterales", "description": "Un panel modal unido a un borde del área visible.", diff --git a/webui/src/dev/gallery/locales/controls/fr.json b/webui/src/dev/gallery/locales/controls/fr.json index aa2f8ad4b..f184695df 100644 --- a/webui/src/dev/gallery/locales/controls/fr.json +++ b/webui/src/dev/gallery/locales/controls/fr.json @@ -106,6 +106,15 @@ "removed": "Exemple retiré.", "available": "Exemple disponible." }, + "toast": { + "title": "Notifications temporaires", + "description": "De courtes notifications pour les erreurs, les réussites et les actions réversibles.", + "options": "Montez ToastProvider et utilisez useToast pour afficher une notification. Une action facultative laisse plus de temps pour réagir.", + "showError": "Afficher une erreur", + "error": "Impossible d’enregistrer l’exemple.", + "pending": "L’exemple va être supprimé.", + "restored": "L’exemple a été rétabli." + }, "sheet": { "title": "Panneaux latéraux", "description": "Un panneau modal attaché à un bord de la zone d’affichage.", diff --git a/webui/src/dev/gallery/locales/controls/id.json b/webui/src/dev/gallery/locales/controls/id.json index 663f0ddca..e62f98b58 100644 --- a/webui/src/dev/gallery/locales/controls/id.json +++ b/webui/src/dev/gallery/locales/controls/id.json @@ -106,6 +106,15 @@ "removed": "Contoh dihapus.", "available": "Contoh tersedia." }, + "toast": { + "title": "Notifikasi singkat", + "description": "Notifikasi singkat untuk kesalahan, keberhasilan, dan tindakan yang dapat dibatalkan.", + "options": "Pasang ToastProvider dan gunakan useToast untuk menampilkan notifikasi. Tindakan opsional memberi waktu lebih lama untuk merespons.", + "showError": "Tampilkan kesalahan", + "error": "Contoh tidak dapat disimpan.", + "pending": "Contoh akan dihapus.", + "restored": "Contoh dipulihkan." + }, "sheet": { "title": "Panel samping", "description": "Panel modal yang menempel pada tepi area tampilan.", diff --git a/webui/src/dev/gallery/locales/controls/ja.json b/webui/src/dev/gallery/locales/controls/ja.json index 682365226..0abdb523c 100644 --- a/webui/src/dev/gallery/locales/controls/ja.json +++ b/webui/src/dev/gallery/locales/controls/ja.json @@ -106,6 +106,15 @@ "removed": "サンプルを削除しました。", "available": "サンプルは利用可能です。" }, + "toast": { + "title": "トースト通知", + "description": "エラー、成功、取り消せる操作を短く知らせます。", + "options": "ToastProvider を配置し、useToast を使って通知を表示します。操作ボタン付きの通知は長めに表示されます。", + "showError": "エラーを表示", + "error": "サンプルを保存できませんでした。", + "pending": "サンプルを削除します。", + "restored": "サンプルを復元しました。" + }, "sheet": { "title": "サイドパネル", "description": "表示領域の端に配置するモーダルパネル。", diff --git a/webui/src/dev/gallery/locales/controls/ko.json b/webui/src/dev/gallery/locales/controls/ko.json index 66de7d765..c64269aa2 100644 --- a/webui/src/dev/gallery/locales/controls/ko.json +++ b/webui/src/dev/gallery/locales/controls/ko.json @@ -106,6 +106,15 @@ "removed": "예제를 제거했습니다.", "available": "예제를 사용할 수 있습니다." }, + "toast": { + "title": "토스트 알림", + "description": "오류, 성공, 실행 취소가 가능한 작업을 짧게 알립니다.", + "options": "ToastProvider를 마운트한 뒤 useToast를 사용해 알림을 표시합니다. 작업 버튼이 있는 알림은 더 오래 표시됩니다.", + "showError": "오류 표시", + "error": "예제를 저장하지 못했습니다.", + "pending": "예제가 삭제될 예정입니다.", + "restored": "예제를 복원했습니다." + }, "sheet": { "title": "측면 패널", "description": "표시 영역의 가장자리에 붙는 모달 패널입니다.", diff --git a/webui/src/dev/gallery/locales/controls/pt-BR.json b/webui/src/dev/gallery/locales/controls/pt-BR.json index 175ba8346..63f41161e 100644 --- a/webui/src/dev/gallery/locales/controls/pt-BR.json +++ b/webui/src/dev/gallery/locales/controls/pt-BR.json @@ -106,6 +106,15 @@ "removed": "Exemplo removido.", "available": "Exemplo disponível." }, + "toast": { + "title": "Avisos temporários", + "description": "Avisos breves de erros, sucessos e ações que podem ser desfeitas.", + "options": "Monte ToastProvider e use useToast para exibir um aviso. Uma ação opcional dá mais tempo para responder.", + "showError": "Mostrar erro", + "error": "Não foi possível salvar o exemplo.", + "pending": "O exemplo será removido.", + "restored": "Exemplo restaurado." + }, "sheet": { "title": "Painéis laterais", "description": "Um painel modal ligado a uma borda da área visível.", diff --git a/webui/src/dev/gallery/locales/controls/vi.json b/webui/src/dev/gallery/locales/controls/vi.json index 335748e52..42f71c898 100644 --- a/webui/src/dev/gallery/locales/controls/vi.json +++ b/webui/src/dev/gallery/locales/controls/vi.json @@ -106,6 +106,15 @@ "removed": "Đã xóa ví dụ.", "available": "Ví dụ khả dụng." }, + "toast": { + "title": "Thông báo tạm thời", + "description": "Thông báo ngắn về lỗi, thành công và thao tác có thể hoàn tác.", + "options": "Gắn ToastProvider và dùng useToast để hiện thông báo. Nếu có nút thao tác, thông báo sẽ hiện lâu hơn.", + "showError": "Hiện lỗi", + "error": "Không thể lưu ví dụ.", + "pending": "Ví dụ sẽ bị xóa.", + "restored": "Đã khôi phục ví dụ." + }, "sheet": { "title": "Bảng bên", "description": "Bảng dạng hộp thoại gắn vào một cạnh vùng hiển thị.", diff --git a/webui/src/dev/gallery/locales/controls/zh-CN.json b/webui/src/dev/gallery/locales/controls/zh-CN.json index bfeeea72e..2ec434f5f 100644 --- a/webui/src/dev/gallery/locales/controls/zh-CN.json +++ b/webui/src/dev/gallery/locales/controls/zh-CN.json @@ -106,6 +106,15 @@ "removed": "示例已移除。", "available": "示例可用。" }, + "toast": { + "title": "轻提示", + "description": "简短提示错误、成功或可撤销操作。", + "options": "挂载 ToastProvider,然后调用 useToast 显示提示。带操作的提示会停留更久,方便用户响应。", + "showError": "显示错误", + "error": "无法保存示例。", + "pending": "即将移除示例。", + "restored": "已恢复示例。" + }, "sheet": { "title": "侧边面板", "description": "贴靠视口边缘的模态面板。", diff --git a/webui/src/dev/gallery/locales/controls/zh-TW.json b/webui/src/dev/gallery/locales/controls/zh-TW.json index 2e06470cd..685f5fd26 100644 --- a/webui/src/dev/gallery/locales/controls/zh-TW.json +++ b/webui/src/dev/gallery/locales/controls/zh-TW.json @@ -106,6 +106,15 @@ "removed": "已移除範例。", "available": "範例可供使用。" }, + "toast": { + "title": "浮動提示", + "description": "簡短提示錯誤、成功或可復原的操作。", + "options": "掛載 ToastProvider,再呼叫 useToast 顯示提示。附帶操作的提示會停留較久,方便使用者回應。", + "showError": "顯示錯誤", + "error": "無法儲存範例。", + "pending": "即將移除範例。", + "restored": "已還原範例。" + }, "sheet": { "title": "側邊面板", "description": "貼靠檢視區邊緣的模態面板。", diff --git a/webui/src/hooks/useSidebarState.ts b/webui/src/hooks/useSidebarState.ts index 2141c5f0d..04b8257fd 100644 --- a/webui/src/hooks/useSidebarState.ts +++ b/webui/src/hooks/useSidebarState.ts @@ -141,9 +141,14 @@ function withTitleOverride( return { ...state, title_overrides: titles }; } -type PendingRename = { - key: string; - title: string; +// Prepare once against the state being saved. Reconcile with any optimistic +// edits that arrived while this confirmed write was in flight. +type PrepareSidebarSave = (state: SidebarStatePayload) => ( + (state: SidebarStatePayload, saved?: SidebarStatePayload) => SidebarStatePayload +) | null; + +type PendingSidebarSave = { + prepare: PrepareSidebarSave; resolve: () => void; reject: (error: unknown) => void; }; @@ -157,6 +162,7 @@ export function useSidebarState( update: ( updater: (state: SidebarStatePayload) => SidebarStatePayload, ) => Promise; + save: (prepare: PrepareSidebarSave) => Promise; rename: (key: string, title: string) => Promise; } { const { client, token } = useClient(); @@ -165,7 +171,7 @@ export function useSidebarState( const loadedRef = useRef(false); const connectionOpenRef = useRef(client.status === "open"); const pendingPersistenceRef = useRef(null); - const pendingRenamesRef = useRef([]); + const pendingSavesRef = useRef([]); const persistenceInFlightRef = useRef(false); const flushPersistenceRef = useRef<() => void>(() => {}); const [state, setState] = useState(DEFAULT_SIDEBAR_STATE); @@ -200,8 +206,8 @@ export function useSidebarState( }; }, []); - const rejectPendingRenames = useCallback((error: unknown) => { - for (const request of pendingRenamesRef.current.splice(0)) request.reject(error); + const rejectPendingSaves = useCallback((error: unknown) => { + for (const request of pendingSavesRef.current.splice(0)) request.reject(error); }, []); const flushPersistence = useCallback(() => { @@ -212,46 +218,48 @@ export function useSidebarState( ) return; const pending = pendingPersistenceRef.current; - // Optimistic snapshots must drain before a rename takes its own snapshot. - const rename = pending === null ? pendingRenamesRef.current.shift() : undefined; - const next = rename - ? normalizeSidebarState(withTitleOverride(stateRef.current, rename.key, rename.title)) - : pending; - if (next === null) return; + // Optimistic snapshots must drain before a confirmed edit takes its own snapshot. + const request = pending === null ? pendingSavesRef.current.shift() : undefined; + const apply = request?.prepare(stateRef.current); + const next = apply ? normalizeSidebarState(apply(stateRef.current)) : pending; + if (next === null) { + if (request) { + request.resolve(); + queueMicrotask(() => flushPersistenceRef.current()); + } + return; + } pendingPersistenceRef.current = null; persistenceInFlightRef.current = true; void client.setSidebarState(next) .then((saved) => { - persistenceInFlightRef.current = false; - if (rename) { - const title = normalizeSidebarState(saved).title_overrides[rename.key]; - if (pendingPersistenceRef.current !== null) { - pendingPersistenceRef.current = withTitleOverride( - pendingPersistenceRef.current, rename.key, title, - ); - } - const renamed = withTitleOverride(stateRef.current, rename.key, title); - stateRef.current = renamed; - setState(renamed); - rename.resolve(); + const canonical = normalizeSidebarState(saved); + if (apply && pendingPersistenceRef.current !== null) { + const reconciled = apply(stateRef.current, canonical); + pendingPersistenceRef.current = reconciled; + stateRef.current = reconciled; + setState(reconciled); } else if (pendingPersistenceRef.current === null) { - const canonical = normalizeSidebarState(saved); stateRef.current = canonical; setState(canonical); } - flushPersistenceRef.current(); + request?.resolve(); }) .catch((error: unknown) => { - persistenceInFlightRef.current = false; - if (rename) { - rename.reject(error); - flushPersistenceRef.current(); + if (request) { + request.reject(error); } else { if (pendingPersistenceRef.current === null) pendingPersistenceRef.current = next; - rejectPendingRenames(error); + rejectPendingSaves(error); } + // Leave the failed optimistic snapshot queued for reconnection. + return !request; + }) + .then((retryOnReconnect) => { + persistenceInFlightRef.current = false; + if (!retryOnReconnect) flushPersistenceRef.current(); }); - }, [client, rejectPendingRenames]); + }, [client, rejectPendingSaves]); flushPersistenceRef.current = flushPersistence; const persist = useCallback((next: SidebarStatePayload) => { @@ -262,8 +270,8 @@ export function useSidebarState( useEffect(() => client.onStatus((status) => { connectionOpenRef.current = status === "open"; if (status === "open") flushPersistence(); - else rejectPendingRenames(new Error("WebUI connection is not open")); - }), [client, flushPersistence, rejectPendingRenames]); + else rejectPendingSaves(new Error("WebUI connection is not open")); + }), [client, flushPersistence, rejectPendingSaves]); useEffect(() => client.onSidebarStateUpdate((incoming) => { if ( @@ -289,17 +297,22 @@ export function useSidebarState( [persist], ); - const rename = useCallback((key: string, title: string): Promise => { + const save = useCallback((prepare: PrepareSidebarSave): Promise => { if (!loadedRef.current) return Promise.reject(new Error("Sidebar state is not loaded")); if (!connectionOpenRef.current) { return Promise.reject(new Error("WebUI connection is not open")); } return new Promise((resolve, reject) => { - pendingRenamesRef.current.push({ key: key.trim(), title, resolve, reject }); + pendingSavesRef.current.push({ prepare, resolve, reject }); flushPersistence(); }); }, [flushPersistence]); + const rename = useCallback((rawKey: string, title: string) => { + const key = rawKey.trim(); + return save(() => (current, saved) => withTitleOverride(current, key, saved ? saved.title_overrides[key] : title)); + }, [save]); + const pruned = useMemo(() => { if (!sessionsLoaded || loading) return state; return pruneMissingSessions(state, sessions); @@ -310,5 +323,5 @@ export function useSidebarState( void update(() => pruned); }, [loading, pruned, sessionsLoaded, state, update]); - return { state, loading, update, rename }; + return { state, loading, update, save, rename }; } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 3c0dedd14..82d5aadd0 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1951,8 +1951,6 @@ "deleteConfirm": { "title": "Delete this topic?", "titleMany": "Delete {{count}} conversations?", - "description": "This action cannot be undone.", - "descriptionMany": "This action cannot be undone.", "cancel": "Cancel", "confirm": "Delete", "automationsDescription": "Deleting this topic also deletes its linked automations.", @@ -2222,7 +2220,7 @@ "tooLong": "Recording is too long.", "tooShort": "Hold a little longer to record voice.", "noInput": "No microphone input detected.", - "noDevice": "No microphone was found. Connect a microphone and try again.", + "noDevice": "Connect a microphone to record.", "failed": "Could not transcribe audio." }, "slash": { @@ -2720,6 +2718,19 @@ "main-stack": "Main and stack" } }, + "toast": { + "undo": "Undo", + "pendingDeleteSingle": "Topic will be deleted", + "archivedSingle": "Topic archived", + "archiveFailed": "Could not change archive status.", + "unarchivedSingle": "Topic unarchived", + "deleteFailedSingle": "Could not delete the topic", + "deleteWindow": "You have {{seconds}} seconds to undo.", + "pendingDelete": "{{count}} topics will be deleted", + "archived": "{{count}} topics archived", + "unarchived": "{{count}} topics unarchived", + "deleteFailed": "Could not delete {{count}} topics" + }, "common": { "retry": "Retry", "dismiss": "Dismiss", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 70f0c00e9..92870496f 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "¿Eliminar este chat?", "titleMany": "¿Eliminar {{count}} conversaciones?", - "description": "Esta acción no se puede deshacer.", - "descriptionMany": "Esta acción no se puede deshacer.", "cancel": "Cancelar", "confirm": "Eliminar", "automationsDescription": "Eliminar este tema también elimina sus tareas automáticas vinculadas.", @@ -2040,7 +2038,7 @@ "tooLong": "La grabación es demasiado larga.", "tooShort": "Mantén pulsado un poco más para grabar voz.", "noInput": "No se detectó entrada del micrófono.", - "noDevice": "No se encontró ningún micrófono. Conéctalo y vuelve a intentarlo.", + "noDevice": "Conecta un micrófono para grabar.", "failed": "No se pudo transcribir el audio." }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "Principal y pila" } }, + "toast": { + "undo": "Deshacer", + "pendingDeleteSingle": "La conversación se eliminará", + "archivedSingle": "Conversación archivada", + "archiveFailed": "No se pudo cambiar el estado de archivado.", + "unarchivedSingle": "Conversación desarchivada", + "deleteFailedSingle": "No se pudo eliminar la conversación", + "deleteWindow": "Tienes {{seconds}} segundos para deshacer la acción.", + "pendingDelete": "Se eliminarán {{count}} conversaciones", + "archived": "{{count}} conversaciones archivadas", + "unarchived": "{{count}} conversaciones desarchivadas", + "deleteFailed": "No se pudieron eliminar {{count}} conversaciones" + }, "common": { "retry": "Reintentar", "dismiss": "Cerrar", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index f196086c8..d3a023d32 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "Supprimer cette discussion ?", "titleMany": "Supprimer {{count}} conversations ?", - "description": "Cette action est irréversible.", - "descriptionMany": "Cette action est irréversible.", "cancel": "Annuler", "confirm": "Supprimer", "automationsDescription": "Supprimer ce sujet supprime aussi ses tâches automatiques liées.", @@ -2040,7 +2038,7 @@ "tooLong": "L'enregistrement est trop long.", "tooShort": "Maintenez un peu plus longtemps pour enregistrer la voix.", "noInput": "Aucune entrée microphone détectée.", - "noDevice": "Aucun microphone trouvé. Connectez-en un, puis réessayez.", + "noDevice": "Branchez un micro pour enregistrer.", "failed": "Impossible de transcrire l'audio." }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "Principal et pile" } }, + "toast": { + "undo": "Annuler", + "pendingDeleteSingle": "La conversation va être supprimée", + "archivedSingle": "Conversation archivée", + "archiveFailed": "Impossible de modifier le statut d’archivage.", + "unarchivedSingle": "Conversation désarchivée", + "deleteFailedSingle": "Impossible de supprimer la conversation", + "deleteWindow": "Vous avez {{seconds}} secondes pour annuler.", + "pendingDelete": "{{count}} conversations vont être supprimées", + "archived": "{{count}} conversations archivées", + "unarchived": "{{count}} conversations désarchivées", + "deleteFailed": "Impossible de supprimer {{count}} conversations" + }, "common": { "retry": "Réessayer", "dismiss": "Fermer", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index d447b92f1..c859b3b5a 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "Hapus obrolan ini?", "titleMany": "Hapus {{count}} percakapan?", - "description": "Tindakan ini tidak dapat dibatalkan.", - "descriptionMany": "Tindakan ini tidak dapat dibatalkan.", "cancel": "Batal", "confirm": "Hapus", "automationsDescription": "Menghapus topik ini juga menghapus tugas otomatis terkait.", @@ -2040,7 +2038,7 @@ "tooLong": "Rekaman terlalu panjang.", "tooShort": "Tahan sedikit lebih lama untuk merekam suara.", "noInput": "Tidak ada input mikrofon yang terdeteksi.", - "noDevice": "Mikrofon tidak ditemukan. Hubungkan mikrofon lalu coba lagi.", + "noDevice": "Hubungkan mikrofon untuk merekam.", "failed": "Tidak dapat mentranskripsi audio." }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "Utama dan tumpukan" } }, + "toast": { + "undo": "Urungkan", + "pendingDeleteSingle": "Percakapan akan dihapus", + "archivedSingle": "Percakapan diarsipkan", + "archiveFailed": "Tidak dapat mengubah status arsip.", + "unarchivedSingle": "Percakapan dikeluarkan dari arsip", + "deleteFailedSingle": "Gagal menghapus percakapan", + "deleteWindow": "Anda punya {{seconds}} detik untuk mengurungkan tindakan.", + "pendingDelete": "{{count}} percakapan akan dihapus", + "archived": "{{count}} percakapan diarsipkan", + "unarchived": "{{count}} percakapan dikeluarkan dari arsip", + "deleteFailed": "Gagal menghapus {{count}} percakapan" + }, "common": { "retry": "Coba lagi", "dismiss": "Tutup", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 3b183d55f..9eee53e08 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "このチャットを削除しますか?", "titleMany": "{{count}} 件の会話を削除しますか?", - "description": "この操作は元に戻せません。", - "descriptionMany": "この操作は元に戻せません。", "cancel": "キャンセル", "confirm": "削除", "automationsDescription": "このトピックを削除すると、関連する自動タスクも削除されます。", @@ -2040,7 +2038,7 @@ "tooLong": "録音が長すぎます。", "tooShort": "もう少し長く録音してください。", "noInput": "マイク入力が検出されませんでした。", - "noDevice": "マイクが見つかりません。接続して再試行してください。", + "noDevice": "録音するにはマイクを接続してください。", "failed": "音声を文字起こしできませんでした。" }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "メインとサブ" } }, + "toast": { + "undo": "元に戻す", + "pendingDeleteSingle": "会話を削除します", + "archivedSingle": "会話をアーカイブしました", + "archiveFailed": "アーカイブ状態を変更できませんでした。", + "unarchivedSingle": "会話のアーカイブを解除しました", + "deleteFailedSingle": "会話を削除できませんでした", + "deleteWindow": "{{seconds}} 秒以内なら元に戻せます。", + "pendingDelete": "{{count}} 件の会話を削除します", + "archived": "{{count}} 件の会話をアーカイブしました", + "unarchived": "{{count}} 件の会話のアーカイブを解除しました", + "deleteFailed": "{{count}} 件の会話を削除できませんでした" + }, "common": { "retry": "再試行", "dismiss": "閉じる", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 353e67389..cb4ef1333 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "이 채팅을 삭제할까요?", "titleMany": "대화 {{count}}개를 삭제할까요?", - "description": "이 작업은 되돌릴 수 없습니다.", - "descriptionMany": "이 작업은 되돌릴 수 없습니다.", "cancel": "취소", "confirm": "삭제", "automationsDescription": "이 주제를 삭제하면 연결된 자동 작업도 삭제됩니다.", @@ -2040,7 +2038,7 @@ "tooLong": "녹음 시간이 너무 깁니다.", "tooShort": "음성을 녹음하려면 조금 더 길게 눌러 주세요.", "noInput": "마이크 입력이 감지되지 않았습니다.", - "noDevice": "마이크를 찾을 수 없습니다. 연결 후 다시 시도하세요.", + "noDevice": "녹음하려면 마이크를 연결하세요.", "failed": "오디오를 변환하지 못했습니다." }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "주 창과 보조 창" } }, + "toast": { + "undo": "실행 취소", + "pendingDeleteSingle": "대화가 곧 삭제됩니다", + "archivedSingle": "대화를 보관했습니다", + "archiveFailed": "보관 상태를 변경하지 못했습니다.", + "unarchivedSingle": "대화 보관을 해제했습니다", + "deleteFailedSingle": "대화를 삭제하지 못했습니다", + "deleteWindow": "{{seconds}}초 안에 삭제를 취소할 수 있습니다.", + "pendingDelete": "대화 {{count}}개가 곧 삭제됩니다", + "archived": "대화 {{count}}개를 보관했습니다", + "unarchived": "대화 {{count}}개의 보관을 해제했습니다", + "deleteFailed": "대화 {{count}}개를 삭제하지 못했습니다" + }, "common": { "retry": "다시 시도", "dismiss": "닫기", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 10afae730..25126de19 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1771,8 +1771,6 @@ "deleteConfirm": { "title": "Excluir esta conversa?", "titleMany": "Excluir {{count}} conversas?", - "description": "Esta ação não pode ser desfeita.", - "descriptionMany": "Esta ação não pode ser desfeita.", "cancel": "Cancelar", "confirm": "Excluir", "automationsDescription": "Excluir este tópico também exclui suas automações vinculadas.", @@ -2042,7 +2040,7 @@ "tooLong": "A gravação é longa demais.", "tooShort": "Segure um pouco mais para gravar voz.", "noInput": "Não foi detectada entrada do microfone.", - "noDevice": "Nenhum microfone encontrado. Conecte um e tente novamente.", + "noDevice": "Conecte um microfone para gravar.", "failed": "Não foi possível transcrever o áudio." }, "slash": { @@ -2540,6 +2538,19 @@ "main-stack": "Principal e pilha" } }, + "toast": { + "undo": "Desfazer", + "pendingDeleteSingle": "A conversa será excluída", + "archivedSingle": "Conversa arquivada", + "archiveFailed": "Não foi possível alterar o status de arquivamento.", + "unarchivedSingle": "Conversa desarquivada", + "deleteFailedSingle": "Não foi possível excluir a conversa", + "deleteWindow": "Você tem {{seconds}} segundos para desfazer a ação.", + "pendingDelete": "{{count}} conversas serão excluídas", + "archived": "{{count}} conversas arquivadas", + "unarchived": "{{count}} conversas desarquivadas", + "deleteFailed": "Não foi possível excluir {{count}} conversas" + }, "common": { "retry": "Tentar novamente", "dismiss": "Descartar", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index ac61398f1..75608193a 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "Xóa cuộc trò chuyện này?", "titleMany": "Xóa {{count}} cuộc trò chuyện?", - "description": "Không thể hoàn tác thao tác này.", - "descriptionMany": "Không thể hoàn tác thao tác này.", "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.", @@ -2040,7 +2038,7 @@ "tooLong": "Bản ghi âm quá dài.", "tooShort": "Giữ lâu hơn một chút để ghi âm giọng nói.", "noInput": "Không phát hiện đầu vào micrô.", - "noDevice": "Không tìm thấy micrô. Hãy kết nối rồi thử lại.", + "noDevice": "Kết nối micrô để ghi âm.", "failed": "Không thể chép lời âm thanh." }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "Chính và phụ" } }, + "toast": { + "undo": "Hoàn tác", + "pendingDeleteSingle": "Sắp xóa cuộc trò chuyện", + "archivedSingle": "Đã lưu trữ cuộc trò chuyện", + "archiveFailed": "Không thể thay đổi trạng thái lưu trữ.", + "unarchivedSingle": "Đã bỏ lưu trữ cuộc trò chuyện", + "deleteFailedSingle": "Không thể xóa cuộc trò chuyện", + "deleteWindow": "Bạn có {{seconds}} giây để hoàn tác.", + "pendingDelete": "Sắp xóa {{count}} cuộc trò chuyện", + "archived": "Đã lưu trữ {{count}} cuộc trò chuyện", + "unarchived": "Đã bỏ lưu trữ {{count}} cuộc trò chuyện", + "deleteFailed": "Không thể xóa {{count}} cuộc trò chuyện" + }, "common": { "retry": "Thử lại", "dismiss": "Đóng", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 8429bbd53..7a0f8c091 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1951,8 +1951,6 @@ "deleteConfirm": { "title": "删除这个话题?", "titleMany": "删除这 {{count}} 个对话?", - "description": "此操作无法撤销。", - "descriptionMany": "此操作无法撤销。", "cancel": "取消", "confirm": "删除", "automationsDescription": "删除话题也会删除关联的自动任务", @@ -2222,7 +2220,7 @@ "tooLong": "录音时间太长。", "tooShort": "请稍微多录一会儿。", "noInput": "没有检测到麦克风输入。", - "noDevice": "没有找到可用的麦克风。请连接麦克风后重试。", + "noDevice": "未找到麦克风,请连接后重试。", "failed": "语音转写失败。" }, "slash": { @@ -2720,6 +2718,19 @@ "main-stack": "主次排列" } }, + "toast": { + "undo": "撤销", + "pendingDeleteSingle": "即将删除会话", + "archivedSingle": "已归档会话", + "archiveFailed": "无法更改归档状态。", + "unarchivedSingle": "已取消归档", + "deleteFailedSingle": "删除会话失败", + "deleteWindow": "可在 {{seconds}} 秒内撤销。", + "pendingDelete": "即将删除 {{count}} 个会话", + "archived": "已归档 {{count}} 个会话", + "unarchived": "已取消归档 {{count}} 个会话", + "deleteFailed": "{{count}} 个会话删除失败" + }, "common": { "retry": "重试", "dismiss": "关闭", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 5119d06ec..672d46be6 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1769,8 +1769,6 @@ "deleteConfirm": { "title": "刪除這個話題?", "titleMany": "刪除這 {{count}} 個對話?", - "description": "此操作無法復原。", - "descriptionMany": "此操作無法復原。", "cancel": "取消", "confirm": "刪除", "automationsDescription": "刪除話題也會刪除關聯的自動任務", @@ -2040,7 +2038,7 @@ "tooLong": "錄音時間太長。", "tooShort": "請延長錄音時間。", "noInput": "沒有偵測到麥克風輸入。", - "noDevice": "找不到可用的麥克風,請連接後重試。", + "noDevice": "找不到麥克風,請連接後重試。", "failed": "語音轉寫失敗。" }, "slash": { @@ -2538,6 +2536,19 @@ "main-stack": "主次排列" } }, + "toast": { + "undo": "復原", + "pendingDeleteSingle": "即將刪除對話", + "archivedSingle": "已封存對話", + "archiveFailed": "無法變更封存狀態。", + "unarchivedSingle": "已取消封存", + "deleteFailedSingle": "無法刪除對話", + "deleteWindow": "可在 {{seconds}} 秒內復原。", + "pendingDelete": "即將刪除 {{count}} 個對話", + "archived": "已封存 {{count}} 個對話", + "unarchived": "已取消封存 {{count}} 個對話", + "deleteFailed": "無法刪除 {{count}} 個對話" + }, "common": { "retry": "重試", "dismiss": "關閉", diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 60c6846f2..3926c14aa 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -6,6 +6,7 @@ import type { Window as HappyWindow } from "happy-dom"; import i18n from "@/i18n"; import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings"; import { useSessions } from "@/hooks/useSessions"; +import { TOAST_ACTION_MS } from "@/components/ui/toast"; import type { NanobotClientOptions, RunState } from "@/lib/nanobot-client"; import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache"; import type { @@ -49,6 +50,13 @@ const pairingChangeHandlers = new Set<() => void>(); const readyHandlers = new Set<() => void>(); let mockSessions: ChatSummary[] = []; +async function confirmTopicDeletion(button: HTMLElement) { + fireEvent.click(button); + // Happy DOM delivers the modal's aria-hidden removal on a timer. Start + // measuring the Undo window after the observer makes the toast reachable. + await act(async () => { await vi.advanceTimersByTimeAsync(0); }); +} + function setNavigatorPlatform(platform: string): void { Object.defineProperty(window.navigator, "platform", { configurable: true, @@ -205,8 +213,8 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => { forkChat: async () => "fork-chat", getSessionAutomations: getSessionAutomationsSpy, deleteChat: async (key: string, options?: { deleteAutomations?: boolean }) => { - if (options === undefined) await deleteChatSpy(key); - else await deleteChatSpy(key, options); + const result = options === undefined ? await deleteChatSpy(key) : await deleteChatSpy(key, options); + if (result && !result.deleted) return result; setSessions((prev: ChatSummary[]) => prev.filter((s) => s.key !== key)); return { deleted: true }; }, @@ -321,6 +329,7 @@ import { BootstrapAuthRequiredError, deriveWsUrl, fetchBootstrap, + loadSavedSecret, } from "@/lib/bootstrap"; import App from "@/App"; import { mockBrowserFocus } from "./browser-focus"; @@ -437,9 +446,10 @@ describe("App layout", () => { expect(requestMutationSpy).not.toHaveBeenCalled(); }); - it("shows the auth form without an invalid-password error on first load", async () => { + it.each(["", "stale-password"])("shows a clean auth form when the initial automatic sign-in fails (saved password: %j)", async (savedPassword) => { + vi.mocked(loadSavedSecret).mockReturnValueOnce(savedPassword); vi.mocked(fetchBootstrap).mockRejectedValueOnce( - new Error("bootstrap failed: HTTP 401"), + new BootstrapAuthRequiredError("bootstrap failed: HTTP 401"), ); render(); @@ -452,8 +462,10 @@ describe("App layout", () => { "autocomplete", "current-password", ); - expect(password).not.toHaveAttribute("placeholder"); + expect(password).toHaveValue(""); + expect(password).toHaveFocus(); expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(fetchBootstrap).toHaveBeenCalledWith("", savedPassword); expect(connectSpy).not.toHaveBeenCalled(); }); @@ -467,6 +479,7 @@ describe("App layout", () => { await user.type(await screen.findByLabelText("WebUI password"), "draft-password"); await user.tab({ shift: true }); + await user.tab({ shift: true }); expect(screen.getByRole("combobox", { name: "Change language" })).toHaveFocus(); await user.keyboard("{Enter}"); await screen.findByRole("listbox"); @@ -474,7 +487,9 @@ describe("App layout", () => { expect(await screen.findByRole("heading", { name: "连接到 nanobot" })) .toBeInTheDocument(); - expect(screen.getByLabelText("WebUI 密码")).toHaveValue("draft-password"); + const password = screen.getByLabelText("WebUI 密码"); + expect(password).toHaveValue("draft-password"); + expect(password).toHaveAttribute("placeholder", "WebUI 密码"); expect(screen.getByRole("button", { name: "连接" })).toBeEnabled(); expect(document.documentElement.lang).toBe("zh-CN"); expect(localStorage.getItem("nanobot.locale")).toBe("zh-CN"); @@ -482,7 +497,7 @@ describe("App layout", () => { expect(connectSpy).not.toHaveBeenCalled(); }); - it("reveals password setup help with the keyboard without submitting the form", async () => { + it("opens password help as a dialog without submitting or clearing the password draft", async () => { vi.mocked(fetchBootstrap).mockRejectedValueOnce( new Error("bootstrap failed: HTTP 401"), ); @@ -492,26 +507,25 @@ describe("App layout", () => { const password = await screen.findByLabelText("WebUI password"); await user.type(password, "draft-password"); - await user.tab(); - await user.tab(); - await user.tab(); - const help = screen.getByRole("button", { name: "Where can I find the password?" }); + await user.tab({ shift: true }); + const helpTitle = "Where can I find the password?"; + const help = screen.getByRole("button", { name: helpTitle }); expect(help).toHaveFocus(); - expect(help).toHaveAttribute("aria-expanded", "false"); - const content = document.getElementById(help.getAttribute("aria-controls")!); - expect(content).toHaveAttribute("aria-hidden", "true"); + expect(await screen.findByRole("tooltip")).toHaveTextContent(helpTitle); await user.keyboard("{Enter}"); - expect(help).toHaveAttribute("aria-expanded", "true"); - expect(content).not.toHaveAttribute("aria-hidden"); - expect(content).toHaveTextContent("~/.nanobot/config.json"); - expect(content).toHaveTextContent("channels.websocket.tokenIssueSecret"); - expect(content).toHaveTextContent("If that value is empty, use channels.websocket.token."); + const dialog = await screen.findByRole("dialog", { name: helpTitle }); + expect(dialog).toHaveFocus(); + expect(screen.queryByRole("tooltip")).not.toBeInTheDocument(); + expect(dialog).toHaveTextContent("~/.nanobot/config.json"); + expect(dialog).toHaveTextContent("channels.websocket.tokenIssueSecret"); + expect(dialog).toHaveTextContent("If that value is empty, use channels.websocket.token."); - await user.keyboard(" "); + await user.keyboard("{Escape}"); - expect(help).toHaveAttribute("aria-expanded", "false"); + await waitFor(() => expect(help).toHaveFocus()); + expect(dialog).not.toBeInTheDocument(); expect(password).toHaveValue("draft-password"); expect(fetchBootstrap).toHaveBeenCalledTimes(1); }); @@ -557,17 +571,13 @@ describe("App layout", () => { expect(await screen.findByRole("alert")).toHaveTextContent( "Enter password", ); - expect(password).toHaveAttribute("placeholder", "Enter password"); expect(password).toHaveAttribute("aria-invalid", "true"); - expect(password).toHaveAttribute( - "aria-describedby", - "webui-auth-error", - ); + expect(password).toHaveAccessibleDescription("Enter password"); expect(password).toHaveFocus(); fireEvent.change(password, { target: { value: " " } }); fireEvent.click(connect); expect(password).toHaveValue(""); - expect(password).toHaveAttribute("placeholder", "Enter password"); + expect(password).toHaveAccessibleDescription("Enter password"); expect(fetchBootstrap).toHaveBeenCalledTimes(1); }); @@ -586,34 +596,47 @@ describe("App layout", () => { expect(connectSpy).not.toHaveBeenCalled(); }); - it("shows an invalid-password error after a submitted password is rejected", async () => { - vi.mocked(fetchBootstrap).mockRejectedValue( - new Error("bootstrap failed: HTTP 401"), - ); + it("keeps the sign-in form mounted during submission and refocuses it on rejection", async () => { + let rejectAttempt!: (error: Error) => void; + vi.mocked(fetchBootstrap) + .mockRejectedValueOnce(new Error("bootstrap failed: HTTP 401")) + .mockReturnValueOnce(new Promise((_, reject) => { rejectAttempt = reject; })); + const user = userEvent.setup(); render(); const password = await screen.findByLabelText("WebUI password"); - fireEvent.change(password, { target: { value: "wrong-password" } }); - fireEvent.click(screen.getByRole("button", { name: "Connect" })); + const submit = screen.getByRole("button", { name: "Connect" }); + await user.type(password, "wrong-password"); + await user.click(screen.getByRole("button", { name: "Show password" })); + await user.click(submit); - const retryPassword = await screen.findByLabelText("WebUI password"); - expect(await screen.findByRole("alert")).toHaveTextContent( - "Incorrect password", - ); - expect(retryPassword).toHaveAttribute("placeholder", "Incorrect password"); - expect(retryPassword).toHaveValue(""); - expect(retryPassword).toHaveAttribute("aria-invalid", "true"); - expect(retryPassword).toHaveFocus(); + expect(screen.getByLabelText("WebUI password")).toBe(password); + expect(submit).toBeDisabled(); + expect(submit).toHaveAttribute("aria-busy", "true"); + expect(password).toHaveAttribute("readonly"); + expect(fetchBootstrap).toHaveBeenCalledTimes(2); expect(fetchBootstrap).toHaveBeenLastCalledWith("", "wrong-password"); + + await act(async () => rejectAttempt(new Error("bootstrap failed: HTTP 401"))); + + expect(screen.getByRole("alert")).toHaveTextContent("Incorrect password"); + expect(screen.getByLabelText("WebUI password")).toBe(password); + expect(submit).toBeEnabled(); + expect(password).toHaveAccessibleDescription("Incorrect password"); + expect(password).toHaveValue(""); + expect(password).toHaveAttribute("type", "password"); + expect(password).toHaveAttribute("aria-invalid", "true"); + expect(password).toHaveFocus(); expect(connectSpy).not.toHaveBeenCalled(); - fireEvent.change(retryPassword, { target: { value: "retry-password" } }); - expect(retryPassword).not.toHaveAttribute("placeholder"); - expect(retryPassword).not.toHaveAttribute("aria-invalid"); + await user.type(password, "retry-password"); + expect(password).toHaveValue("retry-password"); + expect(password).not.toHaveAccessibleDescription(); + expect(password).not.toHaveAttribute("aria-invalid"); expect(screen.queryByRole("alert")).not.toBeInTheDocument(); }); - it("clears auth feedback after three seconds without moving focus", async () => { + it("keeps auth errors on the password field while the user waits", async () => { vi.mocked(fetchBootstrap).mockRejectedValue( new Error("bootstrap failed: HTTP 401"), ); @@ -622,9 +645,9 @@ describe("App layout", () => { vi.useFakeTimers(); fireEvent.click(screen.getByRole("button", { name: "Connect" })); - expect(password).toHaveAttribute("placeholder", "Enter password"); - act(() => vi.advanceTimersByTime(3_000)); - expect(password).not.toHaveAttribute("placeholder"); + act(() => vi.advanceTimersByTime(5_000)); + expect(screen.getByRole("alert")).toHaveTextContent("Enter password"); + expect(password).toHaveAccessibleDescription("Enter password"); expect(password).toHaveFocus(); await act(async () => { @@ -632,13 +655,10 @@ describe("App layout", () => { fireEvent.click(screen.getByRole("button", { name: "Connect" })); }); const retryPassword = screen.getByLabelText("WebUI password"); - expect(retryPassword).toHaveAttribute("placeholder", "Incorrect password"); - act(() => vi.advanceTimersByTime(2_999)); - expect(retryPassword).toHaveAttribute("placeholder", "Incorrect password"); - act(() => vi.advanceTimersByTime(1)); - expect(retryPassword).not.toHaveAttribute("placeholder"); - expect(retryPassword).not.toHaveAttribute("aria-invalid"); - expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + act(() => vi.advanceTimersByTime(5_000)); + expect(screen.getByRole("alert")).toHaveTextContent("Incorrect password"); + expect(retryPassword).toHaveAccessibleDescription("Incorrect password"); + expect(retryPassword).toHaveAttribute("aria-invalid", "true"); expect(retryPassword).toHaveFocus(); }); @@ -2468,23 +2488,27 @@ describe("App layout", () => { await waitFor(() => expect(screen.getByText("Delete this topic?")).toBeInTheDocument(), ); - fireEvent.click(screen.getByRole("button", { name: "Delete" })); - - await waitFor(() => - expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a"), - ); - await waitFor(() => - expect( - within(sidebar).getByRole("button", { name: /^Second chat$/ }), - ).toBeInTheDocument(), - ); + vi.useFakeTimers(); + await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" })); + expect(screen.getByText("Topic will be deleted")).toBeVisible(); + expect(within(sidebar).queryByRole("button", { name: /^First chat$/ })).not.toBeInTheDocument(); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS - 1); }); + expect(deleteChatSpy).not.toHaveBeenCalled(); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + vi.useRealTimers(); + expect(deleteChatSpy).toHaveBeenCalledTimes(1); + expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a"); + expect(within(sidebar).getByRole("button", { name: /^Second chat$/ })).toBeInTheDocument(); expect(screen.queryByText("Delete this topic?")).not.toBeInTheDocument(); expect(document.body.style.pointerEvents).not.toBe("none"); fireEvent.pointerDown(screen.getByLabelText("Topic actions for Second chat"), { button: 0 }); fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" })); - fireEvent.click(within(await screen.findByRole("alertdialog")).getByRole("button", { name: "Delete" })); - await waitFor(() => expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "56px" })); + const lastDelete = await screen.findByRole("alertdialog", { name: "Delete this topic?" }); + vi.useFakeTimers(); + await confirmTopicDeletion(within(lastDelete).getByRole("button", { name: "Delete" })); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "56px" }); }, 15_000); it.each([false, true])("archives only persisted selected topics in one sidebar update (draft=%s)", async (includeDraft) => { @@ -2523,9 +2547,68 @@ describe("App layout", () => { if (includeDraft) expect(within(sidebar).getByRole("button", { name: "Topic a" })).toBeInTheDocument(); else expect(within(sidebar).queryByRole("button", { name: "Topic a" })).not.toBeInTheDocument(); expect(within(sidebar).queryByRole("button", { name: "Topic b" })).not.toBeInTheDocument(); + const fallback = window.location.hash; + const undo = await screen.findByRole("button", { name: "Undo" }); + expect(screen.getByText(includeDraft ? "Topic archived" : "2 topics archived")).toBeVisible(); + fireEvent.click(undo); + await waitFor(() => expect(setSidebarStateSpy).toHaveBeenCalledTimes(2)); + expect(setSidebarStateSpy).toHaveBeenLastCalledWith(expect.objectContaining({ + archived_keys: [], pinned_keys: ["websocket:chat-a", "websocket:chat-b"], + })); + expect(within(sidebar).getByRole("button", { name: "Topic b" })).toBeInTheDocument(); + expect(window.location.hash).toBe(fallback); expect(deleteChatSpy).not.toHaveBeenCalled(); }); + it("keeps the topic and reports archive failure instead of retrying it silently", async () => { + const key = "websocket:chat-a"; + mockSessions = [{ + key, channel: "websocket", chatId: "chat-a", title: "Review notes", preview: "", + createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z", + }]; + mockFetchRoutes({ "/api/webui/sidebar-state": { pinned_keys: [key] } }); + let rejectSave!: (error: Error) => void; + setSidebarStateSpy.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectSave = reject; })); + render(); + const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" }); + act(() => statusHandlers.forEach((handler) => handler("open"))); + fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Review notes"), { button: 0 }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Archive" })); + await waitFor(() => expect(setSidebarStateSpy).toHaveBeenCalledTimes(1)); + expect(within(sidebar).getByRole("button", { name: "Review notes" })).toBeVisible(); + expect(screen.queryByText("Topic archived")).not.toBeInTheDocument(); + await act(async () => rejectSave(new Error("Disk full"))); + expect(await screen.findByText("Could not change archive status.")).toBeVisible(); + expect(within(sidebar).getByRole("button", { name: "Review notes" })).toBeVisible(); + expect(screen.queryByRole("button", { name: "Undo" })).not.toBeInTheDocument(); + act(() => statusHandlers.forEach((handler) => { handler("reconnecting"); handler("open"); })); + expect(setSidebarStateSpy).toHaveBeenCalledTimes(1); + }); + + it.each([["a", "b"], ["b", "a"]])("restores pin order when undoing archives in %s, %s order", async (first, second) => { + const keys = ["a", "b", "c"].map((id) => `websocket:chat-${id}`); + mockSessions = ["a", "b", "c"].map((id, index) => ({ + key: keys[index], channel: "websocket", chatId: `chat-${id}`, title: `Topic ${id}`, preview: "", + createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z", + })); + mockFetchRoutes({ "/api/webui/sidebar-state": { pinned_keys: keys } }); + render(); + const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" }); + act(() => statusHandlers.forEach((handler) => handler("open"))); + for (const id of ["a", "b"]) { + fireEvent.pointerDown(await within(sidebar).findByLabelText(`Topic actions for Topic ${id}`), { button: 0 }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Archive" })); + await waitFor(() => expect(within(sidebar).queryByRole("button", { name: `Topic ${id}` })).not.toBeInTheDocument()); + } + for (const id of [first, second]) { + const card = screen.getByText(`Topic ${id}`, { selector: '[role="status"] span' }).closest("[data-toast-tone]")!; + fireEvent.click(within(card).getByRole("button", { name: "Undo" })); + await within(sidebar).findByRole("button", { name: `Topic ${id}` }); + } + expect(setSidebarStateSpy).toHaveBeenCalledTimes(4); + expect(setSidebarStateSpy).toHaveBeenLastCalledWith(expect.objectContaining({ pinned_keys: keys, archived_keys: [] })); + }); + it("deletes multiple selected topics through one confirmation", async () => { mockSessions = [ { @@ -2580,10 +2663,14 @@ describe("App layout", () => { getSessionAutomationsSpy.mockResolvedValue([]); fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" })); expect(await screen.findByText("Delete 2 conversations?")).toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "Delete" })); + vi.useFakeTimers(); + await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" })); expect(screen.queryByTestId("delete-selection-bar")).not.toBeInTheDocument(); - - await waitFor(() => expect(deleteChatSpy).toHaveBeenCalledTimes(2)); + expect(screen.getByText("2 topics will be deleted")).toBeVisible(); + expect(screen.getAllByRole("button", { name: "Undo" })).toHaveLength(1); + expect(deleteChatSpy).not.toHaveBeenCalled(); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(deleteChatSpy).toHaveBeenCalledTimes(2); expect(deleteChatSpy.mock.calls.map(([key]) => key)).toEqual([ "websocket:chat-a", "websocket:chat-b", @@ -2594,6 +2681,73 @@ describe("App layout", () => { .toBeInTheDocument(); }, 15_000); + it.each(["undo", "failure", "unmount"] as const)("handles pending topic deletion on %s", async (outcome) => { + mockSessions = ["Review notes", "Release notes"].map((title, index) => ({ + key: `websocket:chat-${index}`, + channel: "websocket", + chatId: `chat-${index}`, + createdAt: "2026-04-16T10:00:00Z", + updatedAt: "2026-04-16T10:00:00Z", + title, + preview: "", + })); + if (outcome === "failure") deleteChatSpy.mockRejectedValueOnce(new Error("Offline")); + const { unmount } = render(); + const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" }); + fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Review notes"), { button: 0 }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" })); + expect(await screen.findByRole("alertdialog", { name: "Delete this topic?" })).toBeVisible(); + vi.useFakeTimers(); + await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" })); + expect(within(sidebar).queryByRole("button", { name: "Review notes" })).not.toBeInTheDocument(); + expect(screen.getByText("Topic will be deleted").closest('[role="status"]')).toHaveTextContent("Review notes"); + expect(deleteChatSpy).not.toHaveBeenCalled(); + + if (outcome === "undo") fireEvent.click(screen.getByRole("button", { name: "Undo" })); + if (outcome === "unmount") unmount(); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + + if (outcome === "failure") { + expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-0"); + expect(screen.getByRole("alert")).toHaveTextContent("Could not delete the topic"); + } else { + expect(deleteChatSpy).not.toHaveBeenCalled(); + } + if (outcome !== "unmount") { + expect(within(sidebar).getByRole("button", { name: "Review notes" })).toBeVisible(); + } + }); + + it("asks again only for the topic whose automations appeared during the delete window", async () => { + mockSessions = ["a", "b"].map((id) => ({ + key: `websocket:chat-${id}`, channel: "websocket", chatId: `chat-${id}`, title: `Topic ${id}`, preview: "", + createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z", + })); + const job: SessionAutomationJob = { + id: "late-job", name: "Added during undo", enabled: true, + schedule: { kind: "every", every_ms: 86_400_000 }, payload: { message: "Check the repo" }, state: {}, + }; + deleteChatSpy.mockResolvedValueOnce({ deleted: true }) + .mockResolvedValueOnce({ deleted: false, blocked_by_automations: true, automations: [job] }); + render(); + const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" }); + fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Topic a"), { button: 0 }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Select" })); + fireEvent.click(within(sidebar).getByRole("button", { name: "Topic b" })); + fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" })); + const initial = await screen.findByRole("alertdialog", { name: "Delete 2 conversations?" }); + vi.useFakeTimers(); + await confirmTopicDeletion(within(initial).getByRole("button", { name: "Delete" })); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(deleteChatSpy.mock.calls).toEqual([["websocket:chat-a"], ["websocket:chat-b"]]); + const retry = screen.getByRole("alertdialog", { name: "Delete this topic?" }); + expect(within(retry).getByText("Added during undo")).toBeVisible(); + await confirmTopicDeletion(within(retry).getByRole("button", { name: "Delete" })); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(deleteChatSpy).toHaveBeenCalledTimes(3); + expect(deleteChatSpy).toHaveBeenLastCalledWith("websocket:chat-b", { deleteAutomations: true }); + }, 15_000); + it("shows localized bound automations in the first delete confirmation", async () => { mockSessions = [ { @@ -2651,13 +2805,11 @@ describe("App layout", () => { screen.queryByText("Deleting this topic also deletes its linked automations."), ).not.toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "删除" })); - - await waitFor(() => - expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a", { - deleteAutomations: true, - }), - ); + vi.useFakeTimers(); + await confirmTopicDeletion(screen.getByRole("button", { name: "删除" })); + expect(deleteChatSpy).not.toHaveBeenCalled(); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a", { deleteAutomations: true }); expect(deleteChatSpy).toHaveBeenCalledTimes(1); expect(screen.queryByText("Daily repo check")).not.toBeInTheDocument(); }, 15_000); @@ -4427,15 +4579,18 @@ describe("App layout", () => { const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" }); expect(await within(sidebar).findByRole("button", { name: "Group: Research" })) .toBeInTheDocument(); + expect((await screen.findByTestId("pane-grid")).children).toHaveLength(2); fireEvent.pointerDown(within(sidebar).getByRole("button", { name: "New topic pane actions", }), { button: 0, ctrlKey: false }); fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" })); expect(await screen.findByText("Delete this topic?")).toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "Delete" })); + vi.useFakeTimers(); + await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" })); - await waitFor(() => expect(deleteChatSpy).toHaveBeenCalledWith("websocket:new-pane")); - await waitFor(() => expect(window.location.hash).toBe("#/chat/websocket%3Aalpha")); + await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); }); + expect(deleteChatSpy).toHaveBeenCalledWith("websocket:new-pane"); + expect(window.location.hash).toBe("#/chat/websocket%3Aalpha"); expect(within(sidebar).getByRole("button", { name: "Group: Research" })) .toBeInTheDocument(); expect(screen.getByTestId("pane-grid").children).toHaveLength(1); diff --git a/webui/src/tests/file-actions.test.tsx b/webui/src/tests/file-actions.test.tsx index f1672bcc4..d18898cb8 100644 --- a/webui/src/tests/file-actions.test.tsx +++ b/webui/src/tests/file-actions.test.tsx @@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { FileActions, FileActionsProvider } from "@/components/FileActions"; import { FileReferenceChip } from "@/components/FileReferenceChip"; +import { ToastProvider } from "@/components/ui/toast"; import { copyTextToClipboard } from "@/lib/clipboard"; import type { FileReferenceMetadata } from "@/lib/types"; @@ -84,6 +85,25 @@ describe("File actions", () => { expect(await screen.findByText("Could not copy. Please try again.")).toBeVisible(); }); + it("coalesces repeated file copy success into one toast and makes the failure alert accessible", async () => { + const user = userEvent.setup(); + render(); + const reference = screen.getByRole("button", { name: "notes.md" }); + for (let i = 0; i < 2; i++) { + fireEvent.contextMenu(reference); + await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" })); + await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); + expect(screen.getAllByRole("status")).toHaveLength(1); + expect(screen.getByRole("status")).toHaveTextContent("Copied"); + } + vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false); + fireEvent.contextMenu(reference); + await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not copy. Please try again."); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + expect(reference).toHaveFocus(); + }); + it("ignores late metadata from a previous session", async () => { const user = userEvent.setup(); let resolveOld!: (value: FileReferenceMetadata) => void; diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx index fff21832e..27e5306ad 100644 --- a/webui/src/tests/message-bubble.test.tsx +++ b/webui/src/tests/message-bubble.test.tsx @@ -4,6 +4,7 @@ import { beforeAll, describe, expect, it, vi } from "vitest"; import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble"; import { preloadMarkdownText } from "@/components/MarkdownText"; import { ThreadMessages } from "@/components/thread/ThreadMessages"; +import { ToastProvider } from "@/components/ui/toast"; import { setAppLanguage } from "@/i18n"; import { parseWebuiThreadPayload } from "@/lib/api"; import * as clipboard from "@/lib/clipboard"; @@ -995,6 +996,22 @@ describe("MessageBubble", () => { ); }); + it("announces clipboard failure and leaves Copy available for another attempt", async () => { + const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(false); + try { + const message: UIMessage = { id: "copy-failed", role: "assistant", content: "A reply", createdAt: 1 }; + const { container } = render(, { wrapper: ToastProvider }); + menuActions(container); + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + const alert = await screen.findByRole("alert"); + expect(alert.closest("[data-toast-tone=error]")).not.toBeNull(); + expect(alert).toHaveTextContent("Could not copy. Please try again."); + expect(screen.getByRole("button", { name: "Copy" })).toBeEnabled(); + } finally { + copy.mockRestore(); + } + }); + it("copies completed assistant replies with the textarea fallback", async () => { Object.defineProperty(navigator, "clipboard", { configurable: true, diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsx index d7114e8f8..75ff370d8 100644 --- a/webui/src/tests/remote-instances.test.tsx +++ b/webui/src/tests/remote-instances.test.tsx @@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { RemoteInstances } from "@/components/remote/RemoteInstances"; import { useRemoteConnections } from "@/components/remote/remote-context"; import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage"; +import { PairingCodePopup } from "@/components/pairing/PairingCodePopup"; +import { ToastProvider } from "@/components/ui/toast"; import { Sidebar } from "@/components/Sidebar"; import { HOST_BRIDGE } from "@/components/remote/host-bridge"; import { readSelectedRemote, readRecentRemotes, rememberSelectedRemote, validateRemoteConnection, type RemoteConnection } from "@/lib/remote-instances"; @@ -157,6 +159,28 @@ describe("remote instance UX", () => { expect(mocks.request).toHaveBeenCalledTimes(1); }); + it.each(["toast", "no provider", "pairing popup"])("reports an attempt to open the local gateway (%s)", async (surface) => { + mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, paired: true }] }); + mocks.request.mockRejectedValueOnce(new Error("same_instance")); + const shell = <> + + {surface === "pairing popup" && } + ; + render({surface === "no provider" ? shell : {shell}}); + + const directory = await screen.findByRole("region", { name: i18n.t("remote.title") }); + const server = await within(directory).findByRole("button", { name: "Team server ubuntu@example.test" }); + fireEvent.click(server); + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent(i18n.t("remote.errors.same_instance")); + if (surface === "toast") expect(alert.closest("[data-toast-tone]")).toHaveAttribute("data-toast-tone", "error"); + else expect(within(directory).getByRole("alert")).toBe(alert); + expect(server).toBeEnabled(); + expect(readSelectedRemote()).toBeNull(); + }); + it.each([false, true])("renames an open server without reloading its view (paired: %s)", async (paired) => { let saved = { ...profile, paired, connected: true }; mocks.read.mockImplementation(async () => ({ available: true, profiles: [saved] })); diff --git a/webui/src/tests/session-info-popover.test.tsx b/webui/src/tests/session-info-popover.test.tsx index 3cdcaac17..46e3fd97a 100644 --- a/webui/src/tests/session-info-popover.test.tsx +++ b/webui/src/tests/session-info-popover.test.tsx @@ -1,4 +1,4 @@ -import { act, render, screen, waitFor, within } from "@testing-library/react"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; @@ -156,7 +156,9 @@ describe("SessionInfoPopover", () => { expect(within(detail).getByRole("button", { name: "More actions" })).toHaveFocus(); }); - it("returns from the shared editor to the same task detail", async () => { + it("blocks Escape and outside clicks while saving, then keeps the error and draft in the editor", async () => { + let failSave!: (error: Error) => void; + requestMutation.mockImplementationOnce(() => new Promise((_, reject) => { failSave = reject; })); const user = userEvent.setup(); render( { await user.click(await screen.findByRole("button", { name: "Edit" })); const editor = await screen.findByRole("dialog", { name: "Edit task" }); expect(screen.getAllByRole("dialog")).toHaveLength(1); + const name = within(editor).getByRole("textbox", { name: "Name" }); + await user.clear(name); + await user.type(name, "Edited task name"); + const save = within(editor).getByRole("button", { name: "Save" }); + await user.click(save); + expect(save).toBeDisabled(); + await user.keyboard("{Escape}"); + expect(editor).toBeVisible(); + fireEvent.pointerDown(editor.closest("[data-dialog-backdrop]")!); + expect(editor).toBeVisible(); + + await act(async () => failSave(new Error("Could not save schedule"))); + expect(await within(editor).findByRole("alert")).toHaveTextContent("Could not save schedule"); + expect(save).toBeEnabled(); + expect(name).toHaveValue("Edited task name"); await user.click(within(editor).getByRole("button", { name: "Cancel" })); expect(await screen.findByRole("dialog", { name: "Morning check" })).toBeVisible(); expect(screen.getAllByRole("dialog")).toHaveLength(1); }); + it("keeps the delete confirmation open until the request settles so failures can be retried", async () => { + let failDelete!: (error: Error) => void; + requestMutation.mockImplementationOnce(() => new Promise((_, reject) => { failDelete = reject; })); + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole("button", { name: "Session details" })); + await user.click(await screen.findByRole("button", { name: /Morning check/ })); + const detail = await screen.findByRole("dialog", { name: "Morning check" }); + await user.click(within(detail).getByRole("button", { name: "More actions" })); + await user.click(screen.getByRole("menuitem", { name: "Delete" })); + const confirmation = await screen.findByRole("dialog", { name: "Delete automation" }); + const remove = within(confirmation).getByRole("button", { name: "Delete" }); + await user.click(remove); + expect(remove).toBeDisabled(); + fireEvent.pointerDown(confirmation.closest("[data-dialog-backdrop]")!); + expect(confirmation).toBeVisible(); + await user.keyboard("{Escape}"); + expect(confirmation).toBeVisible(); + + await act(async () => failDelete(new Error("Could not delete schedule"))); + expect(within(confirmation).getByRole("alert")).toHaveTextContent("Could not delete schedule"); + expect(remove).toBeEnabled(); + requestMutation.mockResolvedValueOnce({ jobs: [] }); + await user.click(remove); + await waitFor(() => expect(confirmation).not.toBeInTheDocument()); + }); + it("localizes the panel chrome in Simplified Chinese", async () => { await setAppLanguage("zh-CN"); const user = userEvent.setup(); diff --git a/webui/src/tests/settings-models.test.tsx b/webui/src/tests/settings-models.test.tsx index bec68cffb..0bf9bc658 100644 --- a/webui/src/tests/settings-models.test.tsx +++ b/webui/src/tests/settings-models.test.tsx @@ -1,5 +1,6 @@ import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react"; import { expect, it, vi } from "vitest"; +import { ApiError } from "@/lib/api"; import type { ProviderModelsPayload, SettingsPayload } from "@/lib/types"; import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView as renderSettingsViewBase, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils"; @@ -827,12 +828,12 @@ describe("Settings models", () => { it.each([true, false])("closes the preset editor only after deletion succeeds (success: %s)", async (success) => { const { payload } = settingsPayloadWithBackup(); vi.stubGlobal("fetch", vi.fn(() => new Promise(() => {}))); - if (success) requestMutationMock.mockResolvedValueOnce({ - ...payload, - model_presets: payload.model_presets.filter((preset) => preset.name !== "backup"), - model_call_order: ["primary"], - }); - else requestMutationMock.mockRejectedValueOnce(new Error("Delete failed")); + let finishDelete!: (value: SettingsPayload) => void; + let failDelete!: (error: Error) => void; + requestMutationMock.mockImplementationOnce(() => new Promise((resolve, reject) => { + finishDelete = resolve; + failDelete = reject; + })); renderSettingsView({ initialSection: "models", initialSettings: payload }); fireEvent.click(within(screen.getByTestId("model-call-order-row-backup")).getByRole("button", { name: "Configure" })); fireEvent.click(within(screen.getByTestId("model-preset-editor")).getByRole("button", { name: "Delete" })); @@ -841,11 +842,23 @@ describe("Settings models", () => { await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith( "settings.model_configuration.delete", { name: "backup" }, 20_000, )); + expect(within(confirmation).getByRole("button", { name: /Deleting/ })).toBeDisabled(); + fireEvent.keyDown(confirmation, { key: "Escape" }); + expect(confirmation).toBeVisible(); + fireEvent.pointerDown(confirmation.closest("[data-dialog-backdrop]")!); + expect(confirmation).toBeVisible(); if (success) { + await act(async () => finishDelete({ + ...payload, + model_presets: payload.model_presets.filter((preset) => preset.name !== "backup"), + model_call_order: ["primary"], + })); await waitFor(() => expect(screen.queryByTestId("model-preset-editor")).not.toBeInTheDocument()); expect(screen.queryByTestId("model-call-order-row-backup")).not.toBeInTheDocument(); } else { - await waitFor(() => expect(within(confirmation).getByRole("button", { name: "Delete" })).toBeEnabled()); + await act(async () => failDelete(new Error("Delete failed"))); + expect(await within(confirmation).findByRole("alert")).toHaveTextContent("Delete failed"); + expect(within(confirmation).getByRole("button", { name: "Delete" })).toBeEnabled(); expect(screen.getByTestId("model-preset-editor")).toBeInTheDocument(); } }); @@ -1098,7 +1111,7 @@ describe("Settings models", () => { ); }); - it("restores the model call order when immediate persistence fails", async () => { + it("restores the model call order and announces a transient save failure", async () => { const { payload } = settingsPayloadWithBackup(); const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); @@ -1112,7 +1125,7 @@ describe("Settings models", () => { return { ok: false, status: 404, json: async () => ({}) } as Response; }); vi.stubGlobal("fetch", fetchMock); - requestMutationMock.mockRejectedValueOnce(new Error("Order update failed")); + requestMutationMock.mockRejectedValueOnce(new ApiError(503, "WebUI connection is not open")); renderSettingsView({ initialSection: "models", initialSettings: payload }); @@ -1128,7 +1141,7 @@ describe("Settings models", () => { key: "ArrowUp", }); - expect(await screen.findByText("Order update failed")).toBeInTheDocument(); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not update agent settings"); expect( screen .getAllByTestId(/^model-call-order-row-/) diff --git a/webui/src/tests/settings-system.test.tsx b/webui/src/tests/settings-system.test.tsx index e611a55ef..9801e5eb1 100644 --- a/webui/src/tests/settings-system.test.tsx +++ b/webui/src/tests/settings-system.test.tsx @@ -80,6 +80,35 @@ describe("Settings system domains", () => { expect(restart).toHaveBeenCalledTimes(1); }); + it("announces transient desktop utility failures once per action and keeps the exported path", async () => { + const openLogs = vi.fn().mockRejectedValue(new Error("Host could not open the folder")); + const exportDiagnostics = vi.fn().mockRejectedValueOnce(new Error("Host could not export")) + .mockResolvedValueOnce("/diagnostics/report.zip"); + vi.stubGlobal("nanobotHost", { openLogs, exportDiagnostics }); + renderSettingsView({ initialSection: "runtime", initialSettings: { + ...settingsPayload(), surface: "native", + runtime_capabilities: { can_restart_engine: false, can_open_logs: true, can_export_diagnostics: true }, + } }); + + const open = screen.getByRole("button", { name: "Open" }); + for (const attempts of [1, 2]) { + fireEvent.click(open); + await waitFor(() => expect(open).toBeEnabled()); + expect(openLogs).toHaveBeenCalledTimes(attempts); + expect(screen.getByRole("alert")).toHaveTextContent("Could not open logs folder."); + expect(screen.getAllByText("Could not open logs folder.")).toHaveLength(1); + } + + const exportButton = screen.getByRole("button", { name: "Export" }); + fireEvent.click(exportButton); + await waitFor(() => expect(exportButton).toBeEnabled()); + expect(screen.getAllByRole("alert").map((alert) => alert.textContent)).toContain("Could not export diagnostics."); + expect(screen.getAllByText("Could not export diagnostics.")).toHaveLength(1); + fireEvent.click(exportButton); + fireEvent.click(await screen.findByRole("button", { name: "Diagnostics" })); + expect(await screen.findByRole("tooltip")).toHaveTextContent("Diagnostics exported to /diagnostics/report.zip."); + }); + it("leaves directly when no restart is pending", () => { const leave = vi.fn(); renderSettingsView({ initialSection: "runtime", initialSettings: settingsPayload(), onBackToChat: leave }); @@ -574,6 +603,28 @@ describe("Settings system domains", () => { expect(fetchMock.mock.calls.filter(([url]) => String(url) === "/api/settings/cli-apps")).toHaveLength(1); }); + it("announces when copying an installed app's example prompt fails", async () => { + const writeText = vi.fn().mockRejectedValue(new Error("Clipboard blocked")); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); + try { + vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === "/api/settings/cli-apps") { + return jsonResponse({ apps: [{ ...installedAnyGen, installed: false }], installed_count: 0 }); + } + if (String(input) === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 }); + return jsonResponse(settingsPayload()); + })); + requestMutationMock.mockResolvedValue({ apps: [installedAnyGen], installed_count: 1 }); + renderSettingsView({ initialSection: "apps" }); + fireEvent.click(await screen.findByRole("button", { name: "Install app" })); + fireEvent.click(await screen.findByRole("button", { name: "Try @anygen" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not copy. Please try again."); + expect(writeText).toHaveBeenCalledWith("Ask nanobot to use @anygen for this task."); + } finally { + Reflect.deleteProperty(navigator, "clipboard"); + } + }); + it("shows a visible uninstall button for installed CLI apps and calls uninstall", async () => { const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input); diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsx index 29136ffdc..a6eb6954f 100644 --- a/webui/src/tests/settings-test-utils.tsx +++ b/webui/src/tests/settings-test-utils.tsx @@ -2,6 +2,7 @@ import { cleanup, render, screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, vi } from "vitest"; import { SettingsView } from "@/components/settings/SettingsView"; +import { ToastProvider } from "@/components/ui/toast"; import { ClientProvider } from "@/providers/ClientProvider"; import type { SettingsPayload } from "@/lib/types"; import type { NanobotClient } from "@/lib/nanobot-client"; @@ -164,6 +165,7 @@ export function renderSettingsView(options: SettingsViewTestOptions = {}) { onRestart={options.onRestart} /> , + { wrapper: ToastProvider }, ); } diff --git a/webui/src/tests/thread-composer-attach.test.tsx b/webui/src/tests/thread-composer-attach.test.tsx index 135bd4711..e70dbf4ac 100644 --- a/webui/src/tests/thread-composer-attach.test.tsx +++ b/webui/src/tests/thread-composer-attach.test.tsx @@ -11,6 +11,7 @@ import userEvent from "@testing-library/user-event"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; +import { ToastProvider } from "@/components/ui/toast"; import { ComposerDraftStore } from "@/lib/composer-draft"; import type { EncodeResponse } from "@/lib/imageEncode"; import type { WebUIIngressLimits } from "@/lib/types"; @@ -216,7 +217,7 @@ describe("ThreadComposer — attachments", () => { const file = new File([], "empty.csv", { type: "application/vnd.ms-excel" }); const onSend = vi.fn(); - render(); + render(, { wrapper: ToastProvider }); const input = screen .getByLabelText(/message input/i) @@ -227,7 +228,9 @@ describe("ThreadComposer — attachments", () => { fireEvent.change(input, { target: { files: [file] } }); }); - expect(screen.getByText("Empty files cannot be attached")).toBeInTheDocument(); + const alert = screen.getByRole("alert"); + expect(alert.closest("[data-toast-tone=error]")).not.toBeNull(); + expect(alert).toHaveTextContent("Empty files cannot be attached"); expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument(); expect(encodeImage).not.toHaveBeenCalled(); expect(onSend).not.toHaveBeenCalled(); diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx index 3e87cda7b..453e6e739 100644 --- a/webui/src/tests/thread-composer.test.tsx +++ b/webui/src/tests/thread-composer.test.tsx @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover"; +import { ToastProvider } from "@/components/ui/toast"; import { ComposerDraftStore } from "@/lib/composer-draft"; import { encodeImage } from "@/lib/imageEncode"; import { SESSION_DRAG_TYPE } from "@/lib/session-drag"; @@ -889,7 +890,10 @@ describe("ThreadComposer", () => { + "Open this WebUI over HTTPS to use voice input.", ), ).toBeInTheDocument(); - expect(screen.getByRole("alert")).toHaveClass("max-h-24"); + const input = screen.getByRole("textbox", { name: "Message input" }); + fireEvent.change(input, { target: { value: "Continue by typing" } }); + expect(screen.getByRole("alert").closest("form")).toBe(input.closest("form")); + expect(screen.getByRole("alert")).toHaveTextContent("Open this WebUI over HTTPS"); expect(getUserMedia).not.toHaveBeenCalled(); }); @@ -898,11 +902,8 @@ describe("ThreadComposer", () => { vi.stubGlobal("isSecureContext", true); vi.stubGlobal("MediaRecorder", undefined); render( - "unused")} - placeholder="Type your message..." - />, + "unused")} />, + { wrapper: ToastProvider }, ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); @@ -988,24 +989,23 @@ describe("ThreadComposer", () => { await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("one recording")); }); - it("distinguishes a missing microphone from a blocked permission", async () => { + it("shows microphone-not-found as one toast across repeated attempts", async () => { const { getUserMedia } = mockVoiceRecorder(); - getUserMedia.mockRejectedValue(Object.assign(new Error("no microphone"), { - name: "NotFoundError", - })); + getUserMedia.mockRejectedValue(new DOMException("No microphone", "NotFoundError")); render( - "unused")} - placeholder="Type your message..." - />, + "unused")} />, + { wrapper: ToastProvider }, ); - fireEvent.click(screen.getByRole("button", { name: "Voice input" })); - - await waitFor(() => { - expect(screen.getByText("No microphone was found. Connect a microphone and try again.")).toBeInTheDocument(); - }); + const retry = screen.getByRole("button", { name: "Voice input" }); + fireEvent.click(retry); + const first = await screen.findByRole("alert"); + expect(first.closest("[data-toast-tone=error]")).not.toBeNull(); + expect(first).toHaveTextContent("Connect a microphone to record."); + fireEvent.click(retry); + await waitFor(() => expect(first).not.toBeInTheDocument()); + expect(getUserMedia).toHaveBeenCalledTimes(2); + expect(screen.getByRole("alert")).toHaveTextContent("Connect a microphone to record."); }); it("clears a previous voice error when retrying microphone access", async () => { @@ -1022,7 +1022,9 @@ describe("ThreadComposer", () => { const voiceButton = screen.getByRole("button", { name: "Voice input" }); fireEvent.click(voiceButton); - await waitFor(() => expect(screen.getByText("Allow microphone access in the address bar, then retry.")).toBeInTheDocument()); + const permission = await screen.findByRole("alert"); + expect(permission).toHaveTextContent("Allow microphone access in the address bar, then retry."); + expect(permission.closest("form")).not.toBeNull(); fireEvent.click(voiceButton); @@ -1152,11 +1154,8 @@ describe("ThreadComposer", () => { mockVoiceRecorder(); const onTranscribeAudio = vi.fn(async () => "should not appear"); render( - , + , + { wrapper: ToastProvider }, ); fireEvent.click(screen.getByRole("button", { name: "Voice input" })); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 4267ba649..7a482128a 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -6,6 +6,7 @@ import { preloadMarkdownText } from "@/components/MarkdownText"; import { ThreadCameraController } from "@/components/thread/thread-camera"; import { ThreadShell } from "@/components/thread/ThreadShell"; import { SessionSearchDialog } from "@/components/SessionSearchDialog"; +import { ToastProvider } from "@/components/ui/toast"; import i18n from "@/i18n"; import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft"; import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events"; @@ -5598,7 +5599,7 @@ describe("ThreadShell", () => { it("disables offline goal cancellation and treats an unchanged goal after a control reply as a retryable failure", async () => { const client = makeClient(); const chatId = "cancel-failure"; - render(wrap(client, {}} />)); + render({wrap(client, {}} />)}); await act(async () => {}); act(() => { client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });