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
Restore 4: Restore & colourise in Video tools, the Canvas, Shorts, the Explainer and Assist
Claude2ff166c1a78c
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex 1c1a3ec0..ea446e7f 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -44,7 +44,7 @@ import { Viewer } from "@/components/studio/viewer";import { useIsMobile } from "@/hooks/use-mobile";import { useElements, useEngine, useStatus, type EngineMode } from "@/lib/api";import { getModel } from "@/lib/catalog";-import { onEngine, runsOn } from "@/lib/catalog/engines";+import { dualEngine, onEngine, runsOn } from "@/lib/catalog/engines";import {BOARD_LIMITS,copyPage,@@ -588,6 +588,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv// An install locked to one engine never gets a node on the other.const m = defaultModelForNode({ type: item.type, data }, engine) ?? (mode === "both" ? defaultModelForNode({ type: item.type, data }, engine === "open" ? "cloud" : "open") : undefined);if (m) data.modelId = m.id;+ // A Fuobe Original (both engines) starts on the engine the board is on.+ if (m && dualEngine(m) && runsOn(m, engine)) data.engine = engine;}const node: FlowNode = { id: newId(item.type), type: item.type, position: snap(at), data, selected: true };setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), node]);diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex ce78cc58..f33fced8 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -1769,6 +1769,7 @@ export const NODE_TYPES = {"clone-voice": CloneVoiceNode,translate: GeneratorNode,concat: GeneratorNode,+ restore: GeneratorNode,table: TableNode,output: OutputNode,note: NoteNode,diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxindex ad1f9047..cbfe23d3 100644--- a/src/components/explainer/explainer-studio.tsx+++ b/src/components/explainer/explainer-studio.tsx@@ -12,6 +12,8 @@ import { SidebarTrigger } from "@/components/ui/sidebar";import { Skeleton } from "@/components/ui/skeleton";import { Switch } from "@/components/ui/switch";import { EngineSwitch } from "@/components/studio/engine-switch";+import { grabFrames } from "@/components/restore/hooks";+import { OldFootageOffer } from "@/components/restore/old-footage";import { fileToSlot } from "@/components/studio/media-slot";import { useEngine } from "@/lib/api";import {@@ -156,6 +158,8 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {const [tab, setTab] = useState<"all" | "liked">("all");const [q, setQ] = useState("");const file = useRef<HTMLInputElement>(null);+ /** Old footage attached: its still is a picture source; the clip itself is offered to Restore & colourise. */+ const [footage, setFootage] = useState<{ id: string; name: string; preview: string; url?: string } | null>(null);const create = useCreateExplainer();const history = useExplainers({ q, liked: tab === "liked" });const like = useLikeEpisode();@@ -181,16 +185,31 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {let room = MAX_SOURCES - sources.length;for (const f of files) {if (room <= 0) return void toast("Up to 3 sources per video — remove one to add another");- if (f.type.startsWith("image/")) {+ if (f.type.startsWith("image/") || f.type.startsWith("video/")) {room--;const id = `${f.name}:${Date.now()}:${room}`;+ let image: File = f;+ if (f.type.startsWith("video/")) {+ // Old footage: a still from its middle is the source the pictures read; the clip goes up for the restore step.+ const preview = URL.createObjectURL(f);+ const [still] = await grabFrames(preview, undefined, [0.5], 1280);+ if (!still) {+ URL.revokeObjectURL(preview);+ toast.error(`${f.name}: couldn't read a frame from this clip in the browser — try an MP4`);+ room++;+ continue;+ }+ image = new File([await (await fetch(still)).blob()], `${f.name.replace(/\.[^.]+$/, "")} still.jpg`, { type: "image/jpeg" });+ setFootage({ id, name: f.name, preview });+ void fileToSlot(f, (v) => v && !v.uploading && setFootage((x) => (x?.id === id ? { ...x, url: v.ref } : x)), "video");+ }void fileToSlot(- f,+ image,(v) =>setSources((xs) => {const at = xs.findIndex((x) => x.kind === "image" && x.id === id);if (!v) return xs.filter((_, i) => i !== at);- const next: Draft = { kind: "image", id, url: v.ref, name: f.name, preview: v.preview, uploading: v.uploading };+ const next: Draft = { kind: "image", id, url: v.ref, name: image.name, preview: v.preview, uploading: v.uploading };// A source removed while it uploads stays removed.if (at < 0) return v.uploading ? [...xs, next] : xs;return xs.map((x, i) => (i === at ? next : x));@@ -227,7 +246,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {} else if (/\.(doc|odt|rtf|pages|pptx?|key)$/i.test(f.name) || /msword|opendocument|rtf|presentation/.test(f.type)) {toast.error(`${f.name}: save it as PDF or Word (.docx), or paste the text into the prompt`);} else {- toast.error(`${f.name}: add an image (PNG, JPEG, WebP), a PDF, a Word file (.docx) or a text file (.txt, .md, .csv)`);+ toast.error(`${f.name}: add an image (PNG, JPEG, WebP), a clip (MP4, MOV, WebM), a PDF, a Word file (.docx) or a text file (.txt, .md, .csv)`);}}};@@ -313,7 +332,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {ref={file}type="file"multiple- accept="image/png,image/jpeg,image/webp,.pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.txt,.md,.markdown,.csv,text/plain,text/markdown"+ accept="image/png,image/jpeg,image/webp,video/mp4,video/quicktime,video/webm,.mp4,.mov,.webm,.pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.txt,.md,.markdown,.csv,text/plain,text/markdown"hiddenonChange={(e) => {const fs = [...(e.target.files ?? [])];@@ -322,6 +341,9 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {}}/></div>+ {footage && sources.some((x) => x.kind === "image" && x.id === footage.id) && (+ <OldFootageOffer url={footage.url} src={footage.preview} className="mt-2 px-1" />+ )}<div className="mt-4 flex flex-wrap items-center gap-2 border-t pt-3"><Segmenteddiff --git a/src/components/nav-items.ts b/src/components/nav-items.tsindex 2f68afdf..7d70bba4 100644--- a/src/components/nav-items.ts+++ b/src/components/nav-items.ts@@ -119,7 +119,7 @@ export const NAV: NavGroupDef[] = [{ href: "/video-edit", label: "Edit video", icon: Scissors, keywords: "video edit restyle" },{ href: "/extend", label: "Extend video", icon: FastForward, keywords: "longer continue" },{ href: "/reframe", label: "Reframe", icon: Crop, keywords: "aspect ratio outpaint" },- { href: "/video-tools", label: "Video tools", icon: Layers, keywords: "join trim matte depth captions evolution remove object" },+ { href: "/video-tools", label: "Video tools", icon: Layers, keywords: "join trim matte depth captions evolution remove object restore colourise colorize archive old footage black and white" },{ href: "/elements", label: "Elements", icon: AtSign, keywords: "characters places props" },{ href: "/upscale", label: "Upscale", icon: ZoomIn, keywords: "enhance resolution 4k" },{ href: "/audio", label: "Audio", icon: AudioLines, keywords: "voice tts music sfx dub transcribe" },diff --git a/src/components/restore/hooks.ts b/src/components/restore/hooks.tsnew file mode 100644index 00000000..d706fba3--- /dev/null+++ b/src/components/restore/hooks.ts@@ -0,0 +1,119 @@+"use client";++import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import type { Size } from "@/lib/catalog/restore";+import type { Engine, Generation } from "@/lib/catalog/types";+import { useDebounced } from "@/components/faceless/hooks";+import { send } from "@/components/shorts/hooks";++/** React Query hooks for /api/restore/** (Video tools → Restore & colourise). */++export interface RestoreBody {+ engine: Engine;+ source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };+ prompt?: string;+ negative?: string;+ hint?: string;+ refine?: boolean;+ deinterlace?: boolean;+ reference?: string;+ resolution?: string;+ /** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */+ requestId?: string;+}++export interface RestoreEstimate {+ costUsd: number | null;+ demo: boolean;+ engine: Engine;+ pieces: number;+ canvas: Size;+ tiles: number;+ refined?: Size;+ seconds: number;+ dropped: number;+ steps: number;+ resolution?: string;+ hfToken: boolean;+ notes: string[];+}++export interface PromptAnswer {+ prompt: string;+ negative: string;+ by: "claude" | "ollama" | "offline";+ why?: string;+}++/** The price and shape of a run for the current settings, asked for once typing pauses (300 ms). */+export function useRestoreEstimate(body: RestoreBody | null) {+ // The words don't change the price: they stay out of the key, so typing doesn't ask again.+ const key = useDebounced(body ? JSON.stringify({ ...body, prompt: undefined, negative: undefined, hint: undefined }) : null, 300);+ return useQuery({+ queryKey: ["restore", "estimate", key],+ queryFn: async () => send<RestoreEstimate>("/api/restore/estimate", "POST", JSON.parse(key!)),+ enabled: !!key,+ placeholderData: keepPreviousData,+ retry: false,+ staleTime: 30_000,+ });+}++export function useRestoreActions() {+ const qc = useQueryClient();+ return {+ run: useMutation({+ mutationFn: (b: RestoreBody) => send<{ final: Generation; items: Generation[]; prompt: string; negative: string; by: PromptAnswer["by"] | "you" }>("/api/restore", "POST", b),+ onSuccess: (r) => {+ r.items.forEach((g) => qc.setQueryData(["generation", g.id], g));+ void qc.invalidateQueries({ queryKey: ["generations"] });+ },+ }),+ prompt: useMutation({+ mutationFn: (b: { engine: Engine; hint?: string; frames: string[]; seconds?: number }) => send<PromptAnswer>("/api/restore/prompt", "POST", b),+ }),+ };+}++/**+ * A few frames of a clip as small JPEG data URLs (for the prompt writer): a hidden video seeks to each point and a canvas+ * draws it at `width` px. Frames that can't be read (a codec the browser doesn't play) are left out.+ */+export async function grabFrames(src: string, duration: number | undefined, at = [0.15, 0.5, 0.85], width = 512): Promise<string[]> {+ if (typeof document === "undefined") return [];+ const v = document.createElement("video");+ v.muted = true;+ v.preload = "auto";+ v.crossOrigin = "anonymous";+ v.src = src;+ const ready = await new Promise<boolean>((resolve) => {+ const t = setTimeout(() => resolve(false), 8000);+ v.onloadeddata = () => (clearTimeout(t), resolve(true));+ v.onerror = () => (clearTimeout(t), resolve(false));+ });+ if (!ready) return [];+ const len = duration && duration > 0 ? duration : v.duration;+ if (!len || !Number.isFinite(len)) return [];+ const out: string[] = [];+ const canvas = document.createElement("canvas");+ for (const f of at) {+ const ok = await new Promise<boolean>((resolve) => {+ const t = setTimeout(() => resolve(false), 5000);+ v.onseeked = () => (clearTimeout(t), resolve(true));+ v.currentTime = Math.min(len - 0.05, Math.max(0, f * len));+ });+ if (!ok || !v.videoWidth) continue;+ canvas.width = width;+ canvas.height = Math.round((width * v.videoHeight) / v.videoWidth);+ canvas.getContext("2d")?.drawImage(v, 0, 0, canvas.width, canvas.height);+ try {+ const url = canvas.toDataURL("image/jpeg", 0.8);+ if (url.length < 1_900_000) out.push(url);+ } catch {+ // A clip from another origin taints the canvas: no frames, the writer works from the words.+ }+ }+ v.removeAttribute("src");+ v.load();+ return out;+}diff --git a/src/components/restore/old-footage.tsx b/src/components/restore/old-footage.tsxnew file mode 100644index 00000000..0e4c5305--- /dev/null+++ b/src/components/restore/old-footage.tsx@@ -0,0 +1,82 @@+"use client";++import { ArrowUpRight, Palette } from "lucide-react";+import Link from "next/link";+import { useEffect, useState } from "react";+import { meanChroma, MONOCHROME_CHROMA, restoreHref } from "@/lib/catalog/restore";+import { cn } from "@/lib/utils";++/** The mean chroma of a few small frames of a clip, read in the browser (null when it can't be read). */+export async function clipChroma(src: string, at = [0.2, 0.5, 0.8]): Promise<number | null> {+ if (typeof document === "undefined") return null;+ const v = document.createElement("video");+ v.muted = true;+ v.preload = "auto";+ v.crossOrigin = "anonymous";+ v.src = src;+ const ready = await new Promise<boolean>((resolve) => {+ const t = setTimeout(() => resolve(false), 8000);+ v.onloadeddata = () => (clearTimeout(t), resolve(true));+ v.onerror = () => (clearTimeout(t), resolve(false));+ });+ if (!ready || !v.videoWidth || !Number.isFinite(v.duration)) return null;+ const canvas = document.createElement("canvas");+ canvas.width = 64;+ canvas.height = Math.max(1, Math.round((64 * v.videoHeight) / v.videoWidth));+ const ctx = canvas.getContext("2d", { willReadFrequently: true });+ if (!ctx) return null;+ const seen: number[] = [];+ for (const f of at) {+ const ok = await new Promise<boolean>((resolve) => {+ const t = setTimeout(() => resolve(false), 5000);+ v.onseeked = () => (clearTimeout(t), resolve(true));+ v.currentTime = Math.min(v.duration - 0.05, Math.max(0, f * v.duration));+ });+ if (!ok) continue;+ ctx.drawImage(v, 0, 0, canvas.width, canvas.height);+ try {+ seen.push(meanChroma(ctx.getImageData(0, 0, canvas.width, canvas.height).data));+ } catch {+ return null;+ }+ }+ v.removeAttribute("src");+ v.load();+ return seen.length ? seen.reduce((a, b) => a + b, 0) / seen.length : null;+}++/** Whether a clip looks black-and-white (or toned): null until read, or when it can't be. */+export function useLooksMonochrome(src: string | undefined): boolean | null {+ const [read, setRead] = useState<{ src: string; mono: boolean | null } | null>(null);+ useEffect(() => {+ if (!src) return;+ let live = true;+ void clipChroma(src).then((c) => live && setRead({ src, mono: c === null ? null : c < MONOCHROME_CHROMA }));+ return () => {+ live = false;+ };+ }, [src]);+ return src && read?.src === src ? read.mono : null;+}++/**+ * The restore step offered where your own footage goes in (Shorts, Explainer): a quiet line for any clip, said+ * plainly when its frames carry almost no colour. Restore & colourise opens in a new tab with the clip, so the+ * work here stays; the restored clip lands in the Library, to pick here.+ */+export function OldFootageOffer({ url, src, className }: { url?: string; src?: string; className?: string }) {+ const mono = useLooksMonochrome(src ?? url);+ return (+ <p className={cn("flex gap-1.5 text-[12px] leading-snug", mono ? "text-foreground" : "text-muted-foreground", className)}>+ <Palette className={cn("mt-0.5 size-3.5 shrink-0", mono && "text-brand-text")} />+ <span>+ {mono ? "This looks like black-and-white footage. " : "Old or black-and-white footage? "}+ <Link href={restoreHref(url)} target="_blank" rel="noopener" className="inline-flex items-center gap-0.5 font-medium text-brand-text underline-offset-2 hover:underline">+ Restore & colourise it first+ <ArrowUpRight className="size-3" aria-hidden />+ </Link>+ <span className="text-muted-foreground"> (new tab), then pick the restored clip from your Library.</span>+ </span>+ </p>+ );+}diff --git a/src/components/restore/restore-tool.tsx b/src/components/restore/restore-tool.tsxnew file mode 100644index 00000000..393fac18--- /dev/null+++ b/src/components/restore/restore-tool.tsx@@ -0,0 +1,392 @@+"use client";++import { Cpu, Download, ExternalLink, KeyRound, Loader2, RotateCcw, Sparkles, Wand2 } from "lucide-react";+import Link from "next/link";+import { useEffect, useMemo, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { StepList, type StepRow } from "@/components/av/step-list";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { useGenerationList } from "@/components/av/use-generation";+import { VideoCompare } from "@/components/remove-object/video-compare";+import { useSubmitGuard } from "@/components/shorts/hooks";+import { ClipBar, ClipDrop, costText, Field, Segmented } from "@/components/shorts/ui";+import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-source-clip";+import { Feed } from "@/components/studio/feed";+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";+import { useEngine, useGenerations } from "@/lib/api";+import { CLOUD_NOTE, GPU_NOTE, RESTORE, restoreNegative } from "@/lib/catalog/restore";+import { chainState } from "@/lib/catalog/shorts";+import { downloadHref, downloadName } from "@/lib/library";+import { cn } from "@/lib/utils";+import { grabFrames, useRestoreActions, useRestoreEstimate, type RestoreBody } from "./hooks";++const LIMITS = `MP4, MOV, WebM, MKV or AVI · up to ${RESTORE.maxSeconds / 60} minutes · ${RESTORE.maxBytes / 1024 / 1024 / 1024} GB`;+const BY: Record<string, string> = { claude: "Written by Claude from your frames", ollama: "Written by Ollama on your computer", offline: "Fuobe's template: edit it to fit your footage", you: "Your words" };+const DEFAULT_NEGATIVE = restoreNegative();++interface Run {+ final: string;+ ids: string[];+ before: string;+ ratio?: number;+ prompt: string;+ by: string;+}++/**+ * Video tools → Restore & colourise (Fuobe Restore, package archive-restore): an archive clip, a sentence about its+ * period, place and light (written from a few frames if you like), what must not be invented, and on your GPU Restore+ * to 4K, deinterlacing and a reference picture; priced before it runs ("Free" on your GPU); the result with a before /+ * after wipe. A clip handed over from the Library or a result arrives as ?video=.+ */+export function RestoreTool({ tabs }: { tabs?: React.ReactNode }) {+ const [engine] = useEngine();+ const source = useSourceClip(RESTORE.maxBytes);+ const clip = source.clip;+ const [prompt, setPrompt] = useState("");+ const [negative, setNegative] = useState(DEFAULT_NEGATIVE);+ const [by, setBy] = useState<string | null>(null);+ const [refine, setRefine] = useState(false);+ const [deinterlace, setDeinterlace] = useState(false);+ const [reference, setReference] = useState<SlotValue | null>(null);+ const [resolution, setResolution] = useState<string>(RESTORE.cloudResolution);+ const [run, setRun] = useState<Run | null>(null);+ const [writing, setWriting] = useState(false);+ const actions = useRestoreActions();+ const runGuard = useSubmitGuard();+ const history = useGenerations({ features: [RESTORE.feature], limit: 24 });++ // Hand-off: /video-tools/restore?video=/api/files/… (a result, a Library clip, Upscale's link).+ useEffect(() => {+ const video = new URLSearchParams(window.location.search).get("video");+ if (video?.startsWith("/api/files/")) source.adopt(video, video.split("/").pop());+ // Once, on arrival.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const open = engine === "open";+ const duration = clipDuration(clip);+ const size = clipSize(clip);+ const ready = !!clip?.url && !clip.uploading && !clip.error && !!duration;+ const body: RestoreBody | null = ready+ ? {+ engine,+ source: { url: clip.url!, name: clip.name, duration, fps: clip.info?.fps, width: size.width, height: size.height, hasAudio: clip.info?.hasAudio },+ ...(prompt.trim() ? { prompt: prompt.trim() } : {}),+ ...(negative.trim() && negative.trim() !== DEFAULT_NEGATIVE ? { negative: negative.trim() } : {}),+ ...(open && refine ? { refine: true } : {}),+ ...(open && deinterlace ? { deinterlace: true } : {}),+ ...(reference?.ref && !reference.uploading ? { reference: reference.ref } : {}),+ ...(!open ? { resolution } : {}),+ }+ : null;+ const estimate = useRestoreEstimate(body);+ const est = estimate.data && !estimate.isError ? estimate.data : undefined;++ const blocker = !clip+ ? "Add a clip"+ : clip.error+ ? clip.error+ : clip.uploading+ ? clip.progress < 1+ ? `Uploading… ${Math.round(clip.progress * 100)}%`+ : "Reading the clip…"+ : !duration+ ? "Reading the clip…"+ : reference?.uploading+ ? "Uploading the reference…"+ : estimate.isError+ ? (estimate.error as Error).message+ : null;++ const write = async () => {+ if (!clip) return;+ setWriting(true);+ try {+ const frames = await grabFrames(clip.preview, duration).catch(() => []);+ const r = await actions.prompt.mutateAsync({ engine, hint: prompt.trim() || undefined, frames, seconds: duration });+ setPrompt(r.prompt);+ setNegative(r.negative);+ setBy(r.by);+ if (r.by === "offline" && r.why) toast("Written offline", { description: `Fuobe's template filled it in: ${r.why}. Add the period, the place and the light.` });+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setWriting(false);+ }+ };++ const start = () => {+ if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "restore-blocker" });+ void runGuard(JSON.stringify(body), (requestId) => actions.run.mutateAsync({ ...body, requestId }))+ .then((r) => {+ if (!r) return;+ const ratio = size.width && size.height ? size.width / size.height : undefined;+ setRun({ final: r.final.id, ids: r.items.map((g) => g.id), before: clip!.preview, ratio, prompt: r.prompt, by: body.prompt ? (by ?? "you") : r.by });+ if (!prompt.trim()) {+ setPrompt(r.prompt);+ setBy(r.by);+ }+ toast("Restoring your clip", { description: "Follow it below — it lands in your Library too." });+ })+ .catch((e: Error) => toast.error(e.message));+ };++ return (+ <ToolShell title="Video tools" tabs={tabs} wide>+ {!clip && (+ <ToolHero+ title="Restore & colourise"+ subtitle="Old scans, tape and black-and-white film back in colour, clean and sharp, with Lightricks' Restore IC-LoRA. Priced before it runs; free on your own ComfyUI."+ />+ )}+ <div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>+ {!clip ? (+ <ClipDrop+ accept={RESTORE.accept}+ limits={LIMITS}+ onFile={(f) => {+ const err = source.pick(f);+ if (err) toast.error(err);+ }}+ onLibrary={(url, name) => source.adopt(url, name)}+ />+ ) : (+ <div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">+ <div className="min-w-0 space-y-4">+ <Panel>+ <div className="space-y-3">+ <ClipBar+ clip={clip}+ onRemove={() => {+ source.clear();+ setRun(null);+ }}+ />+ <video+ src={clip.preview}+ controls+ playsInline+ preload="metadata"+ className="max-h-[52vh] w-full rounded-lg bg-black object-contain"+ onLoadedMetadata={(e) => source.setBrowserMeta?.({ duration: e.currentTarget.duration, width: e.currentTarget.videoWidth, height: e.currentTarget.videoHeight })}+ />+ {est && (+ <p className="text-[12px] text-muted-foreground tabular-nums">+ {open+ ? `Canvas ${est.canvas.width}×${est.canvas.height} · ${est.tiles} tiles of 960×544 · ${est.pieces} window${est.pieces > 1 ? "s" : ""} of up to 97 frames${est.refined ? ` · then ${est.refined.width}×${est.refined.height}` : ""}`+ : `${est.canvas.width}×${est.canvas.height} in one pass a piece · ${est.pieces} piece${est.pieces > 1 ? "s" : ""} of up to 97 frames`}+ {est.dropped > 0 ? ` · the last ${est.dropped} frame${est.dropped > 1 ? "s" : ""} left out` : ""}+ </p>+ )}+ </div>+ </Panel>+ {est && !est.hfToken && (+ <Panel>+ <div className="flex gap-3">+ <KeyRound className="mt-0.5 size-4 shrink-0 text-brand-text" aria-hidden />+ <div className="min-w-0 space-y-1.5 text-[13px]">+ <p className="font-medium">One-time setup: the Restore IC-LoRA is gated</p>+ <p className="text-muted-foreground">+ Accept its licence on Hugging Face with your account (it's free under the LTX-2.x Community License below US$10M a year), then add a Hugging Face token. Fuobe+ downloads the 1.7 GB file once{open ? " into ComfyUI's LoRA folder" : " and gives fal its own copy, never your token"}.+ </p>+ <div className="flex flex-wrap gap-2 pt-0.5">+ <Button asChild size="sm" variant="outline" className="rounded-full">+ <a href={RESTORE.loras.restore.page} target="_blank" rel="noreferrer">+ Accept the licence <ExternalLink className="size-3" />+ </a>+ </Button>+ <Button asChild size="sm" variant="outline" className="rounded-full">+ <Link href="/settings#huggingface">Add your token</Link>+ </Button>+ </div>+ </div>+ </div>+ </Panel>+ )}+ </div>++ <Panel className="space-y-4 lg:sticky lg:top-[112px]">+ <p className="flex gap-2 rounded-lg bg-muted/60 px-3 py-2 text-[12px] leading-snug text-muted-foreground">+ <Cpu className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ <span>{open ? GPU_NOTE : CLOUD_NOTE}</span>+ </p>++ <Field label="Describe the scene" htmlFor="restore-prompt" hint={by ? BY[by] : "The period, the place, the light, what people wear. Colour comes from these words"}>+ <Textarea+ id="restore-prompt"+ value={prompt}+ onChange={(e) => {+ setPrompt(e.target.value);+ setBy(e.target.value.trim() ? "you" : null);+ }}+ maxLength={4000}+ rows={4}+ placeholder="e.g. “a steam locomotive arriving at a rural station in 1896, overcast daylight, passengers in period coats and hats, natural colour” — or a few words, then Write it from the frames"+ className="max-h-56 resize-y"+ />+ <div className="flex flex-wrap items-center gap-2">+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => void write()} disabled={writing || !clip}>+ {writing ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />} Write it from the frames+ </Button>+ <span className="text-[12px] text-muted-foreground">{open ? "Ollama with a vision model" : "Claude"}, else Fuobe's template · never starts a run</span>+ </div>+ </Field>++ <Field label="What it must not invent" htmlFor="restore-negative" hint="Modern things the period didn't have, then the damage to clean up">+ <Textarea id="restore-negative" value={negative} onChange={(e) => setNegative(e.target.value)} maxLength={4000} rows={3} className="max-h-40 resize-y text-[13px]" />+ </Field>++ <div className="space-y-3">+ <Toggle+ id="restore-4k"+ label="Restore to 4K"+ hint={open ? "Adds a detail pass at twice the size (Detail Refine IC-LoRA): restore first, refine second" : "Runs on your GPU (open source): the Detail Refine LoRA isn't hosted in the cloud"}+ checked={open && refine}+ disabled={!open}+ onChange={setRefine}+ />+ <Toggle+ id="restore-interlaced"+ label="Interlaced source (TV, tape)"+ hint={open ? "Keeps one field of each frame before restoring, so combing isn't read as texture" : "Runs on your GPU (open source)"}+ checked={open && deinterlace}+ disabled={!open}+ onChange={setDeinterlace}+ />+ </div>++ <Field label={open ? "Reference picture (optional)" : "First frame in colour (optional)"} hint={open ? "True colours, a face or a sign: it guides every window" : "The cloud uses a picture as the clip's first frame"}>+ <MediaSlot label="Reference" kind="image" value={reference} onChange={setReference} size="lg" />+ </Field>++ {!open && (+ <Field label="Size">+ <Segmented label="Size" value={resolution} onChange={setResolution} options={RESTORE.cloudResolutions.map((r) => ({ value: r, label: r, hint: r === "1080p" ? "the card's canvas" : undefined }))} />+ </Field>+ )}++ <div className="space-y-3 border-t pt-3">+ <div className="flex items-center gap-2">+ <div className="min-w-0 flex-1" aria-live="polite">+ {blocker ? (+ <p className="text-[13px] text-muted-foreground">{blocker}</p>+ ) : (+ <>+ <p className="flex items-center gap-1.5 text-[15px] font-semibold tabular-nums">+ {costText(est, engine)}+ {estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" aria-label="Updating the price" />}+ </p>+ {est && (+ <p className="text-[12px] leading-snug text-muted-foreground">+ Fuobe Restore · {est.seconds} s{est.resolution ? ` · ${est.resolution}` : ""}+ </p>+ )}+ </>+ )}+ </div>+ <Button className="rounded-full" onClick={start} disabled={!!blocker || actions.run.isPending}>+ {actions.run.isPending ? <Loader2 className="size-4 animate-spin" /> : <Wand2 className="size-4" />} Restore+ </Button>+ </div>+ {est && est.notes.length > 0 && !blocker && (+ <ul className="space-y-1 text-[12px] leading-snug text-muted-foreground">+ {est.notes+ .filter((n) => n !== GPU_NOTE && n !== CLOUD_NOTE)+ .map((n) => (+ <li key={n} className="flex gap-1.5">+ <Sparkles className="mt-0.5 size-3 shrink-0 text-brand-text" />+ <span>{n.replace(/\.$/, "")}.</span>+ </li>+ ))}+ </ul>+ )}+ </div>+ </Panel>+ </div>+ )}+ </div>++ {run && <RunPanel run={run} onAgain={start} />}++ {(history.data?.length ?? 0) > 0 && (+ <section className="mt-10" aria-labelledby="restorations">+ <h3 id="restorations" className="mb-3 font-heading text-[22px]">+ Your restorations+ </h3>+ <Feed items={history.data!} />+ </section>+ )}+ </ToolShell>+ );+}++function Toggle({ id, label, hint, checked, disabled, onChange }: { id: string; label: string; hint: string; checked: boolean; disabled?: boolean; onChange: (v: boolean) => void }) {+ return (+ <div className="flex items-start gap-3">+ <Switch id={id} checked={checked} disabled={disabled} onCheckedChange={onChange} aria-describedby={`${id}-hint`} className="mt-0.5" />+ <div className="min-w-0">+ <label htmlFor={id} className={cn("text-[13px] font-medium", disabled && "text-muted-foreground")}>+ {label}+ </label>+ <p id={`${id}-hint`} className="text-[12px] leading-snug text-muted-foreground">+ {hint}+ </p>+ </div>+ </div>+ );+}++/** What a run's steps are doing, then the result with a before / after wipe and the words it ran with. */+function RunPanel({ run, onAgain }: { run: Run; onAgain: () => void }) {+ const list = useGenerationList(run.ids).data;+ const byId = useMemo(() => new Map((list ?? []).map((g) => [g.id, g])), [list]);+ const final = byId.get(run.final);+ const rows: StepRow[] = run.ids.map((id) => {+ const g = byId.get(id);+ return { key: id, label: g?.request.step?.label ?? "A step", g };+ });+ const state = chainState(rows.map((r) => ({ g: r.g, label: r.label })).sort((a, b) => (a.g?.id === run.final ? 1 : b.g?.id === run.final ? -1 : 0)));+ const out = final?.status === "succeeded" ? final.outputs.find((o) => o.kind === "video") : undefined;+ return (+ <section className="mt-6" aria-labelledby="run-title">+ <Panel+ title={<span id="run-title">{final?.request.title ?? "Your restoration"}</span>}+ aside={+ out && final ? (+ <Button asChild size="sm" variant="outline" className="rounded-full">+ <a href={downloadHref(out.url, downloadName(final, out, 0))}>+ <Download className="size-3.5" /> Download+ </a>+ </Button>+ ) : state.status === "failed" ? (+ <Button size="sm" variant="outline" className="rounded-full" onClick={onAgain}>+ <RotateCcw className="size-3.5" /> Try again+ </Button>+ ) : null+ }+ >+ {out ? (+ <VideoCompare before={run.before} after={out.url} ratio={run.ratio} label="Compare the archive clip and the restored one" />+ ) : (+ <div className="space-y-3">+ <div className="h-1.5 overflow-hidden rounded-full bg-muted" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(state.progress * 100)} aria-label="Progress">+ <div className={cn("h-full transition-[width]", state.status === "failed" ? "bg-destructive" : "bg-primary")} style={{ width: `${Math.max(4, state.progress * 100)}%` }} />+ </div>+ <p className={cn("text-[13px]", state.status === "failed" ? "text-destructive" : "text-muted-foreground")} aria-live="polite">+ {state.status === "failed" ? `${state.label}: ${state.error}` : state.label}+ </p>+ {rows.length > 1 && <StepList steps={rows} />}+ </div>+ )}+ <p className="mt-3 text-[12px] leading-relaxed break-words text-muted-foreground">+ <span className="font-medium text-foreground">{BY[run.by] ?? "Words"}:</span> {run.prompt}+ </p>+ </Panel>+ </section>+ );+}diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex ac912fc4..83c50904 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -6,6 +6,7 @@ import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { SidebarTrigger } from "@/components/ui/sidebar";+import { OldFootageOffer } from "@/components/restore/old-footage";import { EngineSwitch } from "@/components/studio/engine-switch";import { VideoTrimmer } from "@/components/studio/video-trimmer";import { useEngine, useModelAccess } from "@/lib/api";@@ -437,6 +438,7 @@ function SetupPanel({label="Part of the clip to restyle"onMeta={source.setBrowserMeta}/>+ {clip.url && !clip.uploading && !clip.error && <OldFootageOffer url={clip.url} src={clip.preview} />}</div>)}diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex 98d3c0db..3382dccf 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -28,6 +28,7 @@ import { DubStudio } from "@/components/dub/dub-studio";import { TrimTool } from "@/components/av/trim-tool";import { RemoveObjectTool } from "@/components/remove-object/remove-object-tool";import { EvolutionTool } from "@/components/evolution/evolution-tool";+import { RestoreTool } from "@/components/restore/restore-tool";import { AudioJoinTool, AudioLoopTool } from "@/components/audio-tools/audio-tools";import { SplitSoundtrackTool } from "@/components/audio-tools/split-tool";import { ModeStudio, ModeTabs } from "./mode-studio";@@ -54,7 +55,7 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {},};-/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Remove object, Evolution, Captions, Trim). */+/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Remove object, Evolution, Restore & colourise, Captions, Trim). */const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {audio: {translate: ({ tabs }) => <DubStudio tabs={tabs} />,@@ -65,6 +66,7 @@ const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode"video-tools": {"remove-object": ({ tabs }) => <RemoveObjectTool tabs={tabs} />,evolution: ({ tabs }) => <EvolutionTool tabs={tabs} />,+ restore: ({ tabs }) => <RestoreTool tabs={tabs} />,captions: ({ tabs }) => <CaptionsStudio tabs={tabs} />,trim: ({ tabs }) => <TrimTool tabs={tabs} />,},diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 8df4770b..6ba183c8 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -18,6 +18,7 @@ import {Heart,ImagePlus,Layers2,+ Palette,Mic2,MoreHorizontal,Pin,@@ -108,6 +109,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {delete: Trash2,"delete-upload": Trash2,restore: ArchiveRestore,+ "restore-video": Palette,"delete-forever": Trash2,};diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 149c6e6b..f04e5314 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -57,6 +57,7 @@ export type CanvasNodeType =| "clone-voice"| "translate"| "concat"+ | "restore"| "table"| "output"| "note";@@ -234,12 +235,13 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {"clone-voice": { type: "clone-voice", label: "Clone voice", group: "Inputs", icon: "UserRound", description: "A voice sample (or one of your saved voices) to speak with" },translate: { type: "translate", label: "Translate", group: "Utilities", icon: "Languages", ops: ["translate", "dub"], variants: ["text", "video"], description: "Translate a text, or dub a video into another language" },concat: { type: "concat", label: "Video concatenator", group: "Utilities", icon: "Film", ops: ["concat"], description: "Up to 50 clips in one film: trim and mute each, pick the frame" },+ restore: { type: "restore", label: "Restore & colourise", group: "Utilities", icon: "Palette", ops: ["restore-video"], description: "Old or black-and-white footage, cleaned and in colour (Lightricks' Restore IC-LoRA)" },table: { type: "table", label: "Table", group: "Inputs", icon: "Table", description: "Rows of words: what it feeds runs once per row" },output: { type: "output", label: "Output", group: "Output", icon: "MonitorPlay", description: "Preview what's connected, side by side" },note: { type: "note", label: "Sticky note", group: "Output", icon: "StickyNote", description: "A note on the board (not run)" },};-export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "translate", "concat"]);+export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "translate", "concat", "restore"]);export const isGenerator = (n: Pick<CanvasNode, "type">) => GENERATOR_TYPES.has(n.type);/** Entries of the Add-node palette (several entries can make the same node type). */@@ -276,6 +278,7 @@ export const PALETTE: PaletteItem[] = [{ ...pick("clone-voice"), id: "clone-voice", keywords: "voice sample clone my voice speaker" },{ ...pick("translate"), id: "translate", data: { mediaKind: "text" }, keywords: "language translate dub localize subtitles" },{ ...pick("concat"), id: "concat", keywords: "concatenate join merge stitch edit trim mute film assemble" },+ { ...pick("restore"), id: "restore", keywords: "restore colourise colorize archive old footage black and white film scan vhs" },{ ...pick("table"), id: "table", data: { columns: ["Subject"], rows: [[""], [""], [""]] }, keywords: "rows batch spreadsheet list variations csv grid" },{ ...pick("output"), id: "output", keywords: "preview compare result" },{ ...pick("note"), id: "note", keywords: "comment annotation" },@@ -346,6 +349,7 @@ const PREFERRED: Partial<Record<Operation, Partial<Record<Engine, string>>>> = {frame: { cloud: "extract-frame" },"upscale-image": { cloud: "topaz-image", open: "oss-upscale-image" },"upscale-video": { cloud: "topaz-video", open: "oss-upscale-video-esrgan" },+ "restore-video": { cloud: "fuobe-restore", open: "fuobe-restore" },"bg-remove": { cloud: "birefnet-cloud", open: "oss-rmbg" },"bg-remove-video": { cloud: "birefnet-video", open: "oss-video-matte-birefnet" },write: { cloud: "text-llm", open: "oss-text-llm" },@@ -397,7 +401,8 @@ export const CONCAT_TOOLS = {export function defaultModelFor(op: Operation, engine: Engine, opts: { hidden?: boolean } = {}): ModelDef | undefined {const preferred = PREFERRED[op]?.[engine];const m = preferred ? getModel(preferred) : undefined;- if (m && m.engine === engine && supportsOp(m, op)) return m;+ // A Fuobe Original runs on both engines, so it is the default on either.+ if (m && runsOn(m, engine) && supportsOp(m, op)) return m;return MODELS.find((x) => x.engine === engine && (opts.hidden || !x.hidden) && supportsOp(x, op));}@@ -488,6 +493,8 @@ const OP_PORTS: Partial<Record<Operation, InputPortId[]>> = {"bg-remove-video": ["video"],"depth-video": ["video"],"relight-video": ["prompt", "video", "images"],+ // The archive clip, the period words, and an optional first frame already in colour.+ "restore-video": ["prompt", "video", "images"],concat: ["videos"],frame: ["video"],"color-match": ["images", "video"],diff --git a/src/lib/catalog/restore.ts b/src/lib/catalog/restore.tsindex d2a862c6..ce08425c 100644--- a/src/lib/catalog/restore.ts+++ b/src/lib/catalog/restore.ts@@ -579,3 +579,26 @@ export const CLOUD_NOTE =/** The one-time gated download, as the page says it. */export const GATED_NOTE = "The Restore IC-LoRA (1.7 GB) is gated on Hugging Face: accept its licence there once, then add your Hugging Face token in Settings → LoRAs.";++// ---------------------------------------------------------------------------+// Old footage elsewhere (Shorts, Explainer): how much colour a frame carries++/** Mean chroma (max − min of R, G, B, 0–255) over a frame's RGBA pixels: about 0 for black-and-white, low for sepia. */+export function meanChroma(rgba: ArrayLike<number>): number {+ let sum = 0;+ let n = 0;+ for (let i = 0; i + 3 < rgba.length; i += 4) {+ const r = rgba[i];+ const g = rgba[i + 1];+ const b = rgba[i + 2];+ sum += Math.max(r, g, b) - Math.min(r, g, b);+ n++;+ }+ return n ? sum / n : 0;+}++/** Below this mean chroma a clip reads as black-and-white or toned (sepia, cyanotype) footage. */+export const MONOCHROME_CHROMA = 24;++/** The Restore tool, with a clip handed over. */+export const restoreHref = (url?: string) => (url ? `/video-tools/restore?video=${encodeURIComponent(url)}` : "/video-tools/restore");diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsindex d6e0b1a5..0cce5811 100644--- a/src/lib/hubs.ts+++ b/src/lib/hubs.ts@@ -30,6 +30,7 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {{ id: "matte", label: "Remove background" },{ id: "remove-object", label: "Remove object" },{ id: "evolution", label: "Evolution" },+ { id: "restore", label: "Restore & colourise" },{ id: "relight", label: "Relight" },{ id: "depth", label: "Depth map" },{ id: "captions", label: "Captions" },diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 381a860f..9c3d070c 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -47,6 +47,7 @@ export type OutputActionId =| "delete"| "delete-upload"| "restore"+ | "restore-video"| "delete-forever";export interface OutputAction {@@ -119,6 +120,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =link("reframe", "Reframe", `/reframe?video=${q(o.url)}`);link("lipsync", "Lipsync", `/lipsync?video=${q(o.url)}`);link("upscale", "Upscale", `/upscale/video?video=${q(o.url)}`);+ // Old, faded or black-and-white footage (Fuobe Restore): Video tools → Restore & colourise with the clip in.+ link("restore-video", "Restore & colourise", `/video-tools/restore?video=${q(o.url)}`);link("add-sound", "Add sound", `/audio/video?video=${q(o.url)}`);link("split-soundtrack", "Split soundtrack", `/audio/split?video=${q(o.url)}`);// A Fuobe DoP colour-grade effect: the clip opens in Color grading with its grade picked (one click to export).diff --git a/src/lib/studios.ts b/src/lib/studios.tsindex cfc8e515..73fe3e25 100644--- a/src/lib/studios.ts+++ b/src/lib/studios.ts@@ -136,6 +136,8 @@ export const VIDEO_UPSCALE_STUDIO: StudioConfig = {kind: "video",hero: "Sharper, bigger, cleaner video",subtitle: "Upscale a clip to 1080p, 4K or up to 8K, and restore faces, textures and text.",+ // Archive footage (scans, tape, black and white) is restored and colourised first: Fuobe Restore rebuilds it, then upscales.+ related: { href: "/video-tools/restore", label: "Old or black-and-white footage? Restore archive footage first" },slots: [{ key: "video", label: "Video", accept: "video", required: true }],defaultModels: { cloud: "topaz-video", open: "oss-seedvr2" },clipFacts: true,diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex 1ece204d..588daa23 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -586,7 +586,7 @@ How you work:- Call generate (or create_storyboard) directly. The app shows the user a plan card with the cost and runs it when they approve — never ask "shall I go ahead?" in text.- For multi-step work (an image, then animate it; transcribe, translate, then voice it), put the steps in one generate call and set "after" on each later job: it starts by itself when the earlier job finishes and gets its result as input. When you need to judge a result before deciding the next step, wait with check_generations instead (look=true to see images) and pass the output URL into the next call.- Besides images, video and audio, models can transcribe speech, translate or write text (scripts, captions, ad copy), split images into layers, separate voice from background, trim, caption or re-sound clips, and turn an image into a 3D model: search_models with kind "text" or "model3d" finds the text and 3D ones.-- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).+- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor), restore_video (old or black-and-white footage restored and colourised, in Restore & colourise) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).- Use the user's files by the URLs listed in their message. Earlier outputs are found with list_recent. Saved characters and products are Elements: check list_elements and write their @handle in prompts.- Results show up in the chat by themselves, so don't repeat URLs back. After starting jobs, say briefly what's coming; after they finish, give a short take and suggest a next step.- Be brief and friendly. Plain sentences, no headings. Prices are estimates in USD; open-source models run free on the user's own GPU.diff --git a/src/server/assist/studio-routes.ts b/src/server/assist/studio-routes.tsindex 852e9e65..2e2191b3 100644--- a/src/server/assist/studio-routes.ts+++ b/src/server/assist/studio-routes.ts@@ -8,6 +8,7 @@ import { getModel } from "@/lib/catalog";import { routesFor } from "@/lib/catalog/plan";import { defaultSettings, genreInfo, PART_LABELS, type EpisodeAspect, type EpisodeSettings, type NarratorVoice, type StepPart } from "@/lib/catalog/faceless";import { AD_RATIOS, emptyKit, type BrandKit, type Product } from "@/lib/catalog/marketing";+import { RESTORE } from "@/lib/catalog/restore";import { lookFromPreset, SHORTS, SHORTS_MODELS, type ShortsLook } from "@/lib/catalog/shorts";import type { Engine, GenerationRequest, MediaKind, Operation } from "@/lib/catalog/types";import { modeHref } from "@/lib/hubs";@@ -22,10 +23,11 @@ import { chooseRoute } from "../generations";import { createProject, deleteProject, FileUrl, jobSteps, startJob } from "../layers";import { firstOn } from "../model-access";import { engineMode } from "../settings";+import { createRestore, estimateRestore, RestoreBodySchema, RestoreEstimateSchema } from "../restore";import { createSession, estimateWith, sourceInfo, type ShortsBody, type SourceInfo } from "../shorts";import { absolutePath, getAsset } from "../storage";import type { ToolContext } from "./define";-import { planSteps, STUDIO_ROUTES, type AdsToolInput, type CaptionsToolInput, type DubToolInput, type FacelessToolInput, type LayersToolInput, type RestyleToolInput, type StudioRoute } from "./studio-tools";+import { planSteps, STUDIO_ROUTES, type AdsToolInput, type CaptionsToolInput, type DubToolInput, type FacelessToolInput, type LayersToolInput, type RestoreToolInput, type RestyleToolInput, type StudioRoute } from "./studio-tools";/*** The Assist / MCP studio tools, wired to the studios' own server modules: each adapter turns a tool@@ -669,9 +671,67 @@ const captionsRoute: StudioRoute<CaptionsToolInput> = {},};+// ---------------------------------------------------------------------------+// Restore & colourise: one restoration, in Video tools → Restore & colourise (src/server/restore.ts)++function restoreBody(i: RestoreToolInput, ctx: ToolContext) {+ const info = clipInfo(i.video);+ return {+ engine: engineOf(ctx),+ source: { url: i.video, name: fileTitle(i.video), duration: info?.duration, fps: info?.fps, width: info?.width, height: info?.height, hasAudio: info?.hasAudio },+ prompt: i.prompt,+ hint: i.hint,+ negative: i.negative,+ refine: i.restore_to_4k,+ deinterlace: i.deinterlace,+ reference: i.reference,+ resolution: i.resolution,+ };+}++/** The body checked as /api/restore checks it, refused in words (a reference that isn't a Fuobe file). */+function parsed<T>(schema: { safeParse: (v: unknown) => { success: true; data: T } | { success: false } }, body: unknown): T {+ const r = schema.safeParse(body);+ if (!r.success) throw new Error("The clip and the reference picture must be files in Fuobe (/api/files/…): attach them to the chat first");+ return r.data;+}++const restoreRoute: StudioRoute<RestoreToolInput> = {+ studio: "Restore & colourise",+ page: modeHref("video-tools", "restore"),+ // Only a clip Fuobe can't read runs elsewhere (one generation on the whole clip); every other refusal is the card's error.+ refuse: (i) => (i.video.startsWith("/api/files/") && clipInfo(i.video)?.duration ? null : "Fuobe couldn't read this clip's length and frame rate"),+ plan: (i, ctx) => {+ const est = estimateRestore(parsed(RestoreEstimateSchema, restoreBody(i, ctx)));+ const job: PlannedJob = {+ tool: "restore_video",+ modelId: RESTORE.model,+ modelName: getModel(RESTORE.model)?.name ?? RESTORE.model,+ kind: "video",+ op: "restore-video",+ prompt: i.prompt?.trim() || "Written for the clip when it runs",+ count: 1,+ costUsd: est.costUsd,+ demo: est.demo,+ note: [`${est.pieces} ${est.engine === "open" ? "window" : "piece"}${est.pieces === 1 ? "" : "s"} at ${est.canvas.width}×${est.canvas.height}${est.refined ? `, then ${est.refined.width}×${est.refined.height}` : ""}`, ...est.notes].join(" · "),+ atomic: true,+ };+ return [job];+ },+ async run(i, ctx) {+ const r = await createRestore(parsed(RestoreBodySchema, restoreBody(i, ctx)));+ return {+ ids: [r.final.id],+ href: modeHref("video-tools", "restore"),+ info: { prompt: r.prompt, negative: r.negative, writtenBy: r.by, note: "The restoration is listed under Your restorations in Restore & colourise, beside the original with a Before/After wipe." },+ };+ },+};+STUDIO_ROUTES.split_layers = layersRoute;STUDIO_ROUTES.restyle_footage = shortsRoute;STUDIO_ROUTES.dub_video = dubRoute;STUDIO_ROUTES.faceless_episode = facelessRoute;STUDIO_ROUTES.create_ads = adsRoute;STUDIO_ROUTES.add_captions = captionsRoute;+STUDIO_ROUTES.restore_video = restoreRoute;diff --git a/src/server/assist/studio-tools.ts b/src/server/assist/studio-tools.tsindex abeb35d1..66ef4427 100644--- a/src/server/assist/studio-tools.ts+++ b/src/server/assist/studio-tools.ts@@ -6,6 +6,7 @@ import { getModel } from "@/lib/catalog";import { routesFor } from "@/lib/catalog/plan";import { FACELESS_STYLE_IDS, STYLES } from "@/lib/catalog/faceless";import { FRAME_SEED, MIXED_ORIGINAL } from "@/lib/catalog/mixed-media";+import { offlineRestorePrompt, RESTORE, restoreNegative } from "@/lib/catalog/restore";import { SHORTS_MODELS } from "@/lib/catalog/shorts";import type { ChainSlot, Engine, GenerationRequest, Operation } from "@/lib/catalog/types";import { TOOL_MODELS } from "@/lib/layers";@@ -129,7 +130,22 @@ const CaptionsInput = z.object({translate_to: z.string().optional().describe("Caption in this language instead (translated subtitles)."),});+const RestoreInput = z.object({+ video: ref.describe("The archive clip: an old scan, tape or black-and-white film (up to 2 minutes)."),+ prompt: z+ .string()+ .optional()+ .describe("Period, place, light, materials and clothing, ending with the colour wanted, e.g. 'a harbour in the 1930s, overcast morning, wool coats, natural colour'. Left out: written for the clip."),+ hint: z.string().optional().describe("A few words for the writer when prompt is left out, e.g. 'fishing boats, 1930s'."),+ negative: z.string().optional().describe("What it must not invent (default: modern objects and video artefacts such as blocky compression)."),+ restore_to_4k: z.boolean().optional().describe("Your GPU only: a detail pass at twice the size with Lightricks' Detail Refine IC-LoRA."),+ deinterlace: z.boolean().optional().describe("Your GPU only: keep one field of interlaced tape first."),+ reference: ref.optional().describe("A picture with the true colours (a colour photo of the place, a face). In the cloud it is the first frame: give the clip's first frame already in colour."),+ resolution: z.enum(["720p", "1080p"]).optional().describe("Cloud size (default 720p)."),+});+export type LayersToolInput = z.infer<typeof LayersInput>;+export type RestoreToolInput = z.infer<typeof RestoreInput>;export type RestyleToolInput = z.infer<typeof RestyleInput>;export type DubToolInput = z.infer<typeof DubInput>;export type FacelessToolInput = z.infer<typeof FacelessInput>;@@ -144,6 +160,7 @@ export const STUDIO_ROUTES: {faceless_episode?: StudioRoute<FacelessToolInput>;create_ads?: StudioRoute<AdsToolInput>;add_captions?: StudioRoute<CaptionsToolInput>;+ restore_video?: StudioRoute<RestoreToolInput>;} = {};// ---------------------------------------------------------------------------@@ -620,7 +637,43 @@ const addCaptions = defineTool({},});-export const STUDIO_TOOLS = [splitLayers, restyleFootage, dubVideo, facelessEpisode, createAds, addCaptions];+/** A clip the restore tool can't read: one generation of Fuobe Restore on the whole clip (the graph streams it up to 481 frames). */+function restoreSteps(i: RestoreToolInput, ctx: ToolContext): PipelineStep[] {+ const engine = engineOf(ctx);+ return labelled([+ {+ key: "restore",+ label: "Restored video",+ request: req({+ modelId: RESTORE.model,+ engine,+ op: "restore-video",+ prompt: i.prompt?.trim() || offlineRestorePrompt(i.hint).prompt,+ negativePrompt: i.negative?.trim() || restoreNegative(),+ inputs: { video: i.video, ...(i.reference && { images: [i.reference] }) },+ ...(engine === "cloud" && { params: { resolution: i.resolution ?? RESTORE.cloudResolution } }),+ }),+ },+ ]);+}++const restoreVideo = defineTool({+ name: "restore_video",+ description:+ "Restore and colourise archive footage (old scans, tape, black-and-white film, up to 2 minutes) with Lightricks' Restore IC-LoRA — Fuobe's Restore & colourise tool (Video tools → Restore & colourise), where the result sits beside the original with a Before/After wipe. " ++ "On your GPU: LTX-2.5 with tiled fusion in 97-frame windows, the sound kept, optional Restore to 4K and deinterlacing (the LoRA is gated: a Hugging Face token in Settings → Connections downloads it). " ++ "In the cloud: fal's LTX-2.3 reference video-to-video in pieces, priced per megapixel. Leave prompt out to have one written. Gated by the same approval card as generate.",+ schema: RestoreInput,+ gated: true,+ title: () => "Restore & colourise",+ place: (i, ctx) => placeFor(STUDIO_ROUTES.restore_video, i, ctx),+ plan: (i, ctx) => planVia("restore_video", STUDIO_ROUTES.restore_video, i, ctx, () => planSteps("restore_video", restoreSteps(i, ctx))),+ async run(i, ctx) {+ return runVia(STUDIO_ROUTES.restore_video, i, ctx, "Started a restoration", () => startPipeline("Restore & colourise", restoreSteps(i, ctx), "Restore & colourise"));+ },+});++export const STUDIO_TOOLS = [splitLayers, restyleFootage, dubVideo, facelessEpisode, createAds, addCaptions, restoreVideo];/** For tests: the fallback pipelines, as they would be created. */-export const fallbackSteps = { layers: layerSteps, restyle: restyleSteps, dub: dubSteps, faceless: facelessSteps, captions: captionSteps, ads: adRequests };+export const fallbackSteps = { restore: restoreSteps, layers: layerSteps, restyle: restyleSteps, dub: dubSteps, faceless: facelessSteps, captions: captionSteps, ads: adRequests };diff --git a/src/server/mcp.ts b/src/server/mcp.tsindex 1aa41165..923f48d0 100644--- a/src/server/mcp.ts+++ b/src/server/mcp.ts@@ -24,7 +24,7 @@ const INSTRUCTIONS ="Fuobe is an AI image, video and audio studio (paid cloud models and open-source ComfyUI workflows); it also transcribes, translates and writes text and turns images into 3D models. " +"Look up models with search_models (kinds image, video, audio, text, model3d), price a plan with estimate_cost and tell the user the cost before you call generate or create_storyboard. " +'Chain steps in one generate call with "after" (a still, then animate it). ' +- "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions, and katana, which rebuilds a 1–30 s reference edit shot for shot with the user's own subject from 1–5 photos): price them with estimate_job first. " ++ "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions, restore_video, and katana, which rebuilds a 1–30 s reference edit shot for shot with the user's own subject from 1–5 photos): price them with estimate_job first. " +"Each studio job opens in that Fuobe studio (a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions editor, Katana): the result's href is its page on this Fuobe server, so give the user that link; a call the studio can't take runs as plain steps and says why. " +"Skills are playbooks for kinds of jobs (product photos, UGC videos, thumbnails…): list_skills, then load_skill to read one — they're also offered as prompts. " +"Generations run in the background: poll check_generations (wait_seconds up to 120) for output URLs; text results come back inline. Output URLs are paths on this Fuobe server.";diff --git a/tests/assist-context.test.ts b/tests/assist-context.test.tsindex 1020de55..5580a9e8 100644--- a/tests/assist-context.test.ts+++ b/tests/assist-context.test.ts@@ -323,6 +323,7 @@ describe("studio tools", () => {],create_ads: [{ brief: "oat milk for runners" }, { brief: "oat milk", product_image: image, count: 2, aspect_ratios: ["1:1", "9:16"] }],add_captions: [{ video }, { video, translate_to: "Spanish" }],+ restore_video: [{ video }, { video, prompt: "a harbour in the 1930s, natural colour", reference: image }],};it("every studio tool plans without errors on both engines in demo mode", () => {diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.tsindex ed3d4bbd..317981c5 100644--- a/tests/library-pure.test.ts+++ b/tests/library-pure.test.ts@@ -110,6 +110,7 @@ describe("outputActions", () => {"menu:reframe","menu:lipsync","menu:upscale",+ "menu:restore-video","menu:add-sound","menu:split-soundtrack","menu:grade",diff --git a/tests/restore-api.test.ts b/tests/restore-api.test.tsindex 90373309..1c4fabe8 100644--- a/tests/restore-api.test.ts+++ b/tests/restore-api.test.ts@@ -20,6 +20,8 @@ const { db } = await import("@/server/db");const createRoute = await import("@/app/api/restore/route");const estimateRoute = await import("@/app/api/restore/estimate/route");const promptRoute = await import("@/app/api/restore/prompt/route");+const tools = await import("@/server/assist/tools");+const { handleMcp } = await import("@/server/mcp");const json = (body?: unknown) => new Request("http://x/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });@@ -134,3 +136,31 @@ describe("Restore: runs in demo mode", () => {expect((await settle(out.final.id)).status).toBe("succeeded");});});++describe("Restore: the Assist / MCP tool", () => {+ const plan = (input: unknown, engine: "cloud" | "open" = "open") => tools.planFor("restore_video", input, { engine });++ it("prices the clip as the tool does and opens in Restore & colourise; GPU-only options refused in the cloud, in words", async () => {+ const p = plan({ video: clip, hint: "a harbour" });+ expect(p.studio).toBe("Restore & colourise");+ expect(p.jobs).toMatchObject([{ tool: "restore_video", modelId: "fuobe-restore", op: "restore-video", costUsd: 0, atomic: true }]);+ expect(p.jobs[0].note).toMatch(/^3 windows at 1088×1920/);+ expect(plan({ video: clip, restore_to_4k: true }, "cloud").jobs[0].error).toMatch(/Restore to 4K runs on your GPU/);+ const est = (await handleMcp({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "estimate_job", arguments: { tool: "restore_video", arguments: { video: clip } } } })) as {+ result: { structuredContent: { studio?: string; jobs: { error?: string }[] }; isError: boolean };+ };+ expect(est.result.isError).toBe(false);+ expect(est.result.structuredContent.studio).toBe("Restore & colourise");+ });++ it("runs one restoration with the words written for it; a clip it can't read is one generation in the Library", async () => {+ const out = await tools.executeTool("restore_video", { video: clip, hint: "fishing boats, 1930s" }, { engine: "open" });+ const res = JSON.parse(out.content as string);+ expect(res).toMatchObject({ studio: "Restore & colourise", href: "/video-tools/restore", writtenBy: "offline" });+ expect(res.prompt).toMatch(/natural colour/);+ expect((await settle(res.results[0])).status).toBe("succeeded");+ const lost = plan({ video: "/api/files/uploads/gone.mp4" });+ expect(lost.fallback).toMatch(/couldn't read this clip/);+ expect(lost.jobs).toMatchObject([{ modelId: "fuobe-restore", op: "restore-video" }]);+ });+});diff --git a/tests/restore.test.ts b/tests/restore.test.tsindex bc303697..e8c3ea40 100644--- a/tests/restore.test.ts+++ b/tests/restore.test.ts@@ -3,6 +3,9 @@ import path from "node:path";import { describe, expect, it } from "vitest";import {ARTEFACTS,+ meanChroma,+ MONOCHROME_CHROMA,+ restoreHref,cloudPieceFrames,cloudShape,framesCovered,@@ -24,6 +27,7 @@ import type { ComfyWorkflow } from "@/lib/comfy";import { getModel, getPreset } from "@/lib/catalog";import { onEngine } from "@/lib/catalog/engines";import { estimateCost, planGeneration } from "@/lib/catalog/plan";+import { convertEngine, defaultModelForNode, describeNode, inputPorts, nodeEngine, outputType, paletteItems, type CanvasGraph, type CanvasNode } from "@/lib/catalog/canvas";const research = JSON.parse(fs.readFileSync(path.join(__dirname, "../docs/research/fuobe-originals-recipes-5.json"), "utf8"));const record = research.studios.find((s: { id: string }) => s.id === "archive-restore").original;@@ -313,3 +317,46 @@ describe("Restore & colourise: one run of the GPU graph", () => {expect(prefixOnly.sample.inputs).toMatchObject({ positive: ["prefix", 0], negative: ["prefix", 1], latents: ["prefix", 2] });});});++describe("Restore & colourise on the canvas", () => {+ const n = (id: string, type: CanvasNode["type"], data: CanvasNode["data"] = {}): CanvasNode => ({ id, type, position: { x: 0, y: 0 }, data });++ it("a Utilities node on both engines: Fuobe Restore by default, the clip, the words and an optional coloured first frame in, a video out", () => {+ const item = paletteItems().find((p) => p.id === "restore")!;+ expect(item).toMatchObject({ type: "restore", label: "Restore & colourise", group: "Utilities" });+ for (const mode of ["open", "cloud"] as const) {+ expect(paletteItems(mode).find((p) => p.id === "restore")!.disabled).toBeUndefined();+ expect(defaultModelForNode({ type: "restore", data: {} }, mode)?.id).toBe(RESTORE.model);+ }+ const node = n("r", "restore", { modelId: RESTORE.model, engine: "cloud" });+ expect(inputPorts(node).map((p) => p.id)).toEqual(["prompt", "images", "video"]);+ expect(outputType({ nodes: [node], edges: [] }, node)).toBe("video");+ expect(nodeEngine(node, getModel(RESTORE.model)!)).toBe("cloud");+ });++ it("runs a clip from the board as one restore-video generation; switching the board's engine keeps the Original", () => {+ const g: CanvasGraph = {+ nodes: [n("clip", "video-input", { url: "/api/files/scan.mp4" }), { ...n("r", "restore", { modelId: RESTORE.model, prompt: "a harbour in the 1930s, natural colour" }), position: { x: 300, y: 0 } }],+ edges: [{ id: "e", source: "clip", sourceHandle: "out", target: "r", targetHandle: "video" }],+ };+ const d = describeNode(g, g.nodes[1]);+ expect(d.error).toBeUndefined();+ expect(d.plan?.op).toBe("restore-video");+ const cloud = convertEngine(g, "cloud");+ expect(cloud.missing).toEqual([]);+ expect(cloud.graph.nodes[1].data).toMatchObject({ modelId: RESTORE.model, engine: "cloud" });+ });+});++describe("Old footage in Shorts and the Explainer", () => {+ const px = (...rgb: [number, number, number][]) => rgb.flatMap(([r, g, b]) => [r, g, b, 255]);+ it("reads black-and-white and sepia frames as monochrome, a colour frame not; the Restore link carries the clip", () => {+ expect(meanChroma(px([10, 10, 10], [200, 200, 200]))).toBe(0);+ // A sepia-toned print stays under the line; a colour street does not.+ expect(meanChroma(px([120, 110, 98], [190, 182, 172]))).toBeLessThan(MONOCHROME_CHROMA);+ expect(meanChroma(px([200, 40, 40], [30, 160, 60]))).toBeGreaterThan(MONOCHROME_CHROMA);+ expect(meanChroma([])).toBe(0);+ expect(restoreHref("/api/files/a b.mp4")).toBe("/video-tools/restore?video=%2Fapi%2Ffiles%2Fa%20b.mp4");+ expect(restoreHref()).toBe("/video-tools/restore");+ });+});