The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Studios: each studio's own requests show the card alone too
Adarsh54579dbd2c1b
diff --git a/src/components/accounts-admin.tsx b/src/components/accounts-admin.tsxindex 4d0444ad..a5b931e9 100644--- a/src/components/accounts-admin.tsx+++ b/src/components/accounts-admin.tsx@@ -9,6 +9,7 @@ import { Button } from "@/components/ui/button";import { useViewer } from "@/lib/api";import { storageSize, timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { responseError, toastError } from "@/lib/refusals";/** An account as GET /api/admin/accounts lists it: who, and what it made (src/server/account-admin.ts). */export interface AccountRow {@@ -44,7 +45,7 @@ export async function adminCall<T>(url: string, method = "GET", body?: unknown):const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });if (res.status === 204) return undefined as T;const j = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, j.error ?? `Request failed (${res.status})`);return j;}@@ -66,7 +67,7 @@ export function useAdminAction() {await fn();toast.success(done);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {void qc.invalidateQueries({ queryKey: ["admin-accounts"] });void qc.invalidateQueries({ queryKey: ["admin-runs"] });diff --git a/src/components/ads/ad-chat.tsx b/src/components/ads/ad-chat.tsxindex db04a8d8..bb6bca34 100644--- a/src/components/ads/ad-chat.tsx+++ b/src/components/ads/ad-chat.tsx@@ -9,6 +9,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport type { BrandKit, Product } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useBrandChat, useEstimate, type ChatMessage } from "@/components/marketing/hooks";import { insertMention, mentionMatches, mentionQuery } from "./mention";@@ -67,7 +68,7 @@ function Proposal({ msg, brand, products, engine, onConfirmed }: { msg: ChatMessonClick={() =>confirm.mutate({ messageId: msg.id, engine },- { onSuccess: (r) => (toast.success(`Generating ${total} ads`, { duration: 1500 }), onConfirmed(r.batchId)), onError: (e) => toast.error((e as Error).message) },+ { onSuccess: (r) => (toast.success(`Generating ${total} ads`, { duration: 1500 }), onConfirmed(r.batchId)), onError: (e) => toastError(e) },)}disabled={confirm.isPending}@@ -116,7 +117,7 @@ export function AdChat({ brand, products, engine, onBatch, onClose, className }:if (!v) return;setText("");setMenu("closed");- say.mutate(v, { onError: (e) => toast.error((e as Error).message) });+ say.mutate(v, { onError: (e) => toastError(e) });};const insert = (p: Product) => {const at = box.current?.selectionStart ?? caret;diff --git a/src/components/ads/ad-editor.tsx b/src/components/ads/ad-editor.tsxindex 547c0db3..ca848add 100644--- a/src/components/ads/ad-editor.tsx+++ b/src/components/ads/ad-editor.tsx@@ -10,6 +10,7 @@ import { areaCls, inputCls } from "@/components/brand/fields";import { uploadFile } from "@/lib/api";import type { BrandKit } from "@/lib/catalog/marketing";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { AdCanvas } from "./ad-canvas";import { AD_LAYOUTS, exportName, themeFrom, type AdLayout } from "./layout";import { downloadBlob, exportPng, type RenderInput } from "./render";@@ -99,7 +100,7 @@ export function AdEditor({toast.success("Saved to your library", { duration: 2000 });}} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy("");}diff --git a/src/components/ads/ads-home.tsx b/src/components/ads/ads-home.tsxindex 96fcdbeb..d723f4cd 100644--- a/src/components/ads/ads-home.tsx+++ b/src/components/ads/ads-home.tsx@@ -13,6 +13,7 @@ import { ResearchLabel } from "@/components/brand/research-progress";import type { BrandKit } from "@/lib/catalog/marketing";import { timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useBrandActions, useBrands } from "@/components/marketing/hooks";import { MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";@@ -80,7 +81,7 @@ function DeleteBrand({ brand, onClose }: { brand: BrandKit | null; onClose: () =onClick={() =>actions.remove.mutate(undefined, {onSuccess: () => toast("Brand deleted", { duration: 1500 }),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/ads/brand-workspace.tsx b/src/components/ads/brand-workspace.tsxindex 014d4d01..0a4c8aad 100644--- a/src/components/ads/brand-workspace.tsx+++ b/src/components/ads/brand-workspace.tsx@@ -11,6 +11,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { BrandKitForm, BrandSummary } from "@/components/brand/brand-kit-form";import { ResearchProgress } from "@/components/brand/research-progress";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useBrand, useBrandActions, useCreatives } from "@/components/marketing/hooks";import { MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";import { AdChat } from "./ad-chat";@@ -128,7 +129,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {<div className="mt-4 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-highlight/20 px-4 py-3 text-[13px]"><span>{brand.error ?? brand.note ?? "Research canceled — the kit keeps what it found."}</span>{brand.website && (- <Button variant="outline" size="sm" onClick={() => actions.retry.mutate(undefined, { onError: (e) => toast.error((e as Error).message) })} disabled={actions.retry.isPending}>+ <Button variant="outline" size="sm" onClick={() => actions.retry.mutate(undefined, { onError: (e) => toastError(e) })} disabled={actions.retry.isPending}>{actions.retry.isPending ? <Loader2 className="animate-spin" /> : <RefreshCw />} Retry research</Button>)}diff --git a/src/components/ads/creative-grid.tsx b/src/components/ads/creative-grid.tsxindex 19ef5c18..262e1eb3 100644--- a/src/components/ads/creative-grid.tsx+++ b/src/components/ads/creative-grid.tsx@@ -9,6 +9,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@import { Switch } from "@/components/ui/switch";import { AD_ANGLES, AD_RATIOS, creativeStatusText, type AdCreative, type AdRatio, type BrandKit, type Product } from "@/lib/catalog/marketing";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useCreativeActions } from "@/components/marketing/hooks";import { AdCanvas } from "./ad-canvas";import { AdEditor, downloadFormats, renderInput } from "./ad-editor";@@ -53,7 +54,7 @@ function CreativeCard({ c, brand, ratio, product, n, onEdit }: { c: AdCreative;{c.error && <p className="mt-1 line-clamp-3 text-[12px] text-muted-foreground">{c.error}</p>}<buttontype="button"- onClick={() => retry.mutate(c.id, { onError: (e) => toast.error((e as Error).message) })}+ onClick={() => retry.mutate(c.id, { onError: (e) => toastError(e) })}className="mt-2 inline-flex h-7 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent"title="Retry uses credits again">@@ -200,7 +201,7 @@ export function CreativeGrid({ brand, products, creatives }: { brand: BrandKit;brand={brand}productName={byId.get(editing.productId ?? "")?.name}number={number.get(editing.id)}- onSaveText={(t) => update.mutate({ id: editing.id, headline: t.headline, body: t.body, cta: t.cta, layout: t.layout }, { onSuccess: () => toast("Saved", { duration: 1200 }), onError: (e) => toast.error((e as Error).message) })}+ onSaveText={(t) => update.mutate({ id: editing.id, headline: t.headline, body: t.body, cta: t.cta, layout: t.layout }, { onSuccess: () => toast("Saved", { duration: 1200 }), onError: (e) => toastError(e) })}onSaveToLibrary={async (url, r) => {await save.mutateAsync({ id: editing.id, url, ratio: r });}}diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxindex 4e34c4d7..13d3926a 100644--- a/src/components/ads/multiplier.tsx+++ b/src/components/ads/multiplier.tsx@@ -18,6 +18,7 @@ import { probeBlob, probeUrl } from "@/lib/media-probe";import { useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { addRuns, send, useEstimate } from "@/components/marketing/hooks";import type { ModelInfo } from "@/components/marketing/model-info";import { RunsList } from "@/components/marketing/runs";@@ -295,7 +296,7 @@ export function AdMultiplier({ models }: { models: Record<string, ModelInfo> })toast.success(r.runs.length > 1 ? `Making ${r.runs.length} versions` : "Making your new version", { duration: 1600 });resultsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(null);}diff --git a/src/components/ads/new-ads.tsx b/src/components/ads/new-ads.tsxindex 52cf99da..0c860735 100644--- a/src/components/ads/new-ads.tsx+++ b/src/components/ads/new-ads.tsx@@ -10,6 +10,7 @@ import { AD_VISUAL_MODELS, MAX_ADS_PER_PRODUCT, MAX_PRODUCTS_PER_RUN, type Brandimport { useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import { formatCost } from "@/lib/format";+import { toastError } from "@/lib/refusals";import { useCreativeActions, useEstimate, useProductActions } from "@/components/marketing/hooks";interface BatchEstimate {@@ -79,7 +80,7 @@ export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKittoast.success(`Generating ${r.creatives.length} ads`, { duration: 1800 });onCreated(r.batchId);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});};const price = est.data ? (est.data.demo ? "Demo · free" : est.data.costUsd == null ? "price unknown" : est.data.costUsd === 0 ? "Free" : `≈ ${formatCost(est.data.costUsd)}`) : "";diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsxindex 3c0a0482..c4023655 100644--- a/src/components/assist-view.tsx+++ b/src/components/assist-view.tsx@@ -24,6 +24,7 @@ import { useAssistActions, useAssistThread, useEngine } from "@/lib/api";import { ASSIST_SUGGESTIONS, modeLabel, type AssistAvailability, type AssistModeChoice, type AssistProject, type AssistThread, type SkillSummary } from "@/lib/assist";import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";/** Skills offered as one-tap starters on the empty page (Supercomputer's suggestion cards). */const STARTER_SKILLS = ["product-photoshoot", "ugc-video", "thumbnail-generation", "faceless-video", "short-film", "localization"];@@ -200,7 +201,7 @@ export function AssistView() {{ASSIST_SUGGESTIONS.map((s) => (<buttonkey={s}- onClick={() => start(s).catch((e) => toast.error((e as Error).message))}+ onClick={() => start(s).catch((e) => toastError(e))}className="max-w-full rounded-full border bg-background px-3.5 py-1.5 text-left text-[13px] text-muted-foreground transition hover:border-primary hover:text-foreground">{s}@@ -243,7 +244,7 @@ export function AssistView() {availability={can}disabled={thread.status === "running"}applyOnClose- onChange={(c) => void actions.patch(thread.id, { mode: c }).catch((e) => toast.error((e as Error).message))}+ onChange={(c) => void actions.patch(thread.id, { mode: c }).catch((e) => toastError(e))}/><AskFirst checked={!thread.autoApprove} onChange={(v) => void assist.setAutoApprove(thread.id, !v)} /></>diff --git a/src/components/assist/chat-menu.tsx b/src/components/assist/chat-menu.tsxindex 10e1f07d..8db55828 100644--- a/src/components/assist/chat-menu.tsx+++ b/src/components/assist/chat-menu.tsx@@ -29,6 +29,7 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import type { AssistThreadSummary } from "@/lib/assist";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useChatActions, useProjects } from "./hooks";import { ProjectDot } from "./project-dot";@@ -58,7 +59,7 @@ export function ChatMenu({const p = projects.data?.find((x) => x.id === projectId);toast(p ? `Moved to ${p.name}` : "Moved out of the project", { duration: 1500 });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};const remove = async () => {@@ -67,7 +68,7 @@ export function ChatMenu({onDeleted?.();toast("Chat deleted", { duration: 1500 });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};return (@@ -143,7 +144,7 @@ function RenameForm({ chat, onDone }: { chat: Pick<AssistThreadSummary, "id" | "await actions.patch(chat.id, { title: t });onDone();} catch (err) {- toast.error((err as Error).message);+ toastError(err);} finally {setBusy(false);}diff --git a/src/components/assist/composer.tsx b/src/components/assist/composer.tsxindex da956662..fd333b26 100644--- a/src/components/assist/composer.tsx+++ b/src/components/assist/composer.tsx@@ -3,7 +3,6 @@import { ArrowUp, AudioLines, Loader2, Paperclip, Slash, X } from "lucide-react";import { nanoid } from "nanoid";import { useEffect, useId, useMemo, useRef, useState } from "react";-import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Kbd } from "@/components/ui/kbd";import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";@@ -143,7 +142,7 @@ export function AssistComposer({setText("");setFiles([]);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setSending(false);}diff --git a/src/components/assist/connectors-settings.tsx b/src/components/assist/connectors-settings.tsxindex 8c942552..3a9cf6ae 100644--- a/src/components/assist/connectors-settings.tsx+++ b/src/components/assist/connectors-settings.tsx@@ -20,6 +20,7 @@ import { Label } from "@/components/ui/label";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { checkConnectorUrl, MAX_CONNECTOR_NAME, MAX_CONNECTORS, parseToolList, type ConnectorView } from "@/lib/assist-connectors";+import { toastError } from "@/lib/refusals";import { useConnectorActions, useConnectors } from "./hooks";/**@@ -113,7 +114,7 @@ function Row({ c, onEdit }: { c: ConnectorView; onEdit: () => void }) {<div className="flex shrink-0 items-center gap-0.5"><Switchchecked={c.enabled}- onCheckedChange={(on) => void actions.update(c.id, { enabled: on }).catch((e) => toast.error((e as Error).message))}+ onCheckedChange={(on) => void actions.update(c.id, { enabled: on }).catch((e) => toastError(e))}aria-label={c.enabled ? `Switch off ${c.name}` : `Switch on ${c.name}`}/><Button size="icon" variant="ghost" className="size-8 text-muted-foreground" aria-label={`Edit ${c.name}`} onClick={onEdit}>@@ -131,7 +132,7 @@ function Row({ c, onEdit }: { c: ConnectorView; onEdit: () => void }) {</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="destructive" onClick={() => void actions.remove(c.id).catch((e) => toast.error((e as Error).message))}>+ <AlertDialogAction variant="destructive" onClick={() => void actions.remove(c.id).catch((e) => toastError(e))}>Delete</AlertDialogAction></AlertDialogFooter>@@ -177,7 +178,7 @@ function ConnectorForm({ connector, onDone }: { connector?: ConnectorView; onDon}onDone();} catch (err) {- toast.error((err as Error).message);+ toastError(err);} finally {setBusy(false);}diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.tsindex fdda011f..215a4bea 100644--- a/src/components/assist/hooks.ts+++ b/src/components/assist/hooks.ts@@ -22,6 +22,7 @@ import type { ScheduleRule, ScheduleView } from "@/lib/assist-schedule";import type { Engine, Generation } from "@/lib/catalog/types";import type { RecipeEstimate, RecipeRun, RecipeView, VerifyResult } from "@/lib/recipe";import type { DraftRefusal, Naming, SkillDraft } from "@/lib/recipe-builder";+import { responseError } from "@/lib/refusals";/** A rule as the dialog sends it: the server sets when "every N hours" starts counting. */export type ScheduleRuleInput = ScheduleRule extends infer R ? (R extends { kind: "hours" } ? Omit<R, "from"> : R) : never;@@ -35,7 +36,7 @@ export type ScheduleRuleInput = ScheduleRule extends infer R ? (R extends { kindasync function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { status: res.status });+ if (!res.ok) throw Object.assign(responseError(res, body.error ?? `Request failed (${res.status})`), { status: res.status });return body;}@@ -187,7 +188,7 @@ export type RecipeFailure = Error & { status?: number; problems?: string[] };async function recipeCall<T>(url: string, body: unknown): Promise<T> {const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });const out = (await res.json().catch(() => ({}))) as T & { error?: string; problems?: string[] };- if (!res.ok) throw Object.assign(new Error(out.error ?? `Request failed (${res.status})`), { status: res.status, problems: out.problems }) as RecipeFailure;+ if (!res.ok) throw Object.assign(responseError(res, out.error ?? `Request failed (${res.status})`), { status: res.status, problems: out.problems }) as RecipeFailure;return out;}@@ -469,7 +470,7 @@ export function useScheduleActions() {const body = (await r.json().catch(() => ({}))) as { threadId?: string | null; error?: string };refresh();if (r.status === 409) return null;- if (!r.ok) throw new Error(body.error ?? `Request failed (${r.status})`);+ if (!r.ok) throw responseError(r, body.error ?? `Request failed (${r.status})`);return body.threadId ?? null;},};diff --git a/src/components/assist/memory-view.tsx b/src/components/assist/memory-view.tsxindex 1ded1e88..8bf223f9 100644--- a/src/components/assist/memory-view.tsx+++ b/src/components/assist/memory-view.tsx@@ -26,6 +26,7 @@ import { copyText } from "@/lib/clipboard";import { guessCategory, MEMORY_CATEGORIES, MEMORY_HINTS, MEMORY_MAX_CHARS, parseMemoryImport, type AssistMemory, type AssistProject, type MemoryCategory, type MemoryScope } from "@/lib/assist";import { timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { useMemories, useMemoryActions, useProjects } from "./hooks";import { ProjectDot, RailButton } from "./shell";@@ -184,7 +185,7 @@ function MemoryRow({ m, project }: { m: AssistMemory; project?: AssistProject })await actions.update(m.id, { text, category });setEditing(false);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}@@ -240,7 +241,7 @@ function MemoryRow({ m, project }: { m: AssistMemory; project?: AssistProject })</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="destructive" onClick={() => void actions.remove(m.id).catch((e) => toast.error((e as Error).message))}>+ <AlertDialogAction variant="destructive" onClick={() => void actions.remove(m.id).catch((e) => toastError(e))}>Delete</AlertDialogAction></AlertDialogFooter>@@ -317,7 +318,7 @@ function AddForm({ place, projects, onDone }: { place: Place; projects: AssistPrtoast.success("Remembered", { duration: 1500 });onDone();} catch (err) {- toast.error((err as Error).message);+ toastError(err);} finally {setBusy(false);}@@ -387,7 +388,7 @@ function ImportForm({ place, projects, onDone }: { place: Place; projects: Assistoast.success(`Imported ${r.added} memor${r.added === 1 ? "y" : "ies"}`, { description: r.skipped ? `${r.skipped} were already there` : undefined });onDone();} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/assist/project-dialog.tsx b/src/components/assist/project-dialog.tsxindex c68e97e8..f64f43a4 100644--- a/src/components/assist/project-dialog.tsx+++ b/src/components/assist/project-dialog.tsx@@ -12,6 +12,7 @@ import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { PROJECT_COLORS, PROJECT_LIMITS, PROJECT_SWATCH, type AssistProject, type ProjectColor } from "@/lib/assist";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { useProjectActions, useSkills } from "./hooks";import { SkillIcon } from "./skill-icon";@@ -59,7 +60,7 @@ function Form({ project, onDone }: { project?: AssistProject; onDone: (p?: Assisif (!project) toast.success("Project created", { duration: 1500 });onDone(p);} catch (err) {- toast.error((err as Error).message);+ toastError(err);} finally {setBusy(false);}diff --git a/src/components/assist/project-view.tsx b/src/components/assist/project-view.tsxindex cbac6f64..d29cc9f0 100644--- a/src/components/assist/project-view.tsx+++ b/src/components/assist/project-view.tsx@@ -49,6 +49,7 @@ import { useElements, useEngine } from "@/lib/api";import { MAX_PROJECT_SOURCES, type AssistProject, type ProjectSource, type SourceKind } from "@/lib/assist";import { timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { ChatMenu } from "./chat-menu";import { useChatActions, useChats, useProject, useProjectActions, useProjectAssets, useSkills } from "./hooks";import { MemoryView } from "./memory-view";@@ -209,7 +210,7 @@ function Project({ p }: { p: AssistProject }) {toast("Project deleted", { duration: 1500 });router.push("/assist");} catch (e) {- toast.error((e as Error).message);+ toastError(e);}}}>@@ -286,7 +287,7 @@ function Sources({ p }: { p: AssistProject }) {else toast.success(`Added ${s.title}`, { duration: 1500 });return true;} catch (e) {- toast.error((e as Error).message);+ toastError(e);return false;} finally {setBusy(null);@@ -444,7 +445,7 @@ function SourceRow({ s, projectId }: { s: ProjectSource; projectId: string }) {const r = await actions.refreshSource(projectId, s.id);toast(r.status === "ready" ? "Updated" : "Still can't read it", { duration: 1500 });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}@@ -453,7 +454,7 @@ function SourceRow({ s, projectId }: { s: ProjectSource; projectId: string }) {<RotateCw className={cn(busy && "animate-spin")} /></Button>)}- <Button variant="ghost" size="icon-sm" className="hover:text-destructive" aria-label={`Remove ${s.title}`} onClick={() => void actions.removeSource(projectId, s.id).catch((e) => toast.error((e as Error).message))}>+ <Button variant="ghost" size="icon-sm" className="hover:text-destructive" aria-label={`Remove ${s.title}`} onClick={() => void actions.removeSource(projectId, s.id).catch((e) => toastError(e))}><Trash2 /></Button></div>diff --git a/src/components/assist/run-skill-dialog.tsx b/src/components/assist/run-skill-dialog.tsxindex 0cd9d080..1ec4b8e7 100644--- a/src/components/assist/run-skill-dialog.tsx+++ b/src/components/assist/run-skill-dialog.tsx@@ -23,6 +23,7 @@ import { formatCost } from "@/lib/format";import { checkValues, isMediaType, parseRows, RECIPE_LIMITS, type RecipeEstimate, type RecipeParam, type RecipeView } from "@/lib/recipe";import { DEMO_NOTE } from "@/lib/recipe-builder";import { cn } from "@/lib/utils";+import { refusalShown, toastError } from "@/lib/refusals";import { useRecipe, useRecipeActions, useSkillActions, type RecipeFailure } from "./hooks";import { PlanJobs } from "./plan-jobs";import { SkillIcon } from "./skill-icon";@@ -142,6 +143,7 @@ function Loaded({ view, onClose, examples, intro }: { view: RecipeView; onClose:if (next.length && !next.includes(engine)) setEngine(next[0]);} catch (e) {const f = e as RecipeFailure;+ if (refusalShown(f)) return;setProblems(f.problems ?? [f.message]);toast.error(f.message);} finally {@@ -155,7 +157,7 @@ function Loaded({ view, onClose, examples, intro }: { view: RecipeView; onClose:await skillActions.toggle(name, true);await qc.invalidateQueries({ queryKey: ["assist-recipe", name] });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(null);}@@ -180,6 +182,7 @@ function Loaded({ view, onClose, examples, intro }: { view: RecipeView; onClose:onClose();} catch (e) {const f = e as RecipeFailure;+ if (refusalShown(f)) return;setProblems(f.problems ?? [f.message]);toast.error(f.message);} finally {diff --git a/src/components/assist/schedule-dialog.tsx b/src/components/assist/schedule-dialog.tsxindex b39ffad0..7f2d3f6c 100644--- a/src/components/assist/schedule-dialog.tsx+++ b/src/components/assist/schedule-dialog.tsx@@ -33,6 +33,7 @@ import {} from "@/lib/assist-schedule";import type { Engine } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useChats, useConnectors, useProjects, useScheduleActions, type ScheduleRuleInput } from "./hooks";import { ModePicker } from "./mode-picker";import { ProjectDot } from "./project-dot";@@ -152,7 +153,7 @@ function Form({ schedule, seed, onDone }: { schedule?: ScheduleView; seed?: Schetoast.success(schedule ? "Schedule saved" : "Scheduled", { description: s.nextRunAt ? `Next run ${formatWhen(s.nextRunAt, s.tz)}` : undefined, duration: 2500 });onDone();} catch (err) {- toast.error((err as Error).message);+ toastError(err);} finally {setBusy(false);}diff --git a/src/components/assist/scheduled-view.tsx b/src/components/assist/scheduled-view.tsxindex 28aea874..1a4c0996 100644--- a/src/components/assist/scheduled-view.tsx+++ b/src/components/assist/scheduled-view.tsx@@ -25,6 +25,7 @@ import { useNow } from "@/components/studio/use-now";import { describeRule, formatWhen, untilText, zoneLabel, type ScheduleResult, type ScheduleView } from "@/lib/assist-schedule";import { formatCost, timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useProjects, useScheduleActions, useSchedules } from "./hooks";import { ScheduleDialog } from "./schedule-dialog";import { ProjectDot, RailButton } from "./shell";@@ -129,7 +130,7 @@ function TaskRow({ s, showProject }: { s: ScheduleView; showProject: boolean })try {await fn();} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsxindex b2177699..3501d68d 100644--- a/src/components/assist/skills-view.tsx+++ b/src/components/assist/skills-view.tsx@@ -30,6 +30,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Textarea } from "@/components/ui/textarea";import { SKILL_LIMITS, SKILL_NAME_RE, skillSlug, type Skill, type SkillSummary } from "@/lib/assist";import { cn } from "@/lib/utils";+import { refusalShown, toastError } from "@/lib/refusals";import { radioKeys } from "@/components/studio/radio-keys";import { useRecipe, useRecipeActions, useSkill, useSkillActions, useSkills, type RecipeFailure, type SkillForm } from "./hooks";import { RunSkillDialog } from "./run-skill-dialog";@@ -89,7 +90,7 @@ function Skills() {} catch (e) {const err = e as Error & { status?: number };if (err.status === 409 && /You already have/.test(err.message)) setConflict(f);- else toast.error(err.message, { duration: 8000 });+ else if (!refusalShown(err)) toast.error(err.message, { duration: 8000 });} finally {setUploading(false);}@@ -142,14 +143,14 @@ function Skills() {</div></div><TabsContent value="builtin">- <SkillGrid loading={skills.isLoading} list={filter(builtin)} onOpen={open} onToggle={(s, v) => void actions.toggle(s.name, v).catch((e) => toast.error((e as Error).message))} empty={<NoMatch onClear={() => setQuery("")} />} />+ <SkillGrid loading={skills.isLoading} list={filter(builtin)} onOpen={open} onToggle={(s, v) => void actions.toggle(s.name, v).catch((e) => toastError(e))} empty={<NoMatch onClear={() => setQuery("")} />} /></TabsContent><TabsContent value="user"><SkillGridloading={skills.isLoading}list={filter(own)}onOpen={open}- onToggle={(s, v) => void actions.toggle(s.name, v).catch((e) => toast.error((e as Error).message))}+ onToggle={(s, v) => void actions.toggle(s.name, v).catch((e) => toastError(e))}empty={q ? (<NoMatch onClear={() => setQuery("")} />@@ -284,7 +285,7 @@ function RecipeStatus({ skill }: { skill: Skill }) {else toast.error("The check didn't pass", { description: r.engines.flatMap((e) => [...e.plan.errors, ...(e.dryRun?.problems ?? [])])[0] });} catch (e) {const f = e as RecipeFailure;- toast.error(f.message, { description: f.problems?.slice(1).join("; ") || undefined });+ if (!refusalShown(f)) toast.error(f.message, { description: f.problems?.slice(1).join("; ") || undefined });} finally {setBusy(false);}@@ -399,7 +400,7 @@ function SkillDetail({ name, onClose, onEdit, onRun }: { name: string | null; ontoast.success(`Copied as /${c.name}`, { duration: 2000 });onEdit(c);} catch (e) {- toast.error((e as Error).message);+ toastError(e);}}}>@@ -447,7 +448,7 @@ function SkillDetail({ name, onClose, onEdit, onRun }: { name: string | null; ontoast("Skill deleted", { duration: 1500 });onClose();} catch (e) {- toast.error((e as Error).message);+ toastError(e);}}}>diff --git a/src/components/assist/transcript.tsx b/src/components/assist/transcript.tsxindex d5701303..e22b5f31 100644--- a/src/components/assist/transcript.tsx+++ b/src/components/assist/transcript.tsx@@ -3,7 +3,6 @@import { AppWindow, ArrowUpRight, Brain, Captions, Check, CircleAlert, Clapperboard, Film, ImageIcon, Info, Languages, Layers, Loader2, Megaphone, Plug, Scissors, Search, Sparkles } from "lucide-react";import Link from "next/link";import { useState } from "react";-import { toast } from "sonner";import { Button } from "@/components/ui/button";import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";import { useCreateGeneration } from "@/lib/api";@@ -62,7 +61,7 @@ export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItetry {await onAnswer(ok);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(null);}diff --git a/src/components/audio-tools/audio-tools.tsx b/src/components/audio-tools/audio-tools.tsxindex efcafd96..bd2397ca 100644--- a/src/components/audio-tools/audio-tools.tsx+++ b/src/components/audio-tools/audio-tools.tsx@@ -29,6 +29,7 @@ import { cloudLoopLength, cloudLoopPasses } from "@/lib/av/crossfade";import { parseCueTime } from "@/lib/av/cue-edit";import type { Engine } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";/**@@ -327,7 +328,7 @@ export function AudioLoopTool({ tabs }: { tabs?: React.ReactNode }) {const go = () => {if (blocker) return void toast(blocker);if (preview.error) return void toast.error((preview.error as Error).message);- run.mutate(body!, { onSuccess: () => toast.success(engine === "open" ? "Looping on your ComfyUI" : "Looping"), onError: (e) => toast.error((e as Error).message) });+ run.mutate(body!, { onSuccess: () => toast.success(engine === "open" ? "Looping on your ComfyUI" : "Looping"), onError: (e) => toastError(e) });};return (<ToolShell title="Audio" tabs={tabs}>@@ -417,7 +418,7 @@ export function AudioJoinTool({ tabs }: { tabs?: React.ReactNode }) {const go = () => {if (blocker) return void toast(blocker);if (preview.error) return void toast.error((preview.error as Error).message);- run.mutate(body!, { onSuccess: () => toast.success(engine === "open" ? "Joining on your ComfyUI" : "Joining"), onError: (e) => toast.error((e as Error).message) });+ run.mutate(body!, { onSuccess: () => toast.success(engine === "open" ? "Joining on your ComfyUI" : "Joining"), onError: (e) => toastError(e) });};return (<ToolShell title="Audio" tabs={tabs}>diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.tsindex 6786c7a2..942aa127 100644--- a/src/components/audio-tools/hooks.ts+++ b/src/components/audio-tools/hooks.ts@@ -4,6 +4,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useEffect, useState } from "react";import type { AudioToolPreview } from "@/lib/av/audio-tools";import type { Engine, Generation } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";export type AudioToolBody =| { tool: "loop"; engine: Engine; audio: string; name?: string; duration: number; sourceDuration?: number; crossfade?: number; curve?: "equal-power" | "linear" }@@ -14,7 +15,7 @@ export type AudioToolBody =async function post<T>(url: string, body: AudioToolBody): Promise<T> {const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });const j = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, j.error ?? `Request failed (${res.status})`);return j;}diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsxindex 0c976951..c585f7b4 100644--- a/src/components/audio-tools/split-tool.tsx+++ b/src/components/audio-tools/split-tool.tsx@@ -54,6 +54,7 @@ import type { Engine, Generation, OutputFile } from "@/lib/catalog/types";import { downloadHref } from "@/lib/library";import { probeUrl } from "@/lib/media-probe";import { cn } from "@/lib/utils";+import { responseError, toastError } from "@/lib/refusals";import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";/**@@ -486,7 +487,7 @@ async function exportWav(stems: Stem[], buffers: Partial<Record<StemId, AudioBufconst q = new URLSearchParams({ offset: String(offset), ...(id && { id }), ...(last && { last: "1", name }) });const res = await fetch(`/api/audio-tools/export?${q}`, { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: new Blob([mixPart(plan, f, f + per, k) as BlobPart]) });const body = (await res.json().catch(() => ({}))) as { id?: string; received?: number; url?: string; error?: string };- if (!res.ok) throw new Error(body.error ?? `Export failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Export failed (${res.status})`);if (last) {if (!body.url) throw new Error("Export failed");return { url: body.url, lowered: k < 1 };@@ -526,7 +527,7 @@ function Mixer({ stems, source, engine }: { stems: Stem[]; source: Source; enginawait exportMix();toast.success("Mix saved to your Library", { action: { label: "Open Library", onClick: () => router.push("/library") } });} catch (e) {- toast.error((e as Error).message || "Couldn't export the mix");+ toastError(e, "Couldn't export the mix");} finally {setBusy(null);}@@ -538,7 +539,7 @@ function Mixer({ stems, source, engine }: { stems: Stem[]; source: Source; enginawait remux.mutateAsync({ tool: "remux", engine, video: source.ref, audio, name });toast.success(engine === "open" ? "Putting the mix on your video (picture copied as it is)" : "Putting the mix on your video");} catch (e) {- toast.error((e as Error).message || "Couldn't put the mix on the video");+ toastError(e, "Couldn't put the mix on the video");} finally {setBusy(null);}@@ -704,7 +705,7 @@ export function SplitSoundtrackTool({ tabs }: { tabs?: React.ReactNode }) {setResultId(r.result.id);toast.success("Splitting on your ComfyUI");},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});};const g = result.data;diff --git a/src/components/brand/brand-dialog.tsx b/src/components/brand/brand-dialog.tsxindex ffc4578b..954d7b99 100644--- a/src/components/brand/brand-dialog.tsx+++ b/src/components/brand/brand-dialog.tsx@@ -11,6 +11,7 @@ import { kmeans, samplePixels } from "@/components/cinema/color-math";import { chipBase, chipIdle, chipOn } from "@/components/studio/chip";import { BRAND_EXAMPLES, type BrandKit } from "@/lib/catalog/marketing";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useBrand, useBrandActions, useBrands, useCreateBrand } from "@/components/marketing/hooks";import { BrandSummary } from "./brand-kit-form";import { areaCls, inputCls } from "./fields";@@ -48,12 +49,12 @@ export function BrandStart({ onDone, compact }: { onDone: (b: BrandKit) => void;const [images, setImages] = useState<string[]>([]);const submitSite = () => {if (!site.trim()) return void toast("Add a website or social link.");- create.mutate({ website: site.trim() }, { onSuccess: onDone, onError: (e) => toast.error((e as Error).message) });+ create.mutate({ website: site.trim() }, { onSuccess: onDone, onError: (e) => toastError(e) });};const submitManual = async () => {if (!desc.trim() && !images.length) return void toast("Add a description or upload images");const colors = images.length ? await paletteFromImages(images) : undefined;- create.mutate({ description: desc.trim(), images, colors: colors?.length ? colors : undefined }, { onSuccess: onDone, onError: (e) => toast.error((e as Error).message) });+ create.mutate({ description: desc.trim(), images, colors: colors?.length ? colors : undefined }, { onSuccess: onDone, onError: (e) => toastError(e) });};return mode === "site" ? (<div className="space-y-3">diff --git a/src/components/brand/brand-kit-form.tsx b/src/components/brand/brand-kit-form.tsxindex 6f6964d2..dae33400 100644--- a/src/components/brand/brand-kit-form.tsx+++ b/src/components/brand/brand-kit-form.tsx@@ -2,10 +2,10 @@import { Check, Loader2, Plus, Trash2, Upload, X } from "lucide-react";import { useEffect, useId, useRef, useState } from "react";-import { toast } from "sonner";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { BRAND_LANGUAGES, MAX_SELLING_POINTS, SOCIAL_NETWORKS, type BrandKit, type BrandKitFields } from "@/lib/catalog/marketing";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useUpdateBrand } from "@/components/marketing/hooks";import { areaCls, ColorList, FieldRow, FontField, inputCls, TagInput } from "./fields";import { ImageList, uploadImages } from "./image-list";@@ -56,7 +56,7 @@ function useAutosave(brand: BrandKit) {},onError: (e) => {setState("idle");- toast.error((e as Error).message);+ toastError(e);},});};diff --git a/src/components/brand/products.tsx b/src/components/brand/products.tsxindex cd9197cf..0649aa63 100644--- a/src/components/brand/products.tsx+++ b/src/components/brand/products.tsx@@ -8,6 +8,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { MAX_SELLING_POINTS, type Product } from "@/lib/catalog/marketing";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useProductActions, type ProductInput } from "@/components/marketing/hooks";import { areaCls, FieldRow, inputCls, TagInput } from "./fields";import { ImageList } from "./image-list";@@ -48,13 +49,13 @@ function ProductForm({ onOpenChange, brandId, product, onSaved }: { onOpenChangeonSaved?.(p);onOpenChange(false);};- if (product) update.mutate({ ...body, id: product.id }, { onSuccess: done, onError: (e) => toast.error((e as Error).message) });+ if (product) update.mutate({ ...body, id: product.id }, { onSuccess: done, onError: (e) => toastError(e) });elsecreate.mutate({ ...body, force },{onSuccess: done,- onError: (e) => ((e as { status?: number }).status === 409 ? setDup((e as Error).message) : toast.error((e as Error).message)),+ onError: (e) => ((e as { status?: number }).status === 409 ? setDup((e as Error).message) : toastError(e)),},);};diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex 1c1a3ec0..12a7dda3 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -95,6 +95,7 @@ import type { Engine, MediaKind, ModelDef } from "@/lib/catalog/types";import { formatCost } from "@/lib/format";import { useModKey } from "@/lib/keys";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import {buildViews,DescribeCache,@@ -452,7 +453,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvsavedName.current = v;void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};@@ -732,7 +733,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvif (!r.ran.length) toast("Everything's up to date", { description: issues, action: { label: "Run again", onClick: () => go(t, true) } });else toast.success(r.ran.length === 1 ? "Running 1 node" : `Running ${r.ran.length} nodes`, { description: issues, duration: 1800 });},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsxindex a641f0d6..e1fd6c9e 100644--- a/src/components/canvas/canvas-list.tsx+++ b/src/components/canvas/canvas-list.tsx@@ -20,6 +20,7 @@ import type { CanvasNodeType, CanvasSummary, Outline } from "@/lib/catalog/canvaimport type { Engine } from "@/lib/catalog/types";import { timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { NodeIcon } from "./canvas-context";import { useCanvasActions, useCanvases } from "./use-canvas";@@ -116,7 +117,7 @@ function CanvasCard({ c, onRename, onDelete }: { c: CanvasSummary; onRename: ()onSelect={() =>void duplicate(c.id).then((copy) => toast.success("Duplicated", { action: { label: "Open", onClick: () => router.push(`/canvas/${copy.id}`) } }),- (e) => toast.error((e as Error).message),+ (e) => toastError(e),)}>@@ -198,7 +199,7 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {const c = await create(body);router.push(`/canvas/${c.id}`);} catch (e) {- toast.error((e as Error).message);+ toastError(e);setCreating(null);}};@@ -322,7 +323,7 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {const c = renaming!;const name = draft.trim();setRenaming(null);- if (name && name !== c.name) void rename(c.id, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toast.error((err as Error).message));+ if (name && name !== c.name) void rename(c.id, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toastError(err));}}><Input autoFocus value={draft} maxLength={80} onChange={(e) => setDraft(e.target.value)} aria-label="Name" />@@ -351,7 +352,7 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {onClick={() => {const c = deleting!;setDeleting(null);- void remove(c.id).then(() => toast("Deleted", { duration: 1500 }), (e) => toast.error((e as Error).message));+ void remove(c.id).then(() => toast("Deleted", { duration: 1500 }), (e) => toastError(e));}}>Deletediff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex ce78cc58..720080f8 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -116,6 +116,7 @@ import { DUB_LANGUAGES, supportsTarget } from "@/lib/av/languages";import { matchSpokenLanguage, spokenLanguageName, spokenLanguageOptions } from "@/lib/speech-languages";import { keyCombo } from "@/lib/keys";import { cn } from "@/lib/utils";+import { responseError, toastError } from "@/lib/refusals";import { BOARD_NODE_TYPES, type BoardType } from "./board";import { NodeIcon, PORT_COLOR, useEditorActions, useEditorGlobals, useEditorSelector, useNodeResults, useNodeView, type EditorSnapshot, type NodeResults } from "./canvas-context";@@ -946,11 +947,11 @@ function OpenDub({ id, data }: { id: string; data: CanvasNodeData }) {try {const res = await fetch("/api/dub", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engine: "open", mode: "steps", video, targets: [lang], source: "auto", title: data.label || "Canvas dub" }) });const body = (await res.json().catch(() => ({}))) as { id?: string; error?: string };- if (!res.ok || !body.id) throw new Error(body.error ?? "Couldn't start the dub");+ if (!res.ok || !body.id) throw responseError(res, body.error ?? "Couldn't start the dub");actions.update(id, { dubId: body.id });toast.success("Dub started", { description: "Check the translation in Translate & dub, then have it spoken. The dubbed video comes back here." });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.tsindex 1bbbf942..ca5960aa 100644--- a/src/components/canvas/use-canvas.ts+++ b/src/components/canvas/use-canvas.ts@@ -5,12 +5,13 @@ import { useGenerationStream } from "@/lib/api";import type { Canvas, CanvasGraph, CanvasPlan, CanvasSummary } from "@/lib/catalog/canvas";import type { CanvasPage } from "@/lib/catalog/canvas-board";import type { Engine, Generation } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";/** Client hooks for /api/canvases (kept next to the canvas UI; the shapes live in src/lib/catalog/canvas.ts). */async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { body, status: res.status });+ if (!res.ok) throw Object.assign(responseError(res, body.error ?? `Request failed (${res.status})`), { body, status: res.status });return body;}@@ -69,7 +70,7 @@ export function useCanvasActions() {remove: async (id: string) => {qc.setQueryData<CanvasSummary[]>(["canvases"], (old) => old?.filter((c) => c.id !== id));const res = await fetch(`/api/canvases/${id}`, { method: "DELETE" });- if (!res.ok && res.status !== 404) throw new Error("Couldn't delete it. Please try again.");+ if (!res.ok && res.status !== 404) throw responseError(res, "Couldn't delete it. Please try again.");qc.removeQueries({ queryKey: ["canvases", id] });refresh();},@@ -96,7 +97,7 @@ export function useRunCanvas(id: string) {mutationFn: async (body: { page: string; targets?: string[]; group?: string; force?: boolean; pages: CanvasPage[] }) => {const res = await send(`/api/canvases/${id}/run`, "POST", body);const data = (await res.json().catch(() => ({}))) as Partial<RunResponse> & { error?: string };- if (!res.ok && !data.errors) throw new Error(data.error ?? `Request failed (${res.status})`);+ if (!res.ok && !data.errors) throw responseError(res, data.error ?? `Request failed (${res.status})`);return { ...data, ok: res.ok } as RunResponse & { ok: boolean; error?: string };},onSuccess: (r) => {diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsxindex 2c111f85..dcf0e470 100644--- a/src/components/cinema/cinema-feed.tsx+++ b/src/components/cinema/cinema-feed.tsx@@ -56,6 +56,7 @@ import type { Generation, OutputFile } from "@/lib/catalog/types";import { formatCost, timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";import { copyWithToast } from "@/lib/clipboard";+import { toastError } from "@/lib/refusals";import { MoveToItems } from "./folder-sidebar";import { foreign, useItemActions, type CinemaGeneration } from "./hooks";@@ -255,7 +256,7 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold</a></DropdownMenuItem>)}- <DropdownMenuItem onClick={() => void actions.favorite([u.g.id], !u.g.favorite).catch((e) => toast.error((e as Error).message))}>+ <DropdownMenuItem onClick={() => void actions.favorite([u.g.id], !u.g.favorite).catch((e) => toastError(e))}><Heart /> {u.g.favorite ? "Unlike" : "Like"}</DropdownMenuItem><DropdownMenuItem@@ -283,7 +284,7 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; foldvoid actions.move([u.g.id], f).then((n) => toast(n ? "Moved" : "That take isn't in this project", { duration: 1500 }))- .catch((e) => toast.error((e as Error).message))+ .catch((e) => toastError(e))}/></DropdownMenuSubContent>@@ -335,7 +336,7 @@ function TileView({active(g) ? (<PendingTile g={g} ratio={aspect} />) : g.status !== "succeeded" ? (- <FailedTile g={g} ratio={aspect} onRetry={() => void actions.retry(g).catch((e) => toast.error((e as Error).message))} />+ <FailedTile g={g} ratio={aspect} onRetry={() => void actions.retry(g).catch((e) => toastError(e))} />) : (<div className={cn("relative size-full", fit && "bg-muted")}>{/* Behind the video: visible until (or if) the browser can draw its first frame. */}@@ -628,13 +629,13 @@ export function CinemaFeed({try {await actions.remove(list);} catch (e) {- toast.error((e as Error).message);+ toastError(e);return;}toast(list.length > 1 ? `${list.length} takes moved to Trash` : "Moved to Trash", {id: "cinema-trash",duration: 6000,- action: { label: "Undo", onClick: () => void actions.restore(list).catch((e) => toast.error((e as Error).message)) },+ action: { label: "Undo", onClick: () => void actions.restore(list).catch((e) => toastError(e)) },});};const own = live.filter((id) => !items.some((g) => g.id === id && foreign(g, projectId)));@@ -722,7 +723,7 @@ export function CinemaFeed({<span className="flex-1" /><buttontype="button"- onClick={() => void actions.favorite(live, !items.filter((g) => live.includes(g.id)).every((g) => g.favorite)).catch((e) => toast.error((e as Error).message))}+ onClick={() => void actions.favorite(live, !items.filter((g) => live.includes(g.id)).every((g) => g.favorite)).catch((e) => toastError(e))}className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[12.5px] font-medium hover:bg-accent"><Heart className="size-3.5" /> {items.filter((g) => live.includes(g.id)).every((g) => g.favorite) ? "Unlike" : "Like"}@@ -745,7 +746,7 @@ export function CinemaFeed({toast(`Moved ${n} take${n === 1 ? "" : "s"}`, { duration: 1500 });setSelected(new Set());})- .catch((e) => toast.error((e as Error).message))+ .catch((e) => toastError(e))}/></DropdownMenuContent>diff --git a/src/components/cinema/folder-sidebar.tsx b/src/components/cinema/folder-sidebar.tsxindex 32d2753b..0520d8e1 100644--- a/src/components/cinema/folder-sidebar.tsx+++ b/src/components/cinema/folder-sidebar.tsx@@ -18,6 +18,7 @@ import { Input } from "@/components/ui/input";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { EMOTION_FAMILIES, type CinemaFolder } from "@/lib/catalog/cinema";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useFolderActions } from "./hooks";/** Which feed the workspace shows. */@@ -141,11 +142,11 @@ function FolderRow({const group = siblings.filter((s) => s.pinned === node.pinned);const at = group.findIndex((s) => s.id === node.id);const reorder = (dir: -1 | 1) =>- void Promise.all(reorderFolders(siblings, node.id, dir).map((c) => actions.update(c.id, { position: c.position }))).catch((e) => toast.error((e as Error).message));+ void Promise.all(reorderFolders(siblings, node.id, dir).map((c) => actions.update(c.id, { position: c.position }))).catch((e) => toastError(e));const parent = node.parentId ? folders.find((f) => f.id === node.parentId) : undefined;const commit = () => {setRenaming(false);- if (name.trim() && name.trim() !== node.name) void actions.update(node.id, { name: name.trim() }).catch((e) => toast.error((e as Error).message));+ if (name.trim() && name.trim() !== node.name) void actions.update(node.id, { name: name.trim() }).catch((e) => toastError(e));else setName(node.name);};return (@@ -250,7 +251,7 @@ function FolderRow({<FolderInput /> Move to</DropdownMenuSubTrigger><DropdownMenuSubContent className="max-h-72 overflow-y-auto">- <MoveToItems folders={folders} exclude={subtree(folders, node.id)} onMove={(parentId) => void actions.update(node.id, { parentId }).catch((e) => toast.error((e as Error).message))} />+ <MoveToItems folders={folders} exclude={subtree(folders, node.id)} onMove={(parentId) => void actions.update(node.id, { parentId }).catch((e) => toastError(e))} /></DropdownMenuSubContent></DropdownMenuSub><DropdownMenuSeparator />@@ -279,7 +280,7 @@ function FolderRow({if (active) setView(parent ? { kind: "folder", id: parent.id } : { kind: "home" });toast(`Folder deleted — its takes moved to ${parent ? parent.name : "Home"}`);})- .catch((e) => toast.error((e as Error).message))+ .catch((e) => toastError(e))}>Delete folder@@ -334,7 +335,7 @@ export function FolderSidebar({setOpen((s) => new Set([...s, f.id]));setView({ kind: "folder", id: f.id });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};return (diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.tsindex d0ccb2dc..86cc5a1b 100644--- a/src/components/cinema/hooks.ts+++ b/src/components/cinema/hooks.ts@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";import type { Generation } from "@/lib/catalog/types";import { useGenerationEvents } from "@/lib/api";+import { responseError } from "@/lib/refusals";import { Autosaver } from "./autosave";import { applyToTakes, type CinemaGeneration } from "./live";@@ -22,7 +23,7 @@ export interface ProjectView {async function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/cinema/project-settings.tsx b/src/components/cinema/project-settings.tsxindex b6067f1c..ab072826 100644--- a/src/components/cinema/project-settings.tsx+++ b/src/components/cinema/project-settings.tsx@@ -21,6 +21,7 @@ import { Textarea } from "@/components/ui/textarea";import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";import type { CinemaProject } from "@/lib/catalog/cinema";import { untitledName } from "@/lib/format";+import { toastError } from "@/lib/refusals";import { formatUsd } from "./money";import { useCinemaProjects, useCreateProject, useDeleteProject, useUpdateProject } from "./hooks";@@ -68,9 +69,9 @@ function ProjectForm({ project, spentUsd, onDone, onDeleted }: FormProps) {toast.success("Saved", { duration: 1500 });onDone(p);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});- else create.mutate(body, { onSuccess: (p) => onDone(p), onError: (e) => toast.error((e as Error).message) });+ else create.mutate(body, { onSuccess: (p) => onDone(p), onError: (e) => toastError(e) });};return (@@ -183,7 +184,7 @@ function ProjectForm({ project, spentUsd, onDone, onDeleted }: FormProps) {toast("Project deleted");onDeleted?.();},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/cinema/prompt-bar.tsx b/src/components/cinema/prompt-bar.tsxindex 6fa4899f..d764b92d 100644--- a/src/components/cinema/prompt-bar.tsx+++ b/src/components/cinema/prompt-bar.tsx@@ -406,7 +406,7 @@ export function PromptBar(props: PromptBarProps) {// The scene was deleted meanwhile: say where the take went.if (folderId && r.folderId === null) toast(r.plan.notes[0] ?? "That scene was deleted, so the take is in Home", { duration: 4000 });},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};diff --git a/src/components/cinema/scene-viewer.tsx b/src/components/cinema/scene-viewer.tsxindex 660e004c..a53288ee 100644--- a/src/components/cinema/scene-viewer.tsx+++ b/src/components/cinema/scene-viewer.tsx@@ -20,6 +20,7 @@ import type { Engine } from "@/lib/catalog/types";import { ACCESS_PLACE, offered } from "@/lib/model-access";import { APERTURE, FLY_KEYS, F_STOPS, LENS, LENS_STOPS, captureSize, formatStop, frameRect, ratioOf, scenePose, twoFinger, type Rect } from "@/lib/scene3d";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useCinemaGenerate } from "./hooks";import { usePlanPrice, type SceneTake } from "./scene-actions";import { FilmButton, OPEN_SECONDS, PathKeys, PathOptions } from "./scene-path";@@ -356,7 +357,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, setting// A render the run didn't take isn't left in Uploads (the server refuses to delete one that is used).if (uploaded) deleteUpload.mutate(uploaded);// Closing the viewer stops a recording: nothing to report then.- if ((e as Error).name !== "AbortError") toast.error((e as Error).message || "Couldn't film this path");+ if ((e as Error).name !== "AbortError") toastError(e, "Couldn't film this path");} finally {setFilming(null);}@@ -387,7 +388,7 @@ export default function SceneViewer({ take, projectId, engine, onEngine, settingsetQueued((n) => n + 1);toast.success("Re-rendering this view — it lands next to the scene as a new take", { duration: 3000 });} catch (e) {- toast.error((e as Error).message || "Couldn't capture this view");+ toastError(e, "Couldn't capture this view");} finally {setCapturing(false);}diff --git a/src/components/cinema/side-panel.tsx b/src/components/cinema/side-panel.tsxindex 5779dc76..fd4e29aa 100644--- a/src/components/cinema/side-panel.tsx+++ b/src/components/cinema/side-panel.tsx@@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { directorSummary, moveBySlug, type CinemaProject, type DirectorMessage, type DirectorSettings, type DirectorShot } from "@/lib/catalog/cinema";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useAutosave, useDirectorChat, useUpdateProject } from "./hooks";const SUGGESTIONS = ["Write a script", "Generate an 8-shot storyboard for a sci-fi chase scene", "Create a 15-second cinematic perfume commercial"];@@ -91,7 +92,7 @@ function DirectorChat({ projectId, onLoadShot, onBrief, promptText }: { projectIconst v = t.trim();if (!v || ask.isPending) return;setText("");- ask.mutate(v, { onError: (e) => toast.error((e as Error).message) });+ ask.mutate(v, { onError: (e) => toastError(e) });};return (<div className="flex min-h-0 flex-1 flex-col">@@ -180,7 +181,7 @@ function Brief({ project }: { project: CinemaProject }) {const [state, setState] = useState<"saved" | "saving" | "dirty">("saved");const saver = useAutosave<{ title: string; body: string }>((brief, { keepalive }) => {setState("saving");- update.mutate({ brief, keepalive }, { onSuccess: () => setState("saved"), onError: (e) => (setState("dirty"), toast.error((e as Error).message)) });+ update.mutate({ brief, keepalive }, { onSuccess: () => setState("saved"), onError: (e) => (setState("dirty"), toastError(e)) });}, 700);const save = (t: string, b: string) => {setState("dirty");@@ -265,7 +266,7 @@ export function SidePanel({setBriefVersion((v) => v + 1);toast.success("Brief updated", { duration: 1500, action: { label: "Open", onClick: () => setTab("brief") } });},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}diff --git a/src/components/cinema/soul-builders.tsx b/src/components/cinema/soul-builders.tsxindex 3caa232c..4b4dec81 100644--- a/src/components/cinema/soul-builders.tsx+++ b/src/components/cinema/soul-builders.tsx@@ -38,6 +38,7 @@ import { finishedUrl } from "@/lib/soul-post";import type { Engine, Generation } from "@/lib/catalog/types";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useCinemaGenerate, useCinemaItems } from "./hooks";interface BuilderProps {@@ -218,7 +219,7 @@ function SaveElement({ kind, defaultName, picked, description, onSaved }: { kindtoast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } });onSaved();},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}@@ -260,7 +261,7 @@ function SoulCast({ projectId, folderId, engine, context, brief, onOpenChange }:setIds(r.items.map((g) => g.id));setPicked([]);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);return (@@ -406,7 +407,7 @@ function SoulLocation({ projectId, folderId, engine, settings, context, brief, osetIds((ids) => (extra ? [...ids, ...r.items.map((g) => g.id)] : r.items.map((g) => g.id)));if (!extra) setPicked([]);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);return (diff --git a/src/components/cinema/workspace.tsx b/src/components/cinema/workspace.tsxindex 665a1ad4..1e76ba18 100644--- a/src/components/cinema/workspace.tsx+++ b/src/components/cinema/workspace.tsx@@ -22,6 +22,7 @@ import type { StudioElement } from "@/lib/catalog/elements";import type { OutputFile } from "@/lib/catalog/types";import { cn } from "@/lib/utils";import { copyWithToast } from "@/lib/clipboard";+import { toastError } from "@/lib/refusals";import { CinemaFeed, type FeedHandlers } from "./cinema-feed";import { initialDraft, type CinemaDraft } from "./draft";import { ElementsPanel } from "./elements-panel";@@ -182,7 +183,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG// Director settings save per project a moment after the last change, and at once when the// workspace goes away (another page, a closed tab): the last pick is never dropped.const settingsSaver = useAutosave<DirectorSettings>(- (director, { keepalive }) => update.mutate({ director, keepalive }, { onError: (e) => toast.error((e as Error).message) }),+ (director, { keepalive }) => update.mutate({ director, keepalive }, { onError: (e) => toastError(e) }),500,);// The last lighting the server would accept: a custom rig being edited into an invalid state isn't saved.@@ -235,7 +236,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG...(asked ? {} : { action: { label: "Ask first", onClick: askSceneConfirmAgain } }),});},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};@@ -325,7 +326,7 @@ function Workspace({ data, items, loading }: { data: ProjectView; items: CinemaG{ name: nameFrom(g.take?.prompt ?? g.request.prompt, kind === "character" ? "New character" : "New location"), kind, references: [url] },{onSuccess: (el) => toast.success(`Saved as @${el.handle}`, { action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } }),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},),onCreateScene: (g, url) => (skipSceneConfirm(scenePrice) ? createScene(g, url, false) : setSceneFrom({ g, url })),diff --git a/src/components/color-grade-view.tsx b/src/components/color-grade-view.tsxindex efdff968..7c65246e 100644--- a/src/components/color-grade-view.tsx+++ b/src/components/color-grade-view.tsx@@ -13,7 +13,7 @@ import { uploadFile } from "@/lib/api";import { applyPreset, CONTROLS, describeGrade, FRAGMENT, isNeutral, NEUTRAL, PRESETS, uniforms, VERTEX, type Grade } from "@/lib/grade";import { cn } from "@/lib/utils";import { loseContext as loseGlContext, releaseVideo } from "@/lib/media-release";-import { toastError } from "@/lib/refusals";+import { responseError, toastError } from "@/lib/refusals";type Source = HTMLImageElement | HTMLVideoElement;@@ -172,7 +172,7 @@ function Grader() {},(e) => {if (cancelled) return;- toast.error((e as Error).message);+ toastError(e);// Back to the empty stage (upload slots, sample photo) instead of a spinner that never ends.setSource(null);setInput(null);@@ -218,7 +218,7 @@ function Grader() {try {renderer.current ??= new GradeRenderer(canvas.current);} catch (e) {- toast.error((e as Error).message);+ toastError(e);return;}const dpr = Math.min(window.devicePixelRatio || 1, 2);@@ -278,7 +278,7 @@ function Grader() {output: { url: asset.url, kind, contentType: asset.contentType },}),});- if (!res.ok) throw new Error(((await res.json()) as { error?: string }).error ?? "Couldn't save");+ if (!res.ok) throw responseError(res, ((await res.json()) as { error?: string }).error ?? "Couldn't save");setSaved(asset.url);toast.success("Saved to your library");};diff --git a/src/components/connect-field.tsx b/src/components/connect-field.tsxindex ec3628bd..aca083e9 100644--- a/src/components/connect-field.tsx+++ b/src/components/connect-field.tsx@@ -10,6 +10,7 @@ import { Label } from "@/components/ui/label";import { saveSettings, testConnection, type ConnectionTest } from "@/lib/api";import { settingProblem, type TestProvider } from "@/lib/connections";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";export interface PublicSetting {name: string;@@ -129,7 +130,7 @@ export function ConnectField({refresh();toast.success("Saved — it didn't connect yet");} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};@@ -141,7 +142,7 @@ export function ConnectField({refresh();toast.success(`${label} cleared`);} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};diff --git a/src/components/content-factory/home.tsx b/src/components/content-factory/home.tsxindex 050d208c..5160a2e7 100644--- a/src/components/content-factory/home.tsx+++ b/src/components/content-factory/home.tsx@@ -196,7 +196,7 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })writeDraft(null);router.push(`/content-factory/${id}`);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {submitting.current = false;}@@ -241,7 +241,7 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })analysis={view.analysis}styleId={view.brief?.styleId ?? "colorful-3d"}onClear={() => choosePreset(DEFAULT_PRESET)}- onReread={() => reread.mutate({ id: view.id, engine }, { onError: (e) => toast.error((e as Error).message) })}+ onReread={() => reread.mutate({ id: view.id, engine }, { onError: (e) => toastError(e) })}rereading={reread.isPending}/>) : seriesId && series.isLoading ? (@@ -457,7 +457,7 @@ export function ContentFactoryHome({ voices }: { voices: PickerData["voices"] })const id = seriesId ?? (await startSeries({ kind: "preset", presetId })).id;await updateBrief.mutateAsync({ id, brief: b });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}}}/>diff --git a/src/components/content-factory/hooks.ts b/src/components/content-factory/hooks.tsindex e3b77805..526d5120 100644--- a/src/components/content-factory/hooks.ts+++ b/src/components/content-factory/hooks.ts@@ -4,6 +4,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstaimport type { ClaudePrompt, SeriesCard, SeriesEstimate, SeriesSettings, SeriesView, StyleBrief } from "@/lib/catalog/content-factory";import type { NarratorVoice } from "@/lib/catalog/faceless";import type { Engine } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";import { useDebounced } from "@/components/faceless/hooks";/** React Query hooks for /api/content-factory/** (kept next to the views that use them). */@@ -20,7 +21,7 @@ export class ApiError extends Error {async function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string; needsUpload?: boolean };- if (!res.ok) throw new ApiError(body.error ?? `Request failed (${res.status})`, !!body.needsUpload);+ if (!res.ok) throw responseError(res, new ApiError(body.error ?? `Request failed (${res.status})`, !!body.needsUpload));return body;}diff --git a/src/components/content-factory/series-view.tsx b/src/components/content-factory/series-view.tsxindex 1097c358..5e25c402 100644--- a/src/components/content-factory/series-view.tsx+++ b/src/components/content-factory/series-view.tsx@@ -23,6 +23,7 @@ import { EpisodeTile } from "@/components/faceless/cards";import { voiceLabel } from "@/components/faceless/narrator";import { animationStyle, CF_LENGTHS, MAX_EPISODES } from "@/lib/catalog/content-factory";import { genreInfo, type PickerData } from "@/lib/catalog/faceless";+import { toastError } from "@/lib/refusals";import { BriefCard, ReferenceCard, SeriesPriceLine } from "./parts";import { useAddEpisodes, useDeleteSeries, useSeries, useSeriesEstimate, useUpdateSeries } from "./hooks";@@ -70,7 +71,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voitoast("Series deleted");router.push("/content-factory");},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});return (<div className="flex min-h-svh min-w-0 flex-col">@@ -150,7 +151,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voibrief={s.brief}note={s.analysis?.note}saving={update.isPending}- onSave={(b) => update.mutate({ id: s.id, brief: b }, { onSuccess: () => toast("Saved — episodes you add from now on follow it"), onError: (e) => toast.error((e as Error).message) })}+ onSave={(b) => update.mutate({ id: s.id, brief: b }, { onSuccess: () => toast("Saved — episodes you add from now on follow it"), onError: (e) => toastError(e) })}/>)}</div>@@ -213,7 +214,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voisetNext("");toast(count === 1 ? "Next episode started" : `${count} episodes started`);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}@@ -247,7 +248,7 @@ export function SeriesView({ id, voices }: { id: string; voices: PickerData["voitoast("Series deleted");router.push("/content-factory");},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxindex 02997765..7fbf102d 100644--- a/src/components/dub/dub-studio.tsx+++ b/src/components/dub/dub-studio.tsx@@ -22,6 +22,7 @@ import { BACKGROUND_DB, crowdedLines, dubResult, languageStage, ONE_SHOT_MODELS,import { languageByCode, supportsTarget, type DubRoute } from "@/lib/av/languages";import type { Cue } from "@/lib/cues";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useDubActions, useDubPrice, useDubSessions, useVoicePrice } from "./hooks";const ONE_SHOT: Record<OneShotModel, { name: string; note: string }> = {@@ -121,7 +122,7 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {setDuration(undefined);onStarted(s.id);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};@@ -363,7 +364,7 @@ function SessionView({ s, onBack }: { s: DubSessionView; onBack: () => void }) {toast("Dub removed");onBack();},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>@@ -480,7 +481,7 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; tiif (body === savedBody) return;const t = setTimeout(() => {setSavedBody(body);- save.current({ id: s.id, lang, cues: JSON.parse(body) as Cue[] }, { onError: (e) => toast.error((e as Error).message) });+ save.current({ id: s.id, lang, cues: JSON.parse(body) as Cue[] }, { onError: (e) => toastError(e) });}, 800);return () => clearTimeout(t);}, [body, savedBody, s.id, lang]);@@ -507,7 +508,7 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ticonst start = (c: Cue[]) =>voice.mutate({ id: s.id, lang, cues: c, lipsync },- { onSuccess: () => toast.success(`Voicing ${name}`), onError: (e) => toast.error((e as Error).message) },+ { onSuccess: () => toast.success(`Voicing ${name}`), onError: (e) => toastError(e) },);return (<>diff --git a/src/components/dub/hooks.ts b/src/components/dub/hooks.tsindex 52e21bf5..374d9816 100644--- a/src/components/dub/hooks.ts+++ b/src/components/dub/hooks.ts@@ -6,10 +6,11 @@ import { useGenerationEvents } from "@/lib/api";import type { DubPrice, DubSessionView, OneShotModel } from "@/lib/av/dub";import type { Cue } from "@/lib/cues";import type { Engine, Generation } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}@@ -109,7 +110,7 @@ export function useDubActions() {const remove = useMutation({mutationFn: async (id: string) => {const res = await fetch(`/api/dub/${id}`, { method: "DELETE" });- if (!res.ok && res.status !== 404) throw new Error("Couldn't remove it");+ if (!res.ok && res.status !== 404) throw responseError(res, "Couldn't remove it");return id;},onSuccess: (id) => qc.setQueryData<DubSessionView[]>(["dub"], (xs) => xs?.filter((x) => x.id !== id)),diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsxindex 633a5fdf..35502aae 100644--- a/src/components/elements-view.tsx+++ b/src/components/elements-view.tsx@@ -32,6 +32,7 @@ import { ELEMENT_KINDS, elementKindInfo, handleFor, MAX_ELEMENT_PHOTOS, type Eleimport { isLegacySoulId, SOUL_ID_PHOTOS } from "@/lib/catalog/training";import { copyText } from "@/lib/clipboard";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";const TIPS: Record<ElementKind, string> = {character: `3+ clear photos of one person (${SOUL_ID_PHOTOS.recommended}+ to train a Soul ID, up to ${SOUL_ID_PHOTOS.max}): different angles, at least one full-body, no sunglasses, filters or group shots.`,@@ -136,7 +137,7 @@ function ElementForm({ onOpenChange, element, defaultKind = "character", onSavedonOpenChange(false);onSaved?.(el);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);@@ -337,7 +338,7 @@ function ElementCard({ el }: { el: StudioElement }) {onClick={() =>del.mutate(el.id, {onSuccess: () => toast(`Deleted ${el.name}`),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/evolution/evolution-tool.tsx b/src/components/evolution/evolution-tool.tsxindex 931c62aa..468f2d74 100644--- a/src/components/evolution/evolution-tool.tsx+++ b/src/components/evolution/evolution-tool.tsx@@ -21,6 +21,7 @@ import { DIRECTION_CUT_NOTE, directionPrompt, EVOLUTION, EVOLUTION_DEFAULT_RESOLimport { chainState } from "@/lib/catalog/shorts";import { downloadHref, downloadName } from "@/lib/library";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useEvolutionActions, useEvolutionEstimate, type EvolutionBody } from "./hooks";const LIMITS = `MP4, MOV or WebM · ${EVOLUTION.minSeconds}–${EVOLUTION.maxSeconds} s · ${EVOLUTION.maxBytes / 1024 / 1024} MB`;@@ -123,7 +124,7 @@ export function EvolutionTool({ tabs }: { tabs?: React.ReactNode }) {setBy(d.by);if (d.by === "offline" && d.why) toast("Written offline", { description: `Fuobe's own writer wrote it: ${d.why}. Edit it as you like.` });},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};@@ -142,7 +143,7 @@ export function EvolutionTool({ tabs }: { tabs?: React.ReactNode }) {}toast("Evolving your clip", { description: "Follow it below — it lands in your Library too." });})- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};const addMany = (files: FileList | null) => {diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxindex ad1f9047..0b7aa928 100644--- a/src/components/explainer/explainer-studio.tsx+++ b/src/components/explainer/explainer-studio.tsx@@ -33,6 +33,7 @@ import {type PickerData,} from "@/lib/catalog/faceless";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { EpisodeTile } from "../faceless/cards";import { EstimateLine, Segmented, ToggleRow } from "../faceless/controls";import { readDocument, readLink, useCreateExplainer, useEstimate, useExplainers, useLikeEpisode } from "../faceless/hooks";@@ -95,7 +96,7 @@ function LinkPopover({ engine, disabled, onAdd }: { engine: EpisodeSettings["engsetUrl("");setOpen(false);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}@@ -221,7 +222,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {},(e: Error) => {setSources((xs) => xs.filter((x) => !(x.kind === "reading" && x.id === id)));- toast.error(e.message);+ toastError(e);},);} else if (/\.(doc|odt|rtf|pages|pptx?|key)$/i.test(f.name) || /msword|opendocument|rtf|presentation/.test(f.type)) {@@ -244,7 +245,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {{ prompt: prompt.trim(), sources: payload, settings, review },{onSuccess: (ep) => router.push(`/explainer/${ep.id}`),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};diff --git a/src/components/faceless/channel-view.tsx b/src/components/faceless/channel-view.tsxindex d6063aa0..679d73a9 100644--- a/src/components/faceless/channel-view.tsx+++ b/src/components/faceless/channel-view.tsx@@ -24,6 +24,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { NotFoundState } from "@/components/empty-state";import { FACELESS_STYLE_IDS, genreInfo, getStyle, type ChannelSettings, type FacelessChannel, type PickerData } from "@/lib/catalog/faceless";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { ChannelAvatar, EpisodeTile } from "./cards";import { Section, Segmented, ToggleRow } from "./controls";import { makeAvatar, useChannel, useDeleteChannel, useLikeEpisode, useUpdateChannel } from "./hooks";@@ -87,7 +88,7 @@ function ChannelSettingsSheet({ channel, picker, open, onOpenChange }: { channeltoast.success("Saved");onOpenChange(false);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}@@ -129,7 +130,7 @@ export function ChannelView({ id, picker }: { id: string; picker: PickerData })await qc.invalidateQueries({ queryKey: ["faceless", "channel", id] });toast("Drawing a new avatar", { description: "It appears here when it's done — you can leave this page." });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setAsking(false);}@@ -176,7 +177,7 @@ export function ChannelView({ id, picker }: { id: string; picker: PickerData })className="flex items-center gap-2"onSubmit={(e) => {e.preventDefault();- update.mutate({ name }, { onError: (err) => toast.error((err as Error).message) });+ update.mutate({ name }, { onError: (err) => toastError(err) });setEditing(false);}}>@@ -308,7 +309,7 @@ export function ChannelView({ id, picker }: { id: string; picker: PickerData })toast("Channel deleted");router.push("/faceless");},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/faceless/episode-view.tsx b/src/components/faceless/episode-view.tsxindex 2a5597db..ebcfd946 100644--- a/src/components/faceless/episode-view.tsx+++ b/src/components/faceless/episode-view.tsx@@ -58,6 +58,7 @@ import type { Generation } from "@/lib/catalog/types";import { timeAgo } from "@/lib/format";import { downloadHref, downloadName } from "@/lib/library";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { Segmented, usd } from "./controls";import { useApplyChange, useChangePreview, useDeleteEpisode, useEpisode, useEpisodeAction, useUpdateEpisode, type ChangeDraft } from "./hooks";import { ScriptReview } from "./script-review";@@ -251,7 +252,7 @@ function SceneEditor({ view, scenes, onClose, onOpen }: { view: View; scenes: Sctoast.success(`Re-rendering ${scenes.length > 1 ? `${scenes.length} scenes` : `scene ${scenes[0].index + 1}`}`);discard();},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});};@@ -294,7 +295,7 @@ function SceneEditor({ view, scenes, onClose, onOpen }: { view: View; scenes: Scsize="sm"variant="outline"disabled={retry.isPending || busy}- onClick={() => retry.mutate("retry", { onSuccess: () => toast.success("Retrying what failed"), onError: (e) => toast.error((e as Error).message) })}+ onClick={() => retry.mutate("retry", { onSuccess: () => toast.success("Retrying what failed"), onError: (e) => toastError(e) })}><RotateCcw /> Retry</Button>@@ -476,7 +477,7 @@ export function EpisodeView({ id, backHref, backLabel }: { id: string; backHref:const upscaling = !!view?.upscaled && active(view.upscaled);const film = upscaled ?? view?.final;const filmOut = film?.outputs.find((o) => o.kind === "video");- const run = (a: "retry" | "rewrite" | "undo" | "upscale", ok?: string) => action.mutate(a, { onSuccess: () => ok && toast.success(ok), onError: (e) => toast.error((e as Error).message) });+ const run = (a: "retry" | "rewrite" | "undo" | "upscale", ok?: string) => action.mutate(a, { onSuccess: () => ok && toast.success(ok), onError: (e) => toastError(e) });return (<div className="flex min-h-svh min-w-0 flex-col">@@ -639,7 +640,7 @@ export function EpisodeView({ id, backHref, backLabel }: { id: string; backHref:toast("Episode deleted");router.push(backHref);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/faceless/episode-wizard.tsx b/src/components/faceless/episode-wizard.tsxindex 069466e2..e2596f4b 100644--- a/src/components/faceless/episode-wizard.tsx+++ b/src/components/faceless/episode-wizard.tsx@@ -25,6 +25,7 @@ import {type TopicIdea,} from "@/lib/catalog/faceless";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { ChannelAvatar } from "./cards";import { EstimateLine, Section, Segmented, ToggleRow } from "./controls";import { pendingScriptKey } from "./faceless-home";@@ -122,7 +123,7 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; pickersetOffline(res.offline);setPicked(null);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setLoadingTopics(false);}@@ -163,7 +164,7 @@ export function EpisodeWizard({ channelId, picker }: { channelId: string; picker{ channelId, topic: topic || script.trim().slice(0, 120), script: scriptMode === "pasted" ? script : undefined, settings, saveLook: keepLook },{onSuccess: (ep) => router.push(`/faceless/${channelId}/${ep.id}`),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};diff --git a/src/components/faceless/faceless-home.tsx b/src/components/faceless/faceless-home.tsxindex 6bfb3ca5..2ff1575e 100644--- a/src/components/faceless/faceless-home.tsx+++ b/src/components/faceless/faceless-home.tsx@@ -12,6 +12,7 @@ import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { useEngine } from "@/lib/api";import { CHANNEL_IDEAS, GENRES, MAX_IDEA, MAX_SCRIPT, wordCount, youtubeKind, YOUTUBE_ERROR, type FacelessGenre } from "@/lib/catalog/faceless";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { ChannelCard, EmptyChannels } from "./cards";import { useChannels, useCreateChannel } from "./hooks";@@ -59,7 +60,7 @@ export function FacelessHome() {}router.push(`/faceless/${c.id}/new`);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};diff --git a/src/components/faceless/hooks.ts b/src/components/faceless/hooks.tsindex dac56590..74ac2de5 100644--- a/src/components/faceless/hooks.ts+++ b/src/components/faceless/hooks.ts@@ -19,13 +19,14 @@ import type {TopicIdea,} from "@/lib/catalog/faceless";import type { Engine, Generation } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";/** React Query hooks for /api/faceless/** and /api/explainer/** (kept next to the views that use them). */async function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/faceless/narrator.tsx b/src/components/faceless/narrator.tsxindex 3349f223..f3b6cc65 100644--- a/src/components/faceless/narrator.tsx+++ b/src/components/faceless/narrator.tsx@@ -12,6 +12,7 @@ import { useElements } from "@/lib/api";import type { NarratorVoice, PickerData } from "@/lib/catalog/faceless";import type { Engine } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { voicePreview, waitFor } from "./hooks";/** One shared player, so starting a sample stops the one before. */@@ -51,7 +52,7 @@ function usePlayer() {cache.current.set(key, url);play(key, url);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setLoading((l) => (l === key ? "" : l));}diff --git a/src/components/faceless/script-review.tsx b/src/components/faceless/script-review.tsxindex 86aa5dc9..2b1be281 100644--- a/src/components/faceless/script-review.tsx+++ b/src/components/faceless/script-review.tsx@@ -2,7 +2,6 @@import { AlertTriangle, ArrowDown, ArrowUp, Check, Info, Loader2, Plus, Trash2, Wand2 } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";-import { toast } from "sonner";import {AlertDialog,AlertDialogAction,@@ -16,6 +15,7 @@ import {import { Button } from "@/components/ui/button";import { blockId, formatLength, secondsFor, splitScript, tooLong, totalSeconds, wordCount, type EpisodeView, type ScriptBlock } from "@/lib/catalog/faceless";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { EstimateLine } from "./controls";import { useEpisodeAction, useEstimate, useUpdateEpisode } from "./hooks";@@ -159,7 +159,7 @@ export function ScriptReview({ view }: { view: EpisodeView }) {edits.current++;deferred.current = null;if (timer.current) clearTimeout(timer.current);- timer.current = setTimeout(() => void save().catch((e) => toast.error((e as Error).message)), SAVE_MS);+ timer.current = setTimeout(() => void save().catch((e) => toastError(e)), SAVE_MS);};// Leaving with an edit not saved yet (Back, another page, closing the tab): send it now, in a request that outlives the page.@@ -194,7 +194,7 @@ export function ScriptReview({ view }: { view: EpisodeView }) {if (dirty) show((await save()).episode.script.blocks);await action.mutateAsync("render");} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};@@ -204,7 +204,7 @@ export function ScriptReview({ view }: { view: EpisodeView }) {timer.current = null;pending.current = false;setDirty(false);- action.mutate("rewrite", { onError: (e) => toast.error((e as Error).message) });+ action.mutate("rewrite", { onError: (e) => toastError(e) });};const seconds = totalSeconds(blocks.map((b) => ({ seconds: secondsFor(b.narration) })));diff --git a/src/components/fashion/character-sheet.tsx b/src/components/fashion/character-sheet.tsxindex 3a47bc0e..20cbaab2 100644--- a/src/components/fashion/character-sheet.tsx+++ b/src/components/fashion/character-sheet.tsx@@ -20,6 +20,7 @@ import { castFieldVisible, castNameFor, randomCast, SHEET_MAX_REFS, type CastAnsimport { sheetPictures } from "@/lib/catalog/turnaround";import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";type Mode = "reference" | "cast" | "describe";const MODES: [Mode, string][] = [@@ -130,7 +131,7 @@ export function SaveCharacter({ item, extra, defaultName }: { item: Generation;{ name: name.trim(), kind: "character", references: refs },{// The card turns into "Saved as @handle · Open": no toast needed.- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}@@ -189,7 +190,7 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldDatarun.mutate(body, {// The run line already says which model runs and why (its notes), so no toast here.onSuccess: (r) => setIds((xs) => [...r.items.map((g) => g.id), ...xs]),- onError: (e) => toast.error((e as Error).message || "Failed to create character sheet"),+ onError: (e) => toastError(e, "Failed to create character sheet"),});};diff --git a/src/components/fashion/fashion-view.tsx b/src/components/fashion/fashion-view.tsxindex 1fd0eff4..0caebec3 100644--- a/src/components/fashion/fashion-view.tsx+++ b/src/components/fashion/fashion-view.tsx@@ -19,6 +19,7 @@ import { keepOffered, offered } from "@/lib/model-access";import { FASHION, FASHION_MODELS, FASHION_START, FASHION_STEPS, fashionBlocker, fashionReducer, getTemplate, type FashionState } from "@/lib/catalog/packs";import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useStoredReducer } from "./stored";import { TemplatePreview } from "./template-preview";@@ -115,21 +116,21 @@ export function FashionView() {if (block(fashionBlocker(s)) || !baseBody) return;base.mutate(baseBody, {onSuccess: (r) => dispatch({ type: "baseStarted", ids: r.items.map((g) => g.id) }),- onError: (e) => toast.error((e as Error).message || "JobSet wasn't created"),+ onError: (e) => toastError(e, "JobSet wasn't created"),});};const startOutfit = () => {if (block(fashionBlocker(s, "outfit")) || !outfitBody) return;outfit.mutate(outfitBody, {onSuccess: (r) => dispatch({ type: "outfitStarted", ids: r.items.map((g) => g.id) }),- onError: (e) => toast.error((e as Error).message || "JobSet wasn't created"),+ onError: (e) => toastError(e, "JobSet wasn't created"),});};const startSet = () => {if (block(fashionBlocker(s)) || !setBody) return;photoset.mutate(setBody, {onSuccess: (r) => dispatch({ type: "photosetStarted", batchId: r.batchId ?? r.items[0]?.batchId ?? r.items[0]?.id }),- onError: (e) => toast.error((e as Error).message || "JobSet wasn't created"),+ onError: (e) => toastError(e, "JobSet wasn't created"),});};diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex c1aa2e2b..4f8d70c5 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -54,6 +54,7 @@ import type { Generation, PixelPoint } from "@/lib/catalog/types";import { downloadHref, downloadName } from "@/lib/library";import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";+import { refusalShown, toastError } from "@/lib/refusals";import { CharacterControls, CharacterFacts } from "./character-panel";import { useDescribeCharacter, useGenjutsuEstimate, useGenjutsuRun, useTranscribeClip, waitForGeneration, type GenjutsuBody } from "./hooks";import { LookPicker, type LookSource } from "./look-picker";@@ -198,7 +199,7 @@ export function GenjutsuStudio() {if (r.problem) toast.error(r.problem, { description: "The project is open: add the clip there." });router.push(`/character-swap/${encodeURIComponent(r.id)}`);} catch (e) {- toast.error((e as Error).message);+ toastError(e);setOpening(false);}};@@ -214,7 +215,7 @@ export function GenjutsuStudio() {describeMutation.mutateAsync({ engine, image }).then((r) => setCharacter((c) => ({ ...c, description: r.description })))- .catch((e: Error) => toast.error(friendly(e.message)));+ .catch((e: Error) => !refusalShown(e) && toast.error(friendly(e.message)));};const fillClipWords = async () => {if (!clip?.url || !range) return;@@ -459,7 +460,7 @@ export function GenjutsuStudio() {setRun({ final: r.final.id, ids: r.items.map((g) => g.id), before, start: at, ratio, body: base });toast("Genjutsu is on it", { description: "Follow it below — it lands in your Library too." });})- .catch((e: Error) => toast.error(friendly(e.message)));+ .catch((e: Error) => !refusalShown(e) && toast.error(friendly(e.message)));};const modeInfo = getMode(mode);diff --git a/src/components/get-started.tsx b/src/components/get-started.tsxindex 3c50a0ec..66fb7056 100644--- a/src/components/get-started.tsx+++ b/src/components/get-started.tsx@@ -11,6 +11,7 @@ import { saveSettings, useEngineMode, type StatusInfo } from "@/lib/api";import { copyWithToast } from "@/lib/clipboard";import { COMFY_INSTALL_COMMAND, COMFY_INSTALL_DOCS, FAL_KEYS_URL, nothingConnected } from "@/lib/connections";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";/*** "What do you want to do?" — Liner's first-run question, as one tap to the right place. Image and@@ -94,7 +95,7 @@ export function GetStarted({onHide?.();return true;} catch (e) {- toast.error((e as Error).message);+ toastError(e);return false;} finally {setHiding(false);diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsxindex 0803b5ed..518868bc 100644--- a/src/components/gpu/your-gpu.tsx+++ b/src/components/gpu/your-gpu.tsx@@ -8,6 +8,7 @@ import { ComfyFinder, gib, isLocalAddress } from "@/components/gpu/comfy-finder"import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { responseError, toastError } from "@/lib/refusals";interface GpuState {gpu: { url: string; hasToken: boolean } | null;@@ -25,7 +26,7 @@ async function call<T>(method: string, body?: unknown, test = false): Promise<T>body: body === undefined ? undefined : JSON.stringify(body),});const j = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, j.error ?? `Request failed (${res.status})`);return j;}@@ -70,7 +71,7 @@ export function YourGpu() {qc.setQueryData(["account-gpu"], await call<GpuState>("DELETE"));setInfo(null);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(null);}diff --git a/src/components/influencer/influencer-builder.tsx b/src/components/influencer/influencer-builder.tsxindex 8e4cc7a9..dc4472f8 100644--- a/src/components/influencer/influencer-builder.tsx+++ b/src/components/influencer/influencer-builder.tsx@@ -40,6 +40,7 @@ import {type InfluencerState,} from "@/lib/influencer";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { CATEGORY_ICON, LockButton, OptionTiles, pickRule, TierPanel } from "./option-panel";const STARTS: [InfluencerStart, string][] = [@@ -190,7 +191,7 @@ export function InfluencerBuilder() {if (!body) return toast("Wait for the uploads to finish");run.mutate(body, {onSuccess: (r) => setIds((xs) => [...r.items.map((g) => g.id), ...xs]),- onError: (e) => toast.error((e as Error).message || "Couldn't start the sheet"),+ onError: (e) => toastError(e, "Couldn't start the sheet"),});};diff --git a/src/components/katana/hooks.ts b/src/components/katana/hooks.tsindex c1cc7c3e..2a553fac 100644--- a/src/components/katana/hooks.ts+++ b/src/components/katana/hooks.ts@@ -4,10 +4,11 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useGenerationEvents } from "@/lib/api";import type { KatanaJobView, Segment } from "@/lib/av/katana";import type { Engine } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}@@ -70,7 +71,7 @@ export function useKatanaActions() {const remove = useMutation({mutationFn: async (id: string) => {const res = await fetch(`/api/katana/${id}`, { method: "DELETE" });- if (!res.ok && res.status !== 404) throw new Error("Couldn't remove it");+ if (!res.ok && res.status !== 404) throw responseError(res, "Couldn't remove it");return id;},onSuccess: (id) => qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => xs?.filter((j) => j.id !== id)),diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsxindex f226c828..2fc10a3f 100644--- a/src/components/katana/katana-studio.tsx+++ b/src/components/katana/katana-studio.tsx@@ -23,6 +23,7 @@ import { formatCueTime } from "@/lib/av/cue-edit";import { detectCutIndices, KATANA_LIMITS, katanaProgress, katanaStage, motionModel, MOTION_MODELS, nearestAspect, planSegments, refineCut, refineTimes, type KatanaJobView, type Segment } from "@/lib/av/katana";import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useKatanaActions, useKatanaJobs, useKatanaPreview, type KatanaBody } from "./hooks";type SplitMode = "fixed" | "scenes";@@ -132,7 +133,7 @@ export function KatanaStudio() {toast(found.length ? `${found.length} cut${found.length === 1 ? "" : "s"} found` : "No hard cuts — it'll be split evenly");} catch (e) {if (!cuts) setMode("fixed");- toast.error((e as Error).message);+ toastError(e);} finally {setScanning(null);}@@ -142,7 +143,7 @@ export function KatanaStudio() {if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "katana-blocker" });start.mutate(body, {onSuccess: (j) => toast.success(`Katana started · ${j.segments.length} segment${j.segments.length === 1 ? "" : "s"}`),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});};@@ -336,7 +337,7 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {const again = (id: string, all: boolean) =>retry.mutate({ id, all },- { onSuccess: (j) => toast.success(all ? `Started again · ${j.segments.length} segment${j.segments.length === 1 ? "" : "s"}` : "Retrying the failed steps"), onError: (e) => toast.error((e as Error).message) },+ { onSuccess: (j) => toast.success(all ? `Started again · ${j.segments.length} segment${j.segments.length === 1 ? "" : "s"}` : "Retrying the failed steps"), onError: (e) => toastError(e) },);if (loading)return (@@ -394,7 +395,7 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Keep it</AlertDialogCancel>- <AlertDialogAction onClick={() => remove.mutate(j.id, { onSuccess: () => toast("Removed — its clips stay in your Library"), onError: (e) => toast.error((e as Error).message) })}>Remove</AlertDialogAction>+ <AlertDialogAction onClick={() => remove.mutate(j.id, { onSuccess: () => toast("Removed — its clips stay in your Library"), onError: (e) => toastError(e) })}>Remove</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>diff --git a/src/components/layers/layers-editor.tsx b/src/components/layers/layers-editor.tsxindex eeef8a28..25007e7b 100644--- a/src/components/layers/layers-editor.tsx+++ b/src/components/layers/layers-editor.tsx@@ -32,6 +32,7 @@ import {type LayerProjectView,type LayerTool,} from "@/lib/layers";+import { toastError } from "@/lib/refusals";import { applyMeasured, idPool, type Applied } from "./apply";import { costLabel, Ctx, isFailed, isRunning, keysBelongElsewhere, latestJob, TOOL_FOR_JOB, type EditorCtx, type MaskEdit, type PaintEdit, type RunInput, type StageMode, type ToolId } from "./editor-context";import { LayersPanel } from "./layers-panel";@@ -335,7 +336,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()settings: { aspect, ...rest.settings },});} catch (e) {- toast.error((e as Error).message || "Could not start the tool");+ toastError(e, "Could not start the tool");return null;}},@@ -343,7 +344,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ());const endJob = useCallback<EditorCtx["endJob"]>(- (jobId, how) => void actions.endJob(id, jobId, how).catch((e) => toast.error((e as Error).message)),+ (jobId, how) => void actions.endJob(id, jobId, how).catch((e) => toastError(e)),[actions, id],);@@ -473,7 +474,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()toast.success("Mask saved", { duration: 1500 });setMode("select");} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setSavingMask(false);}@@ -663,7 +664,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()<div className="flex h-svh min-w-0 flex-col overflow-hidden md:h-[calc(100svh-0.5rem)]"><TopBarname={view.project.name}- onRename={(n) => void actions.rename(id, n).catch((e) => toast.error((e as Error).message))}+ onRename={(n) => void actions.rename(id, n).catch((e) => toastError(e))}save={save}onRetrySave={() => void saveNow()}canUndo={hist.past.length > 0}@@ -681,7 +682,7 @@ function Editor({ view, refetch, models }: { view: LayerProjectView; refetch: ()select(null);toast.success("Version restored", { duration: 1500 });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}}}compare={compare}diff --git a/src/components/layers/projects-view.tsx b/src/components/layers/projects-view.tsxindex 65317ddf..ee323679 100644--- a/src/components/layers/projects-view.tsx+++ b/src/components/layers/projects-view.tsx@@ -69,7 +69,7 @@ function useOpenImage(onLeft?: () => void) {leaving.current = true;router.replace(`/layers/${v.project.id}`);} catch (e) {- toast.error((e as Error).message || "Couldn't open the editor for this image. Please try again.");+ toastError(e, "Couldn't open the editor for this image. Please try again.");setBusy(null);}},@@ -380,7 +380,7 @@ function ProjectsInner() {const p = renaming!;const name = draft.trim();setRenaming(null);- if (name && name !== p.name) void rename(p.id, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toast.error((err as Error).message));+ if (name && name !== p.name) void rename(p.id, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toastError(err));}}><Input autoFocus value={draft} maxLength={80} onChange={(e) => setDraft(e.target.value)} aria-label="Project name" onFocus={(e) => e.currentTarget.select()} />@@ -409,7 +409,7 @@ function ProjectsInner() {onClick={() => {const p = deleting!;setDeleting(null);- void remove(p.id).then(() => toast("Project deleted", { duration: 1500 }), (e) => toast.error((e as Error).message));+ void remove(p.id).then(() => toast("Project deleted", { duration: 1500 }), (e) => toastError(e));}}>Delete projectdiff --git a/src/components/layers/render.ts b/src/components/layers/render.tsindex acb85737..7c3a012d 100644--- a/src/components/layers/render.ts+++ b/src/components/layers/render.ts@@ -21,6 +21,7 @@ import {type LayerDoc,type LayerNode,} from "@/lib/layers";+import { responseError } from "@/lib/refusals";// ---------------------------------------------------------------------------// Images@@ -258,7 +259,7 @@ export async function uploadDerived(blob: Blob, name: string): Promise<string> {form.append("file", new File([blob], `${slugify(name) || "layer"}.png`, { type: "image/png" }));const res = await fetch("/api/layers/renders", { method: "POST", body: form });const body = (await res.json().catch(() => ({}))) as { url?: string; error?: string };- if (!res.ok || !body.url) throw new Error(body.error ?? "Couldn't save the picture for the model. Please try again.");+ if (!res.ok || !body.url) throw responseError(res, body.error ?? "Couldn't save the picture for the model. Please try again.");return body.url;}diff --git a/src/components/layers/save-element.tsx b/src/components/layers/save-element.tsxindex 9ac411f6..7035126b 100644--- a/src/components/layers/save-element.tsx+++ b/src/components/layers/save-element.tsx@@ -9,6 +9,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { Input } from "@/components/ui/input";import { useSaveElement } from "@/lib/api";import { bboxFromAlpha, elementDraft, LAYER_ELEMENT_KINDS, type LayerElementKind, type LayerNode } from "@/lib/layers";+import { toastError } from "@/lib/refusals";import { Field, Segmented } from "./bits";import { LayerThumb } from "./layers-panel";import { renderNative, uploadRender } from "./render";@@ -50,7 +51,7 @@ export function SaveElementDialog({ node, open, onOpenChange }: { node: LayerNodonOpenChange(false);toast.success(`Saved as @${el.handle}`, { description: `${info.label} · use it in any prompt`, action: { label: "Open", onClick: () => router.push(`/elements/${el.id}`) } });} catch (e) {- toast.error((e as Error).message || "Couldn't save the element");+ toastError(e, "Couldn't save the element");} finally {setBusy(false);}diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsxindex a7bfb5ea..421af496 100644--- a/src/components/layers/tools.tsx+++ b/src/components/layers/tools.tsx@@ -76,6 +76,7 @@ import {} from "@/lib/layers";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { Field, Segmented } from "./bits";import { costLabel, isFailed, isRunning, latestJob, modelsFor, useEditor, type Target, type ToolId } from "./editor-context";import { LayerGrader } from "./grade-gl";@@ -983,7 +984,7 @@ function InpaintTool() {const [image, maskUrl, sketchUrl] = await Promise.all([uploadRender(picture, `inpaint-${name}`), uploadRender(mask, `inpaint-mask-${name}`), uploadRender(sketch, `inpaint-marked-${name}`)]);await go({ tool: "inpaint", target, image, mask: maskUrl, sketch: sketchUrl, modelId, prompt: prompt.trim(), settings: { keepAlpha }, label: "Inpaint" });} catch (e) {- toast.error((e as Error).message || "Couldn't prepare the painted area");+ toastError(e, "Couldn't prepare the painted area");} finally {setPreparing(false);}@@ -1125,7 +1126,7 @@ function ExpandTool() {commit(reframeDoc(doc, f));toast.success(grows ? "Canvas expanded" : "Canvas cropped", { duration: 1500 });} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};@@ -1133,7 +1134,7 @@ function ExpandTool() {try {reframeDoc(doc, f); // the same check as Apply} catch (e) {- toast.error((e as Error).message);+ toastError(e);return;}const [fx, fy, fw, fh] = f.map(Math.round) as Box;@@ -1215,7 +1216,7 @@ function GradeTool() {try {grader.current = new LayerGrader();} catch (e) {- toast.error((e as Error).message);+ toastError(e);}return () => {grader.current?.dispose();@@ -1266,7 +1267,7 @@ function GradeTool() {setPreset(null);toast.success("Grade applied", { duration: 1500 });} catch (e) {- toast.error((e as Error).message || "Couldn't apply the grade");+ toastError(e, "Couldn't apply the grade");} finally {setSaving(false);}diff --git a/src/components/layers/use-layers.ts b/src/components/layers/use-layers.tsindex 6b82f45d..459e9656 100644--- a/src/components/layers/use-layers.ts+++ b/src/components/layers/use-layers.ts@@ -4,6 +4,7 @@ import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-querimport { useCallback, useMemo, useRef } from "react";import { useGenerationEvents } from "@/lib/api";import type { LayerDoc, LayerJob, LayerJobInput, LayerProject, LayerProjectView } from "@/lib/layers";+import { responseError } from "@/lib/refusals";/** Client hooks for /api/layers (kept next to the Layers UI; the shapes live in src/lib/layers.ts). */@@ -18,7 +19,7 @@ export class LayersRequestError extends Error {async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new LayersRequestError(body.error ?? `Request failed (${res.status})`, res.status);+ if (!res.ok) throw responseError(res, new LayersRequestError(body.error ?? `Request failed (${res.status})`, res.status));return body;}@@ -95,7 +96,7 @@ function layerActions(qc: QueryClient) {remove: async (id: string) => {qc.setQueryData<LayerProject[]>(["layers"], (old) => old?.filter((p) => p.id !== id));const res = await fetch(`/api/layers/${id}`, { method: "DELETE" });- if (!res.ok && res.status !== 404) throw new Error("Couldn't delete this project. Please try again.");+ if (!res.ok && res.status !== 404) throw responseError(res, "Couldn't delete this project. Please try again.");qc.removeQueries({ queryKey: ["layers", id] });refreshList();},diff --git a/src/components/library/folders.tsx b/src/components/library/folders.tsxindex 98b7d07a..637a9f53 100644--- a/src/components/library/folders.tsx+++ b/src/components/library/folders.tsx@@ -30,6 +30,7 @@ import {import { useFolderActions } from "@/lib/api";import { childFolders, DEFAULT_FOLDER_COLOR, FOLDER_COLORS, folderMoveError, folderPath, folderSwatch, folderTree, MAX_FOLDER_DEPTH, type Folder } from "@/lib/library";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";/** Generation ids dragged from a card (the selection when the card is selected). */export const DRAG_TYPE = "application/x-fuobe-generations";@@ -123,7 +124,7 @@ export function useMoveFolder(all: Folder[]) {if (error) return void toast(error);actions.update(id, { parentId: target?.id ?? null }).then(() => toast.success(target ? `Moved “${f.name}” into “${target.name}”` : `Moved “${f.name}” to the top of your Library`),- (e: Error) => toast.error(e.message),+ (e: Error) => toastError(e),);};}@@ -158,7 +159,7 @@ export function FolderDialog({onSaved?.(f);if (!folder) toast.success(parent ? `Created “${f.name}” in “${parent.name}”` : `Created “${f.name}”`);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}@@ -271,7 +272,7 @@ function FolderMenu({ folder, all, onOpen, onGone, steps, triggerClassName }: {<DropdownMenuItem onSelect={later("edit")}><Pencil /> Rename or recolour</DropdownMenuItem>- <DropdownMenuItem onSelect={() => void actions.update(folder.id, { pinned: !folder.pinnedAt }).catch((e: Error) => toast.error(e.message))}>+ <DropdownMenuItem onSelect={() => void actions.update(folder.id, { pinned: !folder.pinnedAt }).catch((e: Error) => toastError(e))}>{folder.pinnedAt ? <PinOff /> : <Pin />} {folder.pinnedAt ? "Unpin" : "Pin to top"}</DropdownMenuItem><DropdownMenuSub>diff --git a/src/components/library/upload-delete.tsx b/src/components/library/upload-delete.tsxindex e08e6cfe..dc2f3825 100644--- a/src/components/library/upload-delete.tsx+++ b/src/components/library/upload-delete.tsx@@ -16,6 +16,7 @@ import {} from "@/components/ui/alert-dialog";import { assetUsage, useDeleteUpload } from "@/lib/api";import type { Generation } from "@/lib/catalog/types";+import { toastError } from "@/lib/refusals";type Check = { state: "checking" } | { state: "free" } | { state: "used"; usedBy: string } | { state: "error"; message: string };@@ -72,7 +73,7 @@ export function UploadDeleteProvider({ children }: { children: React.ReactNode }if (!pending) return;remove.mutate(pending.g.id, {onSuccess: () => toast("Upload deleted"),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});pending.after?.();}}diff --git a/src/components/lora-settings.tsx b/src/components/lora-settings.tsxindex b8b46859..5c842135 100644--- a/src/components/lora-settings.tsx+++ b/src/components/lora-settings.tsx@@ -12,6 +12,7 @@ import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { saveSettings } from "@/lib/api";import { CIVITAI_KEYS_URL } from "@/lib/connections";import { cn } from "@/lib/utils";+import { responseError, toastError } from "@/lib/refusals";interface LibraryLora {key: string;@@ -86,7 +87,7 @@ function FolderField({ setting }: { setting?: PublicSetting }) {void qc.invalidateQueries({ queryKey: ["settings"] });void qc.invalidateQueries({ queryKey: ["loras"] });},- onError: (e: Error) => toast.error(e.message),+ onError: (e: Error) => toastError(e),});return (<div className="min-w-0 space-y-1.5">@@ -194,11 +195,11 @@ export function LoraSettings({ folder, civitaiKey }: { folder?: PublicSetting; csetPending(l.file);const res = await fetch("/api/loras", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ file: l.file }) });const body = (await res.json().catch(() => ({}))) as { error?: string };- if (!res.ok) throw new Error(body.error ?? `The download didn't finish (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `The download didn't finish (${res.status})`);return l;},onSuccess: (l) => toast.success(`${l.name} is in your LoRA folder`),- onError: (e: Error) => toast.error(e.message),+ onError: (e: Error) => toastError(e),onSettled: () => {setPending(null);void qc.invalidateQueries({ queryKey: ["loras"] });diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsxindex e922a132..b3f868dd 100644--- a/src/components/marketing/click-to-ad.tsx+++ b/src/components/marketing/click-to-ad.tsx@@ -16,6 +16,7 @@ import { uploadFile } from "@/lib/api";import { AD_STYLES, END_CARD, KIT_LABELS, type BrandKit, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { endCardPng, renderEndCard, siteLabel, type EndCardInput } from "./end-card";import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts, useReadingProduct, useUpdateBrand } from "./hooks";import type { ModelInfo } from "./model-info";@@ -93,7 +94,7 @@ function KitBrand({ brand }: { brand: BrandKit }) {}const timer = useRef<ReturnType<typeof setTimeout> | null>(null);const pending = useRef<(() => void) | null>(null);- const save = (patch: Partial<Pick<BrandKit, "logo" | "colors">>) => update.mutate(patch, { onError: (e) => toast.error((e as Error).message) });+ const save = (patch: Partial<Pick<BrandKit, "logo" | "colors">>) => update.mutate(patch, { onError: (e) => toastError(e) });// Colours typed just before leaving the step still get saved.useEffect(() => {const t = timer;@@ -227,7 +228,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {setScript(r.script);if (r.by === "rules") toast("Written from your product's facts — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for livelier scripts", { duration: 4000 });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setWriting(false);}@@ -243,7 +244,7 @@ export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {toast.success("Creating your video", { duration: 1600 });resultsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/marketing/hooks.ts b/src/components/marketing/hooks.tsindex 85a0b5ec..920a2ff4 100644--- a/src/components/marketing/hooks.ts+++ b/src/components/marketing/hooks.ts@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from "react";import { useGenerationEvents } from "@/lib/api";import type { AdCreative, BrandKit, BrandKitFields, MarketingRun, Product, RunEstimate, RunFeature } from "@/lib/catalog/marketing";import type { Generation } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";/*** React Query hooks for /api/brands, /api/products, /api/marketing and /api/ads (kept next to the@@ -14,7 +15,7 @@ import type { Generation } from "@/lib/catalog/types";async function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { status: res.status });+ if (!res.ok) throw Object.assign(responseError(res, body.error ?? `Request failed (${res.status})`), { status: res.status });return body;}diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsxindex 22e88d61..a866fe11 100644--- a/src/components/marketing/marketing-studio.tsx+++ b/src/components/marketing/marketing-studio.tsx@@ -18,6 +18,7 @@ import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";import { addRuns, send, useBrands, useEstimate } from "./hooks";import type { MarketingRun } from "@/lib/catalog/marketing";+import { toastError } from "@/lib/refusals";import type { ModelInfo } from "./model-info";import { AvatarSlot, HookPicker, ProductSlot, SettingPicker, VoiceControl, type ProductChoice } from "./pickers";import { RunsList } from "./runs";@@ -355,7 +356,7 @@ export function MarketingStudio({ models }: { models: Record<string, ModelInfo>toast.success(r.runs.length > 1 ? `${r.runs.length} runs started` : f.pipeline === "image" ? "Generating" : `Started · ${est.data?.steps.length ?? ""} steps`, { duration: 1600 });set({ prompt: "" });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/marketing/runs.tsx b/src/components/marketing/runs.tsxindex 5502f293..51b3a075 100644--- a/src/components/marketing/runs.tsx+++ b/src/components/marketing/runs.tsx@@ -14,6 +14,7 @@ import { FORMATS, overlayLayout, runStatus, type BrandKit, type MarketingRun, tyimport type { Generation } from "@/lib/catalog/types";import { elapsed, formatCost, ratioValue, timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { addRuns, send, useBrands, useForgetRun, useRuns } from "./hooks";const Viewer = dynamic(() => import("@/components/studio/viewer").then((m) => m.Viewer), { ssr: false });@@ -107,7 +108,7 @@ function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?:addRuns(qc, run.feature, r.runs);toast.success("Started again", { duration: 1500 });})- .catch((e) => toast.error((e as Error).message))+ .catch((e) => toastError(e)).finally(() => setAgain(false));};return (diff --git a/src/components/mixed-media/history.tsx b/src/components/mixed-media/history.tsxindex a07b12f4..18de81e7 100644--- a/src/components/mixed-media/history.tsx+++ b/src/components/mixed-media/history.tsx@@ -14,6 +14,7 @@ import { chainState } from "@/lib/catalog/shorts";import type { Generation } from "@/lib/catalog/types";import { timeAgo } from "@/lib/format";import { downloadHref, downloadName, userTitle } from "@/lib/library";+import { toastError } from "@/lib/refusals";import { isFrameRender, renderSteps, useFramesProgress, useMixedActions } from "./hooks";/** The finished videos and their helper steps (a failed render shows the failing step's own error). */@@ -42,7 +43,7 @@ export function MixedHistory({ onStart }: { onStart: () => void }) {if (actions.retry.isPending) return;void guard(`retry:${id}`, (requestId) => actions.retry.mutateAsync({ id, requestId })).then((r) => r && toast("Rendering it again"))- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};if (list.isLoading)return (diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex bbbfb13d..c8f34d9c 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -38,6 +38,7 @@ import type { Engine, Generation } from "@/lib/catalog/types";import { downloadHref, downloadName } from "@/lib/library";import type { TrimRange } from "@/lib/trim-range";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { MixedHistory } from "./history";import { isFrameRender, renderSteps, useFramesProgress, useMixedActions, useMixedEstimate, useWatchedChain, useWatchedGeneration, type MixedBody } from "./hooks";import { AdvancedSettings, loadSaved } from "./settings";@@ -438,7 +439,7 @@ function Editor({}const g = await actions.preview.mutateAsync({ ...body, frameUrl, requestId });setPreviewId(g.id);- }).catch((e: Error) => toast.error(e.message));+ }).catch((e: Error) => toastError(e));};const generate = () => {@@ -451,7 +452,7 @@ function Editor({setRenderFrames(r.frames ?? 0);toast("Rendering your video", { description: "It shows up in History too." });})- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};return (diff --git a/src/components/model-access-view.tsx b/src/components/model-access-view.tsxindex 103196d3..b7b158ad 100644--- a/src/components/model-access-view.tsx+++ b/src/components/model-access-view.tsx@@ -11,6 +11,7 @@ import { useProgressive } from "@/components/use-progressive";import { kindLabel, LICENCE_CLASSES, CLASS_LABEL, type LicenceClass, type LicenceInfo } from "@/lib/licences";import { allOn, applyChange, type AccessChange, type AccessList, type LoraInfo, type ModelAccess, type ModelEntry, type PackInfo } from "@/lib/model-access";import { cn } from "@/lib/utils";+import { responseError } from "@/lib/refusals";/** Settings → Models & licences: every model, LoRA and node pack with its licence, and the switches. */@@ -208,7 +209,7 @@ export function ModelAccessView() {mutationFn: async (changes: AccessChange[]) => {const res = await fetch("/api/settings/models", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ changes }) });const body = (await res.json().catch(() => ({}))) as Partial<AccessList> & { error?: string };- if (!res.ok || !body.access) throw new Error(body.error ?? `The switch didn't save (${res.status})`);+ if (!res.ok || !body.access) throw responseError(res, body.error ?? `The switch didn't save (${res.status})`);return body as AccessList;},// The switch moves at once; the server's answer brings what else changed (models now off, counts).diff --git a/src/components/model3d/hooks.ts b/src/components/model3d/hooks.tsindex 3ce1fc30..94ccf8ab 100644--- a/src/components/model3d/hooks.ts+++ b/src/components/model3d/hooks.ts@@ -3,6 +3,7 @@import { useQuery } from "@tanstack/react-query";import { useEffect, useState } from "react";import type { GenerationRequest } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";/** What /api/generations?preview=1 says a request would run as (the parts the page shows). */export interface RunPreview {@@ -35,7 +36,7 @@ export function useRunPreview(req: GenerationRequest | null) {queryFn: async () => {const res = await fetch("/api/generations?preview=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: body! });const j = (await res.json().catch(() => ({}))) as RunPreview & { error?: string };- if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, j.error ?? `Request failed (${res.status})`);return j;},});diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsxindex 56e0485c..e135779b 100644--- a/src/components/model3d/model-card.tsx+++ b/src/components/model3d/model-card.tsx@@ -9,6 +9,7 @@ import { uploadFile, useHydrated } from "@/lib/api";import { animateSpinHref, animationName, model3dView, stillOf, type Model3dView } from "@/lib/av/model3d";import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { loadModelViewer, TURNTABLE_BACKDROP, useViewerSrc, viewerLook } from "./model-viewer";import type { Model3dInfo } from "./model3d-studio";import { RigDialog } from "./rig-dialog";@@ -100,7 +101,7 @@ export function ModelCard({ g, info, cloudAllowed }: { g: Generation; info: RecosetRecorded({ url, saved: asset.url });toast.success("Turntable recorded — saved to your uploads");} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setRecording(null);}diff --git a/src/components/moodboards/create-moodboard.tsx b/src/components/moodboards/create-moodboard.tsxindex 0069b5ba..5553b171 100644--- a/src/components/moodboards/create-moodboard.tsx+++ b/src/components/moodboards/create-moodboard.tsx@@ -122,7 +122,7 @@ export function CreateMoodboardDialog({ open, onOpenChange, onCreated }: { open:onCreated?.(m);setOpen(false);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/moodboards/hooks.ts b/src/components/moodboards/hooks.tsindex 17d6450b..7a94b2ce 100644--- a/src/components/moodboards/hooks.ts+++ b/src/components/moodboards/hooks.ts@@ -3,6 +3,7 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useCallback, useMemo } from "react";import type { Engine } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";import { CURATED_SETS, type CuratedMoodboard, type CuratedSource, type Moodboard } from "./logic";/** A curated set (Fuobe Soul's Soul 2.0 looks or its Soul looks): built in, nothing to fetch. */@@ -12,7 +13,7 @@ export function useCuratedSet(source: CuratedSource): CuratedMoodboard[] {async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/moodboards/moodboards-view.tsx b/src/components/moodboards/moodboards-view.tsxindex 9473dc80..6a989ca8 100644--- a/src/components/moodboards/moodboards-view.tsx+++ b/src/components/moodboards/moodboards-view.tsx@@ -24,6 +24,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { EngineSwitch } from "@/components/studio/engine-switch";import { useEngine } from "@/lib/api";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { BoardCover, CuratedCover, StatusBadge } from "./cards";import { CreateMoodboardDialog } from "./create-moodboard";import { TrainBoardDialog } from "./train-board";@@ -98,7 +99,7 @@ function BoardCard({ m, onRename, onDelete }: { m: Moodboard; onRename: () => voonSelect={() =>retry.mutate({ id: m.id, engine: m.status === "complete" ? (m.engine === "cloud" ? "open" : "cloud") : undefined },- { onSuccess: () => toast("Rebuilding the moodboard"), onError: (e) => toast.error((e as Error).message) },+ { onSuccess: () => toast("Rebuilding the moodboard"), onError: (e) => toastError(e) },)}>@@ -291,7 +292,7 @@ export function MoodboardsView() {renaming &&rename.mutate({ id: renaming.id, name: newName },- { onSuccess: () => (setRenaming(null), toast("Renamed")), onError: (e) => toast.error((e as Error).message) },+ { onSuccess: () => (setRenaming(null), toast("Renamed")), onError: (e) => toastError(e) },)}>@@ -311,7 +312,7 @@ export function MoodboardsView() {<AlertDialogCancel>{COPY.deleteNo}</AlertDialogCancel><AlertDialogActionvariant="destructive"- onClick={() => deleting && remove.mutate(deleting.id, { onSuccess: () => toast("Moodboard deleted"), onError: (e) => toast.error((e as Error).message) })}+ onClick={() => deleting && remove.mutate(deleting.id, { onSuccess: () => toast("Moodboard deleted"), onError: (e) => toastError(e) })}>{COPY.deleteYes}</AlertDialogAction>diff --git a/src/components/moodboards/train-board.tsx b/src/components/moodboards/train-board.tsxindex d65475d3..5f069f58 100644--- a/src/components/moodboards/train-board.tsx+++ b/src/components/moodboards/train-board.tsx@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { licenceNote, trainingSettingsHref, type TrainingTarget } from "@/lib/catalog/training";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useMoodboardActions } from "./hooks";import type { Moodboard } from "./logic";@@ -69,7 +70,7 @@ export function TrainBoardDialog({ board, open, onOpenChange }: { board: Moodboatoast.success(t.demo ? "Demo training: nothing real is trained" : `Training “${board.name}” as a look — you can keep working`);onOpenChange(false);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}diff --git a/src/components/palettes/color-signature-panel.tsx b/src/components/palettes/color-signature-panel.tsxindex 72415842..9e644a07 100644--- a/src/components/palettes/color-signature-panel.tsx+++ b/src/components/palettes/color-signature-panel.tsx@@ -20,6 +20,7 @@ import { Switch } from "@/components/ui/switch";import { uploadFile } from "@/lib/api";import { MAX_SOURCE_IMAGES, NAME_MAX, suggestName, type Palette, type PalettePick } from "@/lib/catalog/palettes";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { extractFromFiles } from "./extract";import { usePaletteActions, usePalettes } from "./hooks";import { PaletteCard, Strip } from "./palette-card";@@ -52,7 +53,7 @@ function FromImages({ files, setFiles, onSaved }: { files: File[]; setFiles: (f:.catch((e) => {if (!live) return;setDone({ files, colors: [], background: null, name: "" });- toast.error((e as Error).message);+ toastError(e);});return () => {live = false;@@ -71,7 +72,7 @@ function FromImages({ files, setFiles, onSaved }: { files: File[]; setFiles: (f:toast.success("Palette saved");onSaved(p);} catch (e) {- toast.error((e as Error).message || "Failed to save palette");+ toastError(e, "Failed to save palette");} finally {setSaving(false);}@@ -212,7 +213,7 @@ export function ColorSignaturePanel({if (value?.id === p.id) onPick(undefined);toast("Palette deleted");},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}/>@@ -276,7 +277,7 @@ export function ColorSignaturePanel({setView("list");onPick(toPalettePick(p, value?.lock));},- onError: (e) => toast.error((e as Error).message || "Failed to save palette"),+ onError: (e) => toastError(e, "Failed to save palette"),},)}diff --git a/src/components/palettes/hooks.ts b/src/components/palettes/hooks.tsindex 39d7d883..20de50bd 100644--- a/src/components/palettes/hooks.ts+++ b/src/components/palettes/hooks.ts@@ -3,10 +3,11 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useCallback, useMemo } from "react";import type { Palette, SignatureCaps } from "@/lib/catalog/palettes";+import { responseError } from "@/lib/refusals";async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/palettes/use-signature.ts b/src/components/palettes/use-signature.tsindex 991c056e..24a6fc83 100644--- a/src/components/palettes/use-signature.ts+++ b/src/components/palettes/use-signature.ts@@ -4,6 +4,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { useCallback } from "react";import { applySignature, withSignatureWords, type Signature, type SignedRequest } from "@/lib/catalog/palettes";import type { Generation, GenerationRequest } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";import { useCatalog } from "@/components/studio/catalog";import { usePalettes } from "./hooks";@@ -30,7 +31,7 @@ export function useSignature(enabled: boolean, signature: Signature | undefined)mutationFn: async (b: { request: GenerationRequest; colors: string[] }) => {const res = await fetch("/api/palettes/lock", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });const body = (await res.json().catch(() => ({}))) as { items?: Generation[]; error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body.items ?? [];},onSuccess: () => void qc.invalidateQueries({ queryKey: ["generations"] }),diff --git a/src/components/photodump/hooks.ts b/src/components/photodump/hooks.tsindex 209e398a..3a5f762f 100644--- a/src/components/photodump/hooks.ts+++ b/src/components/photodump/hooks.ts@@ -2,10 +2,11 @@import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type { Generation } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/photodump/photodump-view.tsx b/src/components/photodump/photodump-view.tsxindex d80697b0..ebfc281c 100644--- a/src/components/photodump/photodump-view.tsx+++ b/src/components/photodump/photodump-view.tsx@@ -17,6 +17,7 @@ import { customPack, DEFAULT_ASPECT, MAX_PACK_REFS, MAX_SELFIE_MB, PACKS, PHOTODimport type { Generation } from "@/lib/catalog/types";import { timeAgo } from "@/lib/format";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { PackCover } from "./covers";import { useRun, useRunPreview, usePackActions, useUserPacks } from "./hooks";import { DownloadAll, ResultsGrid, runState } from "./results";@@ -107,7 +108,7 @@ function CreatePack({ open, onOpenChange, onCreated }: { open: boolean; onOpenChonOpenChange(false);onCreated(p.id);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}@@ -208,7 +209,7 @@ export function PhotodumpView() {setBatchId(res.batchId ?? res.items[0]?.batchId ?? undefined);go(2);},- onError: (e) => toast.error((e as Error).message || "Cannot start photodump generation, please try again"),+ onError: (e) => toastError(e, "Cannot start photodump generation, please try again"),});};diff --git a/src/components/photodump/results.tsx b/src/components/photodump/results.tsxindex 9d242941..0225682d 100644--- a/src/components/photodump/results.tsx+++ b/src/components/photodump/results.tsx@@ -3,13 +3,13 @@import { Check, Download, Film, Loader2, Maximize2, Pencil, RotateCcw, Trash2 } from "lucide-react";import Link from "next/link";import { useMemo, useState } from "react";-import { toast } from "sonner";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { MediaThumb, PendingTile } from "@/components/studio/feed";import { Viewer } from "@/components/studio/viewer";import { useGenerationActions } from "@/lib/api";import type { Generation, OutputFile } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useRetryPhoto } from "./hooks";export interface Tile {@@ -131,7 +131,7 @@ export function ResultsGrid({onRetry={() =>retry.mutate(t.g.id, {onSuccess: (r) => onRetried?.(t.g.id, r.items.map((x) => x.id)),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}/>diff --git a/src/components/photodump/subject.tsx b/src/components/photodump/subject.tsxindex deea829c..293383d0 100644--- a/src/components/photodump/subject.tsx+++ b/src/components/photodump/subject.tsx@@ -13,6 +13,7 @@ import { useElements, useSaveElement } from "@/lib/api";import type { StudioElement } from "@/lib/catalog/elements";import { SOUL_ID_COPY, SOUL_ID_PHOTOS } from "@/lib/catalog/training";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";/** What a character brings: a trained Soul ID (Fuobe Soul), an old Higgsfield one to retrain, or just photos. */export function identityLabel(el: StudioElement): string {@@ -110,7 +111,7 @@ export function QuickCharacter({ open, onOpenChange, onCreated }: { open: booleasetPhotos([]);onOpenChange(false);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},)}diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsxindex f1a66f39..53492a3d 100644--- a/src/components/remove-object/remove-object-tool.tsx+++ b/src/components/remove-object/remove-object-tool.tsx@@ -33,6 +33,7 @@ import type { Generation, PixelPoint } from "@/lib/catalog/types";import { downloadHref, downloadName } from "@/lib/library";import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { FrameStage, frameFromBlob, type Frame } from "./frame-stage";import { useRemovalActions, useRemovalEstimate, type RemovalBody } from "./hooks";import { VideoCompare } from "./video-compare";@@ -219,7 +220,7 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {setRun({ final: r.final.id, ids: r.items.map((g) => g.id), before: clip!.preview, start: range!.startTime, ratio });toast("Removing it", { description: "Follow it below — it lands in your Library too." });})- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};const canPreview = !!body && est?.previewUsd != null;@@ -228,7 +229,7 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {const of = { exact: est.previewExact, eraser: est.modelName };void previewGuard(JSON.stringify(body), (requestId) => actions.preview.mutateAsync({ ...body, requestId })).then((g) => g && setPreviewOf({ id: g.id, ...of }))- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};const preview = useGeneration(previewOf?.id ?? null).data;diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex ba5967c6..edc80100 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -22,6 +22,7 @@ import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";import { copyWithToast } from "@/lib/clipboard";import { timeAgo } from "@/lib/format";+import { responseError, toastError } from "@/lib/refusals";interface TokenInfo {id: string;@@ -40,7 +41,7 @@ async function call<T>(url: string, method: string, body?: unknown): Promise<T>const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });if (res.status === 204) return undefined as T;const j = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, j.error ?? `Request failed (${res.status})`);return j;}@@ -60,7 +61,7 @@ function PasswordForm({ status, onDone }: { status: AuthStatus; onDone: () => vosetConfirm("");onDone();} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}@@ -136,7 +137,7 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => voidsetName("");onChange();} catch (e) {- toast.error((e as Error).message);+ toastError(e);}};return (@@ -179,7 +180,7 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => voidclassName="size-8 text-muted-foreground hover:text-destructive"aria-label={`Revoke ${t.name}`}onClick={async () => {- await call(`/api/auth/tokens?id=${t.id}`, "DELETE").catch((e) => toast.error((e as Error).message));+ await call(`/api/auth/tokens?id=${t.id}`, "DELETE").catch((e) => toastError(e));onChange();}}>@@ -225,7 +226,7 @@ function SignOutEveryone({ tokens }: { tokens: number }) {// This browser is signed out too.router.replace("/login?owner=1");} catch (e) {- toast.error((e as Error).message);+ toastError(e);setBusy(false);}};@@ -284,7 +285,7 @@ function PublicSignup() {qc.setQueryData(["auth", "public"], await call<PublicSignupStatus>("/api/auth/public", "PUT", { on }));void qc.invalidateQueries({ queryKey: ["viewer"] });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/share/publish-wizard.tsx b/src/components/share/publish-wizard.tsxindex 7e105df0..75c59494 100644--- a/src/components/share/publish-wizard.tsx+++ b/src/components/share/publish-wizard.tsx@@ -16,6 +16,7 @@ import { userTitle } from "@/lib/library";import { shownOutputs } from "@/lib/output-actions";import { MAX_PUBLISH_ITEMS, MAX_TAGS, moveItem, parseTags, pieces, PUBLISH_LAYOUTS, type ShareCreated, type ShareLayout } from "@/lib/share";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { ExpiryPicker } from "./share-dialog";const STEPS = ["Details", "Assets", "Cover", "Access"] as const;@@ -60,7 +61,7 @@ export function PublishWizard({ items, onClose, onPublished }: { items: Generatiawait actions.create({ kind: "publish", items: order.map((g) => g.id), title, description, tags, layout, cover: coverOf, showPrompts, expiresInDays: days }),);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/share/share-dialog.tsx b/src/components/share/share-dialog.tsxindex 24831852..dcf1b686 100644--- a/src/components/share/share-dialog.tsx+++ b/src/components/share/share-dialog.tsx@@ -3,7 +3,6 @@import { Check, Copy, ExternalLink, Link2, Loader2, TriangleAlert } from "lucide-react";import Link from "next/link";import { useState } from "react";-import { toast } from "sonner";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";@@ -15,6 +14,7 @@ import type { Generation } from "@/lib/catalog/types";import { copyWithToast } from "@/lib/clipboard";import { EXPIRY_CHOICES, expiryLabel, type ShareCreated, type ShareInfo } from "@/lib/share";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { PublishWizard } from "./publish-wizard";import { rememberLink, shareUrl, type ShareTarget } from "./share-provider";@@ -54,7 +54,7 @@ function ShareForm({ target, onMade }: { target: ShareTarget; onMade: (c: ShareCtry {onMade(await actions.create({ kind: target.kind, targetId: target.id, title, showPrompts, expiresInDays: days }));} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setBusy(false);}diff --git a/src/components/share/shared-links.tsx b/src/components/share/shared-links.tsxindex 4afe2ed7..b127069f 100644--- a/src/components/share/shared-links.tsx+++ b/src/components/share/shared-links.tsx@@ -32,6 +32,7 @@ import { copyWithToast } from "@/lib/clipboard";import { timeAgo } from "@/lib/format";import { EXPIRY_CHOICES, expiryLabel, isExpired, KIND_LABELS, pieces, PUBLISH_LAYOUTS, type ShareListItem, type SharePatch } from "@/lib/share";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { forgetLink, rememberLink, shareUrl, useRememberedLinks, useShare } from "./share-provider";/**@@ -111,7 +112,7 @@ function Row({ s, token, now }: { s: ShareListItem; token?: string; now: numberconst [confirm, setConfirm] = useState(false);const expired = isExpired(s, now);const dead = s.gone || expired;- const fail = (e: Error) => toast.error(e.message);+ const fail = (e: Error) => toastError(e);const kind = s.kind === "publish" ? `${PUBLISH_LAYOUTS.find((l) => l.id === s.layout)?.label ?? "Published"} page` : KIND_LABELS[s.kind];// A new token (and, for an expired link, a new expiry with it): the dialog shows the link to copy.const renew = (patch: SharePatch = {}) =>diff --git a/src/components/shorts/custom-preset-dialog.tsx b/src/components/shorts/custom-preset-dialog.tsxindex aa57d734..9e538fe4 100644--- a/src/components/shorts/custom-preset-dialog.tsx+++ b/src/components/shorts/custom-preset-dialog.tsx@@ -89,7 +89,7 @@ export function CustomPresetDialog({onSaved(p);onOpenChange(false);};- const fail = (e: Error) => toast.error(e.message);+ const fail = (e: Error) => toastError(e);if (preset) actions.update.mutate({ id: preset.id, ...body }, { onSuccess: done, onError: fail });else actions.create.mutate(body, { onSuccess: done, onError: fail });};@@ -199,7 +199,7 @@ export function CustomPresetDialog({toast("Preset deleted");onOpenChange(false);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.tsindex f13e7117..2f00c77b 100644--- a/src/components/shorts/hooks.ts+++ b/src/components/shorts/hooks.ts@@ -6,13 +6,14 @@ import { useCallback, useDeferredValue, useRef } from "react";import type { ShortsCustomPreset, ShortsRange, ShortsRatio, ShortsSession } from "@/lib/catalog/shorts";import type { Engine, Generation } from "@/lib/catalog/types";import { useGenerationEvents } from "@/lib/api";+import { responseError } from "@/lib/refusals";/** React Query hooks for /api/shorts/** (kept next to the studio that uses them). */async function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex feab9745..1846244c 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -27,6 +27,7 @@ import type { Generation } from "@/lib/catalog/types";import { formatCost, ratioValue, timeAgo } from "@/lib/format";import { downloadHref, downloadName } from "@/lib/library";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useShortsActions, useShortsSession, useSubmitGuard, type ShortsSessionView as View } from "./hooks";import { Steps } from "./ui";@@ -120,13 +121,13 @@ function Session({ s }: { s: View }) {if (!canStitch || actions.stitch.isPending) return;void stitchGuard(`stitch:${s.segments.map((g) => g.primary).join(",")}`, (requestId) => actions.stitch.mutateAsync({ requestId })).then((v) => v && toast("Stitching your short"))- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};const regenerate = (i: number) => {if (actions.regenerate.isPending) return;void takeGuard(`take:${i}:${s.segments[i].takes.length}`, (requestId) => actions.regenerate.mutateAsync({ index: i, requestId })).then((v) => v && toast(`New take of segment ${i + 1} on the way`))- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};return (@@ -244,7 +245,7 @@ function Session({ s }: { s: View }) {onRegenerate={() => regenerate(i)}regenerating={actions.regenerate.isPending && actions.regenerate.variables?.index === i}busy={actions.regenerate.isPending}- onPrimary={(gid) => actions.primary.mutate({ index: i, generationId: gid }, { onError: (e) => toast.error((e as Error).message) })}+ onPrimary={(gid) => actions.primary.mutate({ index: i, generationId: gid }, { onError: (e) => toastError(e) })}/>))}</div>@@ -267,7 +268,7 @@ function Session({ s }: { s: View }) {toast("Moved to Trash");router.push("/shorts?tab=history");},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex ac912fc4..7b0f6a50 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -27,6 +27,7 @@ import type { Engine } from "@/lib/catalog/types";import type { TrimRange } from "@/lib/trim-range";import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { CustomPresetDialog } from "./custom-preset-dialog";import { useShortsActions, useShortsEstimate, useShortsPresets, useSubmitGuard, type ShortsBody } from "./hooks";import { CreateCard, CustomCard, LookCard } from "./preset-card";@@ -384,7 +385,7 @@ function SetupPanel({setLeaving(true);router.push(`/shorts/${s.id}`);})- .catch((e: Error) => toast.error(e.message));+ .catch((e: Error) => toastError(e));};return (diff --git a/src/components/skills/skill-builder.tsx b/src/components/skills/skill-builder.tsxindex 160201b0..b4c3293f 100644--- a/src/components/skills/skill-builder.tsx+++ b/src/components/skills/skill-builder.tsx@@ -17,6 +17,7 @@ import { SKILL_LIMITS, SKILL_NAME_RE } from "@/lib/assist";import { formatCost } from "@/lib/format";import { isMediaType, recipeProblems, RECIPE_LIMITS, type ParamType } from "@/lib/recipe";import { buildRecipe, paramIdFrom, skillBody, slugify, type DraftCandidate, type DraftRefusal, type DraftStep, type Naming, type SkillDraft, type Slot } from "@/lib/recipe-builder";+import { refusalShown } from "@/lib/refusals";import { cn } from "@/lib/utils";/**@@ -159,6 +160,7 @@ function Review({ draft, refusals, ids, onClose, onSaved, header }: { draft: SkionSaved(view.name);} catch (e) {const f = e as Error & { problems?: string[] };+ if (refusalShown(f)) return;setProblems(f.problems ?? [f.message]);toast.error(f.message);} finally {diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsxindex 72715b20..0f637a10 100644--- a/src/components/storyboard-view.tsx+++ b/src/components/storyboard-view.tsx@@ -330,7 +330,7 @@ export function StoryboardView({ modelNames = {} }: { /** Display names of the squeryFn: async () => {const res = await fetch("/api/storyboards/estimate", { method: "POST", headers: { "Content-Type": "application/json" }, body: priceKey });const body = await res.json();- if (!res.ok) throw new Error(body.error);+ if (!res.ok) throw responseError(res, body.error);return body as BoardEstimate;},placeholderData: keepPreviousData,diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 798e9dec..4fee6597 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -511,7 +511,7 @@ export function Composer({ docked }: { docked: boolean }) {// No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.const sent = signature.apply(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)));// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).- if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors }, { onError: (e) => toast.error((e as Error).message) });+ if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors }, { onError: (e) => toastError(e) });// If the server's pre-flight stops it (409 gpu-setup), the guided fix that opens can try again, or run it anyway.setGpuRetry(() => submitRef.current(),diff --git a/src/components/studio/sketch-editor.tsx b/src/components/studio/sketch-editor.tsxindex ae4ce354..49233220 100644--- a/src/components/studio/sketch-editor.tsx+++ b/src/components/studio/sketch-editor.tsx@@ -2,7 +2,6 @@import { Brush, Eraser, Loader2, Redo2, RotateCcw, Type, Undo2 } from "lucide-react";import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";-import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Slider } from "@/components/ui/slider";@@ -11,6 +10,7 @@ import { uploadFile } from "@/lib/api";import type { MotionPaths } from "@/lib/motion-paths";import { keyCombo, useModKey } from "@/lib/keys";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";/*** Paint on top of an image.@@ -191,7 +191,7 @@ function SketchCanvas({const noteOpen = useRef(false);useEffect(() => {- loadImage(image).then(setImg, (e) => toast.error((e as Error).message));+ loadImage(image).then(setImg, (e) => toastError(e));}, [image]);// Fit the image into the available area; strokes are stored in image pixels.@@ -428,7 +428,7 @@ function SketchCanvas({onDone({ mask: maskUrl, overlay: overlay.url, preview: overlay.url, motion, strokes });onOpenChange(false);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setSaving(false);}diff --git a/src/components/swap-studio/home.tsx b/src/components/swap-studio/home.tsxindex 40aea647..eb78eef5 100644--- a/src/components/swap-studio/home.tsx+++ b/src/components/swap-studio/home.tsx@@ -14,6 +14,7 @@ import { useEngine } from "@/lib/api";import { characterLicenceLine } from "@/lib/catalog/character-swap";import { SWAP_STUDIO, type SwapProjectCard } from "@/lib/catalog/swap-studio";import { STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";+import { toastError } from "@/lib/refusals";import { useCreateSwapProject, useDeleteSwapProject, useSwapProjects } from "./hooks";const STEPS = [@@ -46,7 +47,7 @@ export function SwapStudioHome() {{ name: name.trim() || undefined, engine },{onSuccess: (p) => router.push(`/character-swap/${p.id}`),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);@@ -166,7 +167,7 @@ export function SwapStudioHome() {confirm &&del.mutate(confirm.id, {onSuccess: () => toast("Project deleted"),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),})}>diff --git a/src/components/swap-studio/hooks.ts b/src/components/swap-studio/hooks.tsindex 1858ea9a..1dc34b4d 100644--- a/src/components/swap-studio/hooks.ts+++ b/src/components/swap-studio/hooks.ts@@ -4,13 +4,14 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstaimport { studioHandOff, type HandOffInput, type QueueMode, type StudioEstimate, type SwapProject, type SwapProjectCard, type SwapProjectView } from "@/lib/catalog/swap-studio";import type { SwapEdit } from "@/lib/catalog/swap-studio-edit";import type { Engine, PixelPoint } from "@/lib/catalog/types";+import { responseError } from "@/lib/refusals";/** React Query hooks for /api/swap-studio/** (Character Swap Studio). */async function json<T>(res: Response): Promise<T> {if (res.status === 204) return undefined as T;const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}diff --git a/src/components/swap-studio/stage-anchors.tsx b/src/components/swap-studio/stage-anchors.tsxindex 04cbdebc..a066e995 100644--- a/src/components/swap-studio/stage-anchors.tsx+++ b/src/components/swap-studio/stage-anchors.tsx@@ -68,7 +68,7 @@ export function AnchorMaker({ id, project, clip, shotId, segment, estimate }: Pidisabled={make.isPending || !project.character.image}title={!project.character.image ? "Add a picture of your character first" : picked?.note}onClick={() =>- make.mutate({ clipId: clip.id, shotId, ...(segment ? { segmentId: segment.id } : {}), modelId }, { onSuccess: () => toast(`Making a ${which} with ${picked?.label ?? "the image model"}`), onError: (e) => toast.error((e as Error).message) })+ make.mutate({ clipId: clip.id, shotId, ...(segment ? { segmentId: segment.id } : {}), modelId }, { onSuccess: () => toast(`Making a ${which} with ${picked?.label ?? "the image model"}`), onError: (e) => toastError(e) })}>{make.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />} Make {which}diff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsxindex 9b306db0..d42e2ce1 100644--- a/src/components/swap-studio/stage-review.tsx+++ b/src/components/swap-studio/stage-review.tsx@@ -13,6 +13,7 @@ import { assemblyPieces, assemblyTakes, currentSegments, DECISION_LABELS, FINISHimport { STUDIO_MODELS } from "@/lib/catalog/swap-studio-plan";import { downloadHref } from "@/lib/library";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { decisionsHref, useAssemble, useStopJob } from "./hooks";import { GenChip, JobError, Note, priceText, SavedText } from "./parts";import type { StageProps } from "./workbench";@@ -211,7 +212,7 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)<ButtonclassName="h-9 rounded-full"disabled={"problem" in found || assemble.isPending || state.status === "queued" || state.status === "running" || (current && state.status === "succeeded")}- onClick={() => assemble.mutate({ clipId: clip.id }, { onSuccess: () => toast("Assembling the clip"), onError: (e) => toast.error((e as Error).message) })}+ onClick={() => assemble.mutate({ clipId: clip.id }, { onSuccess: () => toast("Assembling the clip"), onError: (e) => toastError(e) })}>{assemble.isPending ? <Loader2 className="size-4 animate-spin" /> : <Film className="size-4" />} {a ? "Assemble again" : "Assemble clip"}</Button>diff --git a/src/components/swap-studio/stage-segments.tsx b/src/components/swap-studio/stage-segments.tsxindex f29bb6f5..b2b6c67a 100644--- a/src/components/swap-studio/stage-segments.tsx+++ b/src/components/swap-studio/stage-segments.tsx@@ -25,6 +25,7 @@ import {type SwapTake,} from "@/lib/catalog/swap-studio";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useQueue, useStopJob, useStopTake } from "./hooks";import { AnchorGrid, AnchorMaker } from "./stage-anchors";import { JobChip, Note, NumberField, priceText, SavedText } from "./parts";@@ -178,7 +179,7 @@ function SegmentCard(props: StageProps & { shot: SwapShot; seg: SwapSegment; indtoast(`Queued ${r.takes.length} take${r.takes.length === 1 ? "" : "s"}`);for (const note of r.notes) toast(note);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);const price = estimate?.segments[seg.id];@@ -339,7 +340,7 @@ function SegmentCard(props: StageProps & { shot: SwapShot; seg: SwapSegment; indselected={seg.selectedTake === t.id}gens={gens}onSelect={() => void edit({ type: "take", clipId: clip.id, shotId: shot.id, segmentId: seg.id, takeId: t.id, select: true })}- onStop={() => stopTake.mutate({ clipId: clip.id, shotId: shot.id, segmentId: seg.id, takeId: t.id }, { onError: (e) => toast.error((e as Error).message) })}+ onStop={() => stopTake.mutate({ clipId: clip.id, shotId: shot.id, segmentId: seg.id, takeId: t.id }, { onError: (e) => toastError(e) })}onRetry={() => run("segment")}/>))}@@ -403,7 +404,7 @@ export function SegmentsStage(props: StageProps) {onClick={() =>queue.mutate({ clipId: clip.id, shotId: shot.id, segmentId: items[0].id, mode: "all" },- { onSuccess: (r) => toast(`Queued ${r.takes.length} take${r.takes.length === 1 ? "" : "s"}`), onError: (e) => toast.error((e as Error).message) },+ { onSuccess: (r) => toast(`Queued ${r.takes.length} take${r.takes.length === 1 ? "" : "s"}`), onError: (e) => toastError(e) },)}>diff --git a/src/components/swap-studio/stage-who.tsx b/src/components/swap-studio/stage-who.tsxindex 0a7dd1a0..6564d1a4 100644--- a/src/components/swap-studio/stage-who.tsx+++ b/src/components/swap-studio/stage-who.tsx@@ -12,6 +12,7 @@ import { WHO_INDEX_LABEL, WHO_LABELS, type SwapWho } from "@/lib/catalog/charactimport { approvedMask, at, jobState, maskPieceAt, secondsLabel, SWAP_STUDIO, type MaskVersion } from "@/lib/catalog/swap-studio";import type { PixelPoint } from "@/lib/catalog/types";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { useMakeMask, useStopJob } from "./hooks";import { GenChip, grabFrame, JobError, Note, priceText } from "./parts";import type { StageProps } from "./workbench";@@ -48,7 +49,7 @@ export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }:setFrame({ shot: shot.id, f, image });setPoints([]);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setLoading(false);}@@ -62,7 +63,7 @@ export function WhoStage({ id, project, clip, shot, gens, estimate, edit, src }:setPoints([]);toast(kind === "track" ? `Tracking from frame ${f + 1} to the shot's end` : `Updating frame ${f + 1}`);},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),},);};diff --git a/src/components/swap-studio/stage-words.tsx b/src/components/swap-studio/stage-words.tsxindex 335590e8..862a91cd 100644--- a/src/components/swap-studio/stage-words.tsx+++ b/src/components/swap-studio/stage-words.tsx@@ -1,11 +1,11 @@"use client";import { Loader2, Mic, Wand2 } from "lucide-react";-import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Panel } from "@/components/av/tool-shell";import { buildShotPrompt, ROLE_LABELS, secondsLabel, shotDialogue, shotSpeaker, SWAP_STUDIO, voiceLabel, voicesOf, type SwapRole } from "@/lib/catalog/swap-studio";+import { toastError } from "@/lib/refusals";import { useTranscribe } from "./hooks";import { GenChip, JobError, Note, priceText, SavedText } from "./parts";import type { StageProps } from "./workbench";@@ -49,7 +49,7 @@ export function WordsStage({ id, project, clip, gens, estimate, edit }: StageProvariant={t?.cues ? "outline" : "default"}className="h-8 rounded-full"disabled={busy || transcribe.isPending || !clip.source.hasAudio}- onClick={() => transcribe.mutate({ clipId: clip.id }, { onError: (e) => toast.error((e as Error).message) })}+ onClick={() => transcribe.mutate({ clipId: clip.id }, { onError: (e) => toastError(e) })}>{busy || transcribe.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Mic className="size-3.5" />}{t?.cues ? "Transcribe again" : "Transcribe"}diff --git a/src/components/swap-studio/workbench.tsx b/src/components/swap-studio/workbench.tsxindex 9ae01614..85836566 100644--- a/src/components/swap-studio/workbench.tsx+++ b/src/components/swap-studio/workbench.tsx@@ -102,7 +102,7 @@ export function SwapWorkbench({ id }: { id: string }) {try {return await editMutation.mutateAsync(e);} catch (err) {- toast.error((err as Error).message);+ toastError(err);return undefined;}};@@ -337,7 +337,7 @@ function ClipsPanel({const p = await add.mutateAsync({ url: up.url, name: file.name, bytes: file.size, playable, ...facts });onSelect(p.clips.at(-1)!.id);} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setUpload(null);}@@ -435,7 +435,7 @@ function ClipHeader({ id, project, clip, gens }: StageProps) {<span className="text-[12px] text-muted-foreground">24 fps copy</span><GenChip genId={clip.normalized?.genId} gens={gens} />{(!clip.normalized?.genId || norm.status === "failed" || norm.status === "canceled" || norm.status === "missing") && (- <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" disabled={prepare.isPending} onClick={() => prepare.mutate({ clipId: clip.id }, { onError: (e) => toast.error((e as Error).message) })}>+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" disabled={prepare.isPending} onClick={() => prepare.mutate({ clipId: clip.id }, { onError: (e) => toastError(e) })}><RotateCcw className="size-3.5" /> Prepare at 24 fps</Button>)}@@ -446,7 +446,7 @@ function ClipHeader({ id, project, clip, gens }: StageProps) {<span className="text-[12px] text-muted-foreground">Browser copy</span><GenChip genId={clip.preview?.genId} gens={gens} />{(!clip.preview?.genId || copy.status === "failed" || copy.status === "canceled" || copy.status === "missing") && (- <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" disabled={prepare.isPending} onClick={() => prepare.mutate({ clipId: clip.id }, { onError: (e) => toast.error((e as Error).message) })}>+ <Button size="sm" variant="outline" className="h-7 rounded-full px-2.5 text-[12px]" disabled={prepare.isPending} onClick={() => prepare.mutate({ clipId: clip.id }, { onError: (e) => toastError(e) })}><RotateCcw className="size-3.5" /> Make a browser copy</Button>)}diff --git a/src/components/train-dialog.tsx b/src/components/train-dialog.tsxindex c1270c55..0c63fa64 100644--- a/src/components/train-dialog.tsx+++ b/src/components/train-dialog.tsx@@ -30,6 +30,7 @@ import {type TrainingTarget,} from "@/lib/catalog/training";import { cn } from "@/lib/utils";+import { responseError, toastError } from "@/lib/refusals";interface Training {id: string;@@ -99,14 +100,14 @@ export function TrainDialog({ element, open, onOpenChange }: { element: StudioElbody: JSON.stringify({ target, consent: person ? consent : undefined }),});const body = await res.json();- if (!res.ok) throw new Error(body.error);+ if (!res.ok) throw responseError(res, body.error);return body as { provider: string };},onSuccess: (t) => {toast.success(t.provider === "demo" ? `Demo training for ${element.name}: nothing real is trained` : `Training ${element.name} — you can keep working`);refresh();},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});const attach = useMutation({mutationFn: async () => {@@ -116,14 +117,14 @@ export function TrainDialog({ element, open, onOpenChange }: { element: StudioElbody: JSON.stringify({ file, trigger: triggerFor(element.handle), family: kitFamily }),});const body = await res.json();- if (!res.ok) throw new Error(body.error);+ if (!res.ok) throw responseError(res, body.error);},onSuccess: () => {toast.success("LoRA attached");setFile("");refresh();},- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});const remove = async (l: ElementLora) => {await fetch(`/api/elements/${element.id}`, {diff --git a/src/components/turnaround/turnaround-dialog.tsx b/src/components/turnaround/turnaround-dialog.tsxindex 21246ed4..c47a13a2 100644--- a/src/components/turnaround/turnaround-dialog.tsx+++ b/src/components/turnaround/turnaround-dialog.tsx@@ -4,7 +4,6 @@ import { useMutation, useQuery, keepPreviousData } from "@tanstack/react-query";import { AlertTriangle, Check, ImageOff, Loader2, Rotate3d, Sparkles } from "lucide-react";import Link from "next/link";import { useEffect, useMemo, useState } from "react";-import { toast } from "sonner";import { useSubmitGuard } from "@/components/shorts/hooks";import { EngineSwitch } from "@/components/studio/engine-switch";import { radioKeys, radioTab } from "@/components/studio/radio-keys";@@ -32,6 +31,7 @@ import {import type { Engine, Generation } from "@/lib/catalog/types";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";+import { responseError, toastError } from "@/lib/refusals";/** The body /api/turnaround takes (src/server/turnaround.ts TurnaroundSchema). */export interface TurnaroundBody {@@ -73,7 +73,7 @@ interface Props {async function post<T>(url: string, body: unknown): Promise<T> {const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });const out = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(out.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, out.error ?? `Request failed (${res.status})`);return out;}@@ -203,7 +203,7 @@ function TurnaroundForm({ pictures, name, realPerson: realDefault = false, elemeonRun ? { items: await onRun(b) } : post<{ items: Generation[]; filmId: string }>("/api/turnaround", { ...b, requestId }),// The film: the one the server names, else the joined clips, else the one video the run makes (drawn pictures are stills).onSuccess: ({ items, filmId }) => onStarted({ ids: items.map((g) => g.id), filmId: filmId ?? (items.find((g) => g.op === "concat") ?? items.find((g) => g.kind === "video") ?? items[0])?.id }),- onError: (e) => toast.error((e as Error).message),+ onError: (e) => toastError(e),});const makeIt = () => void guard(JSON.stringify(body), (requestId) => make.mutateAsync({ b: body, requestId })).catch(() => {});diff --git a/src/components/virality/virality-studio.tsx b/src/components/virality/virality-studio.tsxindex 1dafabdd..ee5e25a2 100644--- a/src/components/virality/virality-studio.tsx+++ b/src/components/virality/virality-studio.tsx@@ -13,6 +13,7 @@ import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { uploadFile } from "@/lib/api";import { HOOK_SECONDS, hookSignals, hookSummary, SILENCE_DB, TRIBE_WORKER, VIRALITY_PARITY, type HookSignal, type SignalId, type Verdict } from "@/lib/av/virality";import { cn } from "@/lib/utils";+import { toastError } from "@/lib/refusals";import { measureHook, type HookMeasure } from "./measure";type Run =@@ -250,7 +251,7 @@ function NextSteps({ clip, measure, byId }: { clip: SlotValue; measure: HookMeasconst asset = await uploadFile(new File([blob], `${(clip.name ?? "video").replace(/\.[^.]+$/, "")} opening frame.jpg`, { type: "image/jpeg" }));router.push(`${HOOK_FRAME_APP}?${new URLSearchParams({ image: asset.url })}`);} catch (e) {- toast.error((e as Error).message);+ toastError(e);setBusy(false);}};diff --git a/src/hooks/use-gpu.ts b/src/hooks/use-gpu.tsindex 0034667f..b902d862 100644--- a/src/hooks/use-gpu.ts+++ b/src/hooks/use-gpu.ts@@ -5,6 +5,7 @@ import { useCallback, useRef, useState } from "react";import { GPU_SETUP_EVENT } from "@/lib/api";import { BADGE_STATE } from "@/lib/gpu/readiness";import type { Badge, BadgeMap, CheckLine, FixPlan, GpuProblem, ReadinessReport, Readiness } from "@/lib/gpu/types";+import { responseError } from "@/lib/refusals";/*** The GPU pre-flight in the browser: the readiness board, the badge map and a tool's fix plan (react-query keys@@ -123,7 +124,7 @@ export async function runGpuCheck(onLine: (l: CheckLine) => void): Promise<Readiconst res = await fetch("/api/gpu/check", { method: "POST" });if (!res.ok || !res.body) {const body = (await res.json().catch(() => ({}))) as { error?: string; wait?: number };- throw Object.assign(new Error(body.error ?? `The check didn't start (${res.status})`), { status: res.status, wait: body.wait });+ throw Object.assign(responseError(res, body.error ?? `The check didn't start (${res.status})`), { status: res.status, wait: body.wait });}const reader = res.body.getReader();const decoder = new TextDecoder();diff --git a/src/lib/refusals.ts b/src/lib/refusals.tsindex 38972d66..a34bf0c4 100644--- a/src/lib/refusals.ts+++ b/src/lib/refusals.ts@@ -11,10 +11,12 @@ export function markRefusalShown(res: Response): void {shown.add(res);}-/** The error for a failed response: marked when its refusal shows its own card. */-export function responseError(res: Response, message: string): Error {- const e = new Error(message);- return shown.has(res) ? Object.assign(e, { refusalShown: true }) : e;+/** The error for a failed response (`e`, or an Error with that message): marked when its refusal shows its own card. */+export function responseError(res: Response, message: string): Error;+export function responseError<E extends Error>(res: Response, e: E): E;+export function responseError(res: Response, e: string | Error): Error {+ const err = typeof e === "string" ? new Error(e) : e;+ return shown.has(res) ? Object.assign(err, { refusalShown: true }) : err;}/** The refusal behind this error shows its own card already: no toast on top of it. */diff --git a/tests/e2e/guest-prompt.mjs b/tests/e2e/guest-prompt.mjsindex aece8e5c..ca227c11 100644--- a/tests/e2e/guest-prompt.mjs+++ b/tests/e2e/guest-prompt.mjs@@ -1,7 +1,9 @@// A refused change shows one card, in the browser. A guest uploads a picture in Color Grading: "Create a free account// to run this" opens alone (no error toast, no trip to the sign-in page). Its Log in and Sign up free open the sign-in// page with the card closed, Back closes it too, and a wrong password on the sign-in page is the form's own error.-// Then an account without its GPU: "Connect your GPU" opens alone, its form inside it, and closes when the page changes.+// The same in the studios with their own fetch helpers: a guest presses New canvas in Canvas and sends a message in Assist.+// Then an account without its GPU: "Connect your GPU" opens alone, its form inside it, and closes when the page changes;+// alone again on a message in Assist, and none on New canvas, whose refusal ("Free accounts can't save…") is its toast.// Usage: node tests/e2e/guest-prompt.mjs [appUrl] [--shots <dir>] (the app with a password and FUOBE_PUBLIC_SIGNUP=1).// Signs up one throwaway account. Exits 1 on a failed check.import fs from "node:fs";@@ -40,6 +42,24 @@ const seen = async (page) => ({});const settled = (page) => page.waitForTimeout(1500);+/** Press New canvas in Canvas, and wait for the server's answer. */+async function newCanvas(page) {+ await openRoute(page, `${app}/canvas`);+ const answered = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/canvases" && r.request().method() === "POST");+ await page.getByRole("button", { name: "New canvas" }).first().click();+ return answered;+}++/** Send a message in Assist, and wait for the server's answer. */+async function sendInAssist(page) {+ await openRoute(page, `${app}/assist`);+ const box = page.locator("textarea").first();+ await box.fill("Plan a three-shot teaser for a summer coat");+ const answered = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/assist" && r.request().method() === "POST");+ await box.press("Enter");+ return answered;+}+/** Upload a picture through Color Grading's Image tile, and wait for the server's answer. */async function uploadPicture(page) {const answered = page.waitForResponse((r) => r.url().endsWith("/api/uploads") && r.request().method() === "POST");@@ -111,6 +131,30 @@ try {await context.close();}+ // ---------------------------------------------------------------------------+ // A guest in Canvas and Assist: each studio's own fetch helper, the same one card.+ {+ const { context, page } = await contextFor();+ const res = await newCanvas(page);+ check("the guest's New canvas is refused (401, marked for the card)", res.status() === 401 && res.headers()["x-fuobe-guest"] === "1", String(res.status()));+ await page.getByRole("dialog").waitFor();+ await settled(page);+ let s = await seen(page);+ await shot(page, "6-guest-new-canvas");+ check("Canvas: one card opens: Create a free account", s.cards.length === 1 && s.cards[0] === GUEST_CARD, JSON.stringify(s.cards));+ check("Canvas: no error toast on top of it", s.errors.length === 0, JSON.stringify(s.errors));++ const sent = await sendInAssist(page);+ check("the guest's message in Assist is refused (401)", sent.status() === 401, String(sent.status()));+ await page.getByRole("dialog").waitFor();+ await settled(page);+ s = await seen(page);+ await shot(page, "7-guest-assist-send");+ check("Assist: one card opens: Create a free account", s.cards.length === 1 && s.cards[0] === GUEST_CARD, JSON.stringify(s.cards));+ check("Assist: no error toast on top of it", s.errors.length === 0, JSON.stringify(s.errors));+ await context.close();+ }+// ---------------------------------------------------------------------------// An account without its GPU: "Connect your GPU", alone, closed when the page changes.{@@ -139,6 +183,25 @@ try {await settled(page);s = await seen(page);check("Back closes it", s.cards.length === 0, JSON.stringify(s.cards));++ // A message in Assist (its own fetch helper): Connect your GPU again, alone.+ const sent = await sendInAssist(page);+ check("the account's message in Assist is refused until it connects a GPU (403)", sent.status() === 403 && sent.headers()["x-fuobe-connect-gpu"] === "1", String(sent.status()));+ await page.getByRole("dialog").waitFor();+ await settled(page);+ s = await seen(page);+ await shot(page, "8-account-assist-send");+ check("Assist: one card opens: Connect your GPU", s.cards.length === 1 && s.cards[0] === GPU_CARD, JSON.stringify(s.cards));+ check("Assist: no error toast on top of it", s.errors.length === 0, JSON.stringify(s.errors));++ // New canvas: a refusal with no card of its own, so its toast is the one thing shown.+ const made = await newCanvas(page);+ check("the account's New canvas is refused (403, no card for it)", made.status() === 403 && !made.headers()["x-fuobe-connect-gpu"], String(made.status()));+ await page.locator("[data-sonner-toast][data-type=error]").first().waitFor();+ await settled(page);+ s = await seen(page);+ await shot(page, "9-account-new-canvas");+ check("Canvas: its own error toast, with no card", s.cards.length === 0 && s.errors.length === 1, JSON.stringify(s));await context.close();}} finally {diff --git a/tests/guest-prompt.test.ts b/tests/guest-prompt.test.tsindex d2d1fd27..c46a889b 100644--- a/tests/guest-prompt.test.ts+++ b/tests/guest-prompt.test.ts@@ -5,8 +5,33 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const toasts = vi.hoisted(() => ({ error: [] as string[] }));vi.mock("sonner", () => ({ toast: Object.assign(() => {}, { error: (m: string) => void toasts.error.push(m) }) }));-+// The studios' hooks, called outside React: a mutation is its mutationFn, and the query client does nothing.+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQueryClient: () => new Proxy({}, { get: () => () => undefined }),+ useMutation: (o: { mutationFn: (v: unknown) => Promise<unknown> }) => ({ mutateAsync: o.mutationFn }),+}));+vi.mock("react", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react")>()),+ useCallback: <T,>(f: T) => f,+ useMemo: <T,>(f: () => T) => f(),+}));++import { useChatActions } from "@/components/assist/hooks";+import { useCanvasActions } from "@/components/canvas/use-canvas";+import { useCreateProject } from "@/components/cinema/hooks";+import { ApiError, useCreateSeries } from "@/components/content-factory/hooks";+import { useDubActions } from "@/components/dub/hooks";+import { readDocument } from "@/components/faceless/hooks";+import { uploadDerived } from "@/components/layers/render";+import { LayersRequestError, useLayerActions } from "@/components/layers/use-layers";+import { useCreateBrand } from "@/components/marketing/hooks";+import { useMoodboardActions } from "@/components/moodboards/hooks";+import { usePaletteActions } from "@/components/palettes/hooks";+import { send as shortsSend } from "@/components/shorts/hooks";import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";+import { useCreateSwapProject } from "@/components/swap-studio/hooks";+import { runGpuCheck } from "@/hooks/use-gpu";import { assetUsage, CONNECT_GPU_EVENT, enhance, GUEST_PROMPT_EVENT, refusalCard, signInHref, watchGuestRefusals } from "@/lib/api";import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_HEADER, GUEST_LIBRARY_MESSAGE, GUEST_RUN_MESSAGE } from "@/lib/guest-access";import { refusalShown, toastError } from "@/lib/refusals";@@ -111,6 +136,82 @@ describe("a guest's refused run", () => {});});+describe("each studio's own fetch helper", () => {+ // The first thing a guest tries in each studio: the error its helper throws says the card shows it already.+ const runs: [string, () => Promise<unknown>][] = [+ ["Assist: send a message", () => useChatActions().start({ text: "a red coat", engine: "cloud", autoApprove: false })],+ ["Canvas: New canvas", () => useCanvasActions().create({ name: "Untitled canvas" })],+ ["Cinema: Create project", () => useCreateProject().mutateAsync({ name: "Untitled project" })],+ ["Content Factory: a series", () => useCreateSeries().mutateAsync({ reference: null, engine: "cloud" })],+ ["Dub: a video", () => useDubActions().create.mutateAsync({ engine: "cloud", mode: "oneshot", video: "/api/files/clip.mp4", targets: ["es"] })],+ ["Explainer: read a document", () => readDocument(new File(["A red coat"], "notes.txt", { type: "text/plain" }), "cloud")],+ ["Layers: a project", () => useLayerActions().create({ source: "/api/files/photo.png", width: 640, height: 480 })],+ ["Layers: a picture for the model", () => uploadDerived(new Blob([new Uint8Array([1])], { type: "image/png" }), "mask")],+ ["Marketing: a brand", () => useCreateBrand().mutateAsync({ description: "A red coat label" })],+ ["Moodboards: a board", () => useMoodboardActions().create.mutateAsync({ name: "Coats", images: [], collages: [], engine: "cloud" })],+ ["Palettes: a palette", () => usePaletteActions().create.mutateAsync({ name: "Coats", colors: ["#aa2222"], source: "manual" })],+ ["Shorts and Genjutsu: a run", () => shortsSend("/api/genjutsu", "POST", {})],+ ["Swap Studio: a project", () => useCreateSwapProject().mutateAsync({ engine: "cloud" })],+ ["Your GPU: the check", () => runGpuCheck(() => {})],+ ];++ it.each(runs)("%s: a guest's 401 opens the card, and its error is marked", async (_, run) => {+ page("/studio");+ server = () => guestRefusal();+ const e = await run().catch((err: unknown) => err);+ expect(events).toEqual([GUEST_PROMPT_EVENT]);+ expect((e as Error).message).toBe(GUEST_RUN_MESSAGE);+ expect(refusalShown(e)).toBe(true);+ toastError(e);+ expect(toasts.error).toEqual([]);+ });++ it("an account without its GPU: Connect your GPU marks it the same way", async () => {+ page("/canvas/abc");+ server = () => answer(403, { error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });+ const e = await useCanvasActions()+ .create({ name: "Untitled canvas" })+ .catch((err: unknown) => err);+ expect(events).toEqual([CONNECT_GPU_EVENT]);+ expect(refusalShown(e)).toBe(true);+ });++ it("keeps each helper's own error: its class, status and body", async () => {+ page("/studio");+ server = () => guestRefusal();+ const assist = (await useChatActions()+ .start({ text: "a red coat", engine: "cloud", autoApprove: false })+ .catch((err: unknown) => err)) as Error & { status?: number };+ expect(assist.status).toBe(401);+ const canvas = (await useCanvasActions()+ .create({})+ .catch((err: unknown) => err)) as Error & { status?: number; body?: { error?: string } };+ expect([canvas.status, canvas.body?.error]).toEqual([401, GUEST_RUN_MESSAGE]);+ const series = await useCreateSeries()+ .mutateAsync({ reference: null, engine: "cloud" })+ .catch((err: unknown) => err);+ expect(series).toBeInstanceOf(ApiError);+ expect(refusalShown(series)).toBe(true);+ const layers = await useLayerActions()+ .create({ source: "/api/files/photo.png", width: 640, height: 480 })+ .catch((err: unknown) => err);+ expect(layers).toBeInstanceOf(LayersRequestError);+ expect((layers as LayersRequestError).status).toBe(401);+ });++ it("any other failure is never marked, so its toast still shows", async () => {+ page("/canvas");+ server = () => answer(500, { error: "The canvas couldn't be saved" });+ const e = await useCanvasActions()+ .create({ name: "Untitled canvas" })+ .catch((err: unknown) => err);+ expect(events).toEqual([]);+ expect(refusalShown(e)).toBe(false);+ toastError(e);+ expect(toasts.error).toEqual(["The canvas couldn't be saved"]);+ });+});+describe("the sign-in page", () => {it("never opens a card: a refusal there keeps its own message", async () => {page("/login", "?next=%2Fcolor-grade");