The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Live edit: renders always end, stay bounded, and phones get every action
Adarsh315a43cb8938
diff --git a/public/previews/live-edit/demo.json b/public/previews/live-edit/demo.jsonindex aaaa3fa9..01a036bc 100644--- a/public/previews/live-edit/demo.json+++ b/public/previews/live-edit/demo.json@@ -2,17 +2,15 @@"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" }+ "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 }+ {"type": "frame", "frame": "before", "ms": 900},+ {"type": "type", "text": "evening makeup, deep red lips", "ms": 1900},+ {"type": "frame", "frame": "after", "live": true, "ms": 1200},+ {"type": "keep", "label": "evening makeup, deep red lips", "ms": 1300},+ {"type": "compare", "ms": 2800},+ {"type": "pause", "ms": 1400}]}diff --git a/scripts/comfy/test_fuobe_live.py b/scripts/comfy/test_fuobe_live.pyindex 1ae97f18..855fea48 100644--- a/scripts/comfy/test_fuobe_live.py+++ b/scripts/comfy/test_fuobe_live.py@@ -12,6 +12,7 @@ import sysos.environ["FUOBE_LIVE_PURE"] = "1"import torch # noqa: E402+import torch.nn.functional as F # noqa: E402here = sys.argv[1]spec = importlib.util.spec_from_file_location("fuobe_live", os.path.join(here, "fuobe_live.py"))@@ -52,10 +53,11 @@ u8 = lambda t: (t.clamp(0, 1) * 255 + 0.5).to(torch.uint8)check("paste_back keeps untouched pixels bit-identical", bool(torch.equal(u8(out)[0, 200:], u8(base)[0, 200:])))check("paste_back carries the edit", float((out[0, 60:80, 70:100] - base[0, 60:80, 70:100]).abs().mean()) > 0.1)-# A global change (over 60 %) takes the whole edit.+# A global change (over 60 %) takes the whole edit's light and colour; the base's detail stays where the structure did.glob = (base * 0.5).clamp(0, 1)out2 = fl.paste_back(base, glob, "auto", 0.06, 8, True, 0)-check("a global edit replaces the picture", float((out2 - glob).abs().max()) < 1e-5)+check("a global edit takes the edit's light", abs(float(out2.mean() - glob.mean())) < 0.01)+check("without detail, a global edit is the edit", float((fl.paste_back(base, glob, "auto", 0.06, 8, True, 0, None, None, False) - glob).abs().max()) < 1e-5)# The edit made smaller (a live frame) is scaled to the base, and out_max_side downscales the composite.small = fl.resize(edited, W // 2, H // 2)@@ -81,6 +83,95 @@ out4 = fl.paste_back(base, ed_crop, "mask", 0.06, 6, False, 0, box, mimg)check("mask mode keeps pixels outside the box", bool(torch.equal(u8(out4)[0, :y0], u8(base)[0, :y0])))check("mask mode keeps pixels far from the mask inside the box", bool(torch.equal(u8(out4)[0, y0:y0 + 2, x0:x0 + 2], u8(base)[0, y0:y0 + 2, x0:x0 + 2])))+# ---------------------------------------------------------------------------+# Real renders: a 1024 edit of a 2048 master (half the size), with VAE-like noise and blur over the whole frame.++H2, W2 = 512, 384+yy, xx = torch.meshgrid(torch.linspace(0, 1, H2), torch.linspace(0, 1, W2), indexing="ij")+img = torch.stack([0.3 + 0.4 * xx, 0.25 + 0.5 * yy, 0.5 + 0.2 * torch.sin(6 * xx + 3 * yy)], -1)+for (cy, cx, r, col) in [(0.3, 0.4, 0.15, (0.8, 0.6, 0.5)), (0.7, 0.6, 0.12, (0.2, 0.3, 0.6)), (0.5, 0.2, 0.08, (0.9, 0.9, 0.85))]:+ dist = ((yy - cy) ** 2 + ((xx - cx) * W2 / H2) ** 2).sqrt()+ img = torch.where((dist < r)[..., None], torch.tensor(col), img)+tex = fl._gauss(torch.randn(1, 1, H2, W2), 0.8)[0, 0]+img = (img + (tex / tex.std() * 0.05)[..., None]).clamp(0, 1)+photo = ((img * 255).round() / 255.0)[None]+++def render(x, seed):+ """x made at half its size, with +-2/255 noise and a slight blur: what comes back from the model and its VAE."""+ g = torch.Generator().manual_seed(seed)+ s = fl.resize(x, x.shape[2] // 2, x.shape[1] // 2)+ s = s + torch.randint(-2, 3, s.shape, generator=g).float() / 255.0+ return fl._blur_img(s, 0.5).clamp(0, 1)+++def luma_hp(x):+ return fl.luma(x - fl._blur_img(x, 1.0))+++def lapvar(x):+ k = torch.tensor([[0.0, 1.0, 0.0], [1.0, -4.0, 1.0], [0.0, 1.0, 0.0]]).view(1, 1, 3, 3)+ return float(F.conv2d(fl.luma(x), k).var())+++def ssim(a, b):+ a, b = fl.luma(a), fl.luma(b)+ g = lambda t: F.avg_pool2d(t, 8, 8)+ ma, mb = g(a), g(b)+ va, vb, cov = g(a * a) - ma * ma, g(b * b) - mb * mb, g(a * b) - ma * mb+ return float((((2 * ma * mb + 1e-4) * (2 * cov + 9e-4)) / ((ma ** 2 + mb ** 2 + 1e-4) * (va + vb + 9e-4))).mean())+++def corr(a, b):+ a, b = a - a.mean(), b - b.mean()+ return float((a * b).sum() / ((a * a).sum() * (b * b).sum()).sqrt())+++# A local change on a whole-frame lossy render: the mask stays local, and untouched pixels stay bit-identical.+e = render(photo, 1)+e[:, 60:110, 40:100] = torch.tensor([0.9, 0.1, 0.1])+m = fl.change_mask(fl.resize(photo, e.shape[2], e.shape[1]), e)+check("a lossy render's mask stays local (%.3f of the picture)" % float(m.mean()), float(m.mean()) < 0.2)+out5 = fl.paste_back(photo, e, "auto", 0.06, 24, True, 0)+same = float((u8(out5) == u8(photo)).all(-1).float().mean())+check("a lossy render leaves %.1f %% of pixels bit-identical" % (same * 100), same > 0.85)+check("far from the change, every pixel is the base's", bool(torch.equal(u8(out5)[0, 300:], u8(photo)[0, 300:])))+check("the local change is carried", float((out5[0, 140:200, 100:180] - photo[0, 140:200, 100:180]).abs().mean()) > 0.2)++# 10 stacked global grades (warm, then cool): the picture keeps its sharpness and structure. Without the detail+# transfer it doesn't (the reason for it).+def grade(x, k):+ f = torch.tensor([1.15, 1.02, 0.85])+ return ((x * f) if k % 2 == 0 else (x / f)).clamp(0, 1) ** (0.97 if k % 2 == 0 else 1 / 0.97)+++scores = {}+for detail in (True, False):+ cur, ref = photo.clone(), photo.clone()+ for k in range(10):+ ref = grade(ref, k)+ cur = fl.paste_back(cur, render(grade(cur, k), 100 + k), "auto", 0.06, 24, True, 0, None, None, detail)+ cur = u8(cur).float() / 255.0+ scores[detail] = (lapvar(cur) / lapvar(ref), ssim(cur, ref))+print(" 10 global edits: sharpness %.3f, SSIM %.4f (without detail transfer: %.3f, %.4f)" % (scores[True] + scores[False]))+check("10 global edits keep 90 %% of the sharpness", scores[True][0] >= 0.9)+check("10 global edits keep SSIM 0.98 against the ideal grade", scores[True][1] >= 0.98)+check("without detail transfer they don't", scores[False][0] < 0.5 and scores[False][1] < 0.9)++# A style edit (new texture, new colour) keeps its own texture, not the base's.+small = fl.resize(photo, W2 // 2, H2 // 2)+nt = fl._gauss(torch.randn(1, 1, H2 // 2, W2 // 2), 0.6)[0, 0]+style = ((fl._blur_img(small, 2.0) + (nt / nt.std() * 0.06)[..., None]) * torch.tensor([1.2, 0.9, 0.7])).clamp(0, 1)+out6 = fl.paste_back(photo, style, "auto", 0.06, 24, True, 0)+c_edit, c_base = corr(luma_hp(out6), luma_hp(fl.resize(style, W2, H2))), corr(luma_hp(out6), luma_hp(photo))+check("a style edit keeps its own texture (%.3f against %.3f)" % (c_edit, c_base), c_edit > 0.9 and c_base < 0.2)++# The save node is never served from ComfyUI's cache, and /fuobe/live reports this file's hash.+src = open(os.path.join(here, "fuobe_live.py"), "rb").read()+check("the save node always runs", b'def IS_CHANGED(cls, **kwargs):' in src and b'return float("nan")' in src)+import hashlib # noqa: E402+check("the module hashes its own file", fl.FUOBE_LIVE_SHA256 == hashlib.sha256(src).hexdigest())+# The socket frame body.data, kind = fl.encode_picture(base, "webp", 85)check("encode webp", kind == "image/webp" and data[:4] == b"RIFF")diff --git a/src/app/api/live/render/route.ts b/src/app/api/live/render/route.tsindex dd8adaac..a98dad1e 100644--- a/src/app/api/live/render/route.ts+++ b/src/app/api/live/render/route.ts@@ -1,15 +1,16 @@import { connection } from "next/server";import { eventFrame, imageFrame, LIVE_STREAM_TYPE, type LiveEvent } from "@/lib/live/frames";import { MAX_GRAPH_PROMPT, slotBindings, type LiveGraphParams } from "@/lib/live/graph";-import { LIVE_INPUT } from "@/lib/live/names";-import { isAspect, isKeepRes, isLiveSize, editSize } from "@/lib/live/sizes";+import { LIVE_INPUT, pictureExt, pngSize } from "@/lib/live/names";+import { isAspect, isKeepRes, isLiveSize, editSize, MAX_MASTER_SIDE } from "@/lib/live/sizes";+import { METHODS, type Method } from "@/lib/live/steps";import { MAX_LIVE_TEXT, normalize, renderKey } from "@/lib/live/text";import { ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { asWho, liveWho } from "@/server/live/access";import { LiveRenderError } from "@/server/live/comfy-live";import { sessionOf, stage, submit, type Rendered } from "@/server/live/sessions";import { enter, hit } from "@/server/rate";-import { readRef, saveFile } from "@/server/storage";+import { deleteAsset, readRef, saveFile } from "@/server/storage";const SLOTS = new Set(["live", "settle", "keep", "warm"]);@@ -56,8 +57,10 @@ export async function POST(request: Request) {if (!live.ok || !all.ok) return Response.json({ error: "Too many renders" }, { status: 429, headers: { "Retry-After": "1" } });// What to render: every value checked against the session and the size tables.+ if (b.method !== undefined && !METHODS.includes(b.method as Method)) return Response.json({ error: "Bad method" }, { status: 400 });+ const method: Method = (b.method as Method | undefined) ?? "hybrid";const text = typeof b.text === "string" ? b.text : "";- const compose = who.kind === "owner" && b.method === "compose" && typeof b.compose === "string" ? b.compose : null;+ const compose = who.kind === "owner" && method === "compose" && typeof b.compose === "string" ? b.compose : null;const prompt = compose !== null ? compose.slice(0, MAX_GRAPH_PROMPT) : normalize(text.slice(0, MAX_LIVE_TEXT * 2));const seed = Number(b.seed);if (!Number.isSafeInteger(seed) || seed < 0) return Response.json({ error: "Bad seed" }, { status: 400 });@@ -85,7 +88,7 @@ export async function POST(request: Request) {...(!base && { aspect }),};const quality = slot === "settle" || slot === "keep" ? "keep" : "live";- const key = renderKey({ base: base ?? "", refs: refs as string[], mask, text: prompt, seed, size: params.res, aspect, method: typeof b.method === "string" ? b.method : "hybrid", quality });+ const key = renderKey({ base: base ?? "", refs: refs as string[], mask, text: prompt, seed, size: params.res, aspect, method, quality });// Keep after a settle of the same text, seed and size: the settled picture on screen is stored as it is (no new render).const fromSettled = slot === "keep" && b.fromSettled !== false ? key : undefined;@@ -141,10 +144,16 @@ export async function POST(request: Request) {/** Store a kept picture as the step's master (the owner's file, or the account's own) and stage it as the next base. */const keepMaster = async (pic: Rendered): Promise<{ masterId?: string; url?: string; name?: string } & { error?: true }> => {- if (pic.type !== "image/png") {+ // Checked by its bytes, not by what ComfyUI said it is.+ const size = pictureExt(pic.data) === "png" ? pngSize(pic.data) : null;+ if (pic.type !== "image/png" || !size) {onEvent({ type: "error", message: "A kept picture must be a PNG master" });return { error: true };}+ if (Math.max(size.w, size.h) > MAX_MASTER_SIDE) {+ onEvent({ type: "error", message: `Kept pictures are at most ${MAX_MASTER_SIDE} px on the long side` });+ return { error: true };+ }const data = Buffer.from(pic.data);if (who.kind === "account") {if (!diskHasRoom()) {@@ -157,8 +166,14 @@ export async function POST(request: Request) {}}const asset = saveFile({ data, contentType: "image/png", name: `live-edit-${seq}.png`, source: "derived", ...(who.kind === "account" && { accountId: who.account.id }) });- const st = await stage(s, pic.data, () => asWho(who, () => readRef(asset.url)).then((r) => new Uint8Array(r.data)));- return { masterId: asset.id, url: asset.url, name: st.name };+ try {+ const st = await stage(s, pic.data, () => asWho(who, () => readRef(asset.url)).then((r) => new Uint8Array(r.data)));+ return { masterId: asset.id, url: asset.url, name: st.name };+ } catch (e) {+ // Not staged, so not kept: the file goes too (it would count against the account's space for nothing).+ deleteAsset(asset.id);+ throw e;+ }};const stream = new ReadableStream<Uint8Array>({diff --git a/src/app/api/live/session/route.ts b/src/app/api/live/session/route.tsindex 6d9eea6b..3e94496d 100644--- a/src/app/api/live/session/route.ts+++ b/src/app/api/live/session/route.ts@@ -3,20 +3,29 @@ import { KEEP_LADDER, LIVE_LADDER } from "@/lib/live/sizes";import { MAX_LIVE_TEXT } from "@/lib/live/text";import { asWho, liveWho } from "@/server/live/access";import { liveFacts, liveSocket } from "@/server/live/comfy-live";-import { openSession } from "@/server/live/sessions";+import { endSession, openSession, sessionOf } from "@/server/live/sessions";+import { hit } from "@/server/rate";import { onOwnGpu } from "@/server/providers/comfyui";/**- * Open (or renew) this tab's live edit session on the server path: the owner's local ComfyUI, or an account's linked- * GPU. The tab on "Use the ComfyUI on this computer" never calls it (it talks to its ComfyUI itself).+ * Open a live edit session for one editor on the server path (the owner's local ComfyUI, or an account's linked GPU),+ * or end one: { sessionId, end: true }. Every editor opens its own (a duplicated tab never shares one), and a person+ * has at most four. The tab on "Use the ComfyUI on this computer" never calls it (it talks to its ComfyUI itself).*/export async function POST(request: Request) {await connection();const who = liveWho(request, { server: true });if (who instanceof Response) return who;- const body = (await request.json().catch(() => ({}))) as { sessionId?: unknown };+ const body = ((await request.json().catch(() => null)) ?? {}) as { sessionId?: unknown; end?: unknown };+ if (body.end === true) {+ const had = sessionOf(who.principal, body.sessionId);+ if (had) endSession(had.id);+ return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });+ }+ const rate = hit(`live-session:${who.principal}`, 20, 60_000);+ if (!rate.ok) return Response.json({ error: "Live edit opened too often. Try again in a moment." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });const gpu = who.kind === "account" ? who.gpu : undefined;- const s = openSession(who.principal, gpu, typeof body.sessionId === "string" ? body.sessionId : undefined);+ const s = openSession(who.principal, gpu);if (!gpu) liveSocket();const facts = await asWho(who, () => (gpu ? onOwnGpu(gpu, liveFacts) : liveFacts()));return Response.json(@@ -25,7 +34,7 @@ export async function POST(request: Request) {mode: gpu ? "link" : "server",seed: s.seed,sizes: { live: LIVE_LADDER, keep: KEEP_LADDER },- nodes: { live: facts.nodes > 0, version: facts.nodes, ws: !gpu },+ nodes: { live: facts.nodes > 0, version: facts.nodes, outdated: facts.outdated, ws: !gpu },highvram: facts.highvram,missing: facts.missing,maxText: MAX_LIVE_TEXT,diff --git a/src/components/home-view.tsx b/src/components/home-view.tsxindex 387b7b9e..aff84e30 100644--- a/src/components/home-view.tsx+++ b/src/components/home-view.tsx@@ -30,7 +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…" },+ { id: "live", label: "Live", icon: Zap, href: "/live-edit", placeholder: "Type a change, then open Live edit…" },];/** A Try chip under the composer: it picks the mode and fills in the prompt; Start still runs it. */diff --git a/src/components/live/live-demo.tsx b/src/components/live/live-demo.tsxindex 727adc21..679394c5 100644--- a/src/components/live/live-demo.tsx+++ b/src/components/live/live-demo.tsx@@ -17,7 +17,8 @@ interface DemoFrame {small?: string;}type DemoStep =- | { type: "frame"; frame: string; live?: string; ms: number }+ /** live: a live frame (the pill says Live); the recording's real times join it once there are real-GPU numbers. */+ | { type: "frame"; frame: string; live?: boolean; ms: number }| { type: "type"; text: string; ms: number }| { type: "keep"; label: string; ms: number }| { type: "compare"; ms: number }@@ -59,7 +60,7 @@ export function LiveDemo({ compact, className, onTypeAttempt }: { compact?: boolconst 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" });+ const [view, setView] = useState<View>({ frame: "before", under: null, typed: "", steps: [], keepPulse: false, compare: null, pill: "Live" });useEffect(() => {let alive = true;@@ -95,12 +96,12 @@ export function LiveDemo({ compact, className, onTypeAttempt }: { compact?: boolconst 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" });+ setView({ frame: first, under: null, typed: "", steps: [], keepPulse: false, compare: null, pill: "Live" });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 }));+ setView((v) => ({ ...v, under: v.frame === s.frame ? v.under : v.frame, frame: s.frame, pill: s.live ? "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)));@@ -115,7 +116,7 @@ export function LiveDemo({ compact, className, onTypeAttempt }: { compact?: boolsetView((v) => ({ ...v, keepPulse: true }));await wait(380);typed = "";- setView((v) => ({ ...v, keepPulse: false, typed: "", steps: [...v.steps, s.label], pill: "Kept ✓ · 1024" }));+ setView((v) => ({ ...v, keepPulse: false, typed: "", steps: [...v.steps, s.label], pill: "Kept ✓" }));await wait(s.ms - 380);} else if (s.type === "compare") {const t0 = performance.now();@@ -163,7 +164,7 @@ export function LiveDemo({ compact, className, onTypeAttempt }: { compact?: bool</>))}<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={cn("absolute inline-flex items-center gap-1.5 rounded-full bg-black/45 font-medium backdrop-blur", compact ? "top-1.5 left-1.5 px-2 py-0.5 text-[10.5px]" : "top-3 left-3 px-2.5 py-1 text-[11px]")} role="status" aria-live="off"><span className="size-1.5 animate-pulse rounded-full bg-emerald-400" />{view.pill}</span>@@ -182,16 +183,17 @@ export function LiveDemo({ compact, className, onTypeAttempt }: { compact?: booltype="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]")}+ className={cn("flex min-w-0 flex-1 items-center gap-2 rounded-xl bg-white/12 text-left ring-1 ring-white/15 backdrop-blur-md", compact ? "h-8 px-2 text-[11.5px]" : "h-11 px-3 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>+ <Zap className={cn("shrink-0 text-amber-300", compact ? "size-3" : "size-3.5")} />+ {/* The end of the text stays in view as it grows. */}+ <span className={cn("flex min-w-0 overflow-hidden whitespace-nowrap", view.typed && "justify-end")}>{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")}>+ <span className={cn("inline-flex shrink-0 items-center justify-center gap-1 rounded-xl bg-white font-medium text-black transition-transform", compact ? "size-8" : "h-11 px-3.5 text-[13px]", view.keepPulse && "scale-95 ring-4 ring-primary/60")} aria-label={compact ? "Keep" : undefined}>{view.steps.length && !view.typed ? <Check className="size-3.5" /> : <CornerDownLeft className="size-3.5" />}- Keep+ {!compact && "Keep"}</span></div></div>diff --git a/src/components/live/live-editor.tsx b/src/components/live/live-editor.tsxindex f97c4ea3..0f8ad780 100644--- a/src/components/live/live-editor.tsx+++ b/src/components/live/live-editor.tsx@@ -39,7 +39,7 @@ import { restoreStack, StepStack, type Method, type Step } from "@/lib/live/stepimport { 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";+import { idbDel, idbGet, idbPrune, idbPut } from "./live-store";/*** Live edit: change a picture as you type. The text box drives throwaway live frames (small WebP, a few hundred@@ -104,6 +104,23 @@ interface Try {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"}`;+/** Remembered dismissals (this browser only). */+const HIGHVRAM_HINT = "fuobe-live-hint:highvram";+const HOLD_HINT = "fuobe-live-hint:hold";++/** The masters stored in this browser that any saved session still refers to. */+function idbInUse(): Set<string> {+ const keep = new Set<string>();+ try {+ for (let i = 0; i < localStorage.length; i++) {+ const k = localStorage.key(i);+ if (!k?.startsWith("fuobe-live:")) continue;+ const st = load<{ stack?: { steps?: { master?: { idb?: unknown } }[] } }>(k);+ for (const step of st?.stack?.steps ?? []) if (typeof step?.master?.idb === "string") keep.add(step.master.idb);+ }+ } catch {}+ return keep;+}/** What the page shows of the kept steps (a snapshot: the stack itself lives in a ref and changes in handlers). */interface StackView {@@ -196,7 +213,7 @@ export function LiveEditor(props: LiveEditorProps) {const [lastMs, setLastMs] = useState<number | null>(null);const [keptFlash, setKeptFlash] = useState(false);const [hidden, setHidden] = useState(false);- const [highvramHint, setHighvramHint] = useState(true);+ const [highvramHint, setHighvramHint] = useState(() => load<boolean>(HIGHVRAM_HINT) !== false);// Compare and tools.const [hold, setHold] = useState<"prev" | "orig" | null>(null);@@ -249,8 +266,9 @@ export function LiveEditor(props: LiveEditorProps) {return;}if (s.master.idb) {- const bytes = await idbGet(s.master.idb);- if (bytes) await transport.stageBytes(bytes, "master");+ const key = s.master.idb;+ const bytes = await idbGet(key);+ if (bytes) await transport.stageBytes(bytes, "master", () => idbGet(key));}},[transport],@@ -282,6 +300,8 @@ export function LiveEditor(props: LiveEditorProps) {setPhase({ s: "setup", facts: r });return;}+ // Masters this browser kept for steps no saved session refers to any more go.+ void idbPrune(idbInUse());// 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();@@ -509,13 +529,42 @@ export function LiveEditor(props: LiveEditorProps) {// ---------------------------------------------------------------------------// Keeping, undo and redo+ /**+ * Let go of this tab's copies of older masters that the server keeps (the step trail and undo read them from their+ * file): only the newest few, the original and the step before stay in memory.+ */+ const releaseBlobs = () => {+ const s = stack.current;+ const near = new Set([s.head, s.previous(), s.original, ...s.path().slice(-4)].flatMap((x) => (x ? [x.master.name] : [])));+ const drop: string[] = [];+ for (const [name, url] of masterUrls.current) {+ const step = s.all.find((x) => x.master.name === name);+ if (near.has(name) || !step?.master.url || !url.startsWith("blob:")) continue;+ // A settled frame's picture is also the render cache's: that one is let go when the cache drops it.+ if (![...cache.current.values()].some((c) => c.url === url)) URL.revokeObjectURL(url);+ masterUrls.current.delete(name);+ drop.push(name);+ }+ if (drop.length)+ setUrls((u) => {+ const next = { ...u };+ for (const n of drop) delete next[n];+ return next;+ });+ };+const [keeping, setKeeping] = useState(false);+ /** A keep is running (a ref: two Enters in one tick must not both start one). */+ const keepingRef = useRef(false);const keep = async (choice?: { text: string; seed: number }, download = false) => {- if (keeping || phase.s !== "ready") return;+ if (keepingRef.current || phase.s !== "ready") return;const t = choice?.text ?? textRef.current;if (!normalize(t)) return;const keepSeed = choice?.seed ?? seedRef.current;+ keepingRef.current = true;+ // The step joins the head it started from (undo, redo and a new picture wait until the keep is done).+ const parent = stack.current.head?.id ?? null;setKeeping(true);clearTimeout(idle.current);clearTimeout(settle.current);@@ -544,20 +593,27 @@ export function LiveEditor(props: LiveEditorProps) {let name = out.masterName;let idb: string | undefined;let local = false;+ // Where the master lives once this tab lets its copy go: the server's file, or this browser's.+ const where: { url?: string; idb?: string } = {};if (!name) {- const st = await transport.stageBytes(out.data, "master");+ const st = await transport.stageBytes(out.data, "master", async () => (where.url ? dataUrlBytes(where.url) : where.idb ? idbGet(where.idb) : null));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.+ // The computer path: the server keeps the master; this browser keeps it until then, and only if it can't.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;+ if (url) {+ void idbDel(idb);+ idb = undefined;+ } else local = true;}+ where.url = url;+ where.idb = idb;const step = stack.current.keep({text: t,norm: normalize(t),@@ -568,8 +624,9 @@ export function LiveEditor(props: LiveEditorProps) {master: { name, w: size.w, h: size.h, sha256: out.sha256, format: "png", ...(url && { url }), ...(idb && { idb }) },ms: out.ms,...(local && { local: true }),- });+ }, parent);bump();+ releaseBlobs();setText("");textRef.current = "";setTries([]);@@ -579,15 +636,22 @@ export function LiveEditor(props: LiveEditorProps) {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." });+ // Once, on a touch screen: how to compare.+ if (load<boolean>(HOLD_HINT) === null && window.matchMedia?.("(pointer: coarse)").matches) {+ save(HOLD_HINT, true);+ toast.message("Press and hold the picture to see the step before", { description: "The … menu compares with the original too." });+ }} catch (e) {toast.error((e as Error).message);} finally {+ keepingRef.current = false;setKeeping(false);setBusy(null);}};const move = async (to: "undo" | "redo" | string) => {+ if (keepingRef.current) return;const s = stack.current;const step = to === "undo" ? s.undo() : to === "redo" ? s.redo() : s.jump(to);if (!step) return;@@ -621,6 +685,10 @@ export function LiveEditor(props: LiveEditorProps) {// Pictures in: a file, a paste, a dropconst addFile = async (file: File) => {+ if (keepingRef.current) {+ toast.message("One moment: keeping the change");+ return;+ }if (!/^image\/(png|jpeg|webp)$/.test(file.type)) {toast.error("Add a PNG, JPEG or WebP picture");return;@@ -767,9 +835,12 @@ export function LiveEditor(props: LiveEditorProps) {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 label = link ? "Live (slower over a link)" : "Live";+ // A kept picture's size is on its badge; the pill tells the live size and time only for live and settled frames.+ if (!shown || shown.kind === "master") return { tone: busy ? "busy" : "ok", text: label };+ const size = shown.kind === "live" ? sizeShown : Math.max(shown.w, shown.h);+ return { tone: busy ? "busy" : "ok", text: label, detail: `${size}${lastMs !== null ? ` · ${(lastMs / 1000).toFixed(2)} s` : ""}` };+ })() as { tone: string; text: string; detail?: string };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;@@ -795,7 +866,7 @@ export function LiveEditor(props: LiveEditorProps) {}}>{/* Top bar */}- <header className={cn("flex shrink-0 items-center gap-1.5 px-3 sm:px-4", embedded ? "h-12" : "h-14")}>+ <header className={cn("flex min-w-0 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" />@@ -805,8 +876,8 @@ export function LiveEditor(props: LiveEditorProps) {<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">+ <StatusPill tone={pill.tone} text={pill.text} detail={pill.detail} progress={busy?.progress} />+ <div className="ml-auto flex shrink-0 items-center gap-0.5"><ToolButton label="Undo" keys="Ctrl+Z" onClick={() => void move("undo")} disabled={!view.canUndo}><Undo2 /></ToolButton>@@ -816,10 +887,10 @@ export function LiveEditor(props: LiveEditorProps) {<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)}>+ <ToolButton label="Shuffle" keys="R" onClick={shuffle} disabled={!normalize(text)} className="max-sm:hidden"><Shuffle /></ToolButton>- <ToolButton label={mask ? "Change the painted region" : "Paint a region"} keys="B" onClick={() => setBrushOpen(true)} disabled={!hasPicture} active={!!mask}>+ <ToolButton label={mask ? "Change the painted region" : "Paint a region"} keys="B" onClick={() => setBrushOpen(true)} disabled={!hasPicture} active={!!mask} className="max-sm:hidden"><Brush /></ToolButton><ToolButton label={liveOn ? "Live on" : "Live off"} keys="L" onClick={toggleLive} active={!liveOn} className="max-sm:hidden">@@ -838,15 +909,26 @@ export function LiveEditor(props: LiveEditorProps) {method={method}setMethod={setMethod}onKeys={() => setKeysOpen(true)}+ phone={{+ shuffle: normalize(text) ? shuffle : undefined,+ brush: hasPicture ? () => setBrushOpen(true) : undefined,+ brushLabel: mask ? "Change the painted region" : "Paint a region",+ compare: previous || original ? () => setCompareOpen(true) : undefined,+ liveOn,+ toggleLive,+ download: current ? download : undefined,+ save: !embedded && props.canSave && head?.master.url && path.length > 1 ? () => void saveToLibrary() : undefined,+ fullScreen: embedded ? `/live-edit${image ? `?image=${encodeURIComponent(image)}&from=edit` : "?from=edit"}` : undefined,+ }}/>- <ToolButton label="Download" keys="D" onClick={download} disabled={!current}>+ <ToolButton label="Download" keys="D" onClick={download} disabled={!current} className="max-sm:hidden"><Download /></ToolButton>{embedded ? (<><Tooltip><TooltipTrigger asChild>- <Button size="sm" variant="ghost" asChild>+ <Button size="sm" variant="ghost" asChild className="max-sm:hidden"><Link href={`/live-edit${image ? `?image=${encodeURIComponent(image)}&from=edit` : "?from=edit"}`} aria-label="Full screen"><Expand className="size-4" /></Link>@@ -854,8 +936,9 @@ export function LiveEditor(props: LiveEditorProps) {</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 size="sm" onClick={() => head?.master.url && props.onUse?.(head.master.url)} disabled={!head?.master.url || path.length < 2} className="ml-1 max-sm:px-2.5">+ <span className="max-sm:hidden">Use in Edit</span>+ <span className="sm:hidden">Use</span></Button>{props.onClose && (<ToolButton label="Close live" onClick={props.onClose}>@@ -884,14 +967,6 @@ export function LiveEditor(props: LiveEditorProps) {{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 */}@@ -925,9 +1000,11 @@ export function LiveEditor(props: LiveEditorProps) {{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>+ {(tries.length > 0 || hasPicture) && (+ // The row keeps its height from the start, so the picture doesn't move when the first try comes in.+ <div className="mt-2 flex h-[46px] items-center gap-1.5 overflow-x-auto pb-0.5" data-live-tries={tries.length > 0 ? "" : undefined}><span className="shrink-0 text-[11.5px] font-medium text-muted-foreground">Tries</span>+ {tries.length === 0 && <span className="truncate text-[11.5px] text-subtle-foreground">Pause while typing and each take lands here. Click one to keep it.</span>}{tries.map((t) => (<Tooltip key={t.key}><TooltipTrigger asChild>@@ -939,11 +1016,29 @@ export function LiveEditor(props: LiveEditorProps) {<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>+ {tries.length > 0 && (+ <span className="shrink-0 text-[11.5px] text-muted-foreground max-sm:hidden">+ <Kbd>R</Kbd> for another+ </span>+ )}</div>)}+ {facts?.highvram === false && highvramHint && phase.s === "ready" && (+ <p className="mt-1.5 flex items-center gap-1.5 text-[12px] text-muted-foreground" data-live-highvram>+ <span className="min-w-0 flex-1 truncate">Faster: start ComfyUI with --highvram (live frames take about twice as long without it).</span>+ <button+ type="button"+ onClick={() => {+ setHighvramHint(false);+ save(HIGHVRAM_HINT, false);+ }}+ className="shrink-0 rounded p-0.5 hover:bg-accent"+ aria-label="Dismiss"+ >+ <X className="size-3.5" />+ </button>+ </p>+ )}{!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.@@ -974,19 +1069,23 @@ export function downloadUrl(url: string, name: string) {// ---------------------------------------------------------------------------// Parts-function StatusPill({ tone, text, progress }: { tone: string; text: string; progress?: number }) {+/** The live status. `detail` (size and time) is left out on phones, where the picture's badge has the size. */+function StatusPill({ tone, text, detail, progress }: { tone: string; text: string; detail?: string; progress?: number }) {return (<spanrole="status"data-live-pillclassName={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]",+ "relative ml-1 inline-flex h-7 min-w-0 shrink items-center gap-1.5 overflow-hidden rounded-full border px-2.5 text-[12px] font-medium whitespace-nowrap tabular-nums",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>+ <span className="truncate">+ {text}+ {detail && <span className="max-sm:hidden"> · {detail}</span>}+ </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>);@@ -1096,7 +1195,26 @@ function Settings(p: {method: Method;setMethod: (m: Method) => void;onKeys: () => void;+ /** On phones the header keeps Undo, Redo and this menu: the other actions are here. */+ phone: {+ shuffle?: () => void;+ brush?: () => void;+ brushLabel: string;+ compare?: () => void;+ liveOn: boolean;+ toggleLive: () => void;+ download?: () => void;+ save?: () => void;+ fullScreen?: string;+ };}) {+ const [open, setOpen] = useState(false);+ const act = (fn?: () => void) => () => {+ setOpen(false);+ fn?.();+ };+ const item = "flex h-9 w-full items-center gap-2.5 rounded-lg px-2 text-left text-[13.5px] hover:bg-accent disabled:opacity-40 [&_svg]:size-4 [&_svg]:text-muted-foreground";+ const ph = p.phone;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">@@ -1108,7 +1226,7 @@ function Settings(p: {</div>);return (- <Popover>+ <Popover open={open} onOpenChange={setOpen}><Tooltip><TooltipTrigger asChild><PopoverTrigger asChild>@@ -1119,7 +1237,41 @@ function Settings(p: {</TooltipTrigger><TooltipContent>Settings</TooltipContent></Tooltip>- <PopoverContent align="end" className="w-80 text-[13px]">+ <PopoverContent align="end" className="w-80 max-w-[calc(100vw-24px)] text-[13px]">+ <div className="-mx-1 mb-2 grid gap-0.5 border-b pb-2 sm:hidden" data-live-phone-menu>+ {ph.save && (+ <button type="button" className={item} onClick={act(ph.save)}>+ <Save />+ Save to your Library+ </button>+ )}+ <button type="button" className={item} onClick={act(ph.compare)} disabled={!ph.compare}>+ <ArrowLeftRight />+ Compare+ </button>+ <button type="button" className={item} onClick={act(ph.brush)} disabled={!ph.brush}>+ <Brush />+ {ph.brushLabel}+ </button>+ <button type="button" className={item} onClick={act(ph.shuffle)} disabled={!ph.shuffle}>+ <Shuffle />+ Shuffle: another take+ </button>+ <button type="button" className={item} onClick={act(ph.toggleLive)} aria-pressed={!ph.liveOn}>+ {ph.liveOn ? <ZapOff /> : <Zap />}+ {ph.liveOn ? "Pause live" : "Live on"}+ </button>+ <button type="button" className={item} onClick={act(ph.download)} disabled={!ph.download}>+ <Download />+ Download+ </button>+ {ph.fullScreen && (+ <Link href={ph.fullScreen} className={item} onClick={() => setOpen(false)}>+ <Expand />+ Full screen+ </Link>+ )}+ </div><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)}@@ -1241,8 +1393,10 @@ export function LiveSetup({ facts, computer }: { facts: LiveFacts; computer: boo<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's live nodes</p>- <p className="mt-1 text-muted-foreground">One file for ComfyUI's custom_nodes folder (fuobe_live.py). Then restart ComfyUI.</p>+ <p className="font-medium">{facts.outdated ? "Update Fuobe's live nodes" : "Add Fuobe's live nodes"}</p>+ <p className="mt-1 text-muted-foreground">+ {facts.outdated ? "ComfyUI has another copy of fuobe_live.py. Put this one in its place in custom_nodes, then restart ComfyUI." : "One file for ComfyUI'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" />diff --git a/src/components/live/live-store.ts b/src/components/live/live-store.tsindex 826d119d..d7790fab 100644--- a/src/components/live/live-store.ts+++ b/src/components/live/live-store.ts@@ -51,3 +51,34 @@ export async function idbGet(key: string): Promise<Uint8Array | null> {}});}++export async function idbDel(key: string): Promise<void> {+ const db = await open();+ if (!db) return;+ await new Promise<void>((resolve) => {+ try {+ const tx = db.transaction(STORE, "readwrite");+ tx.objectStore(STORE).delete(key);+ tx.oncomplete = () => resolve();+ tx.onerror = () => resolve();+ } catch {+ resolve();+ }+ });+}++/** Delete every stored master no session refers to any more (`keep`: the keys still in use). */+export async function idbPrune(keep: ReadonlySet<string>): Promise<void> {+ const db = await open();+ if (!db) return;+ const keys = await new Promise<IDBValidKey[]>((resolve) => {+ try {+ const req = db.transaction(STORE, "readonly").objectStore(STORE).getAllKeys();+ req.onsuccess = () => resolve(req.result);+ req.onerror = () => resolve([]);+ } catch {+ resolve([]);+ }+ });+ for (const k of keys) if (typeof k === "string" && !keep.has(k)) await idbDel(k);+}diff --git a/src/components/live/live-transport.ts b/src/components/live/live-transport.tsindex 3cf62af7..9e4c8224 100644--- a/src/components/live/live-transport.ts+++ b/src/components/live/live-transport.ts@@ -1,11 +1,12 @@"use client";+import { LIVE_NODES_VERSION, liveNodesState } from "@/lib/comfy-live-nodes";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 { LiveScheduler, RENDER_DEADLINE_MS, 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";@@ -19,7 +20,14 @@ import { imageSize } from "@/lib/image-size";* - 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.+ *+ * Every render ends: by its picture, an error, a stop, ComfyUI finishing without a picture, ComfyUI no longer having+ * the prompt, or a deadline.*/+/** How often a render that hasn't finished checks that ComfyUI still has it. */+const GONE_CHECK_MS = 4000;+/** Staged pictures whose bytes this tab keeps in memory (older ones are read again from their file). */+const COPIES_KEPT = 6;export interface RenderReq {seq: number;@@ -65,6 +73,8 @@ export interface StagedPicture {export interface LiveFacts {nodes: number;+ /** ComfyUI has another copy of the live nodes (an older or changed file): it needs this one. */+ outdated?: boolean;highvram: boolean | null;/** Model files ComfyUI doesn't list (folder/file). */missing: string[];@@ -84,8 +94,11 @@ export interface LiveTransport {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>;+ /**+ * Stage bytes made here (a painted mask; on the computer path, a kept master). `reread` gets them back once this tab+ * has let its copy go (a master's file or this browser's copy).+ */+ stageBytes(bytes: Uint8Array, kind: "mask" | "master", reread?: () => Promise<Uint8Array | null>): 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). */@@ -112,21 +125,25 @@ export class ServerTransport implements LiveTransport {private listeners = new Set<(s: TransportStatus) => void>();private status: TransportStatus = { online: false, running: null, queue: 0, otherRan: false };+ /** Its own session, every time (never one another tab or editor might hold: their renders would knock out each other's). */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 };+ const res = await fetch("/api/live/session", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });+ const j = (await res.json().catch(() => ({}))) as { sessionId?: string; mode?: "server" | "link"; seed?: number; nodes?: { version?: number; outdated?: boolean }; 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 };+ if (this.closed) {+ this.end(j.sessionId);+ return { ok: false, error: "Closed", code: "closed" };+ }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 ?? [] };+ return { ok: true, seed: j.seed ?? 0, nodes: j.nodes?.version ?? 0, outdated: !!j.nodes?.outdated, highvram: j.highvram ?? null, missing: j.missing ?? [] };+ }++ private closed = false;++ private end(id: string) {+ void fetch("/api/live/session", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: id, end: true }), keepalive: true }).catch(() => {});}private listen() {@@ -216,9 +233,11 @@ export class ServerTransport implements LiveTransport {}close(): void {+ this.closed = true;this.cancel(() => true);this.es?.close();this.es = null;+ if (this.sessionId) this.end(this.sessionId);}}@@ -253,8 +272,11 @@ export class ChannelTransport implements LiveTransport {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 }>();+ /**+ * Names this tab staged, with its own copy of the newest ones' bytes and a way to read the others again (to stage+ * them again after ComfyUI restarts). Old copies are let go, so a long session doesn't fill the tab's memory.+ */+ private names = new Map<string, { bytes?: Uint8Array; reread?: () => Promise<Uint8Array | null>; 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 };@@ -294,14 +316,16 @@ export class ChannelTransport implements LiveTransport {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 answer = await this.get("/fuobe/live").then(async (r) => (r.ok ? ((await r.json()) as unknown) : null)).catch(() => null);+ const state = liveNodesState(answer);+ const nodes = state === "ok" ? LIVE_NODES_VERSION : 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 };+ return { ok: true, seed: Math.floor(Math.random() * 2 ** 31), nodes, outdated: state === "outdated", 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" };}@@ -350,7 +374,11 @@ export class ChannelTransport implements LiveTransport {return;}const w = "promptId" in e && e.promptId ? this.waiters.get(e.promptId) : undefined;- if (!w) return;+ if (!w) {+ // One of this tab's, stopped, that started anyway: interrupt it now that it is ours running.+ if (e.type === "execution_start" && this.stopped.delete(e.promptId)) void this.post("/interrupt", { prompt_id: e.promptId }).catch(() => {});+ return;+ }if (e.type === "execution_start") {w.started = true;w.startedAt = performance.now();@@ -360,6 +388,8 @@ export class ChannelTransport implements LiveTransport {} 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"));+ // Finished and no picture came (it is always sent first): an old copy of the nodes served from ComfyUI's cache.+ else if (e.type === "success" || (e.type === "executing" && e.node === null)) w.reject(fail("ComfyUI finished without sending the picture. Update Fuobe's live nodes.", "failed"));};}@@ -381,31 +411,54 @@ export class ChannelTransport implements LiveTransport {if (!res.ok) throw fail(`ComfyUI refused the picture (${res.status})`, "failed");}- private async stage(bytes: Uint8Array): Promise<StagedPicture> {+ private async stage(bytes: Uint8Array, reread?: () => Promise<Uint8Array | null>): 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 };+ if (had) {+ // Newest again: it moves to the end, and keeps its bytes for now.+ this.names.delete(name);+ this.names.set(name, { ...had, bytes, reread: reread ?? had.reread });+ this.trim();+ 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 });+ this.names.set(name, { bytes, reread, type: PICTURE_TYPES[ext], w: size.w, h: size.h, sha256 });await this.upload(name, bytes, PICTURE_TYPES[ext]);+ this.trim();return { name, w: size.w, h: size.h, sha256 };}+ /** Let go of all but the newest copies that can be read again. */+ private trim() {+ const held = [...this.names.values()].filter((x) => x.bytes && x.reread);+ for (const x of held.slice(0, Math.max(0, held.length - COPIES_KEPT))) x.bytes = undefined;+ }++ /** A staged picture's bytes: this tab's copy, or read again. */+ private async bytesOf(name: string): Promise<Uint8Array | null> {+ const c = this.names.get(name);+ if (!c) return null;+ return c.bytes ?? (c.reread ? await c.reread().catch(() => null) : null);+ }+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()));+ const read = async () => {+ const res = await fetch(url);+ if (!res.ok) throw new Error("Couldn't read the picture");+ return new Uint8Array(await res.arrayBuffer());+ };+ return this.stage(await read(), url.startsWith("/api/files/") ? read : undefined);}- stageBytes(bytes: Uint8Array): Promise<StagedPicture> {- return this.stage(bytes);+ stageBytes(bytes: Uint8Array, _kind: "mask" | "master", reread?: () => Promise<Uint8Array | null>): Promise<StagedPicture> {+ return this.stage(bytes, reread);}render(req: RenderReq, onEvent: (e: LiveEvent) => void): Promise<RenderResult> {@@ -455,15 +508,57 @@ export class ChannelTransport implements LiveTransport {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);+ const bytes = await this.bytesOf(n);+ if (!c || !bytes) throw fail("A picture of this session is gone. Add it again.", "missing-input");+ await this.upload(n, bytes, c.type);}} else throw e;}}}+ /** Whether ComfyUI still has a prompt, waiting or running (null: it couldn't be asked). */+ private async inQueue(id: string): Promise<boolean | null> {+ try {+ const r = await this.get("/queue");+ if (!r.ok) return null;+ const q = (await r.json()) as { queue_running?: unknown[][]; queue_pending?: unknown[][] };+ return [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].some((row) => Array.isArray(row) && row[1] === id);+ } catch {+ return null;+ }+ }++ /** Ours, stopped before they were seen to start: interrupted if they start after all. */+ private stopped = new Set<string>();++ /**+ * Take a prompt of this tab's off ComfyUI: deleted if it waits, interrupted if it runs. An interrupt goes only to a+ * prompt seen running (an older ComfyUI stops whatever runs); one not seen to start is interrupted if it starts.+ */+ private takeOff(id: string, started: boolean) {+ void this.post("/queue", { delete: [id] }).catch(() => {});+ if (started) void this.post("/interrupt", { prompt_id: id }).catch(() => {});+ else {+ this.stopped.add(id);+ if (this.stopped.size > 200) this.stopped.delete(this.stopped.values().next().value!);+ }+ }++ /** End a render of ours that is still waited on. */+ private end(id: string, e: Error) {+ const w = this.waiters.get(id);+ if (!w) return;+ const started = w.started;+ w.reject(e);+ this.takeOff(id, started);+ }+private async once(job: ChannelJob, signal: AbortSignal): Promise<RenderOut> {+ if (signal.aborted) throw fail("Stopped", "stopped");if (!(await this.online_(3000))) throw fail("Can't reach ComfyUI. Reconnecting…", "offline");+ // Stopped while waiting for the socket: nothing was sent.+ if (signal.aborted) throw fail("Stopped", "stopped");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()];@@ -492,26 +587,38 @@ export class ChannelTransport implements LiveTransport {});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(() => {});- };+ const stop = () => this.end(id, fail("Stopped", "stopped"));signal.addEventListener("abort", stop, { once: true });+ const deadline = setTimeout(() => this.end(id, fail("ComfyUI took too long with this render", "failed")), RENDER_DEADLINE_MS[job.req.slot]);+ // A prompt ComfyUI dropped without a word (a cleared queue, a restart): gone twice in a row.+ let gone = 0;+ const watch = setInterval(() => {+ if (!this.waiters.has(id)) return;+ void this.inQueue(id).then((has) => {+ gone = has === false ? gone + 1 : 0;+ if (gone >= 2) this.waiters.get(id)?.reject(fail("ComfyUI dropped the render", "failed"));+ });+ }, GONE_CHECK_MS);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 });+ 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 });+ } catch {+ this.waiters.get(id)?.reject(fail("Can't reach ComfyUI", "offline"));+ }+ // Stopped while the prompt was on its way: the first delete may have arrived before it.+ if (signal.aborted) this.takeOff(id, false);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 {+ clearTimeout(deadline);+ clearInterval(watch);signal.removeEventListener("abort", stop);void this.post("/history", { delete: [id] }).catch(() => {});}diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex 752fb01e..5b0611a4 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -465,7 +465,16 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabsheader={config.live ? (<>- {header}+ {/* Live always runs on the viewer's GPU: the engine switch has no say while it is on. */}+ {live ? (+ <span className="inline-flex cursor-not-allowed" title="Live runs on your GPU">+ <span className="pointer-events-none inline-flex opacity-40" aria-disabled>+ {header}+ </span>+ </span>+ ) : (+ header+ )}<LiveSwitch on={live} onChange={setLive} /></>) : (diff --git a/src/lib/comfy-install.ts b/src/lib/comfy-install.tsindex 591d824d..b2921a3b 100644--- a/src/lib/comfy-install.ts+++ b/src/lib/comfy-install.ts@@ -181,7 +181,7 @@ export function psBase64(b64: string): string {}/** Single quotes in a PowerShell string. */-const ps =(s: string) => `'${s.replaceAll("'", "''")}'`;+const ps = (s: string) => `'${s.replaceAll("'", "''")}'`;/*** "Start ComfyUI for Fuobe.bat", made in the browser for the port and this site: it finds the ComfyUI listening on thediff --git a/src/lib/comfy-live-nodes.ts b/src/lib/comfy-live-nodes.tsindex 720406df..f70129f3 100644--- a/src/lib/comfy-live-nodes.ts+++ b/src/lib/comfy-live-nodes.ts@@ -19,7 +19,7 @@export const LIVE_NODES_FILE_NAME = "fuobe_live.py";/** Its version, as GET /fuobe/live answers it. */-export const LIVE_NODES_VERSION = 1;+export const LIVE_NODES_VERSION = 2;/** The node pack's name in the requirement index. */export const LIVE_PACK = "fuobe-live";@@ -34,6 +34,7 @@ They read only Fuobe-named pictures in the input folder and send nothing anywherTo remove them, delete this file and restart ComfyUI."""import asyncio+import hashlibimport ioimport jsonimport math@@ -48,9 +49,19 @@ import torch.nn.functional as Ffrom PIL import Image, ImageOpsFUOBE_LIVE = ${LIVE_NODES_VERSION}+try:+ with open(__file__, "rb") as _f:+ FUOBE_LIVE_SHA256 = hashlib.sha256(_f.read()).hexdigest()+except Exception:+ FUOBE_LIVE_SHA256 = ""NAME = re.compile(r"^fuobe_[A-Za-z0-9_-]{8,24}\.(png|jpg|jpeg|webp)$")MAX_REFERENCES = 4MAX_SIDE = 4096+# Detail transfer: the local correlation of the two pictures' fine detail at which the base's detail starts to come+# back, and at which it fully does.+CORR_LOW = 0.25+CORR_HIGH = 0.6+SPLIT = 2.0# ---------------------------------------------------------------------------@@ -109,17 +120,67 @@ def from_lab(lab):return torch.where(c > 0.0031308, 1.055 * c.clamp(min=1e-8) ** (1.0 / 2.4) - 0.055, 12.92 * c).clamp(0.0, 1.0)-def change_mask(base, edited, threshold=0.06, feather=24, blur=5, grow=8):- """Where the edit changed the picture: per-pixel Lab difference over threshold*100, grown and feathered. [B,H,W] 0..1."""- d = torch.linalg.vector_norm(to_lab(base) - to_lab(edited), dim=-1)[:, None]- d = _gauss(d, blur / 2.0)+def _blur_img(img, sigma):+ """Blur a [B,H,W,C] picture with a separable Gaussian, channel by channel."""+ if sigma <= 0:+ return img+ b, h, w, c = img.shape+ x = img.movedim(-1, 1).reshape(b * c, 1, h, w)+ return _gauss(x, sigma).reshape(b, c, h, w).movedim(1, -1)+++def luma(img):+ """[B,H,W,3] to [B,1,H,W] (Rec. 709 weights)."""+ w = torch.tensor([0.2126, 0.7152, 0.0722], dtype=img.dtype, device=img.device)+ return (img @ w)[:, None]+++def change_mask(base, edited, threshold=0.06, feather=24, blur=3, grow=8):+ """Where the edit changed the picture: both pictures blurred first (so noise, re-made texture and resampling+ differences cancel instead of adding up), their Lab difference over threshold*100, specks removed, grown and+ feathered. Same-size inputs. [B,H,W] 0..1."""+ s = blur / 2.0+ d = torch.linalg.vector_norm(to_lab(_blur_img(base, s)) - to_lab(_blur_img(edited, s)), dim=-1)[:, None]m = (d > threshold * 100.0).to(base.dtype)+ m = -F.max_pool2d(-m, kernel_size=3, stride=1, padding=1)if grow > 0:m = F.max_pool2d(m, kernel_size=2 * grow + 1, stride=1, padding=grow)m = _gauss(m, feather / 3.0).clamp(0.0, 1.0)return m[:, 0]+def resize_mask(m, w, h):+ """A [B,H,W] mask to w x h (bilinear: no ringing, and zeros stay exactly zero)."""+ if m.shape[1] == h and m.shape[2] == w:+ return m+ x = F.interpolate(m[:, None], size=(h, w), mode="bilinear", align_corners=False)[:, 0]+ return torch.where(x < 1.0 / 1024.0, torch.zeros_like(x), x.clamp(0.0, 1.0))+++def detail_transfer(base, ed, edited):+ """The base's finest detail back where the edit kept the base's structure. base: the region at full size; ed: the+ edit at that size (colour matched); edited: the edit at the size it was made. An edit made smaller than the base+ and through a VAE has soft or re-made fine detail. The structure check runs at the edit's own size: where both+ pictures' finest detail there lines up (local correlation), the detail finer than the edit could hold comes from+ the base, scaled by the edit's new light. Where the edit made new detail (an object, a texture, a style) or took+ some away, its own stays."""+ rh, rw = base.shape[1], base.shape[2]+ eh, ew = edited.shape[1], edited.shape[2]+ cw, ch = (ew, eh) if ew * eh <= rw * rh else (rw, rh)+ bs, es = resize(base, cw, ch), resize(edited, cw, ch)+ yb, ye = luma(bs - _blur_img(bs, 1.0)), luma(es - _blur_img(es, 1.0))+ cov = _gauss(yb * ye, 2.0)+ vb = _gauss(yb * yb, 2.0)+ ve = _gauss(ye * ye, 2.0)+ corr = cov / torch.sqrt(vb * ve + 1e-10)+ w = ((corr - CORR_LOW) / (CORR_HIGH - CORR_LOW)).clamp(0.0, 1.0)+ w = resize_mask(w[:, 0], rw, rh)[..., None]+ low_b = _blur_img(resize(bs, rw, rh), SPLIT * rw / float(cw))+ low_e = _blur_img(ed, SPLIT * rw / float(cw))+ gain = ((luma(low_e) + 0.02) / (luma(low_b) + 0.02)).clamp(0.5, 2.0).movedim(1, -1)+ return (low_e + w * gain * (base - low_b) + (1.0 - w) * (ed - low_e)).clamp(0.0, 1.0)++def lab_match(edited, base, keep):"""Move the edit's per-channel Lab mean and spread toward the base's, measured where nothing changed (keep > 0.5)."""sel = keep > 0.5@@ -163,33 +224,54 @@ def crop_box(mask, width, height, context=1.6, multiple=32):return (bx0, by0, bx0 + w, by0 + h)-def paste_back(base, edited, mode="auto", threshold=0.06, feather=24, match_color=True, out_max_side=0, box=None, mask=None):- """The edit, back on the full-size base. mode auto: only what changed; mask: the painted region; off: the whole edit."""+def paste_back(base, edited, mode="auto", threshold=0.06, feather=24, match_color=True, out_max_side=0, box=None, mask=None, detail=True):+ """The edit, back on the full-size base. mode auto: only what changed; mask: the painted region; off: the whole edit.+ Where the result takes the edit, the base's fine detail comes back where the edit kept its structure (detail)."""base = base[:1, :, :, :3]edited = edited[:1, :, :, :3]H, W = base.shape[1], base.shape[2]x0, y0, x1, y1 = box if box is not None else (0, 0, W, H)+ if out_max_side and max(W, H) > out_max_side:+ # A live frame (thrown away): composited at its own small size.+ s = out_max_side / float(max(W, H))+ W2, H2 = max(32, int(round(W * s))), max(32, int(round(H * s)))+ sx, sy = W2 / float(W), H2 / float(H)+ base = resize(base, W2, H2)+ x0, x1 = int(round(x0 * sx)), max(int(round(x0 * sx)) + 1, int(round(x1 * sx)))+ y0, y1 = int(round(y0 * sy)), max(int(round(y0 * sy)) + 1, int(round(y1 * sy)))+ x1, y1 = min(W2, x1), min(H2, y1)+ feather = max(1, int(round(feather * s)))+ W, H = W2, H2region = base[:, y0:y1, x0:x1]- ed = resize(edited, x1 - x0, y1 - y0)+ rh, rw = region.shape[1], region.shape[2]+ eh, ew = edited.shape[1], edited.shape[2]+ ed = resize(edited, rw, rh)if mode == "off":- m = torch.ones(region.shape[:3], dtype=base.dtype, device=base.device)- match_color = False- elif mode == "mask" and mask is not None:+ return _place(base, ed, x0, y0, torch.ones(region.shape[:3], dtype=base.dtype, device=base.device))+ if mode == "mask" and mask is not None:mm = resize(mask[:1, :, :, :1].expand(1, -1, -1, 3), W, H)[..., 0]mm = mm[:, y0:y1, x0:x1]m = _gauss((mm > 0.5).to(base.dtype)[:, None], feather / 3.0)[:, 0].clamp(0.0, 1.0)else:- m = change_mask(region, ed, threshold, feather)+ # Compared at the smaller of the two sizes, so resampling alone never reads as a change.+ cw, ch = (ew, eh) if ew * eh <= rw * rh else (rw, rh)+ k = cw / float(rw)+ m = change_mask(resize(region, cw, ch), resize(edited, cw, ch), threshold, max(1.0, feather * k), 3, max(1, int(round(8 * k))))+ m = resize_mask(m, rw, rh)if float(m.mean()) > 0.6:m = torch.ones_like(m)match_color = Falseif match_color:ed = lab_match(ed, region, 1.0 - m)+ if detail:+ ed = detail_transfer(region, ed, edited)+ return _place(base, ed, x0, y0, m)+++def _place(base, ed, x0, y0, m):out = base.clone()- out[:, y0:y1, x0:x1] = composite(region, ed, m)- if out_max_side and max(W, H) > out_max_side:- s = out_max_side / float(max(W, H))- out = resize(out, max(32, int(round(W * s))), max(32, int(round(H * s))))+ region = base[:, y0:y0 + ed.shape[1], x0:x0 + ed.shape[2]]+ out[:, y0:y0 + ed.shape[1], x0:x0 + ed.shape[2]] = composite(region, ed, m)return out@@ -362,16 +444,16 @@ if not os.environ.get("FUOBE_LIVE_PURE"):"match_color": ("BOOLEAN", {"default": True}),"out_max_side": ("INT", {"default": 0, "min": 0, "max": MAX_SIDE, "step": 32}),},- "optional": {"box": ("FUOBE_BOX",), "mask_image": ("IMAGE",)},+ "optional": {"box": ("FUOBE_BOX",), "mask_image": ("IMAGE",), "detail": ("BOOLEAN", {"default": True})},}RETURN_TYPES = ("IMAGE",)FUNCTION = "paste"CATEGORY = "fuobe/live"- def paste(self, base, edited, mode, threshold, feather, match_color, out_max_side, box=None, mask_image=None):+ def paste(self, base, edited, mode, threshold, feather, match_color, out_max_side, box=None, mask_image=None, detail=True):dev = comfy.model_management.intermediate_device()- out = paste_back(base.to(dev), edited.to(dev), mode, threshold, feather, match_color, out_max_side, box, None if mask_image is None else mask_image.to(dev))+ out = paste_back(base.to(dev), edited.to(dev), mode, threshold, feather, match_color, out_max_side, box, None if mask_image is None else mask_image.to(dev), detail)return (out,)class SaveImageFuobeLive:@@ -392,6 +474,12 @@ if not os.environ.get("FUOBE_LIVE_PURE"):OUTPUT_NODE = TrueCATEGORY = "fuobe/live"+ @classmethod+ def IS_CHANGED(cls, **kwargs):+ # Never served from ComfyUI's cache: the same graph again (a keep of the text just rendered) must still+ # send its picture. The nodes before it stay cached.+ return float("nan")+def save(self, images, format, quality, to, unique_id=None):img = images[:1, :, :, :3]data, image_type = encode_picture(img, format, quality)@@ -431,7 +519,7 @@ if not os.environ.get("FUOBE_LIVE_PURE"):async def _fuobe_live_status(request):from aiohttp import web- return web.json_response({"version": FUOBE_LIVE})+ return web.json_response({"version": FUOBE_LIVE, "sha256": FUOBE_LIVE_SHA256})try:_ps = getattr(server.PromptServer, "instance", None)@@ -450,8 +538,21 @@ export function liveNodesBase64(): string {return btoa(LIVE_NODES_SOURCE);}-/** Its answer at /fuobe/live: there, and this version or newer. */-export const isLiveNodes = (answer: unknown): boolean => !!answer && typeof answer === "object" && Number((answer as { version?: unknown }).version) >= LIVE_NODES_VERSION;+/**+ * The sha256 of LIVE_NODES_SOURCE: the file reports its own at /fuobe/live, and only an exact copy counts. A test+ * (tests/live-nodes.test.ts) fails when the source changes without a new version and hash here.+ */+export const LIVE_NODES_SHA256 = "3386bb3743b41b8618b2da45ee257e48ef34b0d1cdac8abde3a2aa38974285d3";++/** Its answer at /fuobe/live: this version, and exactly this file. */+export const isLiveNodes = (answer: unknown): boolean =>+ !!answer && typeof answer === "object" && Number((answer as { version?: unknown }).version) === LIVE_NODES_VERSION && (answer as { sha256?: unknown }).sha256 === LIVE_NODES_SHA256;++/** What /fuobe/live's answer says: the nodes are there and exact (ok), there but another copy (outdated), or not there. */+export function liveNodesState(answer: unknown): "ok" | "outdated" | "missing" {+ if (isLiveNodes(answer)) return "ok";+ return answer && typeof answer === "object" && Number((answer as { version?: unknown }).version) > 0 ? "outdated" : "missing";+}/** The classes the file defines (the requirement index's pack). */export const LIVE_NODE_CLASSES = ["LoadImageFuobeLive", "CropFuobeLive", "Qwen21ReferenceFuobeLive", "Qwen21EncodeFuobeLive", "PasteBackFuobeLive", "SaveImageFuobeLive"] as const;diff --git a/src/lib/live/scheduler.ts b/src/lib/live/scheduler.tsindex cb9e7abb..ff5c3fc4 100644--- a/src/lib/live/scheduler.ts+++ b/src/lib/live/scheduler.ts@@ -15,6 +15,9 @@export type Slot = "keep" | "live" | "settle" | "warm";+/** How long a render may take before it is taken off ComfyUI and reported failed (the first after another job reloads the model). */+export const RENDER_DEADLINE_MS: Readonly<Record<Slot, number>> = { live: 60_000, settle: 90_000, keep: 180_000, warm: 240_000 };+/** Slots by priority. */export const SLOTS: readonly Slot[] = ["keep", "live", "settle", "warm"];@@ -206,7 +209,8 @@ export class LiveScheduler<P, R> {p = Promise.reject(e);}p.then(- (result) => done({ ok: true, result }),+ // A job stopped while it ran answers as dropped, even when its render came in anyway.+ (result) => done(cur.dropped ? { ok: false, dropped: cur.dropped } : { ok: true, result }),(e) => done(cur.dropped ? { ok: false, dropped: cur.dropped } : { ok: false, error: e instanceof Error ? e.message : String(e) }),);}diff --git a/src/lib/live/steps.ts b/src/lib/live/steps.tsindex 7179da61..0c3bf3ca 100644--- a/src/lib/live/steps.ts+++ b/src/lib/live/steps.ts@@ -122,9 +122,14 @@ export class StepStack {return this.liveShas.has(sha256);}- /** Keep a step on top of the head (or as the first picture, for text to image). */- keep(s: Omit<Step, "id" | "parent" | "at"> & { at?: number }): Step {+ /**+ * Keep a step on top of the head (or as the first picture, for text to image). `parent`: the head the keep started+ * from; if the head moved since (an undo while the keep rendered), the step would sit on a picture that wasn't its+ * base, so it is refused.+ */+ keep(s: Omit<Step, "id" | "parent" | "at"> & { at?: number }, parent?: string | null): Step {const base = this.head;+ if (parent !== undefined && (base?.id ?? null) !== parent) throw new StepError("The picture changed while keeping. Keep again.");if (base && s.master.format !== "png") throw new StepError("A kept master must be a PNG");if (this.liveShas.has(s.master.sha256)) throw new StepError("A live frame can't be kept as a master");if (base && s.method !== "compose" && s.master.w * s.master.h < base.master.w * base.master.h) throw new StepError("A kept master can't be smaller than its base");diff --git a/src/server/live/comfy-live.ts b/src/server/live/comfy-live.tsindex da861865..c26d53c5 100644--- a/src/server/live/comfy-live.ts+++ b/src/server/live/comfy-live.ts@@ -1,7 +1,9 @@import "server-only";import { nanoid } from "nanoid";+import { LIVE_NODES_VERSION, liveNodesState } from "@/lib/comfy-live-nodes";import { parseComfyBinary, parseComfyText } from "@/lib/comfy-ws";import type { LiveEvent } from "@/lib/live/frames";+import { RENDER_DEADLINE_MS } from "@/lib/live/scheduler";import { LIVE_FILES, LIVE_OUTPUT, type LiveGraph } from "@/lib/live/graph";import { comfyRequest, ownGpu } from "../providers/comfyui";import { getSetting } from "../settings";@@ -15,7 +17,7 @@ import { getSetting } from "../settings";* runs; only Fuobe's own live prompts are ever touched.** On an account's linked GPU there is no socket (fetchPublic only): the picture is saved to temp and read back, with- * the history polled every 80 ms.+ * the history polled every 80 ms. Every render has a deadline, and one ComfyUI no longer has ends: nothing waits forever.*/export interface LivePicture {@@ -68,6 +70,8 @@ interface LiveSocket {status: LiveStatus;/** Ours, waiting in ComfyUI's queue. */waiting: number;+ /** Ours, stopped before they were seen to start: interrupted if they start after all. */+ stopped: Set<string>;}declare global {@@ -85,7 +89,7 @@ export function liveSocket(): LiveSocket {s = undefined;}if (!s) {- s = { url, clientId: `fuobe-live-${nanoid(10)}`, online: false, backoff: 250, waiters: new Map(), listeners: new Set(), status: { online: false, running: null, queue: 0, otherRan: false }, waiting: 0 };+ s = { url, clientId: `fuobe-live-${nanoid(10)}`, online: false, backoff: 250, waiters: new Map(), listeners: new Set(), status: { online: false, running: null, queue: 0, otherRan: false }, waiting: 0, stopped: new Set() };globalThis.__fuobeLiveSocket = s;}if (!s.ws && !s.timer) connect(s);@@ -174,7 +178,11 @@ function connect(s: LiveSocket) {return;}const w = "promptId" in e && e.promptId ? s.waiters.get(e.promptId) : undefined;- if (!w) return;+ if (!w) {+ // One of ours that was stopped started anyway (the delete came too late): interrupt it, now that it is ours running.+ if (e.type === "execution_start" && s.stopped.delete(e.promptId)) void post("/interrupt", { prompt_id: e.promptId }).catch(() => undefined);+ return;+ }if (e.type === "execution_start") {w.started = true;w.startedAt = Date.now();@@ -187,6 +195,10 @@ function connect(s: LiveSocket) {w.reject(new LiveRenderError(e.message ?? "The render failed", e.nodeType === "LoadImageFuobeLive" ? "missing-input" : "failed"));} else if (e.type === "interrupted") {w.reject(new LiveRenderError("Stopped", "stopped"));+ } else if (e.type === "success" || (e.type === "executing" && e.node === null)) {+ // Finished, and no picture came (the picture is always sent before this): an old copy of the nodes served from+ // ComfyUI's cache. Never wait forever.+ w.reject(new LiveRenderError("ComfyUI finished without sending the picture. Update Fuobe's live nodes.", "failed"));}};}@@ -233,14 +245,60 @@ async function refusal(res: Response): Promise<LiveRenderError> {return new LiveRenderError(body.error?.message ? `ComfyUI refused the render: ${body.error.message}` : `ComfyUI answered ${res.status}`, "failed");}+export { RENDER_DEADLINE_MS };+/** How often a render that hasn't finished checks that ComfyUI still has it (a restart or a cleared queue drops it without a word). */+export const GONE_CHECK_MS = 4000;+/** The largest picture read back from a linked GPU (a 4096 px PNG master fits with room to spare). */+export const MAX_PICTURE_BYTES = 80 * 2 ** 20;++/** Whether ComfyUI still has a prompt, waiting or running (null: it couldn't be asked). */+async function inQueue(id: string): Promise<boolean | null> {+ try {+ const r = await comfyRequest("/queue");+ if (!r.ok) return null;+ const q = (await r.json()) as { queue_running?: unknown[][]; queue_pending?: unknown[][] };+ return [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].some((row) => Array.isArray(row) && row[1] === id);+ } catch {+ return null;+ }+}++/**+ * Take a prompt of ours off ComfyUI: deleted if it waits, interrupted if it runs. An interrupt goes only to a prompt+ * known to be ours and running (an older ComfyUI stops whatever runs, whatever prompt an interrupt names): one not yet+ * seen to start is remembered, and interrupted if it starts after all.+ */+function takeOff(s: LiveSocket, id: string, started: boolean) {+ void post("/queue", { delete: [id] }).catch(() => undefined);+ if (started) void post("/interrupt", { prompt_id: id }).catch(() => undefined);+ else {+ s.stopped.add(id);+ if (s.stopped.size > 200) s.stopped.delete(s.stopped.values().next().value!);+ }+}++/** The same on a linked GPU (no events): interrupted only when its queue shows this prompt running. */+async function takeOffPolled(id: string) {+ await post("/queue", { delete: [id] }).catch(() => undefined);+ try {+ const r = await comfyRequest("/queue");+ const q = r.ok ? ((await r.json()) as { queue_running?: unknown[][] }) : {};+ if ((q.queue_running ?? []).some((row) => Array.isArray(row) && row[1] === id)) await post("/interrupt", { prompt_id: id });+ } catch {}+}+/*** One render: the graph's picture, or a LiveRenderError. `signal` stops it (deleted while queued, interrupted while- * running). `onEvent` hears started and progress.+ * running). `onEvent` hears started and progress. A render ends, one way or another: by its picture, an error, a stop,+ * ComfyUI finishing without a picture, ComfyUI no longer having the prompt, or `deadlineMs`.*/-export async function renderLive(graph: LiveGraph, signal: AbortSignal, onEvent: (e: LiveEvent) => void): Promise<LivePicture> {- if (ownGpu()) return renderPolling(graph, signal, onEvent);+export async function renderLive(graph: LiveGraph, signal: AbortSignal, onEvent: (e: LiveEvent) => void, deadlineMs: number = RENDER_DEADLINE_MS.keep): Promise<LivePicture> {+ if (signal.aborted) throw new LiveRenderError("Stopped", "stopped");+ if (ownGpu()) return renderPolling(graph, signal, onEvent, deadlineMs);const s = liveSocket();if (!(await online(s, 3000))) throw new LiveRenderError("Can't reach ComfyUI. Reconnecting…", "offline");+ // Stopped while waiting for the socket: nothing was sent, nothing to take off.+ if (signal.aborted) throw new LiveRenderError("Stopped", "stopped");const id = crypto.randomUUID();let settle!: { resolve: (p: LivePicture) => void; reject: (e: Error) => void };const done = new Promise<LivePicture>((resolve, reject) => (settle = { resolve, reject }));@@ -263,37 +321,83 @@ export async function renderLive(graph: LiveGraph, signal: AbortSignal, onEvent:};s.waiters.set(id, waiter);s.waiting++;- const stop = () => {+ const end = (e: LiveRenderError) => {const started = waiter.started;- waiter.reject(new LiveRenderError("Stopped", "stopped"));- void post("/queue", { delete: [id] }).catch(() => undefined);- if (started) void post("/interrupt", { prompt_id: id }).catch(() => undefined);+ const had = s.waiters.get(id) === waiter;+ waiter.reject(e);+ if (had) takeOff(s, id, started);};- if (signal.aborted) stop();- else signal.addEventListener("abort", stop, { once: true });+ const stop = () => end(new LiveRenderError("Stopped", "stopped"));+ signal.addEventListener("abort", stop, { once: true });+ const deadline = setTimeout(() => end(new LiveRenderError("ComfyUI took too long with this render", "failed")), deadlineMs);+ deadline.unref?.();+ // A prompt ComfyUI dropped without a word (a cleared queue, a restart the socket didn't see): gone twice in a row.+ let gone = 0;+ const watch = setInterval(() => {+ if (!s.waiters.has(id)) return;+ void inQueue(id).then((has) => {+ gone = has === false ? gone + 1 : 0;+ if (gone >= 2) waiter.reject(new LiveRenderError("ComfyUI dropped the render", "failed"));+ });+ }, GONE_CHECK_MS);+ watch.unref?.();try {- const res = await post("/prompt", { prompt: graph, prompt_id: id, client_id: s.clientId, front: true });- if (!res.ok) waiter.reject(await refusal(res));- else {- res.body?.cancel().catch(() => {});- onEvent({ type: "queued", pos: Math.max(0, s.status.queue) });+ try {+ const res = await post("/prompt", { prompt: graph, prompt_id: id, client_id: s.clientId, front: true });+ if (!res.ok) waiter.reject(await refusal(res));+ else {+ res.body?.cancel().catch(() => {});+ onEvent({ type: "queued", pos: Math.max(0, s.status.queue) });+ }+ } catch (e) {+ waiter.reject(new LiveRenderError((e as Error).message || "Can't reach ComfyUI", "offline"));}- } catch (e) {- waiter.reject(new LiveRenderError((e as Error).message || "Can't reach ComfyUI", "offline"));- }- try {+ // Stopped while the prompt was on its way: the first delete may have arrived before it, so take it off again.+ if (signal.aborted) takeOff(s, id, false);const p = await done;markWarm();return p;} finally {+ clearTimeout(deadline);+ clearInterval(watch);signal.removeEventListener("abort", stop);// Live renders don't pile up in ComfyUI's history.void post("/history", { delete: [id] }).catch(() => undefined);}}+/** A response body, read up to `max` bytes (null when it is larger). */+async function readCapped(res: Response, max: number): Promise<Uint8Array | null> {+ const declared = Number(res.headers.get("content-length"));+ if (Number.isFinite(declared) && declared > max) {+ res.body?.cancel().catch(() => {});+ return null;+ }+ if (!res.body) return new Uint8Array(0);+ const reader = res.body.getReader();+ const parts: Uint8Array[] = [];+ let n = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ n += value.byteLength;+ if (n > max) {+ reader.cancel().catch(() => {});+ return null;+ }+ parts.push(value);+ }+ const out = new Uint8Array(n);+ let at = 0;+ for (const p of parts) {+ out.set(p, at);+ at += p.byteLength;+ }+ return out;+}+/** An account's linked GPU: no socket; the picture is saved to temp and read back. */-async function renderPolling(graph: LiveGraph, signal: AbortSignal, onEvent: (e: LiveEvent) => void): Promise<LivePicture> {+async function renderPolling(graph: LiveGraph, signal: AbortSignal, onEvent: (e: LiveEvent) => void, deadlineMs: number): Promise<LivePicture> {const id = crypto.randomUUID();const g = structuredClone(graph);if (g[LIVE_OUTPUT]) g[LIVE_OUTPUT].inputs.to = "temp";@@ -305,9 +409,12 @@ async function renderPolling(graph: LiveGraph, signal: AbortSignal, onEvent: (e:res.body?.cancel().catch(() => {});onEvent({ type: "queued", pos: 0 });let started = false;+ let lastCheck = Date.now();+ let gone = 0;try {for (;;) {if (signal.aborted) throw new LiveRenderError("Stopped", "stopped");+ if (Date.now() - t0 > deadlineMs) throw new LiveRenderError("ComfyUI took too long with this render", "failed");await new Promise((r) => setTimeout(r, 80));const h: Record<string, HistoryEntry> = await comfyRequest(`/history/${id}`).then((r) => (r.ok ? (r.json() as Promise<Record<string, HistoryEntry>>) : {}));const entry = h[id];@@ -316,6 +423,12 @@ async function renderPolling(graph: LiveGraph, signal: AbortSignal, onEvent: (e:started = true;onEvent({ type: "started" });}+ if (Date.now() - lastCheck >= GONE_CHECK_MS) {+ lastCheck = Date.now();+ const has = await inQueue(id);+ gone = has === false ? gone + 1 : 0;+ if (gone >= 2) throw new LiveRenderError("ComfyUI dropped the render", "failed");+ }continue;}const err = entry.status?.messages?.find(([t]) => t === "execution_error")?.[1] as { exception_message?: string; node_type?: string } | undefined;@@ -323,15 +436,17 @@ async function renderPolling(graph: LiveGraph, signal: AbortSignal, onEvent: (e:const img = entry.outputs?.[LIVE_OUTPUT]?.images?.[0];if (!img || img.type !== "temp" || !/^[\w.-]+$/.test(img.filename)) throw new LiveRenderError("The render made no picture", "failed");const view = await comfyRequest(`/view?${new URLSearchParams({ filename: img.filename, subfolder: "", type: "temp" })}`);- if (!view.ok) throw new LiveRenderError("Couldn't read the picture", "failed");- const data = new Uint8Array(await view.arrayBuffer());+ if (!view.ok) {+ view.body?.cancel().catch(() => {});+ throw new LiveRenderError("Couldn't read the picture", "failed");+ }+ const data = await readCapped(view, MAX_PICTURE_BYTES);+ if (!data) throw new LiveRenderError("The picture is too large", "failed");return { data, type: view.headers.get("content-type") ?? "image/webp", w: 0, h: 0, ms: Date.now() - t0 };}} catch (e) {- if (signal.aborted) {- void post("/queue", { delete: [id] }).catch(() => undefined);- void post("/interrupt", { prompt_id: id }).catch(() => undefined);- }+ // Stopped, dropped or too slow: off ComfyUI (ours only).+ if (!(e instanceof LiveRenderError) || e.code !== "missing-input") void takeOffPolled(id);throw e;} finally {void post("/history", { delete: [id] }).catch(() => undefined);@@ -366,10 +481,11 @@ const FILES: [string, string][] = [];/**- * Whether ComfyUI has Fuobe's live nodes (their version, or 0), whether it runs with --highvram or --gpu-only, and the- * model files its folders don't list ("folder/file"; a folder that can't be read lists nothing missing).+ * Whether ComfyUI has Fuobe's live nodes (their version when it is exactly this copy, or 0; outdated: another copy),+ * whether it runs with --highvram or --gpu-only, and the model files its folders don't list ("folder/file"; a folder+ * that can't be read lists nothing missing).*/-export async function liveFacts(): Promise<{ nodes: number; highvram: boolean | null; missing: string[] }> {+export async function liveFacts(): Promise<{ nodes: number; outdated: boolean; highvram: boolean | null; missing: string[] }> {const missing = (await Promise.all(FILES.map(async ([folder, file]) => {@@ -382,12 +498,13 @@ export async function liveFacts(): Promise<{ nodes: number; highvram: boolean |).filter((x): x is string => !!x);const [nodes, stats] = await Promise.all([comfyRequest("/fuobe/live")- .then(async (r) => (r.ok ? Number(((await r.json()) as { version?: unknown }).version) || 0 : 0))- .catch(() => 0),+ .then(async (r) => (r.ok ? ((await r.json()) as unknown) : null))+ .catch(() => null),comfyRequest("/system_stats").then(async (r) => (r.ok ? ((await r.json()) as { system?: { argv?: string[] } }) : null)).catch(() => null),]);const argv = stats?.system?.argv;- return { nodes, highvram: Array.isArray(argv) ? argv.includes("--highvram") || argv.includes("--gpu-only") : null, missing };+ const state = liveNodesState(nodes);+ return { nodes: state === "ok" ? LIVE_NODES_VERSION : 0, outdated: state === "outdated", highvram: Array.isArray(argv) ? argv.includes("--highvram") || argv.includes("--gpu-only") : null, missing };}diff --git a/src/server/live/sessions.ts b/src/server/live/sessions.tsindex e7cf6fa2..70ccd01f 100644--- a/src/server/live/sessions.ts+++ b/src/server/live/sessions.ts@@ -5,14 +5,16 @@ import { buildLiveGraph, type LiveGraphParams } from "@/lib/live/graph";import { inputName, pictureExt, PICTURE_TYPES, pngSize } from "@/lib/live/names";import { LiveScheduler, type LiveJob, type Outcome, type Slot } from "@/lib/live/scheduler";import { onOwnGpu, type OwnGpu } from "../providers/comfyui";-import { LiveRenderError, renderLive, stageInput, waitOnline, type LivePicture } from "./comfy-live";+import { LiveRenderError, RENDER_DEADLINE_MS, renderLive, stageInput, waitOnline, type LivePicture } from "./comfy-live";/*** Live edit sessions on the server path (one per tab): the scheduler (src/lib/live/scheduler.ts) that keeps one render* of the tab's in ComfyUI at a time, the pictures it staged (by content name, with Fuobe's copy, so a ComfyUI that* restarted and lost its input folder gets them again), and the newest settled renders (full-quality PNG masters of* the text on screen, held for 2 minutes so Keep stores exactly those bytes). Sessions end 10 minutes after their- * last use.+ * last use, or when their tab closes. Each person has at most 4 (a fifth ends the one used longest ago), and each holds+ * at most 160 MB of pictures: past that, the oldest held renders go first, then copies that can be read again from+ * their file, then the oldest painted regions.*/export const SESSION_IDLE_MS = 10 * 60_000;@@ -20,6 +22,12 @@ const SETTLED_KEPT = 6;const SETTLED_MS = 2 * 60_000;/** Fuobe's copies of staged pictures kept in memory per session (masters at 2048 are ~10 MB): older ones are re-read. */const COPIES_KEPT = 12;+/** Sessions per person (one per tab). */+export const SESSIONS_PER_PRINCIPAL = 4;+/** The pictures a session may hold in memory: staged copies, painted regions and held renders. */+export const SESSION_BYTES = 160 * 2 ** 20;+/** Painted regions whose bytes are kept (to stage again after a restart); older ones must be painted again. */+const MASKS_KEPT = 4;export interface RenderPayload {params: LiveGraphParams;@@ -86,6 +94,9 @@ export function openSession(principal: string, gpu: OwnGpu | undefined, id?: strhad.gpu = gpu;return had;}+ // One person's sessions are capped: the one used longest ago ends.+ const mine = [...s.sessions.values()].filter((x) => x.principal === principal).sort((a, b) => a.lastUsed - b.lastUsed);+ for (const old of mine.slice(0, Math.max(0, mine.length - SESSIONS_PER_PRINCIPAL + 1))) endSession(old.id);const session: LiveSession = {id: `lv_${nanoid(16)}`,principal,@@ -137,9 +148,35 @@ export async function stage(s: LiveSession, data: Uint8Array, reread?: () => Pro// Keep the newest copies in memory; older ones are read again from their file when needed.const withData = [...s.staged.values()].filter((x) => x.data && x.reread);for (const x of withData.slice(0, Math.max(0, withData.length - COPIES_KEPT))) x.data = undefined;+ const masks = [...s.staged.values()].filter((x) => x.data && !x.reread);+ for (const x of masks.slice(0, Math.max(0, masks.length - MASKS_KEPT))) x.data = undefined;+ trim(s);return st;}+/** The bytes a session holds. */+export const heldBytes = (s: LiveSession) => [...s.staged.values()].reduce((n, x) => n + (x.data?.byteLength ?? 0), 0) + [...s.settled.values()].reduce((n, x) => n + x.pic.data.byteLength, 0);++/** Keep a session within SESSION_BYTES: the oldest held renders go, then re-readable copies, then painted regions. */+function trim(s: LiveSession) {+ let total = heldBytes(s);+ if (total <= SESSION_BYTES) return;+ for (const [k, v] of s.settled) {+ if (total <= SESSION_BYTES || s.settled.size <= 1) break;+ s.settled.delete(k);+ total -= v.pic.data.byteLength;+ }+ for (const pass of [true, false])+ for (const x of s.staged.values()) {+ if (total <= SESSION_BYTES) return;+ if (!x.data || !!x.reread !== pass) continue;+ total -= x.data.byteLength;+ x.data = undefined;+ }+ // A single held render larger than the budget still goes.+ if (total > SESSION_BYTES) s.settled.clear();+}+async function sizeOf(data: Uint8Array): Promise<{ w: number; h: number } | null> {const { imageSize } = await import("@/lib/image-size");const s = imageSize(Buffer.from(data));@@ -165,7 +202,7 @@ async function run(s: LiveSession, job: LiveJob<RenderPayload>, signal: AbortSig}const { graph, staged } = buildLiveGraph(params);for (const n of staged) if (!s.staged.has(n)) throw new LiveRenderError("That picture wasn't added to this session", "missing-input");- const once = () => within(s, () => renderLive(graph, signal, onEvent));+ const once = () => within(s, () => renderLive(graph, signal, onEvent, RENDER_DEADLINE_MS[job.slot]));let pic: LivePicture | undefined;for (let tries = 0; !pic; tries++) {try {@@ -189,6 +226,7 @@ async function run(s: LiveSession, job: LiveJob<RenderPayload>, signal: AbortSigfor (const [k, v] of s.settled) if (now - v.at > SETTLED_MS) s.settled.delete(k);s.settled.set(job.key, { pic: out, at: now });while (s.settled.size > SETTLED_KEPT) s.settled.delete(s.settled.keys().next().value!);+ trim(s);}return out;}diff --git a/tests/fixtures/live-type4.bin b/tests/fixtures/live-type4.binindex 34361dbe..23b549f2 100644Binary files a/tests/fixtures/live-type4.bin and b/tests/fixtures/live-type4.bin differdiff --git a/tests/helpers/fake-live.ts b/tests/helpers/fake-live.tsindex 0151d81f..320391d9 100644--- a/tests/helpers/fake-live.ts+++ b/tests/helpers/fake-live.ts@@ -3,8 +3,9 @@* the bookkeeping can be measured. An "edit" paints a rectangle chosen by the prompt and seed (8–20 % of the picture)* in a colour chosen by them, at the model's size (the resolution's area, the base's shape), then scales it back up.* With `lossy`, the whole edited frame also gets ±2 noise and a slight blur, a stand-in for a VAE round trip. The paste- * back copies the base outside the changed rectangle (grown 8 px, feathered), as Fuobe's node does; mode "off" keeps- * the whole edit, "mask" uses the painted region. Only erasable TypeScript (runs under plain Node).+ * back finds what changed the way Fuobe's node does (changeMask: both pictures blurred at the model's size, their Lab+ * difference over the node's threshold, specks removed, grown and feathered), so it doesn't know where it painted;+ * mode "off" keeps the whole edit, "mask" uses the painted region. Only erasable TypeScript (runs under plain Node).*/import { createHash } from "node:crypto";import sharpLib from "sharp";@@ -19,8 +20,10 @@ export interface LiveRender {/** The model's size (sets the render's time). */modelW: number;modelH: number;- /** In the output's pixels: the area the edit may have touched (grown and feathered), or null for a whole-frame edit. */+ /** In the output's pixels: the box around every pixel the paste-back took from the edit, or null (none, or the whole frame). */touched: [number, number, number, number] | null;+ /** The share of the picture the change mask covered (0 for text to image). */+ changed?: number;base?: string;}@@ -73,6 +76,86 @@ async function encode(data: Buffer, w: number, h: number, format: string, qualitreturn format === "png" ? img.png({ compressionLevel: 1 }).toBuffer() : img.webp({ quality }).toBuffer();}+/** sRGB bytes to CIE Lab (D65), as fuobe_live.py's to_lab. */+function toLab(px: Buffer): Float32Array {+ const out = new Float32Array(px.length);+ const lin = (v: number) => {+ const c = v / 255;+ return c > 0.04045 ? ((c + 0.055) / 1.055) ** 2.4 : c / 12.92;+ };+ const e = 216 / 24389;+ const f = (t: number) => (t > e ? Math.cbrt(t) : ((24389 / 27) * t + 16) / 116);+ for (let i = 0; i < px.length; i += 3) {+ const r = lin(px[i]);+ const g = lin(px[i + 1]);+ const b = lin(px[i + 2]);+ const fx = f((0.4124 * r + 0.3576 * g + 0.1805 * b) / 0.95047);+ const fy = f(0.2126 * r + 0.7152 * g + 0.0722 * b);+ const fz = f((0.0193 * r + 0.1192 * g + 0.9505 * b) / 1.08883);+ out[i] = 116 * fy - 16;+ out[i + 1] = 500 * (fx - fy);+ out[i + 2] = 200 * (fy - fz);+ }+ return out;+}++/** A max (or, with min, a min) filter over a (2r+1) square, separably. */+function boxMax(m: Uint8Array, w: number, h: number, r: number, min = false): Uint8Array {+ const pick = min ? Math.min : Math.max;+ const tmp = new Uint8Array(m.length);+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++) {+ let v = m[y * w + x];+ for (let k = Math.max(0, x - r); k <= Math.min(w - 1, x + r); k++) v = pick(v, m[y * w + k]);+ tmp[y * w + x] = v;+ }+ const out = new Uint8Array(m.length);+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++) {+ let v = tmp[y * w + x];+ for (let k = Math.max(0, y - r); k <= Math.min(h - 1, y + r); k++) v = pick(v, tmp[k * w + x]);+ out[y * w + x] = v;+ }+ return out;+}++/** The node's threshold (PasteBackFuobeLive threshold 0.06: a Lab difference of 6), blur 3, grow 8, feather 24. */+export const MASK = { threshold: 6, blur: 3, grow: 8, feather: 24 } as const;++/**+ * Where an edit changed a base, as fuobe_live.py's change_mask: compared at the edit's own size (w x h) after a blur of+ * both, a Lab difference over MASK.threshold, specks removed, grown, feathered, then scaled to the base's size (W x H).+ * 0..255 per pixel; exactly 0 where nothing changed.+ */+export async function changeMask(baseFull: Buffer, W: number, H: number, editAt: Buffer, ew: number, eh: number): Promise<Uint8Array> {+ const s = await sharp();+ // The stand-in compares at 512 px at most (it shares a process with the browser checks: it must stay quick).+ const f = Math.min(1, 512 / Math.max(ew, eh));+ const w = Math.max(8, Math.round(ew * f));+ const h = Math.max(8, Math.round(eh * f));+ const edit = await resize(editAt, ew, eh, w, h);+ const sigma = Math.max(0.3, (MASK.blur / 2) * f);+ const small = await resize(baseFull, W, H, w, h);+ const blur = (px: Buffer) => s(px, { raw: { width: w, height: h, channels: 3 } }).blur(sigma).raw().toBuffer();+ const [a, b] = await Promise.all([blur(small), blur(edit)]);+ const la = toLab(a);+ const lb = toLab(b);+ let m: Uint8Array = new Uint8Array(w * h);+ for (let i = 0; i < m.length; i++) {+ const j = i * 3;+ m[i] = Math.hypot(la[j] - lb[j], la[j + 1] - lb[j + 1], la[j + 2] - lb[j + 2]) > MASK.threshold ? 255 : 0;+ }+ m = boxMax(m, w, h, 1, true);+ const k = w / W;+ m = boxMax(m, w, h, Math.max(1, Math.round(MASK.grow * k)));+ const feather = Math.max(1, MASK.feather * k) / 3;+ const soft = await s(Buffer.from(m), { raw: { width: w, height: h, channels: 1 } }).blur(Math.max(0.3, feather)).extractChannel(0).raw().toBuffer();+ const up = await s(soft, { raw: { width: w, height: h, channels: 1 } }).resize(W, H, { kernel: "linear", fit: "fill" }).extractChannel(0).raw().toBuffer();+ const out = new Uint8Array(W * H);+ for (let i = 0; i < out.length; i++) out[i] = up[i] < 1 ? 0 : up[i];+ return out;+}+/** Render a live graph from the stand-in's input folder. Throws like the node would when a picture is missing. */export async function renderLive(g: Graph, inputs: Map<string, Buffer>, opts: { lossy?: boolean } = {}): Promise<LiveRender> {const prompt = String(g["30"]?.inputs?.prompt ?? "");@@ -161,29 +244,36 @@ export async function renderLive(g: Graph, inputs: Map<string, Buffer>, opts: {}const edited = await resize(model, mw, mh, W, H);- // Paste back: the base where nothing changed.+ // Paste back: the base where nothing changed, found as the node finds it (not from the painted rectangle).const out = Buffer.from(base.data);let touched: [number, number, number, number] | null = null;+ let changed = 0;if (mode === "off") {edited.copy(out);} else {- const grow = 8;- const feather = 24;- const [rx0, ry0, rx1, ry1] = [rect[0] - grow, rect[1] - grow, rect[2] + grow, rect[3] + grow];- touched = [Math.max(0, rx0 - feather), Math.max(0, ry0 - feather), Math.min(W, rx1 + feather), Math.min(H, ry1 + feather)];- for (let y = touched[1]; y < touched[3]; y++)- for (let x = touched[0]; x < touched[2]; x++) {- let m: number;- if (maskFull) m = maskFull[(y * W + x) * 3] / 255;- else {- const dx = Math.max(rx0 - x, 0, x - (rx1 - 1));- const dy = Math.max(ry0 - y, 0, y - (ry1 - 1));- m = Math.max(0, 1 - Math.hypot(dx, dy) / feather);+ let mask: Uint8Array;+ if (maskFull) {+ mask = new Uint8Array(W * H);+ for (let i = 0; i < mask.length; i++) mask[i] = maskFull[i * 3];+ } else mask = await changeMask(base.data, W, H, model, mw, mh);+ let x0 = W, y0 = H, x1 = 0, y1 = 0;+ for (let i = 0; i < mask.length; i++) if (mask[i]) changed++;+ if (!maskFull && changed > 0.6 * W * H) {+ // A global change: the whole edit (the node also brings back the base's fine detail; the stand-in doesn't).+ edited.copy(out);+ } else+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++) {+ const m = mask[y * W + x] / 255;+ if (m <= 0) continue;+ x0 = Math.min(x0, x);+ y0 = Math.min(y0, y);+ x1 = Math.max(x1, x + 1);+ y1 = Math.max(y1, y + 1);+ const i = (y * W + x) * 3;+ for (let c = 0; c < 3; c++) out[i + c] = Math.round(base.data[i + c] * (1 - m) + edited[i + c] * m);}- if (m <= 0) continue;- const i = (y * W + x) * 3;- for (let c = 0; c < 3; c++) out[i + c] = Math.round(base.data[i + c] * (1 - m) + edited[i + c] * m);- }+ if (x1 > x0) touched = [x0, y0, x1, y1];}// The output size (a live frame is the composite made small).@@ -197,7 +287,7 @@ export async function renderLive(g: Graph, inputs: Map<string, Buffer>, opts: {data = await resize(out, W, H, ow, oh);if (touched) touched = [Math.floor(touched[0] * s), Math.floor(touched[1] * s), Math.ceil(touched[2] * s), Math.ceil(touched[3] * s)];}- return { data: await encode(data, ow, oh, format, quality), type: format === "png" ? "image/png" : "image/webp", width: ow, height: oh, modelW: mw, modelH: mh, touched, base: String(g["10"].inputs.image) };+ return { data: await encode(data, ow, oh, format, quality), type: format === "png" ? "image/png" : "image/webp", width: ow, height: oh, modelW: mw, modelH: mh, touched, changed: changed / (W * H), base: String(g["10"].inputs.image) };}/** A picture's size from its header (PNG, JPEG or WebP via sharp's metadata), for timing. */diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.tsindex 737a2eef..8d49b981 100644--- a/tests/helpers/fake-local-comfy.ts+++ b/tests/helpers/fake-local-comfy.ts@@ -18,6 +18,8 @@ import type { Duplex } from "node:stream";import { pathToFileURL } from "node:url";// @ts-expect-error -- plain Node (the review harness) needs the extension; the bundler resolution allows none.import { isLiveGraph, liveModelSize, pictureSize, renderLive, type LiveRender } from "./fake-live.ts";+// @ts-expect-error -- as above.+import { LIVE_NODES_SHA256, LIVE_NODES_VERSION } from "../../src/lib/comfy-live-nodes.ts";export interface LocalComfyOptions {/** "off": ComfyUI's own check (other sites get 403); an origin, or "*". */@@ -58,6 +60,14 @@ export interface LocalComfyOptions {lossy?: boolean;/** The live nodes aren't installed (object_info leaves out the *FuobeLive classes; /fuobe/live is 404). */noLiveNodes?: boolean;+ /**+ * An old copy of the live nodes (version 1): /fuobe/live answers no hash, and its save node has no IS_CHANGED, so a+ * graph identical to the last one is served from ComfyUI's cache: no picture, only execution_cached, executed and+ * execution_success.+ */+ oldLiveNodes?: boolean;+ /** Nothing ever starts: prompts wait in the queue (a stuck ComfyUI). */+ stall?: boolean;}/** One live render the stand-in made (for the bookkeeping checks). */@@ -196,6 +206,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loclet timer: NodeJS.Timeout | undefined;const sockets = new Map<string, Set<Duplex>>();const renders: LiveRenderLog[] = [];+ let lastLive: { graph: string; ui: Record<string, unknown> } | undefined;const temps = new Map<string, { data: Buffer; type: string }>();const sizes = new Map<string, { w: number; h: number }>();let server: http.Server;@@ -245,6 +256,18 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst gen = generation;const alive = () => gen === generation && running === job;const started = Date.now();+ const same = lastLive !== undefined && lastLive.graph === JSON.stringify(job.graph);+ if (same && opts.oldLiveNodes) {+ // ComfyUI's cache: every node, the save node included, is served from the last run. No picture is sent.+ const ui = lastLive!.ui;+ event(job.clientId, "execution_start", { prompt_id: job.id });+ event(job.clientId, "execution_cached", { nodes: Object.keys(job.graph), prompt_id: job.id });+ event(job.clientId, "executed", { node: "90", prompt_id: job.id, output: ui });+ event(job.clientId, "executing", { node: null, prompt_id: job.id });+ event(job.clientId, "execution_success", { prompt_id: job.id });+ timer = setTimeout(() => alive() && finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs: { "90": ui }, status: { status_str: "success", completed: true, messages: [["execution_success", { prompt_id: job.id }]] } }), 1);+ return;+ }event(job.clientId, "execution_start", { prompt_id: job.id });event(job.clientId, "executing", { node: "32", prompt_id: job.id });const size = liveModelSize(job.graph, (n) => sizes.get(n) ?? null);@@ -282,6 +305,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loctemps.set(name, { data, type: r.type });ui = { images: [{ filename: name, subfolder: "", type: "temp" }] };}+ lastLive = { graph: JSON.stringify(job.graph), ui };event(job.clientId, "executed", { node: "90", prompt_id: job.id, output: ui });event(job.clientId, "executing", { node: null, prompt_id: job.id });event(job.clientId, "execution_success", { prompt_id: job.id });@@ -341,7 +365,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locfunction tick() {status();- if (running || !queue.length) return;+ if (running || !queue.length || opts.stall) return;const job = queue.shift()!;run(job);}@@ -417,7 +441,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locif (p === "/fuobe/guard") return opts.guard ? reply(200, { guard: 1 }) : reply(404, { error: "not found" });const has = opts.has ? installed(opts.has) : null;const liveNodes = !!has?.info.SaveImageFuobeLive && !opts.noLiveNodes;- if (p === "/fuobe/live") return liveNodes ? reply(200, { version: 1 }) : reply(404, { error: "not found" });+ if (p === "/fuobe/live") return liveNodes ? reply(200, opts.oldLiveNodes ? { version: 1 } : { version: LIVE_NODES_VERSION, sha256: LIVE_NODES_SHA256 }) : reply(404, { error: "not found" });if (p === "/models") return reply(200, has ? [...has.folders.keys()] : ["checkpoints", "loras", "vae"]);if (p.startsWith("/models/")) return reply(200, (has?.folders.get(decodeURIComponent(p.slice(8))) ?? []).map((f) => f.name));if (p.startsWith("/experiment/models/") && has) {@@ -487,10 +511,11 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc}if (p === "/queue") {if (req.method === "POST") {- const asked = JSON.parse(body.toString("utf8") || "{}") as { delete?: string[] };+ const asked = JSON.parse(body.toString("utf8") || "{}") as { delete?: string[]; clear?: boolean };entry.body = asked;const del = asked.delete ?? [];- queue = queue.filter((j) => !del.includes(j.id));+ queue = asked.clear ? [] : queue.filter((j) => !del.includes(j.id));+ status();return reply(200, {});}const row = (j: Job) => [j.number, j.id, j.graph, { client_id: j.clientId }, []];diff --git a/tests/live-api.test.ts b/tests/live-api.test.tsindex 0c7173b3..2c3ca25a 100644--- a/tests/live-api.test.ts+++ b/tests/live-api.test.ts@@ -170,10 +170,33 @@ describe("the server path", () => {expect(fake.inputs.has(base)).toBe(true);}, 15_000);+ it("a keep of the text just settled, once the held render is gone, still gets its picture (the same graph again)", async () => {+ const settled = image(await frames(await ask({ slot: "settle", text: "a pearl necklace" })))!;+ const posts = fake.posts();+ const kept = image(await frames(await ask({ slot: "keep", text: "a pearl necklace", fromSettled: false })))!;+ expect(fake.posts()).toBe(posts + 1);+ expect(kept.header).toMatchObject({ type: "image/png", w: settled.header.w, h: settled.header.h });+ });+it("refuses pictures the session didn't stage", async () => {const r = await ask({ text: "x", base: "fuobe_lvAAAAAAAAAAAAAAAAAAAA.png" });expect(r.status).toBe(409);});++ it("refuses a method it doesn't know", async () => {+ const r = await ask({ text: "x", method: "hybrid<script>" });+ expect(r.status).toBe(400);+ expect(r.headers.get("X-Live-Key")).toBeNull();+ });++ it("gives every editor its own session, and ends one when its tab closes", async () => {+ const a = ((await (await session.POST(req("/api/live/session", {}))).json()) as { sessionId: string }).sessionId;+ const b = ((await (await session.POST(req("/api/live/session", { sessionId: a }))).json()) as { sessionId: string }).sessionId;+ expect(b).not.toBe(a);+ expect((await session.POST(req("/api/live/session", { sessionId: a, end: true }))).status).toBe(200);+ const r = await render.POST(req("/api/live/render", { sessionId: a, seq: 1, slot: "live", seed: 7, size: 512, keepRes: 1024, text: "x" }));+ expect(r.status).toBe(410);+ });});describe("who may use live edit", () => {diff --git a/tests/live-core.test.ts b/tests/live-core.test.tsindex b4e9a375..2269f0f0 100644--- a/tests/live-core.test.ts+++ b/tests/live-core.test.ts@@ -163,6 +163,17 @@ describe("steps", () => {expect(s.all).toHaveLength(1);});+ it("refuses a keep whose head moved while it rendered (an undo during the keep)", () => {+ const s = StepStack.from(master(0));+ keep(s, 1);+ const parent = s.head!.id;+ s.undo();+ expect(() => s.keep({ text: "late", norm: "late", seed: 2, method: "hybrid", keepRes: 1536, master: master(2), ms: 900 }, parent)).toThrow(/changed while keeping/);+ expect(s.all).toHaveLength(2);+ s.redo();+ expect(s.keep({ text: "late", norm: "late", seed: 2, method: "hybrid", keepRes: 1536, master: master(2), ms: 900 }, parent).parent).toBe(parent);+ });+it("text to image starts empty and keeps a first picture of 1024 or more", () => {const s = new StepStack();expect(s.base("hybrid")).toBeNull();diff --git a/tests/live-drift.test.ts b/tests/live-drift.test.tsindex cb450818..8b13d3df 100644--- a/tests/live-drift.test.ts+++ b/tests/live-drift.test.ts@@ -1,10 +1,11 @@/*** Live edit doesn't wear a picture down (spec §6): 10 kept edits through the scheduler, the graph builder and the step* stack, against the ComfyUI stand-in with a lossy round trip on every render (noise and blur over the whole frame,- * as a VAE's would add). The stand-in can only check the bookkeeping; GPU-TEST.md measures real pictures.+ * as a VAE's would add). The stand-in can only check the bookkeeping; real pictures are measured on a GPU.*- * - hybrid (Fuobe's method): every base is a full-size PNG master, and the pixels no edit touched are bit-identical to- * the original after 10 edits (SSIM 1.000, sharpness 100 %);+ * - hybrid (Fuobe's method): every base is a full-size PNG master, the change mask (found from the lossy render, with+ * the node's threshold, not from where the stand-in painted) stays local, and the pixels no edit touched are+ * bit-identical to the original after 10 edits (SSIM 1.000, sharpness 100 %);* - chain without the paste-back (every edit re-encodes the whole picture): SSIM falls below 0.98;* - the reference app's way, each kept 512 live frame as the next base: SSIM falls below 0.90.*/@@ -91,6 +92,7 @@ async function session(method: Method | "preview") {const stack = StepStack.from(await master(original, first));const bases: string[] = [];const touched: [number, number, number, number][] = [];+ const changed: number[] = [];let seq = 0;let previewBase: { name: string; bytes: Buffer } | null = null;for (const [k, text] of EDITS.entries()) {@@ -122,16 +124,20 @@ async function session(method: Method | "preview") {stack.keep({ text, norm: text, seed, method, keepRes: 1536, master: await master(o.result, name), ms: 0 });bases.push(baseName);const r = fake.renders.at(-1)!;+ if (method === "hybrid") changed.push(r.changed ?? 1);if (r.touched) touched.push(r.touched);}const final = method === "preview" ? previewBase!.bytes : fake.inputs.get(stack.head!.master.name)!;- return { stack, bases, touched, final };+ return { stack, bases, touched, changed, final };}describe("stacked live edits", () => {it("hybrid: every base is a full-size PNG master and untouched pixels stay exactly as they were", async () => {const posted = fake.log.length;- const { stack, touched, final } = await session("hybrid");+ const { stack, touched, changed, final } = await session("hybrid");+ // Every change mask stayed near its edit (8-20 % of the picture painted), never the whole lossy frame.+ for (const c of changed) expect(c).toBeLessThan(0.3);+ expect(touched).toHaveLength(10);expect(stack.path()).toHaveLength(11);// Every graph's node 10 names a PNG master at full size (or the original), never a live frame's bytes.const prompts = fake.log.slice(posted).filter((l) => l.prompt?.prompt);@@ -148,8 +154,20 @@ describe("stacked live edits", () => {const unchanged = outside(touched);const score = ssim(a, b, unchanged);console.log(`hybrid: unchanged-region SSIM after 10 edits = ${score.toFixed(4)}, ${touched.length} edited areas`);- expect(score).toBe(1);- expect(laplacianVariance(b, unchanged) / laplacianVariance(a, unchanged)).toBe(1);+ expect(score).toBeCloseTo(1, 6);+ expect(laplacianVariance(b, unchanged) / laplacianVariance(a, unchanged)).toBeCloseTo(1, 4);+ // Stronger than SSIM: outside every edit, each pixel is the original's.+ let same = 0;+ let total = 0;+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++)+ if (unchanged(x, y)) {+ total++;+ if (a.px[y * W + x] === b.px[y * W + x]) same++;+ }+ console.log(`hybrid: ${total} untouched pixels, ${same} identical`);+ expect(total).toBeGreaterThan(W * H * 0.1);+ expect(same).toBe(total);}, 120_000);it("chain without the paste-back drifts (the reason for it)", async () => {diff --git a/tests/live-nodes.test.ts b/tests/live-nodes.test.tsindex 1140e50a..d5137fd1 100644--- a/tests/live-nodes.test.ts+++ b/tests/live-nodes.test.ts@@ -5,7 +5,8 @@import fs from "node:fs";import path from "node:path";import { describe, expect, it } from "vitest";-import { isLiveNodes, LIVE_NODE_CLASSES, LIVE_NODES_FILE_NAME, LIVE_NODES_SOURCE, LIVE_NODES_VERSION, liveNodesBase64 } from "@/lib/comfy-live-nodes";+import { createHash } from "node:crypto";+import { isLiveNodes, LIVE_NODE_CLASSES, LIVE_NODES_FILE_NAME, LIVE_NODES_SHA256, LIVE_NODES_SOURCE, LIVE_NODES_VERSION, liveNodesBase64, liveNodesState } from "@/lib/comfy-live-nodes";import { startFile } from "@/lib/comfy-install";import { parseComfyBinary } from "@/lib/comfy-ws";import { PACK_LIVE_CLASSES } from "@/lib/live/graph";@@ -39,10 +40,33 @@ describe("fuobe_live.py", () => {expect(bat.replaceAll("'+'", "")).toContain(liveNodesBase64());expect(bat).toContain("fuobe_live.py");});- it("answers its version", () => {- expect(isLiveNodes({ version: 1 })).toBe(true);- expect(isLiveNodes({ version: 0 })).toBe(false);+ it("is pinned by content: a changed file needs a new version and hash", () => {+ // Every released (version, sha256). Changing LIVE_NODES_SOURCE fails here until a new row is added with a new+ // version, and LIVE_NODES_VERSION and LIVE_NODES_SHA256 match it.+ const RELEASED: [number, string][] = [[2, "3386bb3743b41b8618b2da45ee257e48ef34b0d1cdac8abde3a2aa38974285d3"]];+ const sha = createHash("sha256").update(LIVE_NODES_SOURCE, "utf8").digest("hex");+ expect(sha).toBe(LIVE_NODES_SHA256);+ expect(RELEASED.at(-1)).toEqual([LIVE_NODES_VERSION, sha]);+ const versions = RELEASED.map(([v]) => v);+ expect(versions).toEqual([...versions].sort((a, b) => a - b));+ expect(new Set(versions).size).toBe(versions.length);+ expect(new Set(RELEASED.map(([, h]) => h)).size).toBe(RELEASED.length);+ });+ it("counts only an exact copy", () => {+ expect(isLiveNodes({ version: LIVE_NODES_VERSION, sha256: LIVE_NODES_SHA256 })).toBe(true);+ expect(isLiveNodes({ version: LIVE_NODES_VERSION })).toBe(false);+ expect(isLiveNodes({ version: LIVE_NODES_VERSION, sha256: "0".repeat(64) })).toBe(false);+ expect(isLiveNodes({ version: LIVE_NODES_VERSION + 1, sha256: LIVE_NODES_SHA256 })).toBe(false);expect(isLiveNodes(null)).toBe(false);+ expect(liveNodesState({ version: 1 })).toBe("outdated");+ expect(liveNodesState(null)).toBe("missing");+ expect(liveNodesState({ version: LIVE_NODES_VERSION, sha256: LIVE_NODES_SHA256 })).toBe("ok");+ });+ it("its save node is never served from ComfyUI's cache", () => {+ const save = LIVE_NODES_SOURCE.slice(LIVE_NODES_SOURCE.indexOf("class SaveImageFuobeLive:"));+ const isChanged = save.slice(save.indexOf("def IS_CHANGED(cls, **kwargs):"), save.indexOf("def save("));+ expect(isChanged).toContain('return float("nan")');+ expect(LIVE_NODES_SOURCE).toContain('return web.json_response({"version": FUOBE_LIVE, "sha256": FUOBE_LIVE_SHA256})');});});diff --git a/tests/live-render.test.ts b/tests/live-render.test.tsnew file mode 100644index 00000000..d7d06413--- /dev/null+++ b/tests/live-render.test.ts@@ -0,0 +1,150 @@+/**+ * Live edit's renders on the server path end, whatever ComfyUI does: against the ComfyUI stand-in, a graph identical to+ * the last one still sends its picture (the save node is never cached), an old copy of the nodes that serves it from+ * the cache fails instead of hanging, a render ComfyUI never starts hits its deadline, one dropped from the queue is+ * noticed, and a render stopped before or while it is posted never runs. Plus the session caps (sessions per person,+ * bytes per session).+ */+import fs from "node:fs";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { buildLiveGraph, slotBindings } from "@/lib/live/graph";+import { inputName } from "@/lib/live/names";+import { startLocalComfy, type IndexLike, type LocalComfy } from "./helpers/fake-local-comfy";++vi.mock("server-only", () => ({}));++const has = JSON.parse(fs.readFileSync(path.join(process.cwd(), "workflows/comfyui/requirements.json"), "utf8")) as IndexLike;+const fake: LocalComfy = await startLocalComfy({ cors: "off", stepMsAt512: 5, latencyMs: 2, has }, 3357);+process.env.COMFYUI_URL = fake.url;+const live = await import("@/server/live/comfy-live");+const sessions = await import("@/server/live/sessions");++let base = "";++beforeAll(async () => {+ const sharp = (await import("sharp")).default;+ const png = await sharp({ create: { width: 256, height: 320, channels: 3, background: { r: 120, g: 90, b: 60 } } }).png().toBuffer();+ const { name } = await inputName(png, "png");+ await live.stageInput(name, png, "image/png", true);+ base = name;+});+afterAll(async () => {+ globalThis.__fuobeLiveSocket?.ws?.close();+ await fake.close();+});++const graph = (prompt: string, slot: "live" | "keep" = "keep") =>+ buildLiveGraph({ prompt, seed: 7, base, ...slotBindings(slot, { liveSize: 384, keepRes: 1024, hasMask: false, to: "socket" }) }).graph;+const noop = () => {};+const posts = () => fake.log.filter((l) => l.path === "/prompt" && l.method === "POST").length;+/** ComfyUI restarted with other options: wait until the live socket has seen it go and come back. */+async function restart(o: Parameters<LocalComfy["restart"]>[0]) {+ fake.restart(o);+ await new Promise((r) => setTimeout(r, 150));+ expect(await live.waitOnline(5000)).toBe(true);+}+const later = (ms = 150) => new Promise((r) => setTimeout(r, ms));+const deletes = () => fake.log.filter((l) => l.path === "/queue" && (l.body as { delete?: string[] } | undefined)?.delete?.length);++describe("a render always ends", () => {+ it("the same graph twice sends its picture twice (a keep of the text just settled)", async () => {+ const g = graph("a red scarf");+ const a = await live.renderLive(g, new AbortController().signal, noop);+ const b = await live.renderLive(structuredClone(g), new AbortController().signal, noop);+ expect(a.data.length).toBeGreaterThan(100);+ expect(b.data.length).toBeGreaterThan(100);+ });++ it("an old copy of the nodes served from ComfyUI's cache fails at once instead of hanging", async () => {+ await restart({ oldLiveNodes: true });+ try {+ const g = graph("a blue scarf");+ await live.renderLive(g, new AbortController().signal, noop);+ const t0 = Date.now();+ await expect(live.renderLive(structuredClone(g), new AbortController().signal, noop)).rejects.toMatchObject({ code: "failed" });+ expect(Date.now() - t0).toBeLessThan(2000);+ expect((await live.liveFacts()).outdated).toBe(true);+ } finally {+ await restart({ oldLiveNodes: false });+ }+ });++ it("a render ComfyUI never starts hits its deadline and is taken off the queue", async () => {+ await restart({ stall: true });+ try {+ const before = deletes().length;+ await expect(live.renderLive(graph("a green scarf", "live"), new AbortController().signal, noop, 600)).rejects.toMatchObject({ code: "failed" });+ await later();+ expect(deletes().length).toBeGreaterThan(before);+ } finally {+ await restart({ stall: false });+ }+ });++ it("a render dropped from ComfyUI's queue (Clear queue) is noticed", async () => {+ await restart({ stall: true });+ try {+ const p = live.renderLive(graph("a yellow scarf", "live"), new AbortController().signal, noop, 60_000);+ await new Promise((r) => setTimeout(r, 200));+ await fetch(`${fake.url}/queue`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ clear: true }) });+ const t0 = Date.now();+ await expect(p).rejects.toMatchObject({ code: "failed" });+ expect(Date.now() - t0).toBeLessThan(live.GONE_CHECK_MS * 3 + 1000);+ } finally {+ await restart({ stall: false });+ }+ }, 20_000);++ it("a render stopped before it is posted never reaches ComfyUI", async () => {+ const ctl = new AbortController();+ ctl.abort();+ const before = posts();+ await expect(live.renderLive(graph("a pink scarf", "live"), ctl.signal, noop)).rejects.toMatchObject({ code: "stopped" });+ expect(posts()).toBe(before);+ });++ it("a render stopped while it is posted is deleted again once ComfyUI has it", async () => {+ await restart({ stall: true });+ try {+ const ctl = new AbortController();+ const before = deletes().length;+ const sent = posts();+ const p = live.renderLive(graph("a white scarf", "live"), ctl.signal, noop);+ // Abort the moment the prompt reaches ComfyUI, before its answer is back.+ while (posts() === sent) await later(1);+ ctl.abort();+ await expect(p).rejects.toMatchObject({ code: "stopped" });+ await later();+ expect(deletes().length - before).toBeGreaterThanOrEqual(1);+ const q = (await (await fetch(`${fake.url}/queue`)).json()) as { queue_pending: unknown[][] };+ expect(q.queue_pending).toHaveLength(0);+ } finally {+ await restart({ stall: false });+ }+ });+});++describe("live sessions are capped", () => {+ it("a person has at most 4 sessions: a fifth ends the one used longest ago", () => {+ const opened = Array.from({ length: 5 }, () => sessions.openSession("acct:cap", undefined));+ expect(sessions.sessionOf("acct:cap", opened[0].id)).toBeNull();+ for (const s of opened.slice(1)) expect(sessions.sessionOf("acct:cap", s.id)).not.toBeNull();+ // Someone else's sessions don't count.+ expect(sessions.sessionOf("acct:other", opened[1].id)).toBeNull();+ });++ it("a session holds at most SESSION_BYTES of pictures", async () => {+ const s = sessions.openSession("acct:bytes", undefined);+ const big = (i: number) => {+ // A PNG header and a large body: the stand-in takes any bytes.+ const b = new Uint8Array(30 * 2 ** 20);+ b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 1, 0, 0, 0, 1, 0]);+ b[100] = i;+ return b;+ };+ for (let i = 0; i < 8; i++) await sessions.stage(s, big(i), async () => big(i));+ expect(sessions.heldBytes(s)).toBeLessThanOrEqual(sessions.SESSION_BYTES);+ expect(s.staged.size).toBe(8);+ }, 30_000);+});diff --git a/tests/live-scheduler.test.ts b/tests/live-scheduler.test.tsindex c0ce493c..e5a33e9d 100644--- a/tests/live-scheduler.test.ts+++ b/tests/live-scheduler.test.ts@@ -166,6 +166,15 @@ describe("live scheduler", () => {expect(outcome(await s.submit({ seq: 99, slot: "live", key: "z", payload: "z" }))).toBe("dropped:closed");});+ it("a job stopped while it ran is a drop, even when its picture came in anyway", async () => {+ let finish!: (v: string) => void;+ const s = new LiveScheduler<string, string>({ run: () => new Promise<string>((r) => (finish = r)) });+ const p = s.submit({ seq: 1, slot: "live", key: "a", payload: "a" });+ s.cancel(() => true);+ finish("pic:a");+ expect(outcome(await p)).toBe("dropped:cancelled");+ });+it("a failed render is an error, not a drop", async () => {const s = new LiveScheduler<string, string>({ run: () => Promise.reject(new Error("out of memory")) });expect(outcome(await s.submit({ seq: 1, slot: "live", key: "a", payload: "a" }))).toBe("error:out of memory");