Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Live edit: change a picture as you type, as its own page and in Edit

Adarsh4d87473bc98c
diff --git a/README.md b/README.md
index b429dcad..8722c9e6 100644
--- a/README.md
+++ b/README.md
@@ -74,7 +74,7 @@
</tr>
</table>
-**Also inside:** Cinema (with a Fly path through 3D scenes), Shorts, Marketing and Ads studios, Canvas node workflows, Storyboard, Turnaround video, voice and music tools (Split soundtrack takes any soundtrack apart into dialogue, music and effects), skills, MCP and a CLI. [See every feature →](docs/FEATURES.md)
+**Also inside:** Live edit (the picture changes as you type, on your own GPU), Cinema (with a Fly path through 3D scenes), Shorts, Marketing and Ads studios, Canvas node workflows, Storyboard, Turnaround video, voice and music tools (Split soundtrack takes any soundtrack apart into dialogue, music and effects), skills, MCP and a CLI. [See every feature →](docs/FEATURES.md)
## Quick start
diff --git a/docs/FEATURES.md b/docs/FEATURES.md
index 8005bc53..db19f36b 100644
--- a/docs/FEATURES.md
+++ b/docs/FEATURES.md
@@ -57,6 +57,7 @@ Fuobe is a complete creative studio you can run yourself: 108 camera motions, 25
## Create
- **Create:** Image · Video (text, image, start/end frame, **Frames**: up to 10 stills on a timeline, reference images and clips, multi-shot, draft mode) · Edit · **Layers** (split a flat image into editable layers, edit text with the lines found for you on either engine, Inpaint a painted area, an Enhancer (skin, soft glow, sharpen, detail), regional edits, save a layer as an element, cropped or positioned zips) · Inpaint & Draw to Edit · Color grading · Camera motions and Effects (on Fuobe DoP) · Storyboard (Popcorn: a board in one of Fuobe Soul's looks if you like, priced next to Generate, and turned into a film; cloud boards start on hosted open models, Z-Image Turbo or Qwen-Image-Edit, then Qwen-Image-Edit 2509 with a next-scene LoRA, and "Frames made on" switches them to Nano Banana Pro) · **Canvas** (wire prompts, files and models into node workflows; every template in a cloud and an open-source version, 10 Effects 2.0 chains among them (your photo, a "Set the scene" edit, then a 5 s Fuobe DoP clip); up to 20 pages per board, groups you can run as one, comment pins with replies, and drawing, shapes and text from a toolbar with keys; a Table node runs the node it feeds once per row; Change voice, Clone voice, Translate (text, or a dub of a video) and Video concatenator (cut, mute and join up to 50 clips) nodes) · Apps
+- **Live edit** (Create → Live edit, the Edit studio's Live switch, a Library picture's "Change it as you type") — the picture changes as you type, on your own GPU: Qwen-Image 2.1 with linoyts' 2-step DMD2 LoRA on Fuobe's live nodes (fuobe_live.py, which the Windows start file and the setup card add to ComfyUI). Live frames come at 384 to 768 px (Auto steps down on a slower GPU); a pause renders the text on screen at full quality, and Enter, Keep or a click on a Try keeps exactly that picture as a lossless full-size master. Typing never keeps anything by itself. Unchanged pixels are copied from the step before, so stacking edits doesn't wear the picture down. Undo and redo every step, hold C to compare (Shift+C with the original), paint a region to change only that. On "Use the ComfyUI on this computer" the tab talks to its ComfyUI directly. Guests see a recorded session. Non-commercial weights; none of it has rendered on a real GPU yet
- **MOSS-Image** (Image studio → model menu → MOSS-Image) — OpenMOSS's picture model, made for Chinese and English text in pictures. In the cloud it runs on fal at $0.05 per megapixel, up to 4 images (fal's safety checker returns a black image when it flags an output). On your GPU it is free, on ComfyUI's built-in nodes, with about 15 GB of files and 16 GB of VRAM (a guess); **Options → Quality** picks Standard (25 steps), Best (50), Fast (8 steps, an extra 5.4 GB file) or Base model (MOSS-Image Base, 50 steps, an extra 5.4 GB file). Its text encoder is the int8 Qwen3.5-9B: the w4a8 build in ComfyUI's template crashed the graphics driver on a test PC. The Image studio's controls chip now reads **Options** (it read "Director"). Text placed in boxes comes later: the code that turns layout boxes into MOSS's prompt is in (`src/lib/layout-prompt.ts`), but the screen to draw them, Layout mode, is the next package in the queue
- **The newest open image models, first on your GPU** — Ideogram 4, Qwen-Image 2.1 and its Turbo, Krea 2 (Realism, Turbo, Edit, Identity Edit, Image to image, Inpaint) and FIBO 2 (Dev, Edit Turbo), from the owner's ComfyUI workflows. On the open engine the Image studio opens on Ideogram 4 (on Qwen-Image 2.1 for an account, a guest, or an install with no local LLM to write Ideogram's caption) and Edit and Inpaint on Qwen-Image 2.1; every model menu's "Best" list puts the new models first (text to image: Ideogram 4, Qwen-Image 2.1, Krea 2 Realism, MOSS-Image, then FIBO 2 Dev; edits: Qwen-Image 2.1, its Turbo, FIBO 2 Dev and Edit Turbo, then Krea 2 Edit), and so do apps, Layers, Canvas, Cinema stills, Photodump, Fashion Factory and Character swap's anchor. Apps and tools that run a LoRA trained on an older model keep it (Angles, Relight, Product shot, Try-On, Cinema's recompose). Ideogram 4 reads a JSON caption, which Fuobe writes from your words (with your local LLM, never a paid API; a plain caption without one) and keeps as the run's prompt. When Ideogram's safety filter sends its grey card instead of a picture, the run fails and says what to try. Soul Location doesn't offer Ideogram 4 (pictures of empty places hit that filter most), and a new Layers layer starts on Qwen-Image 2.1. Qwen-Image 2.1, FIBO 2 and Krea 2 Edit take up to 4 references (Krea 2 Edit 2) and leave out the ones you don't give; an edit keeps image 1's shape and size, so Edit and Inpaint show no aspect or size choice for them, and Qwen-Image 2.1's inpaint and expand take the picture alone. An app run made before an app moved to Qwen-Image 2.1 (a retry, Run again, Reuse) runs on Qwen-Image 2.1 and says so. About 92 GB of new files, 20–24 GB of VRAM (estimates), ComfyUI 0.42.0; Krea 2 runs Comfy-Org's fp8 Krea 2 Turbo, the file the owner's edit workflow loads. Krea 2 Inpaint also needs the ComfyUI-Krea2-Ostris-Edit node pack, so it isn't in Inpaint's "Best" list. Qwen-Image 2.1, Ideogram 4 and FIBO 2 weights are non-commercial. None of the 16 graphs has rendered through Fuobe yet
diff --git a/public/previews/live-edit/demo.json b/public/previews/live-edit/demo.json
new file mode 100644
index 00000000..aaaa3fa9
--- /dev/null
+++ b/public/previews/live-edit/demo.json
@@ -0,0 +1,18 @@
+{
+ "v": 1,
+ "size": [960, 720],
+ "frames": {
+ "before": { "src": "/previews/presets/ba/960/app-makeup-studio-before.jpg", "small": "/previews/presets/ba/512/app-makeup-studio-before.jpg" },
+ "after": { "src": "/previews/presets/ba/960/app-makeup-studio-after.jpg", "small": "/previews/presets/ba/512/app-makeup-studio-after.jpg" }
+ },
+ "script": [
+ { "type": "frame", "frame": "before", "ms": 900 },
+ { "type": "type", "text": "evening makeup", "ms": 1100 },
+ { "type": "frame", "frame": "after", "live": "0.71 s", "ms": 700 },
+ { "type": "type", "text": ", deep red lips", "ms": 1000 },
+ { "type": "frame", "frame": "after", "live": "0.68 s", "ms": 900 },
+ { "type": "keep", "label": "evening makeup, deep red lips", "ms": 1300 },
+ { "type": "compare", "ms": 2800 },
+ { "type": "pause", "ms": 1400 }
+ ]
+}
diff --git a/src/app/(studio)/apps/page.tsx b/src/app/(studio)/apps/page.tsx
index b7e096a1..0849a816 100644
--- a/src/app/(studio)/apps/page.tsx
+++ b/src/app/(studio)/apps/page.tsx
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
+import { LiveDemo } from "@/components/live/live-demo";
import { PageHeader, PageShell } from "@/components/page-shell";
-import { PresetGallery } from "@/components/preset-gallery";
+import { PresetGallery, type LinkCard } from "@/components/preset-gallery";
import { APPS } from "@/lib/catalog";
import { toPresetCard } from "@/lib/preset-card-data";
import { featuredGallery } from "@/lib/preset-featured";
@@ -10,6 +11,18 @@ export const metadata: Metadata = {
description: "One-click AI tools for faces, products, styles and fun, running on open-source ComfyUI workflows.",
};
+/** Tools of their own, first in the gallery. */
+const LEADING: LinkCard[] = [
+ {
+ href: "/live-edit?from=apps",
+ title: "Live edit",
+ line: "Type a change and watch it happen",
+ words: "realtime live as you type instant change edit",
+ badge: "New",
+ cover: <LiveDemo compact className="absolute inset-0 rounded-none" />,
+ },
+];
+
export default function Page() {
return (
<PageShell>
@@ -18,7 +31,7 @@ export default function Page() {
description="One-click tools for faces, products, styles and fun, each on an open-source ComfyUI workflow (and a cloud model where the studio has one)."
/>
{/* Slim card data only: no prompt templates, routes or LoRA URLs in the page payload. */}
- <PresetGallery {...featuredGallery(APPS.map(toPresetCard))} href="/apps/{id}" noun="apps" />
+ <PresetGallery {...featuredGallery(APPS.map(toPresetCard))} href="/apps/{id}" noun="apps" leading={LEADING} />
</PageShell>
);
}
diff --git a/src/app/(studio)/live-edit/page.tsx b/src/app/(studio)/live-edit/page.tsx
new file mode 100644
index 00000000..4a8e2fe7
--- /dev/null
+++ b/src/app/(studio)/live-edit/page.tsx
@@ -0,0 +1,13 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { LiveEditApp, LiveSkeleton } from "@/components/live/live-edit-app";
+
+export const metadata: Metadata = { title: "Live edit", description: "Change a picture as you type, on your own GPU with Qwen-Image 2.1." };
+
+export default function Page() {
+ return (
+ <Suspense fallback={<LiveSkeleton />}>
+ <LiveEditApp />
+ </Suspense>
+ );
+}
diff --git a/src/app/(studio)/page.tsx b/src/app/(studio)/page.tsx
index caef2726..58a79655 100644
--- a/src/app/(studio)/page.tsx
+++ b/src/app/(studio)/page.tsx
@@ -3,6 +3,7 @@ import {
AssistSection,
EffectsSection,
HomeFooter,
+ LiveEditSection,
MotionsSection,
OpenSourceSection,
ShowcaseWall,
@@ -32,6 +33,7 @@ export default async function Page() {
<EffectsSection facts={home.facts} effects={home.effects} />
<MotionsSection facts={home.facts} motions={home.motions} />
<AppsSection facts={home.facts} beforeAfter={home.beforeAfter} reveals={home.reveals} />
+ <LiveEditSection />
<StudiosSection facts={home.facts} studios={home.studios} audioTools={home.audioTools} pills={home.pills} />
<AssistSection facts={home.facts} runsOn={home.runsOn} skills={home.skills} />
<OpenSourceSection facts={home.facts} newModels={home.newModels} />
diff --git a/src/app/globals.css b/src/app/globals.css
index 58bf5969..9a9129ea 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -658,3 +658,10 @@
@media (prefers-reduced-motion: reduce) {
.pv, .pv * { animation: none !important; transition: none !important; }
}
+
+/* Live edit (src/components/live): a new frame fades in over the last; the demo dock's caret blinks. */
+@keyframes live-fade { from { opacity: 0; } to { opacity: 1; } }
+@keyframes live-caret { 50% { opacity: 0; } }
+@media (prefers-reduced-motion: reduce) {
+ [data-live-stage] img, [data-live-demo] img { animation: none !important; transition: none !important; }
+}
diff --git a/src/components/home-view.tsx b/src/components/home-view.tsx
index d1ebd514..387b7b9e 100644
--- a/src/components/home-view.tsx
+++ b/src/components/home-view.tsx
@@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
-import { ArrowRight, CircleAlert, ImageIcon, Loader2, MessageCircle, Video, Wand2 } from "lucide-react";
+import { ArrowRight, CircleAlert, ImageIcon, Loader2, MessageCircle, Video, Wand2, Zap } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { GetStarted } from "@/components/get-started";
@@ -30,6 +30,7 @@ const MODES = [
{ id: "image", label: "Image", icon: ImageIcon, href: "/image", placeholder: "Describe an image…" },
{ id: "video", label: "Video", icon: Video, href: "/video", placeholder: "Describe a shot…" },
{ id: "edit", label: "Edit", icon: Wand2, href: "/edit", placeholder: "Describe a change (you'll add the image next)…" },
+ { id: "live", label: "Live", icon: Zap, href: "/live-edit", placeholder: "Type and watch it change…" },
];
/** A Try chip under the composer: it picks the mode and fills in the prompt; Start still runs it. */
@@ -212,11 +213,13 @@ export function HomeView({
// carries a one-time token from this tab, so only this button can start a run that way.
const go = () => {
const p = prompt.trim();
+ // Live edit renders as you type there: the words go along, nothing starts by itself.
+ if (mode.id === "live") return router.push(`/live-edit?from=home${p ? `&text=${encodeURIComponent(p)}` : ""}`);
router.push(p ? `${mode.href}?prompt=${encodeURIComponent(p)}&${START_PARAM}=${issueStartToken()}` : mode.href);
};
// What Start will run, and what it costs, before it's pressed (or why it's a demo, and the engine that would run it).
- const runsFor = status ? startLine(status, quotes?.[mode.id], engine, mode.id as "image" | "video" | "edit") : null;
- const openModel = quotes?.[mode.id]?.open?.name;
+ const runsFor = status && mode.id !== "live" ? startLine(status, quotes?.[mode.id as "image" | "video" | "edit"], engine, mode.id as "image" | "video" | "edit") : null;
+ const openModel = mode.id === "live" ? undefined : quotes?.[mode.id as "image" | "video" | "edit"]?.open?.name;
const focusComposer = () => requestAnimationFrame(() => box.current?.focus());
const startOver = useCallback(() => {
setPrompt("");
diff --git a/src/components/home/home-sections.tsx b/src/components/home/home-sections.tsx
index 7acdabe1..a13e510f 100644
--- a/src/components/home/home-sections.tsx
+++ b/src/components/home/home-sections.tsx
@@ -1,6 +1,6 @@
import Link from "next/link";
import { Fragment } from "react";
-import { ArrowRight, AudioLines, Box, CalendarClock, ImageIcon, ListChecks, Plug, ScanEye, Sparkles, Video, type LucideIcon } from "lucide-react";
+import { ArrowRight, AudioLines, Box, CalendarClock, CornerDownLeft, ImageIcon, ListChecks, Plug, ScanEye, Sparkles, Undo2, Video, Zap, type LucideIcon } from "lucide-react";
import { GitHubMark } from "@/components/github-mark";
import { BeforeAfter } from "@/components/home/before-after";
import {
@@ -18,11 +18,12 @@ import {
} from "@/components/home/home-islands";
import { ShowcaseTile } from "@/components/home/showcase-tile";
import { IntentLink } from "@/components/intent-link";
+import { LiveDemo } from "@/components/live/live-demo";
import { NAV } from "@/components/nav-items";
import { PresetCard } from "@/components/preset-gallery";
import { ASSIST_SUGGESTIONS } from "@/lib/assist";
import { FUOBE_REPO } from "@/lib/connections";
-import { presetHref, type HomeShowcase } from "@/lib/home-showcase";
+import { HOME_LIVE, presetHref, type HomeShowcase } from "@/lib/home-showcase";
import { staggered } from "@/lib/preview-playback";
import { cn } from "@/lib/utils";
@@ -159,6 +160,43 @@ export function AppsSection({ facts, beforeAfter, reveals }: Pick<HomeShowcase,
);
}
+/**
+ * Live edit's moment: a recorded session plays beside what it does and one way in. The player is the only island; it
+ * pauses off screen, and nothing here reaches a GPU.
+ */
+export function LiveEditSection() {
+ const points: [LucideIcon, string][] = [
+ [Zap, "Live frames as you type, on your own GPU"],
+ [CornerDownLeft, "Enter keeps a change; typing never does"],
+ [Undo2, "Undo, redo and compare every step"],
+ ];
+ return (
+ <section aria-labelledby="home-live" className={cn(SECTION, "[--cv:720px] sm:[--cv:860px] md:[--cv:820px] lg:[--cv:470px] xl:[--cv:500px]")}>
+ <div className="grid grid-cols-1 items-center gap-6 lg:grid-cols-12 lg:gap-10">
+ <LiveDemo className="aspect-[4/3] w-full shadow-strong lg:col-span-7" />
+ <div className="min-w-0 lg:col-span-5">
+ <span className="inline-flex items-center gap-1.5 rounded-full bg-highlight px-2 py-0.5 text-[11px] font-semibold text-highlight-foreground">New · Live edit</span>
+ <h2 id="home-live" className={cn(H2, "mt-3")}>
+ {HOME_LIVE.title}
+ </h2>
+ <p className={LINE}>{HOME_LIVE.line}</p>
+ <ul className="mt-4 space-y-2 text-[14px]">
+ {points.map(([Icon, t]) => (
+ <li key={t} className="flex items-center gap-2.5">
+ <Icon className="size-4 shrink-0 text-primary" />
+ {t}
+ </li>
+ ))}
+ </ul>
+ <IntentLink href={HOME_LIVE.href} className="group mt-6 inline-flex h-10 items-center gap-2 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground transition hover:opacity-90">
+ Open Live edit <ArrowRight className="size-4 transition-transform duration-150 group-hover:translate-x-0.5" />
+ </IntentLink>
+ </div>
+ </div>
+ </section>
+ );
+}
+
/** Heights of the Audio card's bars (0–1): a waveform drawn once, not a recording. */
const WAVE = [
0.3, 0.45, 0.7, 0.5, 0.85, 1, 0.75, 0.55, 0.4, 0.6, 0.9, 0.7, 0.45, 0.3, 0.5, 0.8, 0.95, 0.65, 0.4, 0.55, 0.75, 0.5, 0.35, 0.6, 0.8, 0.55, 0.35, 0.25,
diff --git a/src/components/live/live-demo.tsx b/src/components/live/live-demo.tsx
new file mode 100644
index 00000000..727adc21
--- /dev/null
+++ b/src/components/live/live-demo.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+import { Check, CornerDownLeft, Zap } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { cn } from "@/lib/utils";
+
+/**
+ * A recorded live edit session, played back: the text types itself into the dock, the picture follows, Keep pulses, a
+ * step joins the trail, and a compare sweep shows the before and after. It loops, pauses off screen and in a hidden
+ * tab, and under reduced motion it is a still before/after. No GPU, no requests: guests, Home and the Apps card see it.
+ */
+
+export const LIVE_DEMO = "/previews/live-edit/demo.json";
+
+interface DemoFrame {
+ src: string;
+ small?: string;
+}
+type DemoStep =
+ | { type: "frame"; frame: string; live?: string; ms: number }
+ | { type: "type"; text: string; ms: number }
+ | { type: "keep"; label: string; ms: number }
+ | { type: "compare"; ms: number }
+ | { type: "pause"; ms: number };
+interface Demo {
+ size: [number, number];
+ frames: Record<string, DemoFrame>;
+ script: DemoStep[];
+}
+
+let loaded: Promise<Demo | null> | null = null;
+const loadDemo = () => (loaded ??= fetch(LIVE_DEMO).then((r) => (r.ok ? (r.json() as Promise<Demo>) : null)).catch(() => null));
+
+function useReducedMotion() {
+ const [reduced, setReduced] = useState(false);
+ useEffect(() => {
+ const q = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const on = () => setReduced(q.matches);
+ on();
+ q.addEventListener("change", on);
+ return () => q.removeEventListener("change", on);
+ }, []);
+ return reduced;
+}
+
+interface View {
+ frame: string;
+ /** The frame under it, fading out. */
+ under: string | null;
+ typed: string;
+ steps: string[];
+ keepPulse: boolean;
+ compare: number | null;
+ pill: string;
+}
+
+export function LiveDemo({ compact, className, onTypeAttempt }: { compact?: boolean; className?: string; onTypeAttempt?: () => void }) {
+ const [demo, setDemo] = useState<Demo | null>(null);
+ const reduced = useReducedMotion();
+ const box = useRef<HTMLDivElement>(null);
+ const [visible, setVisible] = useState(true);
+ const [view, setView] = useState<View>({ frame: "before", under: null, typed: "", steps: [], keepPulse: false, compare: null, pill: "Live · 512" });
+
+ useEffect(() => {
+ let alive = true;
+ void loadDemo().then((d) => alive && setDemo(d));
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ useEffect(() => {
+ const el = box.current;
+ if (!el) return;
+ const io = new IntersectionObserver(([e]) => setVisible(e.isIntersecting), { threshold: 0.15 });
+ io.observe(el);
+ const vis = () => setVisible((v) => v && document.visibilityState === "visible");
+ const back = () => document.visibilityState === "visible" && setVisible(el.getBoundingClientRect().bottom > 0);
+ document.addEventListener("visibilitychange", vis);
+ document.addEventListener("visibilitychange", back);
+ return () => {
+ io.disconnect();
+ document.removeEventListener("visibilitychange", vis);
+ document.removeEventListener("visibilitychange", back);
+ };
+ }, []);
+
+ // The player: one step at a time, each with its own small animation, then round again.
+ useEffect(() => {
+ if (!demo || reduced || !visible) return;
+ let alive = true;
+ const timers = new Set<ReturnType<typeof setTimeout>>();
+ const wait = (ms: number) => new Promise<void>((r) => timers.add(setTimeout(r, ms)));
+ const frameOf = (s: DemoStep) => (s.type === "frame" ? s.frame : null);
+ const first = demo.script.map(frameOf).find(Boolean) ?? Object.keys(demo.frames)[0];
+ void (async () => {
+ while (alive) {
+ setView({ frame: first, under: null, typed: "", steps: [], keepPulse: false, compare: null, pill: "Live · 512" });
+ let typed = "";
+ for (const s of demo.script) {
+ if (!alive) return;
+ if (s.type === "frame") {
+ setView((v) => ({ ...v, under: v.frame === s.frame ? v.under : v.frame, frame: s.frame, pill: s.live ? `Live · 512 · ${s.live}` : v.pill }));
+ await wait(s.ms);
+ } else if (s.type === "type") {
+ const per = Math.max(28, Math.floor(s.ms / Math.max(1, s.text.length)));
+ for (const ch of s.text) {
+ if (!alive) return;
+ typed += ch;
+ const t = typed;
+ setView((v) => ({ ...v, typed: t }));
+ await wait(per + (ch === " " ? 40 : 0));
+ }
+ } else if (s.type === "keep") {
+ setView((v) => ({ ...v, keepPulse: true }));
+ await wait(380);
+ typed = "";
+ setView((v) => ({ ...v, keepPulse: false, typed: "", steps: [...v.steps, s.label], pill: "Kept ✓ · 1024" }));
+ await wait(s.ms - 380);
+ } else if (s.type === "compare") {
+ const t0 = performance.now();
+ while (alive && performance.now() - t0 < s.ms) {
+ const p = (performance.now() - t0) / s.ms;
+ setView((v) => ({ ...v, compare: 50 + 42 * Math.sin(p * Math.PI * 2) }));
+ await wait(33);
+ }
+ setView((v) => ({ ...v, compare: null }));
+ } else await wait(s.ms);
+ }
+ }
+ })();
+ return () => {
+ alive = false;
+ for (const t of timers) clearTimeout(t);
+ };
+ }, [demo, reduced, visible]);
+
+ const src = (id: string | null) => {
+ const f = id ? demo?.frames[id] : undefined;
+ return f ? (compact && f.small ? f.small : f.src) : "";
+ };
+ const firstFrame = demo ? Object.keys(demo.frames)[0] : null;
+ const lastFrame = demo ? Object.keys(demo.frames).at(-1)! : null;
+ const ratio = demo ? `${demo.size[0]} / ${demo.size[1]}` : "4 / 3";
+
+ return (
+ <div ref={box} className={cn("relative isolate overflow-hidden rounded-2xl bg-media text-white", className)} style={{ aspectRatio: compact ? ratio : undefined }} data-live-demo>
+ {demo && (reduced ? (
+ <StillCompare before={src(firstFrame)} after={src(lastFrame)} />
+ ) : (
+ <>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {view.under && <img key={`u-${view.under}`} src={src(view.under)} alt="" className="absolute inset-0 size-full object-cover" draggable={false} />}
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img key={`f-${view.frame}`} src={src(view.frame)} alt="A live edit of a portrait" className="absolute inset-0 size-full animate-[live-fade_140ms_ease-out] object-cover" draggable={false} />
+ {view.compare !== null && (
+ <>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={src(firstFrame)} alt="" className="absolute inset-0 size-full object-cover" style={{ clipPath: `inset(0 ${100 - view.compare}% 0 0)` }} draggable={false} />
+ <span className="absolute inset-y-0 w-0.5 bg-white shadow-[0_0_8px_rgba(0,0,0,.5)]" style={{ left: `${view.compare}%` }} />
+ </>
+ )}
+ </>
+ ))}
+ <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-black/0 to-black/10" />
+ <span className="absolute top-3 left-3 inline-flex items-center gap-1.5 rounded-full bg-black/45 px-2.5 py-1 text-[11px] font-medium backdrop-blur" role="status" aria-live="off">
+ <span className="size-1.5 animate-pulse rounded-full bg-emerald-400" />
+ {view.pill}
+ </span>
+ {!compact && view.steps.length > 0 && (
+ <div className="absolute top-3 right-3 flex max-w-[60%] items-center gap-1 overflow-hidden text-[11px]">
+ <span className="rounded-full bg-black/45 px-2 py-0.5 backdrop-blur">Original</span>
+ {view.steps.map((s, i) => (
+ <span key={i} className="truncate rounded-full bg-white/90 px-2 py-0.5 font-medium text-black">
+ {i + 1} · {s}
+ </span>
+ ))}
+ </div>
+ )}
+ <div className={cn("absolute inset-x-3 bottom-3 flex items-center gap-2", compact && "inset-x-2 bottom-2")}>
+ <button
+ type="button"
+ tabIndex={onTypeAttempt ? 0 : -1}
+ onClick={onTypeAttempt}
+ className={cn("flex min-w-0 flex-1 items-center gap-2 rounded-xl bg-white/12 px-3 text-left ring-1 ring-white/15 backdrop-blur-md", compact ? "h-9 text-[12.5px]" : "h-11 text-[14px]")}
+ aria-label="Type a change"
+ >
+ <Zap className="size-3.5 shrink-0 text-amber-300" />
+ <span className="truncate">{view.typed || <span className="text-white/55">Type a change…</span>}</span>
+ <span className="-ml-1.5 h-4 w-px shrink-0 animate-[live-caret_1s_steps(1)_infinite] bg-white/80" />
+ </button>
+ <span className={cn("inline-flex shrink-0 items-center gap-1 rounded-xl bg-white font-medium text-black transition-transform", compact ? "h-9 px-2.5 text-[12px]" : "h-11 px-3.5 text-[13px]", view.keepPulse && "scale-95 ring-4 ring-primary/60")}>
+ {view.steps.length && !view.typed ? <Check className="size-3.5" /> : <CornerDownLeft className="size-3.5" />}
+ Keep
+ </span>
+ </div>
+ </div>
+ );
+}
+
+function StillCompare({ before, after }: { before: string; after: string }) {
+ const [pos, setPos] = useState(50);
+ return (
+ <div className="absolute inset-0">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={after} alt="After a live edit" className="absolute inset-0 size-full object-cover" />
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={before} alt="Before" className="absolute inset-0 size-full object-cover" style={{ clipPath: `inset(0 ${100 - pos}% 0 0)` }} />
+ <input type="range" min={0} max={100} value={pos} onChange={(e) => setPos(Number(e.target.value))} aria-label="Compare before and after" className="absolute inset-x-6 top-1/2 opacity-0" />
+ <span className="pointer-events-none absolute inset-y-0 w-0.5 bg-white" style={{ left: `${pos}%` }} />
+ </div>
+ );
+}
diff --git a/src/components/live/live-edit-app.tsx b/src/components/live/live-edit-app.tsx
new file mode 100644
index 00000000..2074760d
--- /dev/null
+++ b/src/components/live/live-edit-app.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { Cpu, LogIn, Sparkles, Zap } from "lucide-react";
+import Link from "next/link";
+import { useSearchParams } from "next/navigation";
+import { useMemo, useState } from "react";
+import { openConnect, useComputerSupport } from "@/components/gpu/open-connect";
+import { rememberedComfy } from "@/components/gpu/computer-runtime";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Button } from "@/components/ui/button";
+import { signInHref, useHydrated, useStatus, useViewer } from "@/lib/api";
+import { cn } from "@/lib/utils";
+import { LiveDemo } from "./live-demo";
+import { LiveEditor } from "./live-editor";
+import { ChannelTransport, ServerTransport, type LiveTransport } from "./live-transport";
+
+/** Where a link may start live edit from: a Fuobe file only (anything else is ignored). */
+const fileParam = (v: string | null) => (v && /^\/api\/files\/[\w./%-]{1,300}$/.test(v) ? v : undefined);
+
+/**
+ * The Live edit page: who is looking decides what it shows. A guest sees the recorded session playing and an offer to
+ * sign up; an account without a GPU sees it with "Connect your GPU". The owner, and an account with its own GPU, get
+ * the editor: through the server (a local install, or a linked GPU), or straight from this tab to the ComfyUI on this
+ * computer.
+ */
+export function LiveEditApp() {
+ const sp = useSearchParams();
+ const image = fileParam(sp.get("image"));
+ const text = sp.get("text")?.slice(0, 600) ?? undefined;
+ const from = sp.get("from")?.slice(0, 20) ?? undefined;
+ const lab = sp.get("lab") === "1";
+ const live = useLiveTransport();
+ if (live.s !== "ready") return live.s === "loading" ? <LiveSkeleton /> : <LiveShowcase kind={live.s} />;
+ return <LiveEditor variant="app" transport={live.transport} image={image} text={text} from={from} canSave={live.owner} lab={live.owner && lab} />;
+}
+
+export type LiveAccess = { s: "loading" | "guest" | "connect" | "unsupported" } | { s: "ready"; transport: LiveTransport; owner: boolean };
+
+/** Who is looking, and the way to their ComfyUI: one transport per page. */
+export function useLiveTransport(): LiveAccess {
+ const viewer = useViewer().data;
+ const status = useStatus().data;
+ const support = useComputerSupport();
+ const mounted = useHydrated();
+
+ const who = !viewer ? null : viewer.publicSignup && !viewer.signedIn ? "guest" : viewer.owner ? "owner" : "account";
+ const gpu = status?.viewer?.gpu;
+ const computer = !!viewer?.computer;
+ const noGpu = who === "account" && status !== undefined && !gpu?.connected;
+ const unsupported = computer && support !== "ok";
+ const statusKnown = status !== undefined;
+
+ const transport = useMemo<LiveTransport | null>(() => {
+ if (!mounted || !who || who === "guest" || noGpu || unsupported) return null;
+ if (who === "account" && !statusKnown) return null;
+ if (computer) {
+ const at = rememberedComfy();
+ return new ChannelTransport(at?.port ?? viewer?.comfyPort ?? 8188, at?.host ?? "127.0.0.1");
+ }
+ return new ServerTransport();
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- one transport per page
+ }, [mounted, who, noGpu, unsupported, computer, statusKnown]);
+
+ if (!mounted || !viewer) return { s: "loading" };
+ if (who === "guest") return { s: "guest" };
+ if (noGpu) return { s: "connect" };
+ if (unsupported) return { s: "unsupported" };
+ if (!transport) return { s: "loading" };
+ return { s: "ready", transport, owner: who === "owner" };
+}
+
+/**
+ * Live edit inside the Edit studio (its Live switch): the same editor, seeded with the composer's picture. "Use in
+ * Edit" hands the kept picture back to the composer, so the full model can finish the job.
+ */
+export function LiveEditPanel({ image, text, onUse, onClose }: { image?: string; text?: string; onUse: (url: string) => void; onClose: () => void }) {
+ const live = useLiveTransport();
+ if (live.s === "ready") return <LiveEditor variant="embedded" transport={live.transport} image={fileParam(image ?? null)} text={text} from="edit" canSave={live.owner} onUse={onUse} onClose={onClose} />;
+ return (
+ <div className="grid h-full place-items-center rounded-2xl border p-4" data-live-panel>
+ {live.s === "loading" ? (
+ <span className="text-[13px] text-muted-foreground">Starting Live edit…</span>
+ ) : (
+ <div className="grid w-full max-w-3xl items-center gap-5 md:grid-cols-[1.3fr_1fr]">
+ <LiveDemo className="aspect-[4/3] w-full" />
+ <div>
+ <p className="font-heading text-[24px] leading-tight">Change it as you type</p>
+ <p className="mt-1.5 text-[13.5px] text-muted-foreground">
+ {live.s === "guest"
+ ? "Sign up free to run Live edit on your own GPU."
+ : live.s === "connect"
+ ? "Live edit runs on your own GPU. Connect it to start."
+ : "Live edit on your computer needs Chrome or Edge on a desktop."}
+ </p>
+ <div className="mt-3 flex gap-2">
+ {live.s === "guest" ? (
+ <Button asChild>
+ <Link href={signInHref("signup", "/edit")}>Sign up free</Link>
+ </Button>
+ ) : live.s === "connect" ? (
+ <Button onClick={() => openConnect()}>
+ <Cpu className="size-4" />
+ Connect your GPU
+ </Button>
+ ) : null}
+ <Button variant="ghost" onClick={onClose}>
+ Back to Edit
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function LiveSkeleton() {
+ return (
+ <div className="flex h-[100dvh] flex-col gap-3 p-3 sm:p-4" aria-busy>
+ <div className="h-8 w-48 animate-pulse rounded-lg bg-muted" />
+ <div className="min-h-0 flex-1 animate-pulse rounded-2xl bg-muted" />
+ <div className="h-11 animate-pulse rounded-2xl bg-muted" />
+ </div>
+ );
+}
+
+/** Guests, accounts without a GPU, and browsers that can't reach this computer: the recorded session, and the next step. */
+function LiveShowcase({ kind }: { kind: "guest" | "connect" | "unsupported" }) {
+ const [nudge, setNudge] = useState(false);
+ return (
+ <div className="flex min-h-[100dvh] flex-col">
+ <header className="flex h-14 shrink-0 items-center gap-2 px-3 sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <h1 className="flex items-center gap-2 font-heading text-[22px] leading-none">
+ <Zap className="size-4 text-primary" />
+ Live edit
+ </h1>
+ <span className="ml-1 rounded-full bg-highlight px-2 py-0.5 text-[11px] font-semibold text-highlight-foreground">New</span>
+ </header>
+ <div className="mx-auto grid w-full max-w-6xl flex-1 items-center gap-6 px-3 pb-6 sm:px-6 lg:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)] lg:gap-10">
+ <LiveDemo className="aspect-[4/3] w-full shadow-strong" onTypeAttempt={() => setNudge(true)} />
+ <div className="max-w-md">
+ <p className="font-heading text-[34px] leading-[1.08] text-balance sm:text-[40px]">Change a picture as you type</p>
+ <p className="mt-3 text-[15px] leading-relaxed text-muted-foreground text-pretty">
+ Type a change and the picture follows in under a second. Press Enter to keep it, then type the next. Every kept step is a lossless full-size master, so nothing blurs, however many changes you stack.
+ </p>
+ <ul className="mt-4 space-y-1.5 text-[13.5px]">
+ {["Live frames as you type, on your own GPU", "Keep, undo and redo every step", "Paint a region to change only that", "Compare with the step before or the original"].map((t) => (
+ <li key={t} className="flex items-center gap-2">
+ <Sparkles className="size-3.5 shrink-0 text-primary" />
+ {t}
+ </li>
+ ))}
+ </ul>
+ <div className={cn("mt-6 rounded-2xl border p-4 transition-shadow", nudge && "ring-3 ring-primary/30")} data-live-cta>
+ {kind === "guest" ? (
+ <>
+ <p className="font-medium">{nudge ? "Create a free account to run this." : "Sign up free to run Live edit on your own GPU"}</p>
+ <p className="mt-1 text-[13px] text-muted-foreground">Free accounts run it on their own ComfyUI: this computer, or a GPU you link.</p>
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button asChild>
+ <Link href={signInHref("signup", "/live-edit")}>Sign up free</Link>
+ </Button>
+ <Button asChild variant="secondary">
+ <Link href={signInHref("login", "/live-edit")}>
+ <LogIn className="size-4" />
+ Log in
+ </Link>
+ </Button>
+ </div>
+ </>
+ ) : kind === "connect" ? (
+ <>
+ <p className="font-medium">Connect your GPU to run this</p>
+ <p className="mt-1 text-[13px] text-muted-foreground">Live edit runs on your own ComfyUI: the one on this computer, or one you link.</p>
+ <Button className="mt-3" onClick={() => openConnect()}>
+ <Cpu className="size-4" />
+ Connect your GPU
+ </Button>
+ </>
+ ) : (
+ <>
+ <p className="font-medium">Live edit on your computer needs Chrome or Edge on a desktop</p>
+ <p className="mt-1 text-[13px] text-muted-foreground">This browser can&apos;t reach the ComfyUI on your computer. Open Fuobe in Chrome or Edge there.</p>
+ </>
+ )}
+ </div>
+ <p className="mt-4 text-[12px] text-muted-foreground">
+ Qwen-Image 2.1 with the DMD2 2-step LoRA · non-commercial weights ·{" "}
+ <Link href="/settings/about" className="underline-offset-2 hover:underline">
+ licence
+ </Link>
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/live/live-editor.tsx b/src/components/live/live-editor.tsx
new file mode 100644
index 00000000..f97c4ea3
--- /dev/null
+++ b/src/components/live/live-editor.tsx
@@ -0,0 +1,1300 @@
+"use client";
+
+import {
+ ArrowLeftRight,
+ Brush,
+ Check,
+ ChevronLeft,
+ CornerDownLeft,
+ Download,
+ Expand,
+ ImagePlus,
+ Keyboard,
+ Loader2,
+ MoreHorizontal,
+ Redo2,
+ Save,
+ Shuffle,
+ Undo2,
+ Upload,
+ X,
+ Zap,
+ ZapOff,
+} from "lucide-react";
+import Link from "next/link";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import { CompareSlider } from "@/components/studio/compare-slider";
+import { SketchEditor, type SketchResult } from "@/components/studio/sketch-editor";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Kbd } from "@/components/ui/kbd";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { postFile } from "@/lib/upload";
+import type { LiveEvent } from "@/lib/live/frames";
+import { aspectOf, AutoSize, isAspect, keepAuto, KEEP_LADDER, LIVE_LADDER, type Aspect, type KeepRes, type LiveSize } from "@/lib/live/sizes";
+import { pictureExt, pngSize } from "@/lib/live/names";
+import { restoreStack, StepStack, type Method, type Step } from "@/lib/live/steps";
+import { completedWords, endsWord, MAX_LIVE_TEXT, normalize } from "@/lib/live/text";
+import { cn } from "@/lib/utils";
+import { keyOf, type LiveFacts, type LiveTransport, type RenderOut, type RenderReq, type TransportStatus } from "./live-transport";
+import { idbGet, idbPut } from "./live-store";
+
+/**
+ * Live edit: change a picture as you type. The text box drives throwaway live frames (small WebP, a few hundred
+ * milliseconds each); a pause renders the text on screen at full quality (the settled frame); Keep (Enter, the Keep
+ * button, or a click on a Try) stores that exact picture as a lossless master and the next change builds on it. Typing
+ * never keeps anything by itself. Undo and redo move through the kept steps; hold C to compare with the step before
+ * (Shift+C: the original); B paints a region to change. Two shells: the full-screen app (/live-edit) and a panel in
+ * the Edit studio.
+ */
+
+export interface LiveEditorProps {
+ variant: "app" | "embedded";
+ transport: LiveTransport;
+ /** A Fuobe file to start from. */
+ image?: string;
+ /** Starting text (not kept). */
+ text?: string;
+ /** Where the editor was opened from (the back link, provenance on save). */
+ from?: string;
+ /** The owner may save to the Library; an account downloads instead. */
+ canSave: boolean;
+ /** The owner's lab: the stacking method can be switched (hybrid, chain, compose). */
+ lab?: boolean;
+ /** Embedded: hand the kept picture to the Edit studio. */
+ onUse?: (url: string) => void;
+ onClose?: () => void;
+}
+
+/** When a keystroke's exact text renders (the words so far render at once at a word boundary). */
+const IDLE_MS = 250;
+/** When the text on screen renders at full quality (what Keep stores). */
+const SETTLE_MS = 1200;
+const CACHE_SIZE = 120;
+const MAX_TRIES = 6;
+
+interface Shown {
+ url: string;
+ key: string;
+ seq: number;
+ kind: "live" | "settled" | "master";
+ w: number;
+ h: number;
+ ms: number;
+ sha256: string;
+}
+
+interface Cached {
+ url: string;
+ out: RenderOut;
+ kind: "live" | "settled";
+ seed: number;
+ text: string;
+}
+
+interface Try {
+ key: string;
+ url: string;
+ seed: number;
+ text: string;
+}
+
+type Phase = { s: "connecting" } | { s: "ready" } | { s: "setup"; facts: LiveFacts } | { s: "error"; message: string; code?: string };
+
+const storageKey = (image: string | undefined) => `fuobe-live:${image ?? "new"}`;
+
+/** What the page shows of the kept steps (a snapshot: the stack itself lives in a ref and changes in handlers). */
+interface StackView {
+ head: Step | null;
+ original: Step | null;
+ previous: Step | null;
+ path: Step[];
+ all: readonly Step[];
+ canUndo: boolean;
+ canRedo: boolean;
+}
+const viewOf = (s: StepStack): StackView => ({ head: s.head, original: s.original, previous: s.previous(), path: s.path(), all: [...s.all], canUndo: s.canUndo(), canRedo: s.canRedo() });
+const EMPTY_VIEW: StackView = { head: null, original: null, previous: null, path: [], all: [], canUndo: false, canRedo: false };
+
+function load<T>(key: string): T | null {
+ try {
+ const raw = localStorage.getItem(key);
+ return raw ? (JSON.parse(raw) as T) : null;
+ } catch {
+ return null;
+ }
+}
+function save(key: string, value: unknown) {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {}
+}
+
+const dataUrlBytes = async (url: string) => new Uint8Array(await (await fetch(url)).arrayBuffer());
+
+/**
+ * Render timings for the page's own checks: a page that sets `window.__fuobeLiveTrace = []` gets one row per render
+ * (when it was sent and answered, and ComfyUI's own time). Nothing is kept otherwise.
+ */
+function trace(row: { slot: string; seq: number; sent: number; got: number; ms?: number; outcome: string }) {
+ const t = (window as unknown as { __fuobeLiveTrace?: unknown[] }).__fuobeLiveTrace;
+ if (Array.isArray(t) && t.length < 5000) t.push(row);
+}
+
+export function LiveEditor(props: LiveEditorProps) {
+ const { transport, variant } = props;
+ const embedded = variant === "embedded";
+ const [phase, setPhase] = useState<Phase>({ s: "connecting" });
+ const [facts, setFacts] = useState<LiveFacts | null>(null);
+ const [status, setStatus] = useState<TransportStatus>({ online: false, running: null, queue: 0, otherRan: false });
+ const [image, setImage] = useState<string | undefined>(props.image);
+ const persistKey = storageKey(image);
+
+ // Kept steps and the picture on screen.
+ const stack = useRef<StepStack>(new StepStack());
+ const [view, setView] = useState<StackView>(EMPTY_VIEW);
+ const bump = () => setView(viewOf(stack.current));
+ const [shown, setShown] = useState<Shown | null>(null);
+ const shownSeq = useRef(-1);
+ const shownKey = useRef("");
+ const masterUrls = useRef(new Map<string, string>());
+ const [urls, setUrls] = useState<Record<string, string>>({});
+ const setMasterUrl = (name: string, url: string) => {
+ masterUrls.current.set(name, url);
+ setUrls((u) => ({ ...u, [name]: url }));
+ };
+
+ // The open change.
+ const [text, setText] = useState(props.text ?? "");
+ const textRef = useRef(text);
+ const seedRef = useRef(0);
+ const [seed, setSeed] = useState(0);
+ const [tries, setTries] = useState<Try[]>([]);
+ const [mask, setMask] = useState<{ name: string; preview: string } | null>(null);
+
+ // Settings.
+ const [liveOn, setLiveOn] = useState(true);
+ const [liveChoice, setLiveChoice] = useState<"auto" | LiveSize>("auto");
+ const [keepChoice, setKeepChoice] = useState<"auto" | KeepRes>("auto");
+ const [aspect, setAspect] = useState<Aspect>("3:4");
+ const [method, setMethod] = useState<Method>("hybrid");
+ const auto = useRef(new AutoSize(512));
+ const [liveSize, setLiveSize] = useState<LiveSize>(512);
+ const sizeShown: LiveSize = liveChoice === "auto" ? liveSize : liveChoice;
+
+ // Work in flight.
+ const seq = useRef(0);
+ const inflight = useRef(new Map<string, number>());
+ const cache = useRef(new Map<string, Cached>());
+ /** A live frame of the same text at another live size (the auto size moved): it shows instead of a new render. */
+ const anySize = useRef(new Map<string, string>());
+ const idle = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const settle = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const [busy, setBusy] = useState<{ what: "rendering" | "warming" | "keeping" | "adding"; since: number; progress?: number } | null>(null);
+ const [lastMs, setLastMs] = useState<number | null>(null);
+ const [keptFlash, setKeptFlash] = useState(false);
+ const [hidden, setHidden] = useState(false);
+ const [highvramHint, setHighvramHint] = useState(true);
+
+ // Compare and tools.
+ const [hold, setHold] = useState<"prev" | "orig" | null>(null);
+ const [compareOpen, setCompareOpen] = useState(false);
+ const [compareWith, setCompareWith] = useState<"prev" | "orig">("prev");
+ const [brushOpen, setBrushOpen] = useState(false);
+ const [keysOpen, setKeysOpen] = useState(false);
+ const [dragging, setDragging] = useState(false);
+ const box = useRef<HTMLTextAreaElement>(null);
+ const fileInput = useRef<HTMLInputElement>(null);
+
+ const head = view.head;
+ const hasPicture = !!head;
+ const keepRes: number = keepChoice === "auto" ? keepAuto(head ? Math.max(head.master.w, head.master.h) : undefined) : keepChoice;
+
+ // ---------------------------------------------------------------------------
+ // Opening: the transport, the stored session, the starting picture
+
+ const urlOfMaster = useCallback((s: Step | null): string | null => {
+ if (!s) return null;
+ return masterUrls.current.get(s.master.name) ?? s.master.url ?? null;
+ }, []);
+ /** The same, for what the page draws. */
+ const urlOf = (s: Step | null): string | null => (s ? (urls[s.master.name] ?? s.master.url ?? null) : null);
+
+ const persist = useCallback(() => {
+ save(persistKey, { v: 1, stack: stack.current.toJSON(), seed: seedRef.current, keepChoice, liveChoice, aspect });
+ }, [persistKey, keepChoice, liveChoice, aspect]);
+
+ const showMaster = useCallback(
+ (s: Step | null) => {
+ if (!s) return setShown(null);
+ const url = urlOfMaster(s);
+ if (!url) return;
+ // Late live frames can't cover a picture the person chose.
+ shownSeq.current = seq.current;
+ shownKey.current = `master:${s.id}`;
+ setShown({ url, key: `master:${s.id}`, seq: seq.current, kind: "master", w: s.master.w, h: s.master.h, ms: s.ms, sha256: s.master.sha256 });
+ },
+ [urlOfMaster],
+ );
+
+ /** Make sure a step's master is staged in ComfyUI under its name (after a reload, or on another session). */
+ const ensureStaged = useCallback(
+ async (s: Step) => {
+ const url = s.master.url ?? masterUrls.current.get(s.master.name);
+ if (url) {
+ const st = await transport.stageFile(url);
+ if (st.name !== s.master.name) s.master.name = st.name;
+ return;
+ }
+ if (s.master.idb) {
+ const bytes = await idbGet(s.master.idb);
+ if (bytes) await transport.stageBytes(bytes, "master");
+ }
+ },
+ [transport],
+ );
+
+ const onEvent = (e: LiveEvent) => {
+ if (e.type === "progress") setBusy((b) => (b ? { ...b, progress: e.value / e.max } : b));
+ if (e.type === "reconnecting") setStatus((s) => ({ ...s, online: false }));
+ };
+
+ /** A throwaway render that loads the model (and, with a base, the edit path) before the first keystroke. */
+ const warm = (base?: string) => {
+ setBusy({ what: "warming", since: performance.now() });
+ const req: RenderReq = { seq: ++seq.current, slot: "warm", text: "", seed: 0, size: 384 as LiveSize, keepRes: 1024, aspect: "1:1", method: "hybrid", ...(base && { base }) };
+ void transport.render(req, onEvent).then(() => setBusy((b) => (b?.what === "warming" ? null : b)));
+ };
+ /** The newest handlers, for effects and timers. */
+ const latest = useRef({ warm, render: (() => {}) as (slot: "live" | "settle", t: string, o?: { urgent?: boolean }) => void, schedule: (() => {}) as (t: string, typed?: string) => void, addFile: (async () => {}) as (f: File) => Promise<void> });
+
+ useEffect(() => {
+ let alive = true;
+ const off = transport.onStatus((s) => alive && setStatus(s));
+ void (async () => {
+ const r = await transport.open();
+ if (!alive) return;
+ if (!r.ok) return setPhase({ s: "error", message: r.error, code: r.code });
+ setFacts(r);
+ if (!r.nodes || r.missing.length) {
+ setPhase({ s: "setup", facts: r });
+ return;
+ }
+ // A stored session for this picture comes back as it was.
+ const stored = load<{ stack: unknown; seed: number; keepChoice?: "auto" | KeepRes; liveChoice?: "auto" | LiveSize; aspect?: string }>(storageKey(props.image));
+ const restored = stored ? restoreStack(stored.stack) : new StepStack();
+ seedRef.current = stored?.seed ?? r.seed;
+ setSeed(seedRef.current);
+ if (stored?.keepChoice) setKeepChoice(stored.keepChoice);
+ if (stored?.liveChoice) setLiveChoice(stored.liveChoice);
+ if (stored?.aspect && isAspect(stored.aspect)) setAspect(stored.aspect);
+ try {
+ if (!restored.empty) {
+ stack.current = restored;
+ for (const s of [restored.original, restored.head]) if (s) await ensureStaged(s);
+ } else if (props.image) {
+ setBusy({ what: "adding", since: performance.now() });
+ const st = await transport.stageFile(props.image);
+ const ext = props.image.split("?")[0].split(".").pop()?.toLowerCase();
+ stack.current = StepStack.from({ url: props.image, name: st.name, w: st.w, h: st.h, sha256: st.sha256, format: ext === "png" ? "png" : ext === "webp" ? "webp" : "jpg" });
+ setAspect(aspectOf(st.w, st.h));
+ }
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ if (alive) setBusy(null);
+ }
+ if (!alive) return;
+ bump();
+ showMaster(stack.current.head);
+ setPhase({ s: "ready" });
+ latest.current.warm(stack.current.head?.master.name);
+ })();
+ return () => {
+ alive = false;
+ off();
+ transport.close();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- once per transport
+ }, [transport]);
+
+ useEffect(() => {
+ if (phase.s === "ready") persist();
+ }, [view, phase.s, persist]);
+
+ // The tab in view: renders pause while it is hidden.
+ useEffect(() => {
+ const on = () => setHidden(document.visibilityState !== "visible");
+ document.addEventListener("visibilitychange", on);
+ return () => document.removeEventListener("visibilitychange", on);
+ }, []);
+
+ // ---------------------------------------------------------------------------
+ // Rendering
+
+ const paused = !liveOn || hidden || status.running === "other" || !status.online || phase.s !== "ready";
+ const pausedRef = useRef(paused);
+ useEffect(() => {
+ pausedRef.current = paused;
+ }, [paused]);
+
+ const sizeNow = (): LiveSize => (liveChoice === "auto" ? auto.current.size : liveChoice);
+
+ const reqFor = (slot: RenderReq["slot"], t: string, o: { urgent?: boolean; seed?: number } = {}): RenderReq => {
+ const s = stack.current;
+ const base = s.base(method)?.name;
+ return {
+ seq: ++seq.current,
+ slot,
+ urgent: o.urgent,
+ text: t,
+ ...(method === "compose" && { compose: s.composePrompt(normalize(t)) }),
+ seed: o.seed ?? seedRef.current,
+ size: sizeNow(),
+ keepRes,
+ ...(base && { base }),
+ ...(mask && { mask: mask.name }),
+ aspect,
+ method,
+ };
+ };
+
+ const remember = (key: string, c: Cached) => {
+ cache.current.delete(key);
+ cache.current.set(key, c);
+ while (cache.current.size > CACHE_SIZE) {
+ const [k, v] = cache.current.entries().next().value!;
+ cache.current.delete(k);
+ if (![...masterUrls.current.values()].includes(v.url)) URL.revokeObjectURL(v.url);
+ }
+ };
+
+ /** Show a frame once its picture is decoded, if nothing newer is already on screen. */
+ const present = useCallback((c: Cached, seqNo: number, key: string) => {
+ if (seqNo <= shownSeq.current) return;
+ const img = new Image();
+ img.src = c.url;
+ void img
+ .decode()
+ .catch(() => {})
+ .then(() => {
+ if (seqNo <= shownSeq.current) return;
+ shownSeq.current = seqNo;
+ shownKey.current = key;
+ setShown({ url: c.url, key, seq: seqNo, kind: c.kind, w: c.out.w, h: c.out.h, ms: c.out.ms, sha256: c.out.sha256 });
+ });
+ }, []);
+
+ const failed = (error: string, code?: string) => {
+ if (code === "missing-nodes") return setPhase({ s: "setup", facts: { ...(facts ?? { highvram: null, missing: [] }), nodes: 0 } });
+ if (code === "offline" || code === "stopped") return;
+ if (code === "session") return setPhase({ s: "error", message: "This live session ended. Reload the page to go on.", code });
+ toast.error(error);
+ };
+
+ /** A live or settle render of this text (skipped when it is on screen, in flight, or cached). */
+ const render = (slot: "live" | "settle", t: string, o: { urgent?: boolean } = {}) => {
+ if (pausedRef.current) return;
+ if (!normalize(t) && !stack.current.head) return;
+ if (!normalize(t)) {
+ // An empty box shows the kept picture.
+ showMaster(stack.current.head);
+ return;
+ }
+ const req = reqFor(slot, t, o);
+ const key = keyOf(req);
+ if (shownKey.current === key) return;
+ const alias = slot === "live" ? keyOf({ ...req, size: 0 }) : "";
+ const hadKey = cache.current.has(key) ? key : alias && anySize.current.get(alias);
+ const had = hadKey ? cache.current.get(hadKey) : undefined;
+ if (had && hadKey) {
+ present(had, req.seq, hadKey);
+ return;
+ }
+ // A settled picture of the same text can stand in for a live frame.
+ const settledKey = keyOf({ ...req, slot: "settle" });
+ const settled = slot === "live" ? cache.current.get(settledKey) : undefined;
+ if (settled) {
+ present(settled, req.seq, settledKey);
+ return;
+ }
+ const going = inflight.current.get(key);
+ if (going !== undefined) {
+ if (o.urgent) transport.hurry(going);
+ return;
+ }
+ inflight.current.set(key, req.seq);
+ const baseAtStart = req.base;
+ setBusy((b) => b ?? { what: "rendering", since: performance.now() });
+ const sent = performance.now();
+ void transport.render(req, onEvent).then((res) => {
+ trace({ slot, seq: req.seq, sent, got: performance.now(), ms: res.ok ? res.out.ms : undefined, outcome: res.ok ? "frame" : "dropped" in res ? `dropped:${res.dropped}` : "error" });
+ inflight.current.delete(key);
+ if (!inflight.current.size) setBusy((b) => (b?.what === "rendering" ? null : b));
+ if (!res.ok) {
+ if ("error" in res) failed(res.error, res.code);
+ return;
+ }
+ const out = res.out;
+ const url = URL.createObjectURL(new Blob([out.data as BlobPart], { type: out.type }));
+ const c: Cached = { url, out, kind: slot === "settle" ? "settled" : "live", seed: req.seed, text: t };
+ remember(key, c);
+ if (alias) anySize.current.set(alias, key);
+ if (slot === "live") {
+ stack.current.sawLive(out.sha256);
+ const next = auto.current.record(out.ms);
+ if (next !== liveSize) setLiveSize(next);
+ } else {
+ setTries((ts) => (ts.some((x) => x.key === key) ? ts : [...ts, { key, url, seed: req.seed, text: t }].slice(-MAX_TRIES)));
+ }
+ setLastMs(out.ms);
+ // A frame for a base that is no longer the head doesn't show.
+ if (baseAtStart !== stack.current.base(method)?.name) return;
+ present(c, req.seq, key);
+ });
+ };
+
+
+ // Another job ran on the GPU since our last render: the model may be out of memory, warm it first.
+ const wasOther = useRef(false);
+ useEffect(() => {
+ if (status.running === "other") wasOther.current = true;
+ else if (wasOther.current && status.online && phase.s === "ready") {
+ wasOther.current = false;
+ latest.current.warm(stack.current.head?.master.name);
+ latest.current.render("live", textRef.current, { urgent: true });
+ }
+ }, [status.running, status.online, phase.s]);
+
+ // Coming back from a pause (live switched on, the tab in view again, the connection back): the newest text renders.
+ useEffect(() => {
+ if (!paused && phase.s === "ready" && normalize(textRef.current)) latest.current.render("live", textRef.current, { urgent: true });
+ }, [paused, phase.s]);
+
+ const schedule = (t: string, typed?: string) => {
+ clearTimeout(idle.current);
+ clearTimeout(settle.current);
+ // A word boundary, a line break or a paste: the words so far render at once.
+ if (typed === undefined || (typed.length === 1 && endsWord(typed)) || typed.length > 1) {
+ const words = typed && typed.length > 1 ? t : completedWords(t);
+ if (normalize(words)) render("live", words);
+ }
+ // A pause: the exact text, urgently.
+ idle.current = setTimeout(() => latest.current.render("live", t, { urgent: true }), IDLE_MS);
+ // A longer pause: the full-quality picture of the text on screen (what Keep stores).
+ settle.current = setTimeout(() => normalize(t) && latest.current.render("settle", t), SETTLE_MS);
+ };
+
+ const onType = (next: string, typed?: string) => {
+ const t = next.slice(0, MAX_LIVE_TEXT);
+ setText(t);
+ textRef.current = t;
+ if (!normalize(t)) {
+ clearTimeout(idle.current);
+ clearTimeout(settle.current);
+ transport.cancel((_, slot) => slot === "live" || slot === "settle");
+ showMaster(stack.current.head);
+ return;
+ }
+ schedule(t, typed);
+ };
+
+ // A starting text from the link renders once ready.
+ useEffect(() => {
+ if (phase.s === "ready" && normalize(textRef.current)) latest.current.schedule(textRef.current);
+ }, [phase.s]);
+
+ // ---------------------------------------------------------------------------
+ // Keeping, undo and redo
+
+ const [keeping, setKeeping] = useState(false);
+
+ const keep = async (choice?: { text: string; seed: number }, download = false) => {
+ if (keeping || phase.s !== "ready") return;
+ const t = choice?.text ?? textRef.current;
+ if (!normalize(t)) return;
+ const keepSeed = choice?.seed ?? seedRef.current;
+ setKeeping(true);
+ clearTimeout(idle.current);
+ clearTimeout(settle.current);
+ setBusy({ what: "keeping", since: performance.now() });
+ try {
+ const req = reqFor("keep", t, { seed: keepSeed });
+ const settledKey = keyOf({ ...req, slot: "settle" });
+ const held = cache.current.get(settledKey);
+ // Stale live renders of the old base stop now.
+ transport.cancel((_, slot) => slot === "live" || slot === "settle");
+ let out: RenderOut;
+ if (held && transport.kind === "computer") {
+ // What you saw is what you keep: the settled picture, as it is.
+ out = { ...held.out, reused: true };
+ } else {
+ const res = await transport.render(req, onEvent);
+ if (!res.ok) {
+ if ("error" in res) failed(res.error, res.code);
+ return;
+ }
+ out = res.out;
+ }
+ if (out.type !== "image/png") throw new Error("A kept picture must be a PNG master");
+ const size = pngSize(out.data) ?? { w: out.w, h: out.h };
+ let url = out.masterUrl;
+ let name = out.masterName;
+ let idb: string | undefined;
+ let local = false;
+ if (!name) {
+ const st = await transport.stageBytes(out.data, "master");
+ name = st.name;
+ }
+ const blobUrl = held?.url ?? URL.createObjectURL(new Blob([out.data as BlobPart], { type: "image/png" }));
+ setMasterUrl(name, blobUrl);
+ if (!url) {
+ // The computer path: the server keeps the master (off the critical path); this browser keeps it until then.
+ idb = `master:${out.sha256}`;
+ await idbPut(idb, out.data);
+ const posted = await fetch("/api/live/masters", { method: "POST", headers: { "content-type": "image/png" }, body: out.data as BodyInit }).catch(() => null);
+ if (posted?.ok) url = ((await posted.json()) as { url?: string }).url;
+ else local = true;
+ }
+ const step = stack.current.keep({
+ text: t,
+ norm: normalize(t),
+ seed: keepSeed,
+ method,
+ keepRes: req.keepRes,
+ ...(mask && { mask: { name: mask.name } }),
+ master: { name, w: size.w, h: size.h, sha256: out.sha256, format: "png", ...(url && { url }), ...(idb && { idb }) },
+ ms: out.ms,
+ ...(local && { local: true }),
+ });
+ bump();
+ setText("");
+ textRef.current = "";
+ setTries([]);
+ setMask(null);
+ showMaster(step);
+ setKeptFlash(true);
+ setTimeout(() => setKeptFlash(false), 1000);
+ if (download) downloadUrl(blobUrl, `live-edit-${step.id}.png`);
+ if (local) toast.message("Kept in this browser only", { description: "Your files are full, so this step stays here. Download it to keep it." });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setKeeping(false);
+ setBusy(null);
+ }
+ };
+
+ const move = async (to: "undo" | "redo" | string) => {
+ const s = stack.current;
+ const step = to === "undo" ? s.undo() : to === "redo" ? s.redo() : s.jump(to);
+ if (!step) return;
+ transport.cancel((_, slot) => slot === "live" || slot === "settle");
+ setTries([]);
+ bump();
+ showMaster(step);
+ try {
+ await ensureStaged(step);
+ } catch {}
+ if (normalize(textRef.current)) render("live", textRef.current, { urgent: true });
+ };
+
+ /** Live off stops what is rendering for the text; on again, the newest text renders. */
+ const toggleLive = () => {
+ if (liveOn) {
+ clearTimeout(idle.current);
+ clearTimeout(settle.current);
+ transport.cancel((_, slot) => slot === "live" || slot === "settle");
+ }
+ setLiveOn(!liveOn);
+ };
+
+ const shuffle = () => {
+ seedRef.current = Math.floor(Math.random() * 2 ** 31);
+ setSeed(seedRef.current);
+ if (normalize(textRef.current)) render("live", textRef.current, { urgent: true });
+ };
+
+ // ---------------------------------------------------------------------------
+ // Pictures in: a file, a paste, a drop
+
+ const addFile = async (file: File) => {
+ if (!/^image\/(png|jpeg|webp)$/.test(file.type)) {
+ toast.error("Add a PNG, JPEG or WebP picture");
+ return;
+ }
+ setBusy({ what: "adding", since: performance.now() });
+ try {
+ const asset = await postFile(file);
+ const st = await transport.stageFile(asset.url);
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ const ext = pictureExt(bytes);
+ stack.current = StepStack.from({ url: asset.url, name: st.name, w: st.w, h: st.h, sha256: st.sha256, format: ext ?? "jpg" });
+ setImage(asset.url);
+ setAspect(aspectOf(st.w, st.h));
+ setTries([]);
+ setMask(null);
+ bump();
+ showMaster(stack.current.head);
+ warm(st.name);
+ if (normalize(textRef.current)) schedule(textRef.current);
+ if (variant === "app") {
+ const u = new URL(window.location.href);
+ u.searchParams.set("image", asset.url);
+ window.history.replaceState(null, "", u);
+ }
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(null);
+ }
+ };
+ useEffect(() => {
+ latest.current = { warm, render, schedule, addFile };
+ });
+
+ useEffect(() => {
+ const onPaste = (e: ClipboardEvent) => {
+ const f = [...(e.clipboardData?.files ?? [])].find((x) => x.type.startsWith("image/"));
+ if (f) {
+ e.preventDefault();
+ void latest.current.addFile(f);
+ }
+ };
+ window.addEventListener("paste", onPaste);
+ return () => window.removeEventListener("paste", onPaste);
+ }, []);
+
+ const onBrushDone = async (r: SketchResult) => {
+ if (!r.mask) return;
+ try {
+ const st = await transport.stageBytes(await dataUrlBytes(r.mask), "mask");
+ setMask({ name: st.name, preview: r.overlay });
+ if (normalize(textRef.current)) render("live", textRef.current, { urgent: true });
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // Saving and downloading
+
+ const current = shown?.url ?? urlOf(head);
+ const download = () => current && downloadUrl(current, `live-edit-${head?.id ?? "frame"}.${shown?.kind === "live" ? "webp" : "png"}`);
+ const saveToLibrary = async () => {
+ const s = stack.current;
+ const h = s.head;
+ if (!h?.master.url) return toast.error("Keep a change first");
+ const res = await fetch("/api/live/save", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ master: h.master.url, ...(s.original?.master.url && s.original.parent === null && s.original.text === "" && { original: s.original.master.url }), steps: s.path().filter((x) => x.text).map((x) => ({ text: x.text, seed: x.seed })), ...(props.from && { from: props.from }) }),
+ });
+ if (res.ok) toast.success("Saved to your Library");
+ else toast.error(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't save");
+ };
+
+ // ---------------------------------------------------------------------------
+ // Keys
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement | null;
+ const inBox = el === box.current;
+ const inOther = !inBox && !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
+ if (inOther || brushOpen || compareOpen) return;
+ const mod = e.metaKey || e.ctrlKey;
+ if (mod && (e.key === "z" || e.key === "Z") && !e.shiftKey && (!inBox || !textRef.current)) {
+ e.preventDefault();
+ void move("undo");
+ } else if (mod && (((e.key === "z" || e.key === "Z") && e.shiftKey) || e.key === "y") && (!inBox || !textRef.current)) {
+ e.preventDefault();
+ void move("redo");
+ }
+ if (inBox || mod || e.altKey) return;
+ const k = e.key;
+ if (k === "/") {
+ e.preventDefault();
+ box.current?.focus();
+ } else if (k === "r" || k === "R") shuffle();
+ else if (k === "l" || k === "L") toggleLive();
+ else if (k === "c" || k === "C") setHold(e.shiftKey ? "orig" : "prev");
+ else if ((k === "b" || k === "B") && hasPicture) setBrushOpen(true);
+ else if (k === "d" || k === "D") download();
+ else if ((k === "s" || k === "S") && props.canSave) void saveToLibrary();
+ else if (k === "?") setKeysOpen(true);
+ else if (k === "ArrowLeft" || k === "ArrowRight") {
+ const path = stack.current.path();
+ const all = stack.current.all;
+ const at = all.findIndex((x) => x.id === stack.current.head?.id);
+ const next = all[at + (k === "ArrowLeft" ? -1 : 1)];
+ if (next) void move(next.id);
+ else if (!path.length) return;
+ }
+ };
+ const onUp = (e: KeyboardEvent) => {
+ if (e.key === "c" || e.key === "C" || e.key === "Shift") setHold(null);
+ };
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("keyup", onUp);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("keyup", onUp);
+ };
+ });
+
+ // ---------------------------------------------------------------------------
+ // The page
+
+ const path = view.path;
+ const previous = view.previous;
+ const original = view.original;
+ const heldUrl = hold === "orig" ? urlOf(original) : hold === "prev" ? urlOf(previous ?? original) : null;
+ const stageUrl = heldUrl ?? current;
+ const canKeep = !!normalize(text) && phase.s === "ready" && !keeping;
+ const link = transport.kind === "link";
+
+ const pill = (() => {
+ if (phase.s === "connecting") return { tone: "wait", text: "Connecting…" };
+ if (phase.s === "setup") return { tone: "warn", text: "Set up needed" };
+ if (phase.s === "error") return { tone: "warn", text: "Not available" };
+ if (!status.online) return { tone: "wait", text: "Reconnecting…" };
+ if (status.running === "other") return { tone: "warn", text: "Paused: GPU busy" };
+ if (busy?.what === "keeping") return { tone: "busy", text: "Keeping…" };
+ if (busy?.what === "warming") return { tone: "busy", text: "Warming up (about 20 s)" };
+ if (busy?.what === "adding") return { tone: "busy", text: "Adding the picture…" };
+ if (!liveOn) return { tone: "off", text: "Live off" };
+ if (keptFlash) return { tone: "ok", text: "Kept ✓" };
+ const size = shown?.kind === "live" ? sizeShown : shown ? Math.max(shown.w, shown.h) : sizeShown;
+ return { tone: busy ? "busy" : "ok", text: `${link ? "Live (slower over a link)" : "Live"} · ${size}${lastMs !== null && shown?.kind !== "master" ? ` · ${(lastMs / 1000).toFixed(2)} s` : ""}` };
+ })();
+
+ const setupPanel = phase.s === "setup" ? <LiveSetup facts={phase.facts} computer={transport.kind === "computer"} /> : null;
+ const errorPanel = phase.s === "error" ? <LiveProblem message={phase.message} code={phase.code} /> : null;
+
+ return (
+ <div
+ className={cn("flex min-h-0 w-full flex-col bg-background", embedded ? "h-full rounded-2xl border" : "h-[100dvh]")}
+ data-live-editor
+ onDragOver={(e) => {
+ if ([...e.dataTransfer.items].some((i) => i.kind === "file")) {
+ e.preventDefault();
+ setDragging(true);
+ }
+ }}
+ onDragLeave={() => setDragging(false)}
+ onDrop={(e) => {
+ const f = [...e.dataTransfer.files].find((x) => x.type.startsWith("image/"));
+ setDragging(false);
+ if (f) {
+ e.preventDefault();
+ void addFile(f);
+ }
+ }}
+ >
+ {/* Top bar */}
+ <header className={cn("flex shrink-0 items-center gap-1.5 px-3 sm:px-4", embedded ? "h-12" : "h-14")}>
+ {!embedded && (
+ <Link href={props.from === "edit" ? "/edit" : props.from === "library" ? "/library" : "/"} className="-ml-1 grid size-8 place-items-center rounded-lg text-muted-foreground hover:bg-accent md:hidden" aria-label="Back">
+ <ChevronLeft className="size-4" />
+ </Link>
+ )}
+ <h1 className={cn("flex shrink-0 items-center gap-2 font-heading leading-none whitespace-nowrap", embedded ? "text-[18px]" : "text-[22px]")}>
+ <Zap className="size-4 text-primary" />
+ <span className="max-sm:sr-only">Live edit</span>
+ </h1>
+ <StatusPill tone={pill.tone} text={pill.text} progress={busy?.progress} />
+ <div className="ml-auto flex items-center gap-0.5">
+ <ToolButton label="Undo" keys="Ctrl+Z" onClick={() => void move("undo")} disabled={!view.canUndo}>
+ <Undo2 />
+ </ToolButton>
+ <ToolButton label="Redo" keys="Ctrl+Shift+Z" onClick={() => void move("redo")} disabled={!view.canRedo}>
+ <Redo2 />
+ </ToolButton>
+ <ToolButton label="Compare" keys="hold C" onClick={() => setCompareOpen(true)} disabled={!previous && !original} className="max-sm:hidden">
+ <ArrowLeftRight />
+ </ToolButton>
+ <ToolButton label="Shuffle" keys="R" onClick={shuffle} disabled={!normalize(text)}>
+ <Shuffle />
+ </ToolButton>
+ <ToolButton label={mask ? "Change the painted region" : "Paint a region"} keys="B" onClick={() => setBrushOpen(true)} disabled={!hasPicture} active={!!mask}>
+ <Brush />
+ </ToolButton>
+ <ToolButton label={liveOn ? "Live on" : "Live off"} keys="L" onClick={toggleLive} active={!liveOn} className="max-sm:hidden">
+ {liveOn ? <Zap /> : <ZapOff />}
+ </ToolButton>
+ <Settings
+ liveChoice={liveChoice}
+ setLiveChoice={setLiveChoice}
+ keepChoice={keepChoice}
+ setKeepChoice={setKeepChoice}
+ aspect={aspect}
+ setAspect={setAspect}
+ hasPicture={hasPicture}
+ seed={seed}
+ lab={props.lab}
+ method={method}
+ setMethod={setMethod}
+ onKeys={() => setKeysOpen(true)}
+ />
+ <ToolButton label="Download" keys="D" onClick={download} disabled={!current}>
+ <Download />
+ </ToolButton>
+ {embedded ? (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button size="sm" variant="ghost" asChild>
+ <Link href={`/live-edit${image ? `?image=${encodeURIComponent(image)}&from=edit` : "?from=edit"}`} aria-label="Full screen">
+ <Expand className="size-4" />
+ </Link>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Full screen</TooltipContent>
+ </Tooltip>
+ <Button size="sm" onClick={() => head?.master.url && props.onUse?.(head.master.url)} disabled={!head?.master.url || path.length < 2} className="ml-1">
+ Use in Edit
+ </Button>
+ {props.onClose && (
+ <ToolButton label="Close live" onClick={props.onClose}>
+ <X />
+ </ToolButton>
+ )}
+ </>
+ ) : props.canSave ? (
+ <Button size="sm" variant="secondary" onClick={() => void saveToLibrary()} disabled={!head?.master.url || path.length < 2} className="ml-1 max-sm:hidden">
+ <Save className="size-4" />
+ Save
+ </Button>
+ ) : null}
+ </div>
+ </header>
+
+ {/* Stage */}
+ <div className={cn("relative mx-3 min-h-0 flex-1 overflow-hidden rounded-2xl bg-media sm:mx-4", dragging && "ring-2 ring-primary")} data-live-stage onPointerDown={(e) => e.pointerType !== "mouse" && setHold("prev")} onPointerUp={() => setHold(null)} onPointerLeave={() => setHold(null)}>
+ {setupPanel ?? errorPanel ?? (stageUrl ? <StageImage src={stageUrl} alt={hold ? "The picture before this change" : "Your picture"} /> : <EmptyStage busy={busy?.what === "adding"} onBrowse={() => fileInput.current?.click()} />)}
+ {mask && !hold && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={mask.preview} alt="" className="pointer-events-none absolute inset-0 size-full object-contain opacity-35 mix-blend-screen" />
+ )}
+ {stageUrl && phase.s === "ready" && (
+ <span className="pointer-events-none absolute bottom-3 left-3 rounded-full bg-black/55 px-2.5 py-1 text-[11px] font-medium text-white tabular-nums backdrop-blur" data-live-badge>
+ {hold ? (hold === "orig" ? "Original" : "Before") : shown?.kind === "master" ? `${shown.w}×${shown.h} · kept ✓` : shown?.kind === "settled" ? `${shown.w}×${shown.h} · ready to keep` : `${sizeShown} · live`}
+ </span>
+ )}
+ {facts?.highvram === false && highvramHint && phase.s === "ready" && (
+ <div className="absolute top-3 right-3 left-3 flex items-start gap-2 rounded-xl bg-black/60 p-3 text-[12.5px] text-white backdrop-blur sm:left-auto sm:max-w-sm">
+ <span className="min-w-0 flex-1">ComfyUI runs without --highvram, so live frames take about twice as long. Start it with --highvram for the fastest edits.</span>
+ <button type="button" onClick={() => setHighvramHint(false)} className="shrink-0 rounded p-0.5 hover:bg-white/15" aria-label="Dismiss">
+ <X className="size-3.5" />
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Steps, the box, tries */}
+ <div className={cn("shrink-0 px-3 pt-2 sm:px-4", embedded ? "pb-3" : "pb-[max(12px,env(safe-area-inset-bottom))]")}>
+ <StepTrail path={path} all={view.all} headId={head?.id} onJump={(id) => void move(id)} urlOf={urlOf} />
+ <div className="mt-2 flex items-end gap-2">
+ <div className="relative min-w-0 flex-1 rounded-2xl border bg-card shadow-soft focus-within:border-primary/60 focus-within:ring-3 focus-within:ring-ring/25">
+ <textarea
+ ref={box}
+ value={text}
+ rows={1}
+ maxLength={MAX_LIVE_TEXT}
+ placeholder={hasPicture ? (head?.parent ? "Type the next change…" : "Type a change…") : "Describe a picture, or drop one here…"}
+ aria-label="Type a change"
+ className="block max-h-28 min-h-11 w-full resize-none bg-transparent px-3.5 py-3 text-[15px] leading-5 outline-none placeholder:text-muted-foreground [field-sizing:content]"
+ onChange={(e) => {
+ const native = e.nativeEvent as InputEvent;
+ onType(e.target.value, native.data ?? (native.inputType === "insertLineBreak" ? "\n" : native.inputType === "insertFromPaste" ? e.target.value : undefined));
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void keep(undefined, e.metaKey || e.ctrlKey);
+ } else if (e.key === "Escape") box.current?.blur();
+ }}
+ disabled={phase.s !== "ready"}
+ />
+ </div>
+ <Button size="lg" className={cn("h-11 shrink-0 rounded-2xl px-4", keptFlash && "bg-success hover:bg-success")} onClick={() => void keep()} disabled={!canKeep} data-live-keep>
+ {keeping ? <Loader2 className="size-4 animate-spin" /> : keptFlash ? <Check className="size-4" /> : <CornerDownLeft className="size-4" />}
+ {keptFlash ? "Kept" : "Keep"}
+ </Button>
+ </div>
+ {tries.length > 0 && (
+ <div className="mt-2 flex items-center gap-1.5 overflow-x-auto pb-0.5" data-live-tries>
+ <span className="shrink-0 text-[11.5px] font-medium text-muted-foreground">Tries</span>
+ {tries.map((t) => (
+ <Tooltip key={t.key}>
+ <TooltipTrigger asChild>
+ <button type="button" onClick={() => void keep({ text: t.text, seed: t.seed })} className={cn("relative size-11 shrink-0 overflow-hidden rounded-lg ring-1 ring-border hover:ring-2 hover:ring-primary", shown?.key === t.key && "ring-2 ring-primary")} aria-label={`Keep this try (seed ${t.seed})`}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={t.url} alt="" className="size-full object-cover" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>Keep this one</TooltipContent>
+ </Tooltip>
+ ))}
+ <span className="shrink-0 text-[11.5px] text-muted-foreground max-sm:hidden">
+ <Kbd>R</Kbd> for another
+ </span>
+ </div>
+ )}
+ {!embedded && !hasPicture && phase.s === "ready" && (
+ <p className="mt-2 text-[12px] text-muted-foreground">
+ No picture? Typing makes one. <button type="button" onClick={() => fileInput.current?.click()} className="font-medium text-brand-text hover:underline">Add a picture</button> to change it instead.
+ </p>
+ )}
+ </div>
+
+ <input ref={fileInput} type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={(e) => e.target.files?.[0] && void addFile(e.target.files[0])} />
+
+ {current && (head || shown) && (
+ <SketchEditor open={brushOpen} onOpenChange={setBrushOpen} image={urlOf(head) ?? current} mode="mask" onDone={(r) => void onBrushDone(r)} />
+ )}
+ <CompareDialog open={compareOpen} onOpenChange={setCompareOpen} after={current} before={compareWith === "prev" ? urlOf(previous ?? original) : urlOf(original)} which={compareWith} setWhich={setCompareWith} />
+ <KeysDialog open={keysOpen} onOpenChange={setKeysOpen} canSave={props.canSave} />
+ </div>
+ );
+}
+
+export function downloadUrl(url: string, name: string) {
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = name;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+}
+
+// ---------------------------------------------------------------------------
+// Parts
+
+function StatusPill({ tone, text, progress }: { tone: string; text: string; progress?: number }) {
+ return (
+ <span
+ role="status"
+ data-live-pill
+ className={cn(
+ "relative ml-1 inline-flex h-7 items-center gap-1.5 overflow-hidden rounded-full border px-2.5 text-[12px] font-medium whitespace-nowrap tabular-nums max-sm:max-w-[46vw]",
+ tone === "warn" && "border-warning/40 text-warning",
+ tone === "off" && "text-muted-foreground",
+ )}
+ >
+ <span className={cn("size-1.5 shrink-0 rounded-full", tone === "ok" ? "bg-success" : tone === "busy" ? "animate-pulse bg-primary" : tone === "warn" ? "bg-warning" : tone === "wait" ? "animate-pulse bg-muted-foreground" : "bg-subtle-foreground")} />
+ <span className="truncate">{text}</span>
+ {tone === "busy" && progress !== undefined && <span className="absolute inset-x-0 bottom-0 h-0.5 bg-primary/70 transition-[width]" style={{ width: `${Math.round(progress * 100)}%` }} />}
+ </span>
+ );
+}
+
+function ToolButton({ label, keys, onClick, disabled, active, className, children }: { label: string; keys?: string; onClick: () => void; disabled?: boolean; active?: boolean; className?: string; children: React.ReactNode }) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button size="icon" variant="ghost" onClick={onClick} disabled={disabled} aria-label={label} aria-pressed={active} className={cn("size-8 [&_svg]:size-4", active && "bg-brand-faint text-brand-text", className)}>
+ {children}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {label}
+ {keys && <Kbd className="ml-1.5">{keys}</Kbd>}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+/** Two stacked pictures: a new one is decoded first, then faded in over the last (no flash between frames). */
+function StageImage({ src, alt }: { src: string; alt: string }) {
+ const [layers, setLayers] = useState<{ a: string; b: string | null }>({ a: src, b: null });
+ useEffect(() => {
+ if (src === layers.a) return;
+ let alive = true;
+ const img = new Image();
+ img.src = src;
+ void img
+ .decode()
+ .catch(() => {})
+ .then(() => alive && setLayers((l) => ({ a: src, b: l.a })));
+ return () => {
+ alive = false;
+ };
+ }, [src, layers.a]);
+ return (
+ <div className="absolute inset-0">
+ {layers.b && (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={layers.b} alt="" aria-hidden className="absolute inset-0 box-border size-full object-contain p-2 sm:p-4" draggable={false} />
+ )}
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img key={layers.a} src={layers.a} alt={alt} className="absolute inset-0 box-border size-full animate-[live-fade_120ms_ease-out] object-contain p-2 sm:p-4" draggable={false} data-live-frame />
+ </div>
+ );
+}
+
+function EmptyStage({ busy, onBrowse }: { busy: boolean; onBrowse: () => void }) {
+ return (
+ <div className="absolute inset-0 grid place-items-center p-6 text-center text-white">
+ <div className="max-w-sm">
+ <span className="mx-auto grid size-12 place-items-center rounded-2xl bg-white/10">{busy ? <Loader2 className="size-5 animate-spin" /> : <ImagePlus className="size-5" />}</span>
+ <p className="mt-4 font-heading text-[24px] leading-tight">Drop a picture, paste one, or start typing to make one</p>
+ <p className="mt-2 text-[13px] text-white/65">Each change shows up as you type. Press Enter to keep it, then type the next.</p>
+ <Button variant="secondary" className="mt-5" onClick={onBrowse}>
+ <Upload className="size-4" />
+ Add a picture
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function StepTrail({ path, all, headId, onJump, urlOf }: { path: Step[]; all: readonly Step[]; headId?: string; onJump: (id: string) => void; urlOf: (s: Step) => string | null }) {
+ if (!path.length) return null;
+ const branches = all.length - path.length;
+ return (
+ <div className="flex min-w-0 items-center gap-1 overflow-x-auto pb-0.5 text-[12px]" data-live-steps>
+ {path.map((s, i) => (
+ <div key={s.id} className="flex shrink-0 items-center gap-1">
+ {i > 0 && <span className="text-subtle-foreground">›</span>}
+ <button
+ type="button"
+ onClick={() => onJump(s.id)}
+ className={cn("inline-flex h-7 max-w-52 items-center gap-1.5 rounded-full border pr-2.5 pl-0.5 transition-colors hover:bg-accent", s.id === headId && "border-primary/50 bg-brand-faint text-brand-text")}
+ title={s.text || "Original"}
+ data-live-step={s.id}
+ >
+ {urlOf(s) ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={urlOf(s)!} alt="" className="size-6 rounded-full object-cover" />
+ ) : (
+ <span className="size-6 rounded-full bg-muted" />
+ )}
+ <span className="truncate">{i === 0 && !s.text ? "Original" : `${i} · ${s.text}`}</span>
+ {s.local && <span className="text-[10px] text-warning">this browser</span>}
+ </button>
+ </div>
+ ))}
+ {branches > 0 && <span className="ml-1 shrink-0 text-[11px] text-muted-foreground">+{branches} on another branch</span>}
+ </div>
+ );
+}
+
+function Settings(p: {
+ liveChoice: "auto" | LiveSize;
+ setLiveChoice: (v: "auto" | LiveSize) => void;
+ keepChoice: "auto" | KeepRes;
+ setKeepChoice: (v: "auto" | KeepRes) => void;
+ aspect: Aspect;
+ setAspect: (a: Aspect) => void;
+ hasPicture: boolean;
+ seed: number;
+ lab?: boolean;
+ method: Method;
+ setMethod: (m: Method) => void;
+ onKeys: () => void;
+}) {
+ const row = "flex items-center justify-between gap-3 py-1.5";
+ const seg = <T extends string | number>(value: T, options: { v: T; label: string }[], set: (v: T) => void) => (
+ <div className="flex rounded-lg bg-muted p-0.5">
+ {options.map((o) => (
+ <button key={String(o.v)} type="button" onClick={() => set(o.v)} className={cn("h-6 rounded-md px-2 text-[12px]", value === o.v ? "bg-background font-medium shadow-soft" : "text-muted-foreground")}>
+ {o.label}
+ </button>
+ ))}
+ </div>
+ );
+ return (
+ <Popover>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>
+ <Button size="icon" variant="ghost" className="size-8 [&_svg]:size-4" aria-label="Live settings">
+ <MoreHorizontal />
+ </Button>
+ </PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent>Settings</TooltipContent>
+ </Tooltip>
+ <PopoverContent align="end" className="w-80 text-[13px]">
+ <div className={row}>
+ <span>Live size</span>
+ {seg<"auto" | LiveSize>(p.liveChoice, [{ v: "auto", label: "Auto" }, ...LIVE_LADDER.map((n) => ({ v: n as LiveSize, label: String(n) }))], p.setLiveChoice)}
+ </div>
+ <div className={row}>
+ <span>Keep detail</span>
+ {seg<"auto" | KeepRes>(p.keepChoice, [{ v: "auto", label: "Auto" }, ...KEEP_LADDER.map((n) => ({ v: n as KeepRes, label: String(n) }))], p.setKeepChoice)}
+ </div>
+ {!p.hasPicture && (
+ <div className={row}>
+ <span>Shape</span>
+ <select value={p.aspect} onChange={(e) => p.setAspect(e.target.value as Aspect)} className="h-7 rounded-md border bg-background px-2 text-[12px]">
+ {["1:1", "3:4", "4:3", "2:3", "3:2", "9:16", "16:9"].map((a) => (
+ <option key={a}>{a}</option>
+ ))}
+ </select>
+ </div>
+ )}
+ <div className={row}>
+ <span>Seed</span>
+ <span className="font-mono text-[12px] text-muted-foreground">{p.seed}</span>
+ </div>
+ {p.lab && (
+ <div className={row}>
+ <span>Method</span>
+ {seg<Method>(p.method, [{ v: "hybrid", label: "Hybrid" }, { v: "chain", label: "Chain" }, { v: "compose", label: "Compose" }], p.setMethod)}
+ </div>
+ )}
+ <p className="mt-2 border-t pt-2 text-[12px] text-muted-foreground">
+ Kept steps are lossless masters at full size: unchanged parts of the picture stay exactly as they were, however many changes you stack.
+ </p>
+ <button type="button" onClick={p.onKeys} className="mt-2 inline-flex items-center gap-1.5 text-[12px] font-medium text-brand-text hover:underline">
+ <Keyboard className="size-3.5" />
+ Keyboard shortcuts
+ </button>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function CompareDialog({ open, onOpenChange, before, after, which, setWhich }: { open: boolean; onOpenChange: (o: boolean) => void; before: string | null; after: string | null; which: "prev" | "orig"; setWhich: (w: "prev" | "orig") => void }) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-[min(96vw,1100px)] max-w-none sm:max-w-none">
+ <DialogHeader>
+ <DialogTitle>Compare</DialogTitle>
+ <DialogDescription>Drag across the picture, or use the arrow keys.</DialogDescription>
+ </DialogHeader>
+ <div className="flex gap-1 self-start rounded-lg bg-muted p-0.5 text-[12.5px]">
+ {(["prev", "orig"] as const).map((w) => (
+ <button key={w} type="button" onClick={() => setWhich(w)} className={cn("h-7 rounded-md px-2.5", which === w ? "bg-background font-medium shadow-soft" : "text-muted-foreground")}>
+ {w === "prev" ? "With the step before" : "With the original"}
+ </button>
+ ))}
+ </div>
+ <div className="grid max-h-[72vh] place-items-center overflow-hidden rounded-xl bg-media">{before && after ? <CompareSlider before={before} after={after} /> : <p className="p-10 text-white/70">Keep a change to compare.</p>}</div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const KEYS: [string, string][] = [
+ ["/", "Type a change (Esc leaves the box)"],
+ ["Enter", "Keep the change (Shift+Enter: a new line)"],
+ ["Ctrl+Enter", "Keep it and download it"],
+ ["Ctrl+Z", "Undo a step (in the box: when it is empty)"],
+ ["Ctrl+Shift+Z", "Redo"],
+ ["R", "Shuffle: another take of this change"],
+ ["L", "Live on or off"],
+ ["C (hold)", "Compare with the step before"],
+ ["Shift+C (hold)", "Compare with the original"],
+ ["B", "Paint a region to change"],
+ ["D", "Download"],
+ ["S", "Save to your Library"],
+ ["← →", "Step through the kept steps"],
+ ["?", "These shortcuts"],
+];
+
+function KeysDialog({ open, onOpenChange, canSave }: { open: boolean; onOpenChange: (o: boolean) => void; canSave: boolean }) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>Keyboard shortcuts</DialogTitle>
+ <DialogDescription>Outside the text box, unless it says otherwise.</DialogDescription>
+ </DialogHeader>
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-[13px]">
+ {KEYS.filter(([k]) => canSave || k !== "S").map(([k, v]) => (
+ <div key={k} className="contents">
+ <dt>
+ <Kbd>{k}</Kbd>
+ </dt>
+ <dd className="text-muted-foreground">{v}</dd>
+ </div>
+ ))}
+ </dl>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+/** What this ComfyUI still needs for live edit: Fuobe's live nodes, model files, and a restart. */
+export function LiveSetup({ facts, computer }: { facts: LiveFacts; computer: boolean }) {
+ const [files, setFiles] = useState<{ key: string; url: string; sizeBytes: number; folder: string; file: string }[]>([]);
+ useEffect(() => {
+ void fetch("/api/gpu/requirements")
+ .then((r) => (r.ok ? r.json() : null))
+ .then((idx: { files?: Record<string, { folder: string; file: string; pinnedUrl: string; sizeBytes: number }> } | null) => {
+ if (!idx?.files) return;
+ setFiles(facts.missing.flatMap((k) => (idx.files![k] ? [{ key: k, url: idx.files![k].pinnedUrl, sizeBytes: idx.files![k].sizeBytes, folder: idx.files![k].folder, file: idx.files![k].file }] : [])));
+ })
+ .catch(() => {});
+ }, [facts.missing]);
+ return (
+ <div className="absolute inset-0 overflow-y-auto bg-background/95 p-5 sm:p-8" data-live-setup>
+ <div className="mx-auto max-w-xl">
+ <p className="font-heading text-[26px] leading-tight">Set up live edit on your GPU</p>
+ <p className="mt-1.5 text-[13.5px] text-muted-foreground">Live edit runs Qwen-Image 2.1 with a 2-step LoRA on your own ComfyUI. Best on a GPU with 20 GB or more.</p>
+ <ol className="mt-5 space-y-3 text-[13.5px]">
+ {!facts.nodes && (
+ <li className="rounded-xl border p-3.5">
+ <p className="font-medium">Add Fuobe&apos;s live nodes</p>
+ <p className="mt-1 text-muted-foreground">One file for ComfyUI&apos;s custom_nodes folder (fuobe_live.py). Then restart ComfyUI.</p>
+ <Button asChild size="sm" className="mt-2.5">
+ <a href="/api/live/nodes" download>
+ <Download className="size-4" />
+ Download Fuobe&apos;s live nodes
+ </a>
+ </Button>
+ </li>
+ )}
+ {facts.missing.length > 0 && (
+ <li className="rounded-xl border p-3.5">
+ <p className="font-medium">Add the model files</p>
+ <ul className="mt-2 space-y-1.5">
+ {(files.length ? files : facts.missing.map((k) => ({ key: k, url: "", sizeBytes: 0, folder: k.split("/")[0], file: k.split("/").slice(1).join("/") }))).map((f) => (
+ <li key={f.key} className="flex flex-wrap items-baseline gap-x-2 text-[13px]">
+ {f.url ? (
+ <a href={f.url} className="font-medium text-brand-text hover:underline" rel="noreferrer">
+ {f.file}
+ </a>
+ ) : (
+ <span className="font-medium">{f.file}</span>
+ )}
+ <span className="text-muted-foreground">
+ into models/{f.folder}
+ {f.sizeBytes ? ` · ${(f.sizeBytes / 1e9).toFixed(f.sizeBytes > 1e9 ? 2 : 3)} GB` : ""}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </li>
+ )}
+ <li className="rounded-xl border p-3.5 text-muted-foreground">
+ Restart ComfyUI{facts.highvram === false ? " with --highvram (live frames take about twice as long without it)" : ""}, then reload this page.{" "}
+ <Link href={computer ? "/settings" : "/workflows"} className="font-medium text-brand-text hover:underline">
+ {computer ? "Your GPU" : "Workflows and models"}
+ </Link>
+ </li>
+ </ol>
+ </div>
+ </div>
+ );
+}
+
+function LiveProblem({ message, code }: { message: string; code?: string }) {
+ return (
+ <div className="absolute inset-0 grid place-items-center p-6 text-center text-white">
+ <div className="max-w-sm">
+ <p className="font-heading text-[24px] leading-tight">{code === "off" ? "Live edit is off" : "Live edit can't start"}</p>
+ <p className="mt-2 text-[13px] text-white/70">{message}</p>
+ <Button variant="secondary" className="mt-5" onClick={() => window.location.reload()}>
+ Try again
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/live/live-store.ts b/src/components/live/live-store.ts
new file mode 100644
index 00000000..826d119d
--- /dev/null
+++ b/src/components/live/live-store.ts
@@ -0,0 +1,53 @@
+"use client";
+
+/**
+ * Kept masters in this browser (IndexedDB "fuobe-live"), for the computer path: a step whose master the server couldn't
+ * keep (the account's files are full) stays here, and a reload finds it. Every call is guarded: a browser that blocks
+ * storage (a private window) just keeps nothing.
+ */
+
+const DB = "fuobe-live";
+const STORE = "masters";
+
+function open(): Promise<IDBDatabase | null> {
+ return new Promise((resolve) => {
+ try {
+ const req = indexedDB.open(DB, 1);
+ req.onupgradeneeded = () => req.result.createObjectStore(STORE);
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => resolve(null);
+ req.onblocked = () => resolve(null);
+ } catch {
+ resolve(null);
+ }
+ });
+}
+
+export async function idbPut(key: string, bytes: Uint8Array): Promise<boolean> {
+ const db = await open();
+ if (!db) return false;
+ return new Promise((resolve) => {
+ try {
+ const tx = db.transaction(STORE, "readwrite");
+ tx.objectStore(STORE).put(bytes, key);
+ tx.oncomplete = () => resolve(true);
+ tx.onerror = () => resolve(false);
+ } catch {
+ resolve(false);
+ }
+ });
+}
+
+export async function idbGet(key: string): Promise<Uint8Array | null> {
+ const db = await open();
+ if (!db) return null;
+ return new Promise((resolve) => {
+ try {
+ const req = db.transaction(STORE, "readonly").objectStore(STORE).get(key);
+ req.onsuccess = () => resolve(req.result instanceof Uint8Array ? req.result : null);
+ req.onerror = () => resolve(null);
+ } catch {
+ resolve(null);
+ }
+ });
+}
diff --git a/src/components/live/live-transport.ts b/src/components/live/live-transport.ts
new file mode 100644
index 00000000..3cf62af7
--- /dev/null
+++ b/src/components/live/live-transport.ts
@@ -0,0 +1,531 @@
+"use client";
+
+import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";
+import { loopbackFetch } from "@/lib/gpu/browser-check";
+import { FrameReader, type LiveEvent } from "@/lib/live/frames";
+import { buildLiveGraph, LIVE_FILES, LIVE_OUTPUT, liveGraphProblem, slotBindings, type LiveGraphParams } from "@/lib/live/graph";
+import { inputName, pictureExt, PICTURE_TYPES, pngSize, sha256Hex } from "@/lib/live/names";
+import { LiveScheduler, type Slot } from "@/lib/live/scheduler";
+import { editSize, type Aspect } from "@/lib/live/sizes";
+import { normalize, renderKey } from "@/lib/live/text";
+import { graphProblem, localBase, readPath, writePath } from "@/lib/local-comfy";
+import { imageSize } from "@/lib/image-size";
+
+/**
+ * How the live editor reaches ComfyUI. Two ways, one interface:
+ *
+ * - ServerTransport: through Fuobe's server (a local install, or an account's linked GPU): one streamed POST per
+ * render (POST /api/live/render), status over server-sent events.
+ * - ChannelTransport: from this tab straight to the ComfyUI on this computer ("Use the ComfyUI on this computer"): the
+ * graph is built here, checked by the relay's rules and the live graph check, and sent to 127.0.0.1 with this tab's own
+ * client id; only prompts and pictures this tab made are ever touched. No server hop per render.
+ */
+
+export interface RenderReq {
+ seq: number;
+ slot: Slot;
+ urgent?: boolean;
+ text: string;
+ /** compose (lab): the kept texts and the live text as one instruction. */
+ compose?: string;
+ seed: number;
+ size: number;
+ keepRes: number;
+ base?: string;
+ refs?: string[];
+ mask?: string;
+ aspect: Aspect;
+ method: string;
+}
+
+export interface RenderOut {
+ data: Uint8Array;
+ type: string;
+ w: number;
+ h: number;
+ /** ComfyUI's render time. */
+ ms: number;
+ sha256: string;
+ key: string;
+ /** A kept master: where Fuobe keeps it, and its name in ComfyUI. */
+ masterUrl?: string;
+ masterName?: string;
+ /** Reused the settled render on screen (no new render). */
+ reused?: boolean;
+}
+
+export type RenderResult = { ok: true; out: RenderOut } | { ok: false; dropped: string } | { ok: false; error: string; code?: string };
+
+export interface StagedPicture {
+ name: string;
+ w: number;
+ h: number;
+ sha256: string;
+}
+
+export interface LiveFacts {
+ nodes: number;
+ highvram: boolean | null;
+ /** Model files ComfyUI doesn't list (folder/file). */
+ missing: string[];
+}
+
+export type OpenResult = ({ ok: true; seed: number } & LiveFacts) | { ok: false; error: string; code?: string };
+
+export interface TransportStatus {
+ online: boolean;
+ running: "ours" | "other" | null;
+ queue: number;
+ otherRan: boolean;
+}
+
+export interface LiveTransport {
+ kind: "server" | "link" | "computer";
+ open(): Promise<OpenResult>;
+ /** Stage a Fuobe file (the picture being edited, a reference). */
+ stageFile(url: string): Promise<StagedPicture>;
+ /** Stage bytes made here (a painted mask; on the computer path, a kept master). */
+ stageBytes(bytes: Uint8Array, kind: "mask" | "master"): Promise<StagedPicture>;
+ render(req: RenderReq, onEvent: (e: LiveEvent) => void): Promise<RenderResult>;
+ hurry(seq: number): void;
+ /** Stop renders that no longer matter (the base changed, live was switched off). */
+ cancel(match: (seq: number, slot: Slot) => boolean): void;
+ onStatus(fn: (s: TransportStatus) => void): () => void;
+ close(): void;
+}
+
+/** The key a render is cached by (the server computes the same). */
+export function keyOf(r: Pick<RenderReq, "base" | "refs" | "mask" | "text" | "compose" | "seed" | "size" | "keepRes" | "aspect" | "method" | "slot">): string {
+ const keep = r.slot === "keep" || r.slot === "settle";
+ const prompt = r.method === "compose" && r.compose !== undefined ? r.compose : normalize(r.text);
+ return renderKey({ base: r.base ?? "", refs: r.refs, mask: r.mask, text: prompt, seed: r.seed, size: keep ? r.keepRes : r.size, aspect: r.aspect, method: r.method, quality: keep ? "keep" : "live" });
+}
+
+// ---------------------------------------------------------------------------
+// Through Fuobe's server
+
+export class ServerTransport implements LiveTransport {
+ kind: "server" | "link" = "server";
+ private sessionId = "";
+ private inflight = new Map<number, { ctl: AbortController; slot: Slot }>();
+ private es: EventSource | null = null;
+ private listeners = new Set<(s: TransportStatus) => void>();
+ private status: TransportStatus = { online: false, running: null, queue: 0, otherRan: false };
+
+ async open(): Promise<OpenResult> {
+ let stored: string | undefined;
+ try {
+ stored = sessionStorage.getItem("fuobe-live:session") ?? undefined;
+ } catch {}
+ const res = await fetch("/api/live/session", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: stored }) });
+ const j = (await res.json().catch(() => ({}))) as { sessionId?: string; mode?: "server" | "link"; seed?: number; nodes?: { version?: number }; highvram?: boolean | null; missing?: string[]; error?: string; code?: string };
+ if (!res.ok || !j.sessionId) return { ok: false, error: j.error ?? `Live edit didn't start (${res.status})`, code: j.code };
+ this.sessionId = j.sessionId;
+ this.kind = j.mode === "link" ? "link" : "server";
+ try {
+ sessionStorage.setItem("fuobe-live:session", j.sessionId);
+ } catch {}
+ this.listen();
+ return { ok: true, seed: j.seed ?? 0, nodes: j.nodes?.version ?? 0, highvram: j.highvram ?? null, missing: j.missing ?? [] };
+ }
+
+ private listen() {
+ this.es?.close();
+ const es = new EventSource(`/api/live/events?session=${encodeURIComponent(this.sessionId)}`);
+ this.es = es;
+ es.addEventListener("status", (ev) => {
+ try {
+ this.status = JSON.parse((ev as MessageEvent).data) as TransportStatus;
+ for (const l of this.listeners) l(this.status);
+ } catch {}
+ });
+ es.onerror = () => {
+ this.status = { ...this.status, online: false };
+ for (const l of this.listeners) l(this.status);
+ };
+ }
+
+ onStatus(fn: (s: TransportStatus) => void) {
+ this.listeners.add(fn);
+ fn(this.status);
+ return () => this.listeners.delete(fn);
+ }
+
+ async stageFile(url: string): Promise<StagedPicture> {
+ const res = await fetch("/api/live/inputs", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: this.sessionId, file: url }) });
+ const j = (await res.json().catch(() => ({}))) as { name?: string; width?: number; height?: number; sha256?: string; error?: string };
+ if (!res.ok || !j.name) throw new Error(j.error ?? `Couldn't add the picture (${res.status})`);
+ return { name: j.name, w: j.width ?? 0, h: j.height ?? 0, sha256: j.sha256 ?? "" };
+ }
+
+ async stageBytes(bytes: Uint8Array): Promise<StagedPicture> {
+ const res = await fetch("/api/live/inputs", { method: "POST", headers: { "content-type": "image/png", "x-live-session": this.sessionId }, body: bytes as BodyInit });
+ const j = (await res.json().catch(() => ({}))) as { name?: string; width?: number; height?: number; sha256?: string; error?: string };
+ if (!res.ok || !j.name) throw new Error(j.error ?? `Couldn't add the picture (${res.status})`);
+ return { name: j.name, w: j.width ?? 0, h: j.height ?? 0, sha256: j.sha256 ?? "" };
+ }
+
+ async render(req: RenderReq, onEvent: (e: LiveEvent) => void): Promise<RenderResult> {
+ const ctl = new AbortController();
+ this.inflight.set(req.seq, { ctl, slot: req.slot });
+ const key = keyOf(req);
+ try {
+ const res = await fetch("/api/live/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: this.sessionId, ...req }), signal: ctl.signal });
+ if (!res.ok || !res.body) {
+ const j = (await res.json().catch(() => ({}))) as { error?: string; code?: string };
+ return { ok: false, error: j.error ?? `The render failed (${res.status})`, code: j.code ?? (res.status === 410 ? "session" : undefined) };
+ }
+ const reader = res.body.getReader();
+ const fr = new FrameReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ for (const f of fr.push(value)) {
+ if (f.kind === "event") {
+ if (f.event.type === "dropped") return { ok: false, dropped: f.event.why };
+ if (f.event.type === "error") return { ok: false, error: f.event.message, code: f.event.code };
+ onEvent(f.event);
+ } else {
+ const h = f.header;
+ return { ok: true, out: { data: f.data, type: h.type, w: h.w, h: h.h, ms: h.ms, sha256: h.sha256 ?? (await sha256Hex(f.data)), key, ...(h.url && { masterUrl: h.url }), ...(h.name && { masterName: h.name }) } };
+ }
+ }
+ }
+ return { ok: false, dropped: "closed" };
+ } catch {
+ if (ctl.signal.aborted) return { ok: false, dropped: "cancelled" };
+ return { ok: false, error: "Lost the connection to Fuobe", code: "offline" };
+ } finally {
+ this.inflight.delete(req.seq);
+ }
+ }
+
+ hurry(): void {
+ // The server's scheduler hurries an urgent request itself (it carries `urgent`).
+ }
+
+ cancel(match: (seq: number, slot: Slot) => boolean): void {
+ const seqs: number[] = [];
+ for (const [seq, f] of this.inflight)
+ if (match(seq, f.slot) && f.slot !== "keep") {
+ f.ctl.abort();
+ seqs.push(seq);
+ }
+ // A backup for a browser whose aborted request doesn't reach the server.
+ if (seqs.length) void fetch("/api/live/cancel", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: this.sessionId, seqs }), keepalive: true }).catch(() => {});
+ }
+
+ close(): void {
+ this.cancel(() => true);
+ this.es?.close();
+ this.es = null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// From this tab to the ComfyUI on this computer
+
+interface ChannelJob {
+ req: RenderReq;
+ params: LiveGraphParams;
+ key: string;
+ onEvent: (e: LiveEvent) => void;
+}
+
+interface Waiter {
+ started: boolean;
+ startedAt: number;
+ onEvent: (e: LiveEvent) => void;
+ resolve: (p: { data: Uint8Array; type: string; w: number; h: number; ms: number }) => void;
+ reject: (e: Error & { code?: string }) => void;
+}
+
+const fail = (message: string, code: string) => Object.assign(new Error(message), { code });
+
+export class ChannelTransport implements LiveTransport {
+ kind = "computer" as const;
+ private base: string;
+ private clientId = `fuobe-live-${crypto.randomUUID().replace(/-/g, "").slice(0, 16)}`;
+ private ws: WebSocket | null = null;
+ private online = false;
+ private backoff = 250;
+ private timer: ReturnType<typeof setTimeout> | undefined;
+ private closed = false;
+ /** Prompt ids this tab minted: the only ones it may stop or take out of the history. */
+ private ownIds: string[] = [];
+ /** Names this tab staged, with its own copy of their bytes (to stage again after ComfyUI restarts). */
+ private names = new Map<string, { bytes: Uint8Array; type: string; w: number; h: number; sha256: string }>();
+ private waiters = new Map<string, Waiter>();
+ private listeners = new Set<(s: TransportStatus) => void>();
+ private status: TransportStatus = { online: false, running: null, queue: 0, otherRan: false };
+ private waiting = 0;
+ private scheduler: LiveScheduler<ChannelJob, RenderOut>;
+
+ constructor(port: number, host = "127.0.0.1") {
+ this.base = localBase(port, host);
+ this.scheduler = new LiveScheduler<ChannelJob, RenderOut>({ run: (job, signal) => this.run(job.payload, signal) });
+ }
+
+ private set(patch: Partial<TransportStatus>) {
+ const next = { ...this.status, ...patch };
+ if (JSON.stringify(next) === JSON.stringify(this.status)) return;
+ this.status = next;
+ for (const l of this.listeners) l(next);
+ }
+
+ onStatus(fn: (s: TransportStatus) => void) {
+ this.listeners.add(fn);
+ fn(this.status);
+ return () => this.listeners.delete(fn);
+ }
+
+ private get(path: string) {
+ return loopbackFetch(`${this.base}${readPath(path)}`);
+ }
+
+ private post(path: string, body: unknown) {
+ const p = writePath(path, body, { promptIds: this.ownIds, names: [...this.names.keys()] });
+ return loopbackFetch(`${this.base}${p}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ }
+
+ async open(): Promise<OpenResult> {
+ this.closed = false;
+ try {
+ const stats = await this.get("/system_stats");
+ if (!stats.ok) return { ok: false, error: "ComfyUI on this computer didn't answer", code: "offline" };
+ const argv = ((await stats.json()) as { system?: { argv?: string[] } }).system?.argv;
+ const nodes = await this.get("/fuobe/live").then(async (r) => (r.ok ? Number(((await r.json()) as { version?: number }).version) || 0 : 0)).catch(() => 0);
+ const missing: string[] = [];
+ for (const [folder, file] of [["diffusion_models", LIVE_FILES.unet], ["text_encoders", LIVE_FILES.clip], ["vae", LIVE_FILES.vae], ["loras", LIVE_FILES.lora]] as const) {
+ const list = await this.get(`/models/${folder}`).then((r) => (r.ok ? (r.json() as Promise<string[]>) : null)).catch(() => null);
+ if (Array.isArray(list) && !list.includes(file)) missing.push(`${folder}/${file}`);
+ }
+ this.connect();
+ return { ok: true, seed: Math.floor(Math.random() * 2 ** 31), nodes, highvram: Array.isArray(argv) ? argv.includes("--highvram") || argv.includes("--gpu-only") : null, missing };
+ } catch {
+ return { ok: false, error: "Can't reach the ComfyUI on this computer", code: "offline" };
+ }
+ }
+
+ private connect() {
+ if (this.closed) return;
+ this.timer = undefined;
+ let ws: WebSocket;
+ try {
+ ws = new WebSocket(`${this.base.replace(/^http/, "ws")}${readPath(`/ws?clientId=${this.clientId}`)}`);
+ } catch {
+ return this.retry();
+ }
+ ws.binaryType = "arraybuffer";
+ this.ws = ws;
+ ws.onopen = () => {
+ this.online = true;
+ this.backoff = 250;
+ this.set({ online: true });
+ };
+ ws.onclose = () => {
+ if (this.ws !== ws) return;
+ this.ws = null;
+ this.online = false;
+ for (const w of this.waiters.values()) w.reject(fail("ComfyUI went away. Reconnecting…", "offline"));
+ this.waiters.clear();
+ this.waiting = 0;
+ this.set({ online: false, running: null });
+ this.retry();
+ };
+ ws.onmessage = (ev) => {
+ if (typeof ev.data !== "string") {
+ const p = parseComfyBinary(new Uint8Array(ev.data as ArrayBuffer));
+ const w = p?.promptId ? this.waiters.get(p.promptId) : undefined;
+ if (p && w && (p.live || p.node === LIVE_OUTPUT)) w.resolve({ data: p.data.slice(), type: p.type, w: p.width ?? 0, h: p.height ?? 0, ms: performance.now() - (w.startedAt || performance.now()) });
+ return;
+ }
+ const e = parseComfyText(ev.data);
+ if (!e) return;
+ if (e.type === "status") {
+ const queue = e.queueRemaining ?? 0;
+ const runningOurs = [...this.waiters.values()].some((w) => w.started);
+ const other = queue > this.waiting + (runningOurs ? 1 : 0);
+ this.set({ queue, running: runningOurs ? "ours" : other ? "other" : null, ...(other && { otherRan: true }) });
+ return;
+ }
+ const w = "promptId" in e && e.promptId ? this.waiters.get(e.promptId) : undefined;
+ if (!w) return;
+ if (e.type === "execution_start") {
+ w.started = true;
+ w.startedAt = performance.now();
+ this.waiting = Math.max(0, this.waiting - 1);
+ this.set({ running: "ours" });
+ w.onEvent({ type: "started" });
+ } else if (e.type === "progress" && e.max <= 8) w.onEvent({ type: "progress", value: e.value, max: e.max });
+ else if (e.type === "error") w.reject(fail(e.message ?? "The render failed", e.nodeType === "LoadImageFuobeLive" ? "missing-input" : "failed"));
+ else if (e.type === "interrupted") w.reject(fail("Stopped", "stopped"));
+ };
+ }
+
+ private retry() {
+ if (this.closed || this.timer) return;
+ const wait = Math.min(3000, this.backoff) * (0.75 + Math.random() * 0.5);
+ this.backoff = Math.min(3000, this.backoff * 2);
+ this.timer = setTimeout(() => this.connect(), wait);
+ }
+
+ private async upload(name: string, bytes: Uint8Array, type: string) {
+ const body = { name, type: "input", overwrite: "true" };
+ writePath("/upload/image", body, { promptIds: this.ownIds, names: [...this.names.keys()] });
+ const form = new FormData();
+ form.append("image", new Blob([bytes as BlobPart], { type }), name);
+ form.append("type", "input");
+ form.append("overwrite", "true");
+ const res = await loopbackFetch(`${this.base}/upload/image`, { method: "POST", body: form });
+ if (!res.ok) throw fail(`ComfyUI refused the picture (${res.status})`, "failed");
+ }
+
+ private async stage(bytes: Uint8Array): Promise<StagedPicture> {
+ const ext = pictureExt(bytes);
+ if (!ext) throw new Error("Only PNG, JPEG or WebP pictures");
+ const { name, sha256 } = await inputName(bytes, ext);
+ const had = this.names.get(name);
+ if (had) return { name, w: had.w, h: had.h, sha256 };
+ const size = (ext === "png" ? pngSize(bytes) : null) ?? (() => {
+ const s = imageSize(bytes);
+ return s ? { w: s.width, h: s.height } : { w: 0, h: 0 };
+ })();
+ this.names.set(name, { bytes, type: PICTURE_TYPES[ext], w: size.w, h: size.h, sha256 });
+ await this.upload(name, bytes, PICTURE_TYPES[ext]);
+ return { name, w: size.w, h: size.h, sha256 };
+ }
+
+ async stageFile(url: string): Promise<StagedPicture> {
+ // Fuobe's own file (same site), then into ComfyUI under its content name.
+ if (!url.startsWith("/api/files/") && !url.startsWith("blob:")) throw new Error("Only your own files");
+ const res = await fetch(url);
+ if (!res.ok) throw new Error("Couldn't read the picture");
+ return this.stage(new Uint8Array(await res.arrayBuffer()));
+ }
+
+ stageBytes(bytes: Uint8Array): Promise<StagedPicture> {
+ return this.stage(bytes);
+ }
+
+ render(req: RenderReq, onEvent: (e: LiveEvent) => void): Promise<RenderResult> {
+ const base = req.base ? this.names.get(req.base) : undefined;
+ const liveLong = base?.w ? Math.max(...editSize(req.size, base.w, base.h)) : req.size;
+ const bind = slotBindings(req.slot, { liveSize: req.size, keepRes: req.keepRes, hasMask: !!req.mask, to: "socket", liveLongSide: liveLong });
+ const prompt = req.method === "compose" && req.compose !== undefined ? req.compose : normalize(req.text);
+ const params: LiveGraphParams = {
+ prompt: req.slot === "warm" ? "warm-up" : prompt,
+ seed: req.slot === "warm" ? 0 : req.seed,
+ ...bind,
+ ...(req.base && { base: req.base }),
+ ...(req.refs?.length && { refs: req.refs }),
+ ...(req.mask && { mask: req.mask }),
+ ...(!req.base && { aspect: req.aspect }),
+ };
+ const key = keyOf(req);
+ return this.scheduler.submit({ seq: req.seq, slot: req.slot, key, urgent: req.urgent, payload: { req, params, key, onEvent } }).then((o) => (o.ok ? { ok: true, out: o.result } : "dropped" in o ? { ok: false, dropped: o.dropped } : { ok: false, error: o.error }));
+ }
+
+ hurry(seq: number): void {
+ this.scheduler.hurry(seq);
+ }
+
+ cancel(match: (seq: number, slot: Slot) => boolean): void {
+ this.scheduler.cancel((j) => j.slot !== "keep" && match(j.seq, j.slot));
+ }
+
+ private async online_(ms: number) {
+ const end = performance.now() + ms;
+ while (!this.online && performance.now() < end && !this.closed) await new Promise((r) => setTimeout(r, 30));
+ return this.online;
+ }
+
+ private async run(job: ChannelJob, signal: AbortSignal): Promise<RenderOut> {
+ for (let tries = 0; ; tries++) {
+ try {
+ return await this.once(job, signal);
+ } catch (e) {
+ const code = (e as { code?: string }).code;
+ if (signal.aborted || tries >= 2) throw e;
+ if (code === "offline") {
+ job.onEvent({ type: "reconnecting" });
+ if (!(await this.online_(8000))) throw e;
+ } else if (code === "missing-input") {
+ // ComfyUI lost its input folder (a restart): send this tab's pictures again.
+ const { staged } = buildLiveGraph(job.params);
+ for (const n of staged) {
+ const c = this.names.get(n);
+ if (c) await this.upload(n, c.bytes, c.type);
+ }
+ } else throw e;
+ }
+ }
+ }
+
+ private async once(job: ChannelJob, signal: AbortSignal): Promise<RenderOut> {
+ if (!(await this.online_(3000))) throw fail("Can't reach ComfyUI. Reconnecting…", "offline");
+ const { graph, staged } = buildLiveGraph(job.params);
+ // The tab's own checks, before anything reaches ComfyUI: the relay's loader rule and the live graph's shape.
+ const names = [...this.names.keys()];
+ const problem = graphProblem(graph, staged.filter((n) => names.includes(n))) ?? liveGraphProblem(graph, names);
+ if (problem) throw fail(problem, "failed");
+ const id = crypto.randomUUID();
+ this.ownIds.push(id);
+ if (this.ownIds.length > 200) this.ownIds.splice(0, this.ownIds.length - 200);
+ const t0 = performance.now();
+ const done = new Promise<{ data: Uint8Array; type: string; w: number; h: number; ms: number }>((resolve, reject) => {
+ const w: Waiter = {
+ started: false,
+ startedAt: 0,
+ onEvent: job.onEvent,
+ resolve: (p) => {
+ this.waiters.delete(id);
+ resolve(p);
+ },
+ reject: (e) => {
+ if (this.waiters.get(id) === w && !w.started) this.waiting = Math.max(0, this.waiting - 1);
+ this.waiters.delete(id);
+ reject(e);
+ },
+ };
+ this.waiters.set(id, w);
+ });
+ done.catch(() => {});
+ this.waiting++;
+ const stop = () => {
+ const w = this.waiters.get(id);
+ const started = !!w?.started;
+ w?.reject(fail("Stopped", "stopped"));
+ void this.post("/queue", { delete: [id] }).catch(() => {});
+ if (started) void this.post("/interrupt", { prompt_id: id }).catch(() => {});
+ };
+ signal.addEventListener("abort", stop, { once: true });
+ try {
+ const res = await this.post("/prompt", { prompt: graph, prompt_id: id, client_id: this.clientId, front: true });
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as { error?: { type?: string; message?: string } };
+ this.waiters.get(id)?.reject(body.error?.type === "missing_node_type" ? fail("Fuobe's live nodes aren't installed in ComfyUI", "missing-nodes") : fail(body.error?.message ?? `ComfyUI answered ${res.status}`, "failed"));
+ } else job.onEvent({ type: "queued", pos: this.status.queue });
+ const p = await done;
+ this.set({ otherRan: false });
+ const sha256 = await sha256Hex(p.data);
+ const size = p.type === "image/png" ? pngSize(p.data) : null;
+ return { data: p.data, type: p.type, w: p.w || size?.w || 0, h: p.h || size?.h || 0, ms: p.ms || performance.now() - t0, sha256, key: job.key };
+ } finally {
+ signal.removeEventListener("abort", stop);
+ void this.post("/history", { delete: [id] }).catch(() => {});
+ }
+ }
+
+ close(): void {
+ this.closed = true;
+ this.scheduler.cancelAll("closed");
+ clearTimeout(this.timer);
+ const ws = this.ws;
+ this.ws = null;
+ if (ws) {
+ ws.onclose = null;
+ ws.close();
+ }
+ }
+}
diff --git a/src/components/nav-items.ts b/src/components/nav-items.ts
index 0adfd056..deaa7117 100644
--- a/src/components/nav-items.ts
+++ b/src/components/nav-items.ts
@@ -45,6 +45,7 @@ import {
Wand2,
WandSparkles,
Workflow,
+ Zap,
ZoomIn,
type LucideIcon,
} from "lucide-react";
@@ -80,6 +81,7 @@ export const NAV: NavGroupDef[] = [
{ href: "/image", label: "Image", icon: ImageIcon, eager: true, keywords: "text to image picture photo" },
{ href: "/video", label: "Video", icon: Video, eager: true, keywords: "text to video image to video animate" },
{ href: "/edit", label: "Edit", icon: Wand2, keywords: "edit image change" },
+ { href: "/live-edit", label: "Live edit", icon: Zap, keywords: "realtime live as you type instant change" },
{ href: "/layers", label: "Layers", icon: Layers2, keywords: "layered psd split" },
{ href: "/inpaint", label: "Inpaint", icon: Brush, keywords: "mask fill remove" },
{ href: "/color-grade", label: "Color grading", icon: SlidersHorizontal, keywords: "grade lut colour" },
diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsx
index 01222121..31904c31 100644
--- a/src/components/preset-gallery.tsx
+++ b/src/components/preset-gallery.tsx
@@ -210,6 +210,36 @@ export function useFadeEdges<T extends HTMLElement>() {
return ref;
}
+/**
+ * A card that opens a tool of its own (Live edit), shown before the presets: the same card chrome, its own link. Only
+ * on the All tab with no search, or when the search matches its words; never when the gallery shows cloud tools only.
+ */
+export interface LinkCard {
+ href: string;
+ title: string;
+ line: string;
+ /** More words a search finds it by. */
+ words?: string;
+ badge?: string;
+ /** Its picture: a node (a playing demo), drawn in the card's 4:3 frame. */
+ cover: React.ReactNode;
+}
+
+function LeadingCard({ card }: { card: LinkCard }) {
+ return (
+ <Link href={card.href} className="group/card flex min-w-0 flex-col gap-2 rounded-xl p-1.5 transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring" data-leading-card>
+ <div className="relative aspect-[4/3] overflow-hidden rounded-lg bg-muted">
+ {card.cover}
+ {card.badge && <span className="pointer-events-none absolute top-1.5 right-1.5 rounded-full bg-highlight px-1.5 py-0.5 text-[10.5px] font-semibold text-highlight-foreground">{card.badge}</span>}
+ </div>
+ <div className="min-w-0 px-0.5 pb-0.5">
+ <p className="truncate text-[14px] font-medium">{card.title}</p>
+ <p className="line-clamp-2 text-[12.5px] text-muted-foreground">{card.line}</p>
+ </div>
+ </Link>
+ );
+}
+
const FIRST_PAGE = 30;
const PAGE = 40;
@@ -220,6 +250,7 @@ export function PresetGallery({
categories,
href,
noun = "presets",
+ leading,
}: {
/** In the order the All view shows them (featuredGallery): a category or a search keeps it. */
presets: PresetCardData[];
@@ -229,6 +260,8 @@ export function PresetGallery({
href: string;
/** Plural shown in the result count, e.g. "effects". */
noun?: string;
+ /** Tools of their own shown first (LinkCard). */
+ leading?: LinkCard[];
}) {
const [cat, setCat] = useState("All");
const [q, setQ] = useState("");
@@ -254,6 +287,7 @@ export function PresetGallery({
const strip = useFadeEdges<HTMLDivElement>();
const stale = q.trim().toLowerCase() !== query;
+ const lead = (leading ?? []).filter((c) => cat === "All" && runsOn !== "cloud" && (!query || matchesSearch(`${c.title} ${c.line} ${c.words ?? ""}`.toLowerCase(), query)));
// One fetch of the viewer's chips (the GPU pre-flight); each card gets one string.
const badges = useGpuBadges().data;
const viewer = useViewer().data;
@@ -327,9 +361,12 @@ export function PresetGallery({
))}
</div>
</div>
- {list.length ? (
+ {list.length || lead.length ? (
<>
<div ref={grid} className={cn(GRID, "transition-opacity", stale && "opacity-70")}>
+ {lead.map((c) => (
+ <LeadingCard key={c.href} card={c} />
+ ))}
{list.slice(0, shown).map((p) => (
<PresetCard key={p.id} preset={p} href={href.replace("{id}", p.id)} engine={locked} gpu={p.open ? badgeKey(badges?.presets[p.id]) : undefined} gpuName={badges?.gpu} />
))}
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 8e581a12..488f4129 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -32,6 +32,7 @@ import {
UserRoundPlus,
Wand2,
WandSparkles,
+ Zap,
ZoomIn,
type LucideIcon,
} from "lucide-react";
@@ -77,6 +78,7 @@ import { toastError } from "@/lib/refusals";
export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
animate: Clapperboard,
edit: Wand2,
+ "live-edit": Zap,
upscale: ZoomIn,
reference: ImagePlus,
grade: SlidersHorizontal,
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 3bd52b5c..3b5b2fe1 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -85,6 +85,8 @@ export interface StudioConfig {
comfyOnly?: { note: string; alternative?: { label: string; href: string } };
/** Frames mode (Video studio): up to 10 stills, each at its own time in the clip, instead of a start and an end frame. */
frames?: boolean;
+ /** A Live switch in the header (Edit): the picture changes as you type, on the viewer's own GPU (Live edit). */
+ live?: boolean;
}
export interface Draft {
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 9499316b..752fb01e 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArrowRight, ArrowUp, Loader2, Upload } from "lucide-react";
+import { ArrowRight, ArrowUp, Loader2, Upload, Zap } from "lucide-react";
import Link from "next/link";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
@@ -31,6 +31,48 @@ import { Feed } from "./feed";
import type { SlotValue } from "./media-slot";
import { PresetUrlCtx, StartRequestCtx, StudioProvider, usePresetUrl, useStudio, useStudioActions, type Draft, type StudioConfig } from "./studio-context";
+// Live edit's panel (the Edit studio's Live switch) loads on the first switch.
+const LiveEditPanel = dynamic(() => import("@/components/live/live-edit-app").then((m) => m.LiveEditPanel), { ssr: false });
+
+/** The Live switch: the picture changes as you type, on the viewer's own GPU (whatever the engine). */
+function LiveSwitch({ on, onChange }: { on: boolean; onChange: (on: boolean) => void }) {
+ return (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={on}
+ onClick={() => onChange(!on)}
+ title="Live: the picture changes as you type (runs on your GPU)"
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-full border px-3 text-[13px] font-medium transition-colors",
+ on ? "border-primary/40 bg-brand-faint text-brand-text" : "text-muted-foreground hover:bg-accent hover:text-foreground",
+ )}
+ data-live-switch
+ >
+ <Zap className="size-3.5" />
+ Live
+ </button>
+ );
+}
+
+/** The Live panel, seeded with the composer's picture and words; "Use in Edit" puts the kept picture back in the composer. */
+function LiveArea({ onClose }: { onClose: () => void }) {
+ const { draft, setSlot } = useStudio();
+ const [seed] = useState(() => ({ image: draft.slots.image?.ref, text: draft.prompt }));
+ return (
+ <LiveEditPanel
+ image={seed.image}
+ text={seed.text}
+ onClose={onClose}
+ onUse={(url) => {
+ setSlot("image", slot(url));
+ onClose();
+ toast.success("The kept picture is in Edit");
+ }}
+ />
+ );
+}
+
function kindOfUrl(url: string): MediaKind {
if (/\.(mp4|webm|mov)(\?|$)/i.test(url)) return "video";
if (/\.(mp3|wav|ogg|flac|m4a)(\?|$)/i.test(url)) return "audio";
@@ -379,6 +421,7 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
const hasItems = items.length > 0;
const offscreen = useOffscreenResults(feed.data);
const catalog = useCatalog();
+ const [live, setLive] = useState(false);
const reuse = useCallback(
(g: Generation) => {
@@ -417,9 +460,29 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
else toast("Drop it on the composer");
}}
>
- <StudioHeader title={config.title} header={header} tabs={tabs} />
+ <StudioHeader
+ title={config.title}
+ header={
+ config.live ? (
+ <>
+ {header}
+ <LiveSwitch on={live} onChange={setLive} />
+ </>
+ ) : (
+ header
+ )
+ }
+ tabs={tabs}
+ />
- <div className={cn("mx-auto w-full max-w-[1240px] min-w-0 px-3 sm:px-6", hasItems && "flex-1 pb-8")}>
+ {live && (
+ <div className="mx-auto w-full max-w-[1240px] min-w-0 flex-1 px-3 pb-4 sm:px-6">
+ <div className="h-[calc(100svh-4.5rem)] min-h-[520px]">
+ <LiveArea onClose={() => setLive(false)} />
+ </div>
+ </div>
+ )}
+ <div className={cn("mx-auto w-full max-w-[1240px] min-w-0 px-3 sm:px-6", hasItems && "flex-1 pb-8", live && "hidden")}>
{hasItems ? (
<div className="pt-4">
<Feed items={items} onReuse={reuse} />
@@ -441,6 +504,7 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
{/* One composer for both layouts (centred under the hero, docked under the feed), so it keeps focus and state when the first result arrives. */}
<div
className={cn(
+ live && "hidden",
hasItems
? "sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6"
: "px-3 pt-6 sm:px-6 sm:pt-10",
@@ -469,10 +533,13 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
</div>
</div>
- {!hasItems && config.suggestions && <PromptSuggestions suggestions={config.suggestions} />}
- {!hasItems && config.signature && <SoulPresetCards />}
- {/* Only once the feed is known to be empty: a studio with results would show the row, fetch its covers, then drop it. */}
- {feed.isSuccess && !hasItems && !!examples?.tiles.length && <StudioExamples row={examples} />}
+ {/* Hidden, not unmounted, while Live is on: the page around the panel keeps its state. */}
+ <div className={live ? "hidden" : "contents"}>
+ {!hasItems && config.suggestions && <PromptSuggestions suggestions={config.suggestions} />}
+ {!hasItems && config.signature && <SoulPresetCards />}
+ {/* Only once the feed is known to be empty: a studio with results would show the row, fetch its covers, then drop it. */}
+ {feed.isSuccess && !hasItems && !!examples?.tiles.length && <StudioExamples row={examples} />}
+ </div>
{dragging && (
<div className="pointer-events-none absolute inset-0 z-40 grid place-items-center bg-overlay p-8">
diff --git a/src/lib/home-showcase.ts b/src/lib/home-showcase.ts
index ecca4072..a348fa92 100644
--- a/src/lib/home-showcase.ts
+++ b/src/lib/home-showcase.ts
@@ -108,7 +108,14 @@ export const HOME_STUDIOS: { href: string; id?: string; line: (f: HomeFacts) =>
];
/** Destinations with a section of their own on Home, so they aren't pills as well. */
-export const HOME_OWN_SECTIONS = ["/assist", "/motions", "/effects", "/apps"];
+export const HOME_OWN_SECTIONS = ["/assist", "/motions", "/effects", "/apps", "/live-edit"];
+
+/** Live edit's moment on Home: a recorded session plays (no GPU, no requests), with one way in. */
+export const HOME_LIVE = {
+ href: "/live-edit?from=home",
+ title: "Change it as you type",
+ line: "Type a change and watch the picture follow in under a second. Keep what you like; nothing blurs, however many changes you stack.",
+};
/** Assist's starter skills, as its empty chat lists them first (assist-view.tsx). */
export const HOME_SKILLS = ["product-photoshoot", "ugc-video", "thumbnail-generation", "faceless-video", "short-film", "localization"];
diff --git a/src/lib/nav.ts b/src/lib/nav.ts
index b3b53c14..f46b9a0f 100644
--- a/src/lib/nav.ts
+++ b/src/lib/nav.ts
@@ -75,11 +75,11 @@ export function sidebarCookie(open: boolean): string {
}
/**
- * Full-screen studios: a project open in Cinema, Canvas or Layers, and Assist (with its own rail of
- * chats). They have a sidebar of their own, so the app sidebar folds to its icon rail while one is
+ * Full-screen studios: a project open in Cinema, Canvas or Layers, Assist (with its own rail of
+ * chats), and Live edit (the picture fills the page). They have a sidebar of their own, so the app sidebar folds to its icon rail while one is
* open, without touching the remembered choice, and comes back on the way out.
*/
-const FULL_SCREEN = /^\/(?:(?:cinema|canvas|layers)\/[^/]+\/?|assist(?:\/.*)?)$/;
+const FULL_SCREEN = /^\/(?:(?:cinema|canvas|layers)\/[^/]+\/?|assist(?:\/.*)?|live-edit\/?)$/;
/**
* Which full-screen studio a path belongs to (null on any other page): the project's own path, or
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 9680ec1c..7de0dcb8 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -15,6 +15,7 @@ import { CLEAN_FEATURE } from "./av/clean-voice";
export type OutputActionId =
| "animate"
| "edit"
+ | "live-edit"
| "upscale"
| "reference"
| "grade"
@@ -99,6 +100,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("animate", "Animate", `/video?image=${q(o.url)}`, "primary");
out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
link("edit", "Edit", `/edit?image=${q(o.url)}`);
+ link("live-edit", "Change it as you type", `/live-edit?image=${q(o.url)}&gen=${q(g.id)}&from=library`);
link("upscale", "Upscale", `/upscale?image=${q(o.url)}`);
link("reference", "Use as reference", `/image?ref=${q(o.url)}`);
link("grade", "Color grade", `/color-grade?image=${q(o.url)}`);
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index 29923254..6836df30 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -27,6 +27,7 @@ export const IMAGE_STUDIO: StudioConfig = {
// the face mosaic after the picture: its step's model is known here so the price counts it before the run.
signature: true,
extraModels: [...Object.values(SIGNATURE_MODELS), ...Object.values(FACE_MOSAIC_MODELS)],
+ related: { href: "/live-edit?from=image", label: "Try it live: change a picture as you type" },
suggestions: [
"Editorial portrait of a woman in a yellow raincoat, Tokyo crosswalk at dusk, 35mm film",
"Isometric cozy reading nook with plants and warm lamp light, 3D render",
@@ -46,6 +47,7 @@ export const EDIT_STUDIO: StudioConfig = {
slots: [{ key: "image", label: "Image", accept: "image", required: true }],
multiRef: { label: "Add ref", max: 6 },
sketch: ["mask", "draw"],
+ live: true,
defaultModels: { cloud: "nano-banana-pro", open: "oss-qwen-image-21" },
suggestions: [
"Make it golden hour",
diff --git a/tests/home-showcase.test.ts b/tests/home-showcase.test.ts
index e819ff1d..45ece742 100644
--- a/tests/home-showcase.test.ts
+++ b/tests/home-showcase.test.ts
@@ -161,7 +161,7 @@ describe("Home's showcase", () => {
for (const p of home.pills) expect(routes.has(p.href), p.href).toBe(true);
});
- it("covers every place to create: the studio cards, the pills and the four with a section of their own", async () => {
+ it("covers every place to create: the studio cards, the pills and the five with a section of their own", async () => {
const home = await homeShowcase();
const create = NAV.find((g) => g.label === "Create")!.items.filter((i) => i.href !== "/");
const studios = NAV.find((g) => g.label === "Studios")!.items;
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 5d158840..99a78d3a 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -70,6 +70,7 @@ describe("outputActions", () => {
"bar:download",
"bar:favorite",
"menu:edit",
+ "menu:live-edit",
"menu:upscale",
"menu:reference",
"menu:grade",
diff --git a/tests/nav.test.ts b/tests/nav.test.ts
index 9e31e88c..f7e60d1e 100644
--- a/tests/nav.test.ts
+++ b/tests/nav.test.ts
@@ -70,9 +70,9 @@ describe("remembered sidebar state", () => {
const foldable = NAV.filter((g) => g.collapsible).map((g) => groupId(g.label));
for (const id of DEFAULT_NAV_CLOSED) expect(foldable).toContain(id);
expect(NAV.map((g) => g.label).slice(0, 2)).toEqual(["Create", "Library"]);
- // The part that can't fold stays short: Create and Library hold 15 rows; Studios below them can be folded away.
+ // The part that can't fold stays short: Create and Library hold 16 rows (Live edit joined Create); Studios below them can be folded away.
const always = NAV.filter((g) => !g.collapsible).flatMap((g) => g.items);
- expect(always.length).toBeLessThanOrEqual(15);
+ expect(always.length).toBeLessThanOrEqual(16);
expect(DEFAULT_NAV_CLOSED).not.toContain("studios");
});
@@ -138,7 +138,7 @@ describe("remembered sidebar state", () => {
describe("full-screen studios", () => {
it("are an open Cinema, Canvas or Layers project, and Assist", () => {
- for (const p of ["/cinema/abc", "/canvas/x1", "/layers/l-2/", "/assist", "/assist/memory", "/assist/projects/p1"]) expect(fullScreenStudio(p)).not.toBeNull();
+ for (const p of ["/cinema/abc", "/canvas/x1", "/layers/l-2/", "/assist", "/assist/memory", "/assist/projects/p1", "/live-edit"]) expect(fullScreenStudio(p)).not.toBeNull();
for (const p of ["/", "/cinema", "/canvas", "/layers", "/assistant", "/apps/app-packshot", "/cinema/a/b", "/library"]) expect(fullScreenStudio(p)).toBeNull();
});