fix(webui): make action feedback easier to notice (#6702)
* fix(webui): make action feedback easier to notice * fix(webui): preserve undo and report confirmed action results * refactor(webui): trim toast preview and redundant coverage * test(webui): advance the undo window for the last topic deletion
This commit is contained in:
1 parent
0f45d74fec
commit
9ccf3b6214
59 files changed
+1621
-508
No files matched your search
+324
-237
@@ -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<HTMLInputElement>(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 (
|
||||
<main className="flex h-full w-full flex-col overflow-y-auto bg-background">
|
||||
<div className="mx-5 mt-5 shrink-0 self-end sm:mx-8">
|
||||
<div className="mx-5 mt-3.5 flex shrink-0 items-center gap-2 self-end sm:mx-8">
|
||||
<LanguageSwitcher className="h-8 min-w-0 gap-2 px-3 text-xs" />
|
||||
<Dialog>
|
||||
<HoverHint content={helpTitle} side="bottom" align="end">
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={helpTitle}
|
||||
className="h-11 w-11 rounded-full text-muted-foreground"
|
||||
>
|
||||
<CircleHelp className="h-[18px] w-[18px]" strokeWidth={1.75} aria-hidden />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
</HoverHint>
|
||||
<DialogContent className="max-w-md gap-5">
|
||||
<DialogTitle className="pe-8 leading-snug">{helpTitle}</DialogTitle>
|
||||
<div className="min-w-0 space-y-4 text-sm leading-6 text-muted-foreground">
|
||||
<div>
|
||||
<DialogDescription className="leading-6">{t("app.auth.helpConfig")}</DialogDescription>
|
||||
<code className="mt-2 block rounded-compact bg-muted px-3 py-2 font-mono text-xs leading-5 text-foreground [overflow-wrap:anywhere]">
|
||||
~/.nanobot/config.json
|
||||
</code>
|
||||
</div>
|
||||
<div>
|
||||
<p>{t("app.auth.helpSecret")}</p>
|
||||
<code className="mt-2 block rounded-compact bg-muted px-3 py-2 font-mono text-xs leading-5 text-foreground [overflow-wrap:anywhere]">
|
||||
channels.websocket.tokenIssueSecret
|
||||
</code>
|
||||
</div>
|
||||
<p>
|
||||
<Trans
|
||||
i18nKey="app.auth.helpFallback"
|
||||
components={{ code: <code className="font-mono text-xs text-foreground [overflow-wrap:anywhere]" /> }}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
<div className="flex flex-1 shrink-0 items-center justify-center px-6 pb-20 pt-8">
|
||||
<div className="flex flex-1 shrink-0 items-center justify-center px-4 pb-14 pt-6 sm:px-6 sm:pb-20">
|
||||
<section
|
||||
aria-labelledby="webui-auth-title"
|
||||
className="w-full max-w-xs"
|
||||
className="w-full max-w-[27rem] rounded-modal border border-border/70 bg-muted/55 px-6 pb-6 pt-12 [background-image:radial-gradient(ellipse_at_50%_0%,hsl(var(--usage-token)/0.18),transparent_66%)] sm:px-12 sm:pb-8 sm:pt-14"
|
||||
>
|
||||
<div className="text-center">
|
||||
<img
|
||||
src="/brand/nanobot_mark.svg"
|
||||
alt=""
|
||||
width={56}
|
||||
height={56}
|
||||
draggable={false}
|
||||
className="mx-auto mb-5 h-14 w-14 select-none"
|
||||
/>
|
||||
<h1 id="webui-auth-title" className="text-balance text-2xl font-semibold tracking-tight text-foreground sm:text-[1.75rem]">
|
||||
<div className="mx-auto mb-7 grid h-24 w-24 place-items-center rounded-full bg-gradient-to-b from-card to-card/35 shadow-[0_16px_28px_hsl(var(--foreground)/0.10)] dark:shadow-[0_16px_28px_rgba(0,0,0,0.28)]">
|
||||
<img src="/brand/nanobot_mark.svg" alt="" width={56} height={56}
|
||||
draggable={false} className="h-14 w-14 select-none" />
|
||||
</div>
|
||||
<h1 id="webui-auth-title" className="text-balance text-2xl font-semibold tracking-tight text-foreground">
|
||||
{t("app.auth.title")}
|
||||
</h1>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit} className="mt-8">
|
||||
<label htmlFor="webui-access-password" className="sr-only">{passwordLabel}</label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
id="webui-access-password"
|
||||
name="webui-access-password"
|
||||
aria-label={t("app.auth.label")}
|
||||
type={passwordVisible ? "text" : "password"}
|
||||
autoComplete="current-password"
|
||||
placeholder={passwordLabel}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
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
|
||||
/>
|
||||
<Button
|
||||
@@ -465,7 +498,7 @@ function AuthForm({
|
||||
)}
|
||||
aria-controls="webui-access-password"
|
||||
onClick={() => setPasswordVisible((visible) => !visible)}
|
||||
className="absolute right-12 top-1/2 h-10 w-10 -translate-y-1/2 rounded-full text-muted-foreground hover:text-foreground"
|
||||
className="absolute end-0.5 top-1/2 h-11 w-11 -translate-y-1/2 rounded-full text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{passwordVisible ? (
|
||||
<EyeOff className="h-4 w-4" strokeWidth={1.75} aria-hidden />
|
||||
@@ -473,50 +506,24 @@ function AuthForm({
|
||||
<Eye className="h-4 w-4" strokeWidth={1.75} aria-hidden />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={submitting}
|
||||
aria-label={t("app.auth.submit")}
|
||||
title={t("app.auth.submit")}
|
||||
className="absolute right-1 top-1/2 h-10 w-10 -translate-y-1/2 rounded-full"
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" strokeWidth={1.75} aria-hidden />
|
||||
</Button>
|
||||
</div>
|
||||
{errorMessage ? (
|
||||
<p id="webui-auth-error" role="alert" className="sr-only">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-2 grid px-4 text-[13px] leading-5 text-destructive">
|
||||
<span aria-hidden="true" className="invisible col-start-1 row-start-1">{requiredMessage}</span>
|
||||
<span aria-hidden="true" className="invisible col-start-1 row-start-1">{invalidMessage}</span>
|
||||
{errorMessage ? (
|
||||
<p id="webui-auth-error" role="alert" className="col-start-1 row-start-1">{errorMessage}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button type="submit" size="lg" disabled={submitting} aria-busy={submitting || undefined}
|
||||
className="relative mt-3 w-full rounded-full px-11">
|
||||
{t("app.auth.submit")}
|
||||
{submitting ? (
|
||||
<Loader2 className="absolute end-4 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
|
||||
) : (
|
||||
<ArrowRight className="absolute end-4 h-4 w-4 rtl:rotate-180" strokeWidth={1.75} aria-hidden />
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
<Disclosure
|
||||
className="mt-4"
|
||||
summaryClassName="flex min-h-11 items-center justify-center gap-1.5 rounded-compact text-[13px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
contentClassName="rounded-control bg-muted/50 p-4 text-sm leading-6 text-muted-foreground"
|
||||
summary={(
|
||||
<>
|
||||
<span>{t("app.auth.helpTitle")}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" strokeWidth={1.5} aria-hidden />
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<p>{t("app.auth.helpConfig")}</p>
|
||||
<code className="mt-2 block rounded-compact bg-background px-3 py-2 font-mono text-xs text-foreground [overflow-wrap:anywhere]">
|
||||
~/.nanobot/config.json
|
||||
</code>
|
||||
<p className="mt-4">{t("app.auth.helpSecret")}</p>
|
||||
<code className="mt-2 block rounded-compact bg-background px-3 py-2 font-mono text-xs text-foreground [overflow-wrap:anywhere]">
|
||||
channels.websocket.tokenIssueSecret
|
||||
</code>
|
||||
<p className="mt-3">
|
||||
<Trans
|
||||
i18nKey="app.auth.helpFallback"
|
||||
components={{ code: <code className="font-mono text-xs text-foreground [overflow-wrap:anywhere]" /> }}
|
||||
/>
|
||||
</p>
|
||||
</Disclosure>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
@@ -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 <StartupShell />;
|
||||
}
|
||||
if (state.status === "auth") {
|
||||
return (
|
||||
<AuthForm
|
||||
failed={!!state.failed}
|
||||
onSecret={(s) => bootstrapWithSecret(s)}
|
||||
/>
|
||||
);
|
||||
return <AuthForm onSecret={bootstrapWithSecret} />;
|
||||
}
|
||||
if (state.status === "error") {
|
||||
return (
|
||||
@@ -814,16 +817,37 @@ export default function App() {
|
||||
allowUpdateFlow={state.runtimeSurface !== "native"}
|
||||
>
|
||||
<BrowserNotifications client={state.client} />
|
||||
<BackgroundProvider><RemoteInstances><Shell
|
||||
<BackgroundProvider><RemoteInstances><ToastProvider><Shell
|
||||
runtimeSurface={state.runtimeSurface}
|
||||
onModelNameChange={handleModelNameChange}
|
||||
onLogout={handleLogout}
|
||||
onNativeEngineRestart={handleNativeEngineRestart}
|
||||
/></RemoteInstances></BackgroundProvider>
|
||||
/></ToastProvider></RemoteInstances></BackgroundProvider>
|
||||
</ClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type PendingDelete = {
|
||||
id: number;
|
||||
items: SidebarDeleteItem[];
|
||||
automations: SessionAutomationJob[];
|
||||
automationKeys: Set<string>;
|
||||
onDecision?: SidebarDeleteDecision;
|
||||
};
|
||||
|
||||
function restorePinOrder(pins: readonly string[], previous: readonly string[], restoring: ReadonlySet<string>) {
|
||||
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<string>;
|
||||
}) {
|
||||
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<string, string>());
|
||||
const [creatingPane, setCreatingPane] = useState(false);
|
||||
const topicSessions = sessions;
|
||||
const [pendingDelete, setPendingDelete] = useState<{
|
||||
items: SidebarDeleteItem[];
|
||||
automations?: SessionAutomationJob[];
|
||||
onDecision?: SidebarDeleteDecision;
|
||||
} | null>(null);
|
||||
const [deletingKeys, setDeletingKeys] = useState<Set<string>>(() => new Set());
|
||||
const topicSessions = useMemo(() => deletingKeys.size === 0 ? sessions
|
||||
: sessions.filter((session) => !deletingKeys.has(session.key)), [deletingKeys, sessions]);
|
||||
const [deleteQueue, setDeleteQueue] = useState<PendingDelete[]>([]);
|
||||
const [pendingDelete] = deleteQueue;
|
||||
const nextDeleteId = useRef(0);
|
||||
const archiveUndoOwners = useRef(new Map<string, { operation: symbol; pinOrder?: string[] }>());
|
||||
const canNavigateArchiveRef = useRef(false);
|
||||
useEffect(() => {
|
||||
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<string | null>(null);
|
||||
const [isRestarting, setIsRestarting] = useState(false);
|
||||
const [runningChatIds, setRunningChatIds] = useState<Set<string>>(() => new Set());
|
||||
const [updatedChatIds, setUpdatedChatIds] = useState<Set<string>>(readSessionUpdateChatIds);
|
||||
@@ -1161,8 +1192,8 @@ function Shell({
|
||||
const activeSession = useMemo<ChatSummary | null>(() => {
|
||||
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<string>();
|
||||
let pinOrder: string[] = [];
|
||||
let removedPins = new Set<string>();
|
||||
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<string>, 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<string>();
|
||||
const automations = automationResults.flatMap((result, index) => {
|
||||
if (result.status !== "fulfilled" || !result.value.length) return [];
|
||||
automationKeys.add(uniqueItems[index].key);
|
||||
return result.value;
|
||||
});
|
||||
let decision = onDecision;
|
||||
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 (
|
||||
<ThreadShell
|
||||
session={activeSession}
|
||||
sessions={sessions}
|
||||
sessions={topicSessions}
|
||||
titleOverrides={sidebarState.title_overrides}
|
||||
title={headerTitle}
|
||||
temporary={temporaryChatRequested}
|
||||
@@ -2644,7 +2746,7 @@ function Shell({
|
||||
return (
|
||||
<ThreadShell
|
||||
session={paneSession}
|
||||
sessions={sessions}
|
||||
sessions={topicSessions}
|
||||
titleOverrides={sidebarState.title_overrides}
|
||||
title={pane.title}
|
||||
temporaryChatIds={temporaryChatIds}
|
||||
@@ -2748,17 +2850,15 @@ function Shell({
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{pendingDelete ? (
|
||||
{pendingDelete && localActive && !managingConnections ? (
|
||||
<Suspense fallback={null}>
|
||||
<DeleteConfirm
|
||||
key={pendingDelete.id}
|
||||
open
|
||||
title={pendingDelete.items[0]?.label ?? ""}
|
||||
count={pendingDelete.items.length}
|
||||
automations={pendingDelete.automations}
|
||||
onCancel={() => {
|
||||
pendingDelete.onDecision?.(false);
|
||||
setPendingDelete(null);
|
||||
}}
|
||||
onCancel={() => finishDeleteConfirmation(pendingDelete, false)}
|
||||
onConfirm={onConfirmDelete}
|
||||
/>
|
||||
</Suspense>
|
||||
@@ -2789,19 +2889,6 @@ function Shell({
|
||||
/>
|
||||
</Suspense>
|
||||
) : null}
|
||||
{restartToast ? (
|
||||
<div className="fixed left-1/2 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 flex w-[min(32rem,calc(100vw-1rem))] -translate-x-1/2 flex-col items-center gap-2">
|
||||
<div
|
||||
role="status"
|
||||
className={cn(
|
||||
floatingSurfaceElevationClassName,
|
||||
"max-w-full rounded-full px-4 py-2 text-sm font-medium",
|
||||
)}
|
||||
>
|
||||
{restartToast}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<ChannelPairing />
|
||||
</div>
|
||||
</ThemeProvider>
|
||||
|
||||
@@ -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<HTMLDivElement>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [highlightedSource, setHighlightedSource] = useState<string | null>(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 (
|
||||
<div
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { TOAST_ACTION_MS } from "@/components/ui/toast";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -65,11 +66,7 @@ export function DeleteConfirm({
|
||||
defaultValue: "Linked automations will also be deleted.",
|
||||
})
|
||||
: t("deleteConfirm.automationsDescription")
|
||||
: multiple
|
||||
? t("deleteConfirm.descriptionMany", {
|
||||
defaultValue: "This action cannot be undone.",
|
||||
})
|
||||
: t("deleteConfirm.description")}
|
||||
: t("toast.deleteWindow", { seconds: TOAST_ACTION_MS / 1_000 })}
|
||||
</AlertDialogDescription>
|
||||
{hasAutomations ? (
|
||||
<div className="mt-4 max-h-40 w-full overflow-y-auto rounded-2xl bg-muted/55 px-3 py-2 text-left">
|
||||
|
||||
@@ -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<FileReferenceMetadata | null>(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 };
|
||||
|
||||
@@ -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<number | null>(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 };
|
||||
|
||||
@@ -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<HTMLDivElement>(null);
|
||||
const mono = useRef<HTMLSpanElement>(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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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({
|
||||
<ModelPresetDeleteDialog
|
||||
preset={modelState.modelPresetPendingDelete}
|
||||
deleting={modelState.saving}
|
||||
error={modelState.modelPresetPendingDelete ? modelState.modelPresetDeleteError : null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
modelState.setModelPresetPendingDelete(null);
|
||||
@@ -728,6 +734,7 @@ export function SettingsPage({
|
||||
<AutomationDeleteDialog
|
||||
job={systemState.automationPendingDelete}
|
||||
deleting={systemState.automationAction === `delete:${systemState.automationPendingDelete?.id ?? ""}`}
|
||||
error={systemState.automationPendingDelete ? systemState.automationDialogError : null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) systemState.setAutomationPendingDelete(null);
|
||||
}}
|
||||
@@ -737,6 +744,7 @@ export function SettingsPage({
|
||||
<AutomationEditDialog
|
||||
job={systemState.automationPendingEdit}
|
||||
saving={systemState.automationAction === `update:${systemState.automationPendingEdit?.id ?? ""}`}
|
||||
error={systemState.automationPendingEdit ? systemState.automationDialogError : null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) systemState.setAutomationPendingEdit(null);
|
||||
}}
|
||||
|
||||
@@ -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<string, unknown>) =>
|
||||
t(key, { defaultValue: fallback, ...(values ?? {}) });
|
||||
return (
|
||||
<Dialog open={preset !== null} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[440px]">
|
||||
<Dialog open={preset !== null} onOpenChange={(open) => { if (open || !deleting) onOpenChange(open); }}>
|
||||
<DialogContent showCloseButton={!deleting} className="max-w-[440px]">
|
||||
<DialogHeader className="text-left">
|
||||
<DialogTitle>
|
||||
{tx("settings.models.deletePresetTitle", "Delete model preset?")}
|
||||
@@ -175,6 +177,7 @@ export function ModelPresetDeleteDialog({
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error ? <p role="alert" className="break-words text-sm text-destructive">{error}</p> : null}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from "@/components/settings/models/providerForm";
|
||||
import type { ModelSettingsState } from "@/components/settings/models/useModelSettingsState";
|
||||
import { normalizeContextWindowTokens } from "@/components/settings/shared/ModelControls";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import {
|
||||
ApiError,
|
||||
cancelProviderOAuth,
|
||||
@@ -86,6 +87,7 @@ export function useModelSettingsActions({
|
||||
installCapabilities,
|
||||
configuredModelProviderOptions,
|
||||
}: ModelSettingsActionsOptions) {
|
||||
const showToast = useToast();
|
||||
const oauthMounted = useRef(true);
|
||||
useEffect(() => {
|
||||
oauthMounted.current = true;
|
||||
@@ -117,6 +119,7 @@ export function useModelSettingsActions({
|
||||
setModelPresetEditingName,
|
||||
setModelPresetNameError,
|
||||
setModelPresetPendingDelete,
|
||||
setModelPresetDeleteError,
|
||||
setProviderForms,
|
||||
setProviderOAuthCompleting,
|
||||
setProviderOAuthDialogError,
|
||||
@@ -392,7 +395,15 @@ export function useModelSettingsActions({
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setModelCallOrder(previousOrder);
|
||||
setError((err as Error).message);
|
||||
if (showToast && err instanceof ApiError && (err.status === 503 || err.status === 504)) {
|
||||
showToast({
|
||||
tone: "error",
|
||||
message: t("message.agentActivity.updateAgentSettingsFailed"),
|
||||
dedupeKey: "settings:models:call-order",
|
||||
});
|
||||
} else {
|
||||
setError((err as Error).message);
|
||||
}
|
||||
} finally {
|
||||
setModelCallOrderSaving(false);
|
||||
}
|
||||
@@ -423,14 +434,14 @@ export function useModelSettingsActions({
|
||||
return false;
|
||||
}
|
||||
setSaving(true);
|
||||
setModelPresetDeleteError(null);
|
||||
try {
|
||||
const payload = await deleteModelConfiguration(client, modelPresetPendingDelete.name);
|
||||
applyPayload(payload, { preserveCapabilityForms: true });
|
||||
setModelPresetPendingDelete(null);
|
||||
setError(null);
|
||||
return true;
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
setModelPresetDeleteError(err instanceof Error ? err.message : String(err));
|
||||
return false;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
|
||||
@@ -25,6 +25,7 @@ export function useModelSettingsState(initialSettings: SettingsPayload | null) {
|
||||
const [modelMigrationSaving, setModelMigrationSaving] = useState(false);
|
||||
const [modelPresetPendingDelete, setModelPresetPendingDelete] =
|
||||
useState<SettingsPayload["model_presets"][number] | null>(null);
|
||||
const [modelPresetDeleteError, setModelPresetDeleteError] = useState<string | null>(null);
|
||||
const modelPresetBeforeCreateRef = useRef<string | null>(null);
|
||||
const [providerOperation, setProviderOperation] = useState<ProviderOperation | null>(null);
|
||||
const providerSaving = providerOperation?.provider ?? null;
|
||||
@@ -76,6 +77,8 @@ export function useModelSettingsState(initialSettings: SettingsPayload | null) {
|
||||
setModelPresetEditingName,
|
||||
setModelPresetNameError,
|
||||
setModelPresetPendingDelete,
|
||||
modelPresetDeleteError,
|
||||
setModelPresetDeleteError,
|
||||
setProviderForms,
|
||||
setProviderOAuthCompleting,
|
||||
setProviderOAuthDialogError,
|
||||
|
||||
@@ -55,8 +55,10 @@ import {
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { isGenericRepositoryLogoUrl, logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
CliAppInfo,
|
||||
@@ -1463,17 +1465,20 @@ function CliAppReadyPanel({
|
||||
onBackToChat: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const prompt = t("settings.cliApps.readyPrompt", {
|
||||
name: app.name,
|
||||
defaultValue: "Use @{{name}} to inspect what this CLI can do.",
|
||||
});
|
||||
const copyPrompt = () => {
|
||||
if (!navigator.clipboard) return;
|
||||
void navigator.clipboard.writeText(prompt).then(() => {
|
||||
setCopied(true);
|
||||
const copyPrompt = async () => {
|
||||
const copied = await copyTextToClipboard(prompt);
|
||||
setCopied(copied);
|
||||
if (copied) {
|
||||
window.setTimeout(() => setCopied(false), 1400);
|
||||
});
|
||||
} else {
|
||||
showToast?.({ tone: "error", message: t("fileActions.failed"), dedupeKey: "settings:apps:copy-prompt" });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -690,12 +690,14 @@ const AUTOMATION_EVERY_UNITS: Array<{ value: AutomationEveryUnit; ms: number }>
|
||||
export function AutomationEditDialog({
|
||||
job,
|
||||
saving,
|
||||
error,
|
||||
onOpenChange,
|
||||
onCancel,
|
||||
onSave,
|
||||
}: {
|
||||
job: SessionAutomationJob | null;
|
||||
saving: boolean;
|
||||
error?: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCancel?: (job: SessionAutomationJob) => void;
|
||||
onSave: (job: SessionAutomationJob, values: AutomationUpdatePayload) => void | Promise<void>;
|
||||
@@ -727,11 +729,13 @@ export function AutomationEditDialog({
|
||||
|
||||
const submit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
const payload = automationUpdatePayloadFromDraft(draft, job);
|
||||
if (!job || typeof payload === "string") return;
|
||||
void onSave(job, payload);
|
||||
};
|
||||
const changeOpen = (open: boolean) => {
|
||||
if (!open && saving) return;
|
||||
onOpenChange(open);
|
||||
if (!open && job) onCancel?.(job);
|
||||
};
|
||||
@@ -745,6 +749,7 @@ export function AutomationEditDialog({
|
||||
<DialogContent
|
||||
{...dialogFocus}
|
||||
aria-describedby={undefined}
|
||||
showCloseButton={!saving}
|
||||
className="w-[min(calc(100vw-2rem),34rem)]"
|
||||
onEscapeKeyDown={(event) => {
|
||||
// Escape in the nested date calendar must not cancel the editor.
|
||||
@@ -879,6 +884,7 @@ export function AutomationEditDialog({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{error ? <AutomationError message={error} /> : null}
|
||||
{validation ? (
|
||||
<div id={validationId} className="rounded-control bg-destructive/8 px-3 py-2 text-[12px] text-destructive">
|
||||
{validation}
|
||||
@@ -910,11 +916,13 @@ export function AutomationEditDialog({
|
||||
export function AutomationDeleteDialog({
|
||||
job,
|
||||
deleting,
|
||||
error,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
}: {
|
||||
job: SessionAutomationJob | null;
|
||||
deleting: boolean;
|
||||
error?: string | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: (job: SessionAutomationJob) => void | Promise<void>;
|
||||
}) {
|
||||
@@ -923,8 +931,8 @@ export function AutomationDeleteDialog({
|
||||
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
|
||||
t(key, { defaultValue: fallback, ...(values ?? {}) });
|
||||
return (
|
||||
<Dialog open={Boolean(job)} onOpenChange={onOpenChange}>
|
||||
<DialogContent {...dialogFocus} className="w-[min(calc(100vw-2rem),26rem)]">
|
||||
<Dialog open={Boolean(job)} onOpenChange={(open) => { if (open || !deleting) onOpenChange(open); }}>
|
||||
<DialogContent {...dialogFocus} showCloseButton={!deleting} className="w-[min(calc(100vw-2rem),26rem)]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{tx("settings.automations.deleteTitle", "Delete automation")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -935,6 +943,7 @@ export function AutomationDeleteDialog({
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error ? <AutomationError message={error} /> : null}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
StatusPill,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { getRuntimeHost, isNativeRuntime } from "@/lib/runtime";
|
||||
import type { NanobotFeatureInfo, SettingsPayload } from "@/lib/types";
|
||||
|
||||
@@ -38,6 +39,7 @@ export function RuntimeSettings({
|
||||
onInstallCapability: (name: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const runtimeSurface = settings.surface ?? settings.runtime_surface;
|
||||
const runtimeHost = getRuntimeHost(runtimeSurface, settings.runtime_capabilities);
|
||||
@@ -84,7 +86,11 @@ export function RuntimeSettings({
|
||||
const result = await action();
|
||||
setHostActionMessage({ target, message: successMessage(result) });
|
||||
} catch {
|
||||
setHostActionMessage({ target, message: failureMessage });
|
||||
if (showToast) {
|
||||
showToast({ tone: "error", message: failureMessage, dedupeKey: `settings:runtime:${target}` });
|
||||
} else {
|
||||
setHostActionMessage({ target, message: failureMessage });
|
||||
}
|
||||
} finally {
|
||||
setHostActionBusy(null);
|
||||
}
|
||||
|
||||
@@ -93,6 +93,7 @@ export function createSystemSettingsActions({
|
||||
nanobotFeatureActionRef,
|
||||
nanobotFeatures,
|
||||
setAutomationAction,
|
||||
setAutomationDialogError,
|
||||
setAutomationPendingDelete,
|
||||
setAutomationPendingEdit,
|
||||
setAutomations,
|
||||
@@ -230,8 +231,9 @@ export function createSystemSettingsActions({
|
||||
job: SessionAutomationJob,
|
||||
) => {
|
||||
const key = `${action}:${job.id}`;
|
||||
const reportError = action === "delete" ? setAutomationDialogError : setAutomationsError;
|
||||
setAutomationAction(key);
|
||||
setAutomationsError(null);
|
||||
reportError(null);
|
||||
try {
|
||||
const payload = await runAutomationAction(client, action, job.id);
|
||||
setAutomations(payload);
|
||||
@@ -241,7 +243,7 @@ export function createSystemSettingsActions({
|
||||
window.setTimeout(() => void refreshAutomations(false), 4000);
|
||||
}
|
||||
} catch (err) {
|
||||
setAutomationsError((err as Error).message);
|
||||
reportError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setAutomationAction(null);
|
||||
}
|
||||
@@ -253,13 +255,13 @@ export function createSystemSettingsActions({
|
||||
) => {
|
||||
const key = `update:${job.id}`;
|
||||
setAutomationAction(key);
|
||||
setAutomationsError(null);
|
||||
setAutomationDialogError(null);
|
||||
try {
|
||||
const payload = await updateAutomation(client, job.id, values);
|
||||
setAutomations(payload);
|
||||
setAutomationPendingEdit(null);
|
||||
} catch (err) {
|
||||
setAutomationsError((err as Error).message);
|
||||
setAutomationDialogError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setAutomationAction(null);
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
|
||||
const [mcpMessage, setMcpMessage] = useState<string | null>(null);
|
||||
const [mcpError, setMcpError] = useState<string | null>(null);
|
||||
const [automationsError, setAutomationsError] = useState<string | null>(null);
|
||||
const [automationDialogError, setAutomationDialogError] = useState<string | null>(null);
|
||||
const [automationAction, setAutomationAction] = useState<string | null>(null);
|
||||
const [automationPendingDelete, setAutomationPendingDelete] =
|
||||
useState<SessionAutomationJob | null>(null);
|
||||
@@ -106,6 +107,8 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
|
||||
setAutomationPendingEdit,
|
||||
setAutomations,
|
||||
setAutomationsError,
|
||||
automationDialogError,
|
||||
setAutomationDialogError,
|
||||
setAutomationsFilter,
|
||||
setAutomationsLoading,
|
||||
setCliApps,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
|
||||
import type { GoalStateWsPayload } from "@/lib/types";
|
||||
|
||||
@@ -18,7 +19,7 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
const [cancelFailed, setCancelFailed] = useState(false);
|
||||
const showToast = useToast();
|
||||
const [scrollBody, setScrollBody] = useState<HTMLDivElement | null>(null);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const escapeFocus = useOverlayEscapeFocus();
|
||||
@@ -53,11 +54,10 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
title={cancelDisabled ? t("thread.composer.cancelGoalOffline") : undefined}
|
||||
onClick={async () => {
|
||||
setCancelling(true);
|
||||
setCancelFailed(false);
|
||||
try {
|
||||
await onCancel();
|
||||
} catch {
|
||||
setCancelFailed(true);
|
||||
showToast?.({ message: t("thread.composer.cancelGoalFailed"), tone: "error", dedupeKey: "cancel-goal" });
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!scrollBody) return;
|
||||
if (status === "blocked" || cancelFailed) scrollBody.scrollTop = 0;
|
||||
if (status === "blocked") scrollBody.scrollTop = 0;
|
||||
const measure = () => {
|
||||
scrollBody.toggleAttribute("data-overflow-top", scrollBody.scrollTop > 1);
|
||||
scrollBody.toggleAttribute("data-overflow-bottom", scrollBody.scrollHeight - scrollBody.clientHeight - scrollBody.scrollTop > 1);
|
||||
@@ -80,7 +80,7 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
observer.disconnect();
|
||||
scrollBody.removeEventListener("scroll", measure);
|
||||
};
|
||||
}, [scrollBody, status, cancelFailed]);
|
||||
}, [scrollBody, status]);
|
||||
|
||||
return (
|
||||
<div className="goal-island-position">
|
||||
@@ -120,7 +120,6 @@ export function GoalIsland({ goal, cancelDisabled, onCancel }: {
|
||||
</div> : null}
|
||||
<div ref={setScrollBody} className="goal-island-body">
|
||||
<div className="goal-island-document">
|
||||
{cancelFailed ? <p role="alert" className="mb-2 text-caption text-destructive">{t("thread.composer.cancelGoalFailed")}</p> : null}
|
||||
{status === "blocked" ? <div className="goal-island-blocked">
|
||||
<CircleAlert className="goal-island-status-icon" strokeWidth={2.5} aria-hidden="true" />
|
||||
<span className="sr-only">{t("thread.composer.goalBlocked")}</span>
|
||||
|
||||
@@ -87,6 +87,7 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
|
||||
setDetailOpen(true);
|
||||
};
|
||||
const handOffDetail = (next: () => void) => {
|
||||
setActionError(null);
|
||||
afterDetailClose.current = next;
|
||||
setDetailOpen(false);
|
||||
};
|
||||
@@ -249,8 +250,12 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
|
||||
<AutomationEditDialog
|
||||
job={pendingEdit}
|
||||
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
|
||||
error={pendingEdit ? actionError : null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingEdit(null);
|
||||
if (!nextOpen) {
|
||||
setPendingEdit(null);
|
||||
setActionError(null);
|
||||
}
|
||||
}}
|
||||
onCancel={(job) => {
|
||||
setInspectedJob(job);
|
||||
@@ -261,8 +266,12 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
|
||||
<AutomationDeleteDialog
|
||||
job={pendingDelete}
|
||||
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
|
||||
error={pendingDelete ? actionError : null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingDelete(null);
|
||||
if (!nextOpen) {
|
||||
setPendingDelete(null);
|
||||
setActionError(null);
|
||||
}
|
||||
}}
|
||||
onConfirm={(job) => handleAction("delete", job)}
|
||||
/>
|
||||
|
||||
@@ -66,6 +66,7 @@ import {
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
|
||||
import { ComposerActionIcon, type ComposerActionState } from "@/components/thread/ComposerActionIcon";
|
||||
import {
|
||||
@@ -153,8 +154,6 @@ import {
|
||||
|
||||
const VOICE_SHORTCUT_CODE = "KeyD";
|
||||
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
|
||||
const VOICE_ERROR_VISIBLE_MS = 3_500;
|
||||
const VOICE_ERROR_FADE_MS = 500;
|
||||
type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows";
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
@@ -621,6 +620,8 @@ export function ThreadComposer({
|
||||
end: number;
|
||||
} | null>(null);
|
||||
const [inlineError, setInlineError] = useState<string | null>(null);
|
||||
const [voiceSetupError, setVoiceSetupError] = useState<VoiceRecorderErrorKey | null>(null);
|
||||
const showToast = useToast();
|
||||
const [sendPending, setSendPending] = useState(false);
|
||||
const [pathInspection, setPathInspection] = useState<{
|
||||
generation: number; scope: string; range: PastedPathRange; attachment?: LocalAttachment;
|
||||
@@ -713,7 +714,6 @@ export function ThreadComposer({
|
||||
useEffect(() => {
|
||||
if (queueSnapshot.error) setInlineError(queueSnapshot.error);
|
||||
}, [queueSnapshot.error]);
|
||||
const [voiceErrorFading, setVoiceErrorFading] = useState(false);
|
||||
const [slashMenuDismissed, setSlashMenuDismissed] = useState(false);
|
||||
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
|
||||
const [cliAppMenuDismissed, setCliAppMenuDismissed] = useState(false);
|
||||
@@ -756,7 +756,6 @@ export function ThreadComposer({
|
||||
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const previousPendingQueueKeyRef = useRef(pendingQueueKey);
|
||||
const voiceShortcutDownRef = useRef(false);
|
||||
const voiceErrorFadeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const isHero = variant === "hero";
|
||||
const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []);
|
||||
const projectPickerAvailable =
|
||||
@@ -818,6 +817,10 @@ export function ThreadComposer({
|
||||
const { rejected } = enqueue(files);
|
||||
if (rejected.length > 0) {
|
||||
const { reason, file } = rejected[0];
|
||||
if (reason === "empty_file" || reason === "unsupported_type") {
|
||||
showToast?.({ message: formatRejection(reason), tone: "error", dedupeKey: `attachment:${reason}` });
|
||||
return;
|
||||
}
|
||||
setInlineError(reason === "too_large"
|
||||
? formatUploadTooLarge(file.size, acceptedAttachmentKind(file) === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
|
||||
: formatRejection(reason));
|
||||
@@ -825,7 +828,7 @@ export function ThreadComposer({
|
||||
setInlineError(null);
|
||||
}
|
||||
},
|
||||
[enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes],
|
||||
[enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes, showToast],
|
||||
);
|
||||
|
||||
const {
|
||||
@@ -1391,6 +1394,7 @@ export function ThreadComposer({
|
||||
previousPendingQueueKeyRef.current = pendingQueueKey;
|
||||
setValue("");
|
||||
setInlineError(null);
|
||||
setVoiceSetupError(null);
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setCursorPosition(0);
|
||||
@@ -1407,43 +1411,27 @@ export function ThreadComposer({
|
||||
});
|
||||
setSlashMenuDismissed(false);
|
||||
setCliAppMenuDismissed(false);
|
||||
setInlineError(null);
|
||||
focusTextarea();
|
||||
}, [focusTextarea]);
|
||||
|
||||
const clearVoiceErrorTimers = useCallback(() => {
|
||||
if (voiceErrorFadeTimerRef.current !== null) clearTimeout(voiceErrorFadeTimerRef.current);
|
||||
voiceErrorFadeTimerRef.current = null;
|
||||
}, []);
|
||||
const clearInlineError = useCallback(() => {
|
||||
clearVoiceErrorTimers();
|
||||
setVoiceErrorFading(false);
|
||||
setInlineError(null);
|
||||
}, [clearVoiceErrorTimers]);
|
||||
const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []);
|
||||
const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => {
|
||||
clearVoiceErrorTimers();
|
||||
setVoiceErrorFading(false);
|
||||
setInlineError(t(`thread.composer.voiceErrors.${key}`));
|
||||
voiceErrorFadeTimerRef.current = setTimeout(() => {
|
||||
setVoiceErrorFading(true);
|
||||
voiceErrorFadeTimerRef.current = setTimeout(() => {
|
||||
setInlineError(null);
|
||||
setVoiceErrorFading(false);
|
||||
voiceErrorFadeTimerRef.current = null;
|
||||
}, VOICE_ERROR_FADE_MS);
|
||||
}, VOICE_ERROR_VISIBLE_MS);
|
||||
}, [clearVoiceErrorTimers, t]);
|
||||
// Setup blockers carry instructions users may need to keep in view while fixing them.
|
||||
if (key === "insecureContext" || key === "permission" || key === "notConfigured") {
|
||||
setVoiceSetupError(key);
|
||||
return;
|
||||
}
|
||||
showToast?.({ message: t(`thread.composer.voiceErrors.${key}`), tone: "error", dedupeKey: "voice-input" });
|
||||
}, [showToast, t]);
|
||||
const voiceRecorder = useVoiceRecorder({
|
||||
disabled: interactionDisabled,
|
||||
onClearError: clearInlineError,
|
||||
onClearError: clearVoiceSetupError,
|
||||
onError: setVoiceError,
|
||||
onTranscript: appendTranscription,
|
||||
onTranscribeAudio,
|
||||
wantsWav: transcriptionProvider === "xiaomi_mimo",
|
||||
});
|
||||
|
||||
useEffect(() => () => clearVoiceErrorTimers(), [clearVoiceErrorTimers]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onTranscribeAudio) return;
|
||||
|
||||
@@ -1940,7 +1928,7 @@ export function ThreadComposer({
|
||||
: showStopButton ? "stop" : requiresModelSetup ? "setup" : canSend || !isStreaming ? "send" : "busy";
|
||||
const relaxedHeroInput = isHero && images.length === 0 && !isStreaming;
|
||||
const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused
|
||||
&& value.length === 0 && images.length === 0 && !inlineError
|
||||
&& value.length === 0 && images.length === 0 && !inlineError && !(onTranscribeAudio && voiceSetupError)
|
||||
&& !normalizedQuotedContext && !queuedPrompt
|
||||
&& !isDragging && !sessionDragPreview && !voiceRecorder.isRecording && !showProjectPicker;
|
||||
useLayoutEffect(() => {
|
||||
@@ -2229,16 +2217,9 @@ export function ThreadComposer({
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{inlineError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className={cn(
|
||||
"mx-3 mb-1 max-h-24 overflow-hidden rounded-md border border-destructive/40 bg-destructive/8 px-2.5 py-1",
|
||||
"text-[11.5px] font-medium text-destructive transition-[max-height,margin,padding,opacity] [transition-duration:220ms] ease-out motion-reduce:transition-none",
|
||||
voiceErrorFading && "mb-0 max-h-0 border-transparent py-0 opacity-0",
|
||||
)}
|
||||
>
|
||||
{inlineError}
|
||||
{inlineError || (onTranscribeAudio && voiceSetupError) ? (
|
||||
<div role="alert" className="mx-3 mb-1 break-words rounded-md border border-destructive/40 bg-destructive/8 px-2.5 py-1 text-[11.5px] font-medium text-destructive">
|
||||
{inlineError ?? t(`thread.composer.voiceErrors.${voiceSetupError}`)}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
.toast-card {
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: var(--radius-pill);
|
||||
background: hsl(var(--popover));
|
||||
color: hsl(var(--popover-foreground));
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.04), 0 8px 24px -10px rgb(0 0 0 / 0.16);
|
||||
animation: toast-enter 180ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
|
||||
}
|
||||
|
||||
.dark .toast-card {
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.18), 0 8px 24px -8px rgb(0 0 0 / 0.45);
|
||||
}
|
||||
|
||||
.toast-card::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
border-radius: inherit;
|
||||
--toast-sweep-width: 2.75rem;
|
||||
background-image: linear-gradient(var(--toast-sweep-direction, to right), transparent, hsl(var(--popover-foreground) / 0.055));
|
||||
background-repeat: no-repeat;
|
||||
background-size: var(--toast-sweep-width) 100%;
|
||||
animation: toast-shadow-sweep var(--toast-duration) linear both;
|
||||
animation-play-state: var(--toast-play-state);
|
||||
}
|
||||
|
||||
.toast-card:dir(rtl)::before {
|
||||
--toast-sweep-direction: to left;
|
||||
animation-direction: reverse;
|
||||
}
|
||||
|
||||
@keyframes toast-shadow-sweep {
|
||||
from { background-position: calc(0% - var(--toast-sweep-width)) 0; }
|
||||
to { background-position: calc(100% + var(--toast-sweep-width)) 0; }
|
||||
}
|
||||
|
||||
@keyframes toast-enter {
|
||||
from { opacity: 0; transform: translateY(-0.25rem); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.toast-card { animation: none; }
|
||||
.toast-card::before { content: none; }
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Check, Trash2, TriangleAlert } from "lucide-react";
|
||||
import { createContext, useCallback, useContext, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import "./toast.css";
|
||||
|
||||
const TOAST_NOTICE_MS = 3_000;
|
||||
export const TOAST_ACTION_MS = 8_000;
|
||||
|
||||
type ToastNotice = {
|
||||
message: string;
|
||||
detail?: string;
|
||||
tone: "success" | "error" | "pending";
|
||||
dedupeKey?: string;
|
||||
action?: { label: string; run: () => void };
|
||||
onExpire?: () => void;
|
||||
};
|
||||
|
||||
function toastDurationMs(notice: ToastNotice) {
|
||||
return notice.action ? TOAST_ACTION_MS : TOAST_NOTICE_MS;
|
||||
}
|
||||
|
||||
type ToastEntry = ToastNotice & { id: number };
|
||||
const ToastContext = createContext<((notice: ToastNotice) => void) | null>(null);
|
||||
export const useToast = () => useContext(ToastContext);
|
||||
|
||||
function ToastViewport({ children, viewportRef, hidden }: { children: ReactNode; viewportRef: Ref<HTMLDivElement>; hidden: boolean }) {
|
||||
return <div ref={viewportRef} className="pointer-events-none fixed inset-x-3 top-[calc(0.75rem+env(safe-area-inset-top))] z-50 mx-auto flex max-w-[22rem] flex-col items-center gap-2 [.native-host_&]:top-12" style={hidden ? { visibility: "hidden" } : undefined}>
|
||||
{children}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ToastCard({ notice, paused, onAction, onHoverChange, onFocusChange }: {
|
||||
notice: ToastNotice;
|
||||
paused: boolean;
|
||||
onAction: () => void;
|
||||
onHoverChange?: (hovered: boolean) => void;
|
||||
onFocusChange?: (focused: boolean) => void;
|
||||
}) {
|
||||
const { message, detail, tone, action } = notice;
|
||||
const Icon = tone === "error" ? TriangleAlert : tone === "pending" ? Trash2 : Check;
|
||||
return <div
|
||||
className={`toast-card isolate relative flex min-h-10 max-w-full items-center gap-2 px-3 py-0.5${action ? " pointer-events-auto" : ""}`}
|
||||
style={{
|
||||
"--toast-duration": `${toastDurationMs(notice)}ms`,
|
||||
"--toast-play-state": paused ? "paused" : "running",
|
||||
} as CSSProperties}
|
||||
onPointerEnter={(event) => { if (event.pointerType !== "touch") onHoverChange?.(true); }}
|
||||
onPointerLeave={() => onHoverChange?.(false)}
|
||||
onFocus={() => onFocusChange?.(true)}
|
||||
onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) onFocusChange?.(false); }}
|
||||
data-toast-tone={tone}
|
||||
>
|
||||
<Icon aria-hidden="true" size={15} strokeWidth={2} className="shrink-0" />
|
||||
<div role={tone === "error" ? "alert" : "status"} className="min-w-0 truncate text-sm leading-5"
|
||||
title={detail ? `${message} ${detail}` : message}>
|
||||
<span className={detail ? "text-muted-foreground" : "font-medium"}>{message}</span>
|
||||
{detail && <> <span className="font-medium">{detail}</span></>}
|
||||
</div>
|
||||
{action && <Button type="button" variant="ghost" size="sm" onClick={onAction} className="h-8 shrink-0 px-2">{action.label}</Button>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
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 <ToastCard notice={entry} paused={paused} onAction={() => finish(entry, "action")}
|
||||
onHoverChange={entry.action ? setHovered : undefined} onFocusChange={entry.action ? setFocused : undefined} />;
|
||||
}
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [entries, setEntries] = useState<ToastEntry[]>([]);
|
||||
const [unavailable, setUnavailable] = useState(false);
|
||||
const viewportRef = useRef<HTMLDivElement>(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<number, ToastEntry>());
|
||||
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 <ToastContext.Provider value={show}>
|
||||
{children}
|
||||
<ToastViewport viewportRef={viewportRef} hidden={unavailable}>
|
||||
{entries.map((entry) => <TimedToast key={entry.id} entry={entry} finish={finish} unavailable={unavailable} />)}
|
||||
</ToastViewport>
|
||||
</ToastContext.Provider>;
|
||||
}
|
||||
@@ -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() {
|
||||
</div>;
|
||||
}
|
||||
|
||||
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 <div className="flex flex-wrap gap-3">
|
||||
<Button variant="outline" onClick={() => show?.({ tone: "error", message: t("controls.toast.error"), dedupeKey: "example-error" })}>
|
||||
{t("controls.toast.showError")}
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={remove} disabled={removed}>{t("controls.alert.remove")}</Button>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function Sheets() {
|
||||
const { t } = useGalleryTranslation();
|
||||
return <Sheet><SheetTrigger asChild><Button variant="outline">{t("controls.sheet.open")}</Button></SheetTrigger>
|
||||
@@ -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: '<Button onClick={() => setOpen(true)}>Remove</Button>\n<AlertDialog open={open} onOpenChange={setOpen}>\n <AlertDialogContent><AlertDialogTitle>Remove item?</AlertDialogTitle><AlertDialogDescription>This removes the item.</AlertDialogDescription><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={removeItem}>Remove</AlertDialogAction></AlertDialogContent>\n</AlertDialog>' },
|
||||
{ title: "controls.toast.title", files: ["toast"], Preview: () => <ToastProvider><ToastActions /></ToastProvider>,
|
||||
description: "controls.toast.description", options: "controls.toast.options",
|
||||
code: '<ToastProvider><ExampleActions /></ToastProvider>\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: '<Sheet><SheetTrigger asChild><Button>Details</Button></SheetTrigger><SheetContent side="right"><SheetTitle>Details</SheetTitle><SheetDescription>Additional information.</SheetDescription>{content}</SheetContent></Sheet>' },
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -106,6 +106,15 @@
|
||||
"removed": "サンプルを削除しました。",
|
||||
"available": "サンプルは利用可能です。"
|
||||
},
|
||||
"toast": {
|
||||
"title": "トースト通知",
|
||||
"description": "エラー、成功、取り消せる操作を短く知らせます。",
|
||||
"options": "ToastProvider を配置し、useToast を使って通知を表示します。操作ボタン付きの通知は長めに表示されます。",
|
||||
"showError": "エラーを表示",
|
||||
"error": "サンプルを保存できませんでした。",
|
||||
"pending": "サンプルを削除します。",
|
||||
"restored": "サンプルを復元しました。"
|
||||
},
|
||||
"sheet": {
|
||||
"title": "サイドパネル",
|
||||
"description": "表示領域の端に配置するモーダルパネル。",
|
||||
|
||||
@@ -106,6 +106,15 @@
|
||||
"removed": "예제를 제거했습니다.",
|
||||
"available": "예제를 사용할 수 있습니다."
|
||||
},
|
||||
"toast": {
|
||||
"title": "토스트 알림",
|
||||
"description": "오류, 성공, 실행 취소가 가능한 작업을 짧게 알립니다.",
|
||||
"options": "ToastProvider를 마운트한 뒤 useToast를 사용해 알림을 표시합니다. 작업 버튼이 있는 알림은 더 오래 표시됩니다.",
|
||||
"showError": "오류 표시",
|
||||
"error": "예제를 저장하지 못했습니다.",
|
||||
"pending": "예제가 삭제될 예정입니다.",
|
||||
"restored": "예제를 복원했습니다."
|
||||
},
|
||||
"sheet": {
|
||||
"title": "측면 패널",
|
||||
"description": "표시 영역의 가장자리에 붙는 모달 패널입니다.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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ị.",
|
||||
|
||||
@@ -106,6 +106,15 @@
|
||||
"removed": "示例已移除。",
|
||||
"available": "示例可用。"
|
||||
},
|
||||
"toast": {
|
||||
"title": "轻提示",
|
||||
"description": "简短提示错误、成功或可撤销操作。",
|
||||
"options": "挂载 ToastProvider,然后调用 useToast 显示提示。带操作的提示会停留更久,方便用户响应。",
|
||||
"showError": "显示错误",
|
||||
"error": "无法保存示例。",
|
||||
"pending": "即将移除示例。",
|
||||
"restored": "已恢复示例。"
|
||||
},
|
||||
"sheet": {
|
||||
"title": "侧边面板",
|
||||
"description": "贴靠视口边缘的模态面板。",
|
||||
|
||||
@@ -106,6 +106,15 @@
|
||||
"removed": "已移除範例。",
|
||||
"available": "範例可供使用。"
|
||||
},
|
||||
"toast": {
|
||||
"title": "浮動提示",
|
||||
"description": "簡短提示錯誤、成功或可復原的操作。",
|
||||
"options": "掛載 ToastProvider,再呼叫 useToast 顯示提示。附帶操作的提示會停留較久,方便使用者回應。",
|
||||
"showError": "顯示錯誤",
|
||||
"error": "無法儲存範例。",
|
||||
"pending": "即將移除範例。",
|
||||
"restored": "已還原範例。"
|
||||
},
|
||||
"sheet": {
|
||||
"title": "側邊面板",
|
||||
"description": "貼靠檢視區邊緣的模態面板。",
|
||||
|
||||
@@ -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<void>;
|
||||
save: (prepare: PrepareSidebarSave) => Promise<void>;
|
||||
rename: (key: string, title: string) => Promise<void>;
|
||||
} {
|
||||
const { client, token } = useClient();
|
||||
@@ -165,7 +171,7 @@ export function useSidebarState(
|
||||
const loadedRef = useRef(false);
|
||||
const connectionOpenRef = useRef(client.status === "open");
|
||||
const pendingPersistenceRef = useRef<SidebarStatePayload | null>(null);
|
||||
const pendingRenamesRef = useRef<PendingRename[]>([]);
|
||||
const pendingSavesRef = useRef<PendingSidebarSave[]>([]);
|
||||
const persistenceInFlightRef = useRef(false);
|
||||
const flushPersistenceRef = useRef<() => void>(() => {});
|
||||
const [state, setState] = useState<SidebarStatePayload>(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<void> => {
|
||||
const save = useCallback((prepare: PrepareSidebarSave): Promise<void> => {
|
||||
if (!loadedRef.current) return Promise.reject(new Error("Sidebar state is not loaded"));
|
||||
if (!connectionOpenRef.current) {
|
||||
return Promise.reject(new Error("WebUI connection is not open"));
|
||||
}
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
pendingRenamesRef.current.push({ key: key.trim(), title, resolve, reject });
|
||||
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 };
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "閉じる",
|
||||
|
||||
@@ -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": "닫기",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "关闭",
|
||||
|
||||
@@ -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": "關閉",
|
||||
|
||||
@@ -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(<App />);
|
||||
@@ -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(<App />);
|
||||
|
||||
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(<App />);
|
||||
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(<App />);
|
||||
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<HTMLElement>("[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(<App />);
|
||||
const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });
|
||||
fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Review notes"), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
|
||||
expect(await screen.findByRole("alertdialog", { name: "Delete this topic?" })).toBeVisible();
|
||||
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(<App />);
|
||||
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);
|
||||
|
||||
@@ -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(<ToastProvider><FileActions path="notes.md" metadata={details}><button>notes.md</button></FileActions></ToastProvider>);
|
||||
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;
|
||||
|
||||
@@ -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(<MessageBlockMenuActions message={message} />, { 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,
|
||||
|
||||
@@ -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 = <>
|
||||
<LocalShell initialRemote />
|
||||
{surface === "pairing popup" && <PairingCodePopup
|
||||
requests={[{ code: "ABCD-EFGH", channel: "telegram", sender_id: "alice" }]}
|
||||
total={1} busyCode={null} error={null} onApprove={noop} onDismiss={noop} />}
|
||||
</>;
|
||||
render(<RemoteInstances>{surface === "no provider" ? shell : <ToastProvider>{shell}</ToastProvider>}</RemoteInstances>);
|
||||
|
||||
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] }));
|
||||
|
||||
@@ -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(
|
||||
<SessionInfoPopover
|
||||
@@ -171,12 +173,54 @@ describe("SessionInfoPopover", () => {
|
||||
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(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" />);
|
||||
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();
|
||||
|
||||
@@ -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<Response>(() => {})));
|
||||
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<SettingsPayload>((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-/)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
</ClientProvider>,
|
||||
{ wrapper: ToastProvider },
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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(<ThreadComposer onSend={onSend} />);
|
||||
render(<ThreadComposer onSend={onSend} />, { 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();
|
||||
|
||||
@@ -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(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onTranscribeAudio={vi.fn(async () => "unused")}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
<ThreadComposer onSend={vi.fn()} onTranscribeAudio={vi.fn(async () => "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(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onTranscribeAudio={vi.fn(async () => "unused")}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
<ThreadComposer onSend={vi.fn()} onTranscribeAudio={vi.fn(async () => "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(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onTranscribeAudio={onTranscribeAudio}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
<ThreadComposer onSend={vi.fn()} onTranscribeAudio={onTranscribeAudio} />,
|
||||
{ wrapper: ToastProvider },
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
|
||||
|
||||
@@ -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, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
|
||||
render(<ToastProvider>{wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />)}</ToastProvider>);
|
||||
await act(async () => {});
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });
|
||||
|
||||
Reference in new issue
Block a user