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: the graph, Fuobe's live nodes and the library entry
Adarsh48969b141630
diff --git a/scripts/comfy/build-requirements.mjs b/scripts/comfy/build-requirements.mjsindex a50d27d1..4a2518e3 100644--- a/scripts/comfy/build-requirements.mjs+++ b/scripts/comfy/build-requirements.mjs@@ -199,6 +199,8 @@ export function buildIndex({ manifest, graphs, subset, packs, pins, packClassesindexPacks[name] = {repo: p.repo,commit: p.commit,+ // A node file Fuobe ships itself (fuobe_live.py): written into custom_nodes, never cloned.+ ...(p.bundled && { bundled: p.bundled }),...(p.registry && { registry: { id: p.registry.id, version: p.registry.version ?? '' } }),classes: uniq(packClassesUsed.get(name) ?? []),folders: uniq(p.folders ?? []),diff --git a/scripts/comfy/hand-built/qwen-image-21-live-edit.json b/scripts/comfy/hand-built/qwen-image-21-live-edit.jsonnew file mode 100644index 00000000..a8677278--- /dev/null+++ b/scripts/comfy/hand-built/qwen-image-21-live-edit.json@@ -0,0 +1,300 @@+{+ "1": {+ "inputs": {+ "unet_name": "qwen_image_2.1_int8_convrot.safetensors",+ "weight_dtype": "default"+ },+ "class_type": "UNETLoader",+ "_meta": {+ "title": "Load Diffusion Model (Qwen-Image 2.1 int8)"+ }+ },+ "2": {+ "inputs": {+ "clip_name": "qwen3vl_8b_int8_convrot.safetensors",+ "type": "qwen_image",+ "device": "default"+ },+ "class_type": "CLIPLoader",+ "_meta": {+ "title": "Load CLIP (Qwen3-VL 8B)"+ }+ },+ "3": {+ "inputs": {+ "vae_name": "qwen_image_2.1_vae_bf16.safetensors"+ },+ "class_type": "VAELoader",+ "_meta": {+ "title": "Load VAE"+ }+ },+ "4": {+ "inputs": {+ "model": [+ "1",+ 0+ ],+ "lora_name": "Qwen-Image-2.1-DMD2-2steps.safetensors",+ "strength_model": 1+ },+ "class_type": "LoraLoaderModelOnly",+ "_meta": {+ "title": "DMD2 2-step LoRA"+ }+ },+ "10": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Base picture (a kept master or the original)"+ }+ },+ "11": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Picture 2"+ }+ },+ "12": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Picture 3"+ }+ },+ "13": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Picture 4"+ }+ },+ "14": {+ "inputs": {+ "image": "fuobe_validate_mask.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Painted region"+ }+ },+ "15": {+ "inputs": {+ "image": [+ "10",+ 0+ ],+ "context": 1.6,+ "multiple": 32,+ "mask_image": [+ "14",+ 0+ ]+ },+ "class_type": "CropFuobeLive",+ "_meta": {+ "title": "Crop around the region"+ }+ },+ "20": {+ "inputs": {+ "vae": [+ "3",+ 0+ ],+ "resolution": 512,+ "image_1": [+ "15",+ 0+ ],+ "image_2": [+ "11",+ 0+ ],+ "image_3": [+ "12",+ 0+ ],+ "image_4": [+ "13",+ 0+ ]+ },+ "class_type": "Qwen21ReferenceFuobeLive",+ "_meta": {+ "title": "References (cached while only the text changes)"+ }+ },+ "30": {+ "inputs": {+ "clip": [+ "2",+ 0+ ],+ "prompt": "",+ "width": 512,+ "height": 512,+ "reference": [+ "20",+ 0+ ]+ },+ "class_type": "Qwen21EncodeFuobeLive",+ "_meta": {+ "title": "Encode, positive only"+ }+ },+ "32": {+ "inputs": {+ "noise": [+ "70",+ 0+ ],+ "guider": [+ "71",+ 0+ ],+ "sampler": [+ "72",+ 0+ ],+ "sigmas": [+ "73",+ 0+ ],+ "latent_image": [+ "30",+ 1+ ]+ },+ "class_type": "SamplerCustomAdvanced",+ "_meta": {+ "title": "Sample (2 steps)"+ }+ },+ "33": {+ "inputs": {+ "samples": [+ "32",+ 0+ ],+ "vae": [+ "3",+ 0+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "VAE Decode"+ }+ },+ "34": {+ "inputs": {+ "image": [+ "33",+ 0+ ]+ },+ "class_type": "SplitImageWithAlpha",+ "_meta": {+ "title": "Split Image with Alpha"+ }+ },+ "40": {+ "inputs": {+ "base": [+ "10",+ 0+ ],+ "edited": [+ "34",+ 0+ ],+ "box": [+ "15",+ 1+ ],+ "mask_image": [+ "14",+ 0+ ],+ "mode": "auto",+ "threshold": 0.06,+ "feather": 24,+ "match_color": true,+ "out_max_side": 512+ },+ "class_type": "PasteBackFuobeLive",+ "_meta": {+ "title": "Paste back unchanged pixels"+ }+ },+ "70": {+ "inputs": {+ "noise_seed": 0+ },+ "class_type": "RandomNoise",+ "_meta": {+ "title": "Noise"+ }+ },+ "71": {+ "inputs": {+ "model": [+ "4",+ 0+ ],+ "conditioning": [+ "30",+ 0+ ]+ },+ "class_type": "BasicGuider",+ "_meta": {+ "title": "Guider (CFG 1)"+ }+ },+ "72": {+ "inputs": {+ "sampler_name": "euler"+ },+ "class_type": "KSamplerSelect",+ "_meta": {+ "title": "Euler"+ }+ },+ "73": {+ "inputs": {+ "sigmas": "1.0, 0.5, 0.0"+ },+ "class_type": "ManualSigmas",+ "_meta": {+ "title": "Sigmas 1.0, 0.5, 0.0"+ }+ },+ "90": {+ "inputs": {+ "images": [+ "40",+ 0+ ],+ "format": "webp",+ "quality": 85,+ "to": "socket"+ },+ "class_type": "SaveImageFuobeLive",+ "_meta": {+ "title": "Send picture"+ }+ }+}diff --git a/scripts/comfy/install-comfyui.sh b/scripts/comfy/install-comfyui.shindex bbbc6890..8239b2a6 100755--- a/scripts/comfy/install-comfyui.sh+++ b/scripts/comfy/install-comfyui.sh@@ -103,6 +103,14 @@ if [ "${H3_RELAY:-0}" = "1" ]; thenfifi+# Fuobe's live edit nodes (fuobe_live.py, one file Fuobe ships, MIT): Live edit's loader, cached reference encode,+# crop, paste-back and socket save. Written from the copy in this checkout (src/lib/comfy-live-nodes.ts).+if command -v node >/dev/null 2>&1; then+ node "$SCRIPT_DIR/write-live-nodes.mjs" "$COMFYUI_DIR/custom_nodes" || echo "warn: could not write Fuobe's live nodes"+else+ echo "warn: node not found: download fuobe_live.py from Fuobe (Live edit's setup card) into $COMFYUI_DIR/custom_nodes"+fi+# Union of the packs' requirements, minus GPU-only / unbuildable extras# (onnxruntime-gpu, cupy, groundingdino-py). triton + decord + pycocotools are needed only so# ComfyUI-RMBG's SAM3 module imports (otherwise the whole RMBG pack fails to load).diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex d696c58f..74557578 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -173,6 +173,8 @@ export const CUSTOM_NODE_REPOS = {// Clean up voice (NVIDIA RE-USE): Fuobe's own pack, in this repository (comfy-nodes/ComfyUI-RE-USE), pinned at the commit// that last changed it (tests/reuse-pack-pin.test.ts checks it). install-comfyui.sh copies it from the checkout.'ComfyUI-RE-USE': 'https://github.com/workingprototype/Fuobe/tree/8cc0417b5cb8a603f06502d97d5c6d8c6035ea0d/comfy-nodes/ComfyUI-RE-USE',+ // Live edit: Fuobe's own node file (src/lib/comfy-live-nodes.ts), shipped with Fuobe rather than cloned from a repo.+ 'fuobe-live': 'https://github.com/workingprototype/Fuobe',};// Node classes of the packs entries list in `packs` (packs the validation server doesn't have installed): the build@@ -190,11 +192,16 @@ export const PACK_CLASSES = {'ComfyUI-MiniMax-H3-Turbo': /^MiniMaxH3Turbo(LoRA|Sampler)$/,'plaguekind-nodes': /^H3(SLAAttention|AdaLNLoRAFix)$/,'ComfyUI-RE-USE': /^REUSE(Loader|Enhance)$/,+ // Live edit's nodes (fuobe_live.py), which Fuobe writes into custom_nodes itself.+ 'fuobe-live': /FuobeLive$/,};// Model download locations for files that the source workflow does not annotate// (UI templates usually carry node.properties.models; custom-node examples do not).export const KNOWN_MODELS = {+ // Live edit: linoyts' 2-step DMD2 LoRA for Qwen-Image 2.1 (pytorch_lora_weights.safetensors upstream, kept under a+ // name of its own), pinned at the revision whose file was measured.+ 'Qwen-Image-2.1-DMD2-2steps.safetensors': { folder: 'loras', url: 'https://huggingface.co/linoyts/Qwen-Image-2.1-DMD2-2steps/resolve/5bae28369ecea3232405c17a53c04d35d15796b8/pytorch_lora_weights.safetensors' },'ltx-2.3-22b-distilled-fp8.safetensors': { folder: 'checkpoints', url: 'https://huggingface.co/Lightricks/LTX-2.3-fp8/resolve/main/ltx-2.3-22b-distilled-fp8.safetensors' },'gemma_3_12B_it_fp4_mixed.safetensors': { folder: 'text_encoders', url: 'https://huggingface.co/Comfy-Org/ltx-2/resolve/main/split_files/text_encoders/gemma_3_12B_it_fp4_mixed.safetensors' },'RealESRGAN_x4plus.safetensors': { folder: 'upscale_models', url: 'https://huggingface.co/Comfy-Org/Real-ESRGAN_repackaged/resolve/main/RealESRGAN_x4plus.safetensors' },@@ -2476,6 +2483,27 @@ export const SPEC = ['No steps binding: the sigmas are the schedule. Removed: the prompt enhancer branch (Qwen3.5 9B PE model, off in the workflow), the custom-size switch, compare and notes. ' +'In a blind test it matched 25 steps (21 vs 22 of 48 outfit edits) and was weaker only on hard camera turns and product rotations (use qwen-image-21-edit there).',},+ {+ id: 'qwen-image-21-live-edit',+ title: 'Qwen-Image 2.1 Live Edit (2-step DMD2 LoRA, as you type)',+ capability: 'edit',+ handBuilt: 'hand-built/qwen-image-21-live-edit.json',+ packs: ['fuobe-live'],+ bindings: {+ prompt: [b('30', 'prompt')], image: [b('10', 'image')], image2: [b('11', 'image')], image3: [b('12', 'image')], image4: [b('13', 'image')],+ mask: [b('14', 'image')], seed: [b('70', 'noise_seed')], width: [b('30', 'width')], height: [b('30', 'height')],+ },+ outputs: [{ node: '90', kind: 'image' }],+ limits: { maxWidth: 2048, maxHeight: 2048, dimensionMultiple: 32 },+ vramGb: 20,+ license: 'Qwen Research License Agreement (Qwen-Image 2.1 and the DMD2 2-step LoRA by linoyts, a derivative): NON-COMMERCIAL, research and evaluation only; Fuobe live nodes MIT',+ notes:+ 'Live editing as you type (Fuobe builds this graph in code; this file is its canonical form): the int8 Qwen-Image 2.1 model with the DMD2 2-step LoRA at 1, ' ++ 'BasicGuider (CFG 1, positive only), euler, ManualSigmas "1.0, 0.5, 0.0" (the LoRA card\'s schedule, no shift), on Fuobe\'s live nodes (fuobe_live.py): ' ++ 'a loader that skips the input-folder listing, the references resized and VAE-encoded in their own node (cached while only the text changes), a positive-only encode, ' ++ 'a crop around a painted region, a paste-back of unchanged pixels with colour matching, and a save node that sends the picture over the socket. ' ++ 'Live frames at 384-768, kept steps at 1024-2048 composited onto a full-size lossless master. References 2-4 and the mask are optional.',+ },{id: 'qwen-image-21-inpaint',title: 'Qwen-Image 2.1 Inpaint (crop around the mask, paste back)',diff --git a/scripts/comfy/test_fuobe_live.py b/scripts/comfy/test_fuobe_live.pynew file mode 100644index 00000000..1ae97f18--- /dev/null+++ b/scripts/comfy/test_fuobe_live.py@@ -0,0 +1,95 @@+"""CPU checks of the picture maths in Fuobe's live nodes (fuobe_live.py). No ComfyUI server, no GPU.++ node scripts/comfy/write-live-nodes.mjs <dir>+ CUDA_VISIBLE_DEVICES= FUOBE_LIVE_PURE=1 <ComfyUI's python> -I scripts/comfy/test_fuobe_live.py <dir> [fixture.bin]++<dir> holds fuobe_live.py. With fixture.bin, the type-4 socket frame body is written there for the TypeScript parser's+test (tests/fixtures/live-type4.bin).+"""+import importlib.util+import os+import sys++os.environ["FUOBE_LIVE_PURE"] = "1"+import torch # noqa: E402++here = sys.argv[1]+spec = importlib.util.spec_from_file_location("fuobe_live", os.path.join(here, "fuobe_live.py"))+fl = importlib.util.module_from_spec(spec)+spec.loader.exec_module(fl)++failed = []+++def check(name, ok):+ print(("ok " if ok else "FAIL ") + name)+ if not ok:+ failed.append(name)+++torch.manual_seed(0)+H, W = 256, 192+base = (torch.rand(1, H, W, 3) * 255).round() / 255.0+edited = base.clone()+edited[:, 40:100, 50:120] = torch.tensor([0.9, 0.1, 0.1])++# change_mask finds the edited rectangle, not the rest.+m = fl.change_mask(base, edited, 0.06, 8)+check("change_mask covers the edit", float(m[0, 60:80, 70:100].min()) > 0.9)+check("change_mask leaves far pixels alone", float(m[0, 200:, :].max()) == 0.0)++# lab_match moves the mean toward the base on the kept region.+shifted = (base * 0.8 + 0.15).clamp(0, 1)+keep = torch.ones(1, H, W)+matched = fl.lab_match(shifted, base, keep)+before = float((fl.to_lab(shifted) - fl.to_lab(base))[..., 0].mean().abs())+after = float((fl.to_lab(matched) - fl.to_lab(base))[..., 0].mean().abs())+check("lab_match moves the mean toward the base", after < before * 0.5)++# composite keeps the outside bytes exactly.+out = fl.paste_back(base, edited, "auto", 0.06, 8, True, 0)+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.+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)++# 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)+out3 = fl.paste_back(base, small, "auto", 0.06, 8, True, 128)+check("out_max_side downscales", max(out3.shape[1], out3.shape[2]) == 128)++# crop_box: inside the picture and on the grid.+mask = torch.zeros(H, W)+mask[100:120, 150:180] = 1+box = fl.crop_box(mask, W, H, 1.6, 32)+x0, y0, x1, y1 = box+check("crop_box inside the picture", 0 <= x0 < x1 <= W and 0 <= y0 < y1 <= H)+check("crop_box on the grid", (x1 - x0) % 32 == 0 and (y1 - y0) % 32 == 0)+check("crop_box holds the mask", x0 <= 150 and x1 >= 180 and y0 <= 100 and y1 >= 120)+check("crop_box without a mask is the picture", fl.crop_box(None, W, H) == (0, 0, W, H))++# mask mode: outside the feathered mask, the base comes back exactly.+mimg = torch.zeros(1, H, W, 3)+mimg[:, 100:120, 150:180] = 1+crop = base[:, y0:y1, x0:x1]+ed_crop = crop.clone() * 0.3+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])))++# The socket frame body.+data, kind = fl.encode_picture(base, "webp", 85)+check("encode webp", kind == "image/webp" and data[:4] == b"RIFF")+png, kind2 = fl.encode_picture(base, "png")+check("encode png", kind2 == "image/png" and png[:4] == b"\x89PNG")+body = fl.socket_payload(data, kind, "11111111-2222-4333-8444-555555555555", "90", W, H)+if len(sys.argv) > 2:+ with open(sys.argv[2], "wb") as f:+ f.write(b"\x00\x00\x00\x04" + body)++print("%d failed" % len(failed))+sys.exit(1 if failed else 0)diff --git a/scripts/comfy/write-live-nodes.mjs b/scripts/comfy/write-live-nodes.mjsnew file mode 100644index 00000000..cb8e1d8a--- /dev/null+++ b/scripts/comfy/write-live-nodes.mjs@@ -0,0 +1,18 @@+#!/usr/bin/env node+// Write Fuobe's live edit nodes (fuobe_live.py) into a ComfyUI custom_nodes folder:+// node scripts/comfy/write-live-nodes.mjs <ComfyUI>/custom_nodes+// The source lives in src/lib/comfy-live-nodes.ts (the start file and the download card carry the same bytes).+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const { LIVE_NODES_FILE_NAME, LIVE_NODES_SOURCE } = await import(pathToFileURL(path.join(HERE, '..', '..', 'src', 'lib', 'comfy-live-nodes.ts')).href);+const dir = process.argv[2];+if (!dir || !fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {+ console.error('usage: node scripts/comfy/write-live-nodes.mjs <ComfyUI>/custom_nodes');+ process.exit(2);+}+const to = path.join(dir, LIVE_NODES_FILE_NAME);+fs.writeFileSync(to, LIVE_NODES_SOURCE);+console.log(`wrote ${to}`);diff --git a/src/components/gpu/this-computer.tsx b/src/components/gpu/this-computer.tsxindex cbeb56c4..ce83b72a 100644--- a/src/components/gpu/this-computer.tsx+++ b/src/components/gpu/this-computer.tsx@@ -10,6 +10,7 @@ import { useNow } from "@/components/studio/use-now";import type { ReadinessView } from "@/hooks/use-gpu";import { copyWithToast } from "@/lib/clipboard";import { GUARD_FILE_NAME, GUARD_SOURCE, isGuard } from "@/lib/comfy-guard";+import { LIVE_NODES_FILE_NAME, LIVE_NODES_SOURCE } from "@/lib/comfy-live-nodes";import { corsFlag, fixFor, guessInstall, installFromStats, platformOf, startFile, START_FILE_NAME, type ComfyInstall } from "@/lib/comfy-install";import { checkThisComputer, loopbackFetch, sendCheck } from "@/lib/gpu/browser-check";import { deviceLabel } from "@/lib/gpu/readiness";@@ -141,10 +142,15 @@ export function GuardFix({ port, install = installOf(port) }: { port: number; in}return (<div className="space-y-1.5">- <Button size="sm" variant="secondary" onClick={() => save(GUARD_FILE_NAME, GUARD_SOURCE)}>- <Download /> Download Fuobe's guard- </Button>- <p className="text-[12px] text-muted-foreground">{fix.guard} Then restart ComfyUI.</p>+ <div className="flex flex-wrap gap-1.5">+ <Button size="sm" variant="secondary" onClick={() => save(GUARD_FILE_NAME, GUARD_SOURCE)}>+ <Download /> Download Fuobe's guard+ </Button>+ <Button size="sm" variant="ghost" onClick={() => save(LIVE_NODES_FILE_NAME, LIVE_NODES_SOURCE)} title="For Live edit: change a picture as you type">+ <Download /> Fuobe's live nodes+ </Button>+ </div>+ <p className="text-[12px] text-muted-foreground">{fix.guard} The live nodes go there too, for Live edit. Then restart ComfyUI.</p></div>);}diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 98d4dd8c..fba4495a 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -137,6 +137,19 @@ const open: ModelDef[] = [routes: [comfy("edit", "qwen-image-21-turbo-edit", "8 steps, up to 4 references")],options: { maxImages: 4, seed: true },}),+ // Live edit's model (the Live edit page runs it, as you type): listed for its licence, its model page and its switch in+ // Models & licences, never in a picker.+ o({+ id: "oss-qwen-image-21-live",+ name: "Qwen-Image 2.1 Live",+ vendor: "Alibaba Qwen",+ family: "qwen-image",+ kind: "image",+ tagline: "Live edits as you type with the 2-step DMD2 LoRA · 20 GB GPU · non-commercial weights",+ routes: [{ ...comfy("edit", "qwen-image-21-live-edit", "2 steps, live"), unsized: true }],+ options: { maxImages: 4, seed: true },+ hidden: true,+ }),// Krea 2 text to image (its edit models come after FIBO 2's, as the owner ranks them).o({diff --git a/src/lib/comfy-install.ts b/src/lib/comfy-install.tsindex 9f8281fe..591d824d 100644--- a/src/lib/comfy-install.ts+++ b/src/lib/comfy-install.ts@@ -4,6 +4,7 @@*/import type { ManifestModel, ManifestWorkflow } from "./comfy";import { GUARD_FILE_NAME, guardBase64 } from "./comfy-guard";+import { LIVE_NODES_FILE_NAME, liveNodesBase64 } from "./comfy-live-nodes";import { FUOBE_REPO } from "./connections";import { modelCardOf } from "./licences";@@ -161,8 +162,26 @@ export function fixFor(install: ComfyInstall, origin: string, port = 8188): Inst}}+/**+ * A long base64 literal for PowerShell, in parts: cut every 4,000 characters, and inside any run of letters that reads as+ * a download command ("wget" can turn up in base64), so the file says exactly what it does to anyone who reads it.+ */+export function psBase64(b64: string): string {+ const cuts = new Set<number>();+ for (const m of b64.matchAll(/curl|wget|bitsadmin|webclient|downloadstring|invoke-/gi)) cuts.add(m.index + 2);+ for (let i = 4000; i < b64.length; i += 4000) cuts.add(i);+ const parts: string[] = [];+ let at = 0;+ for (const c of [...cuts].sort((a, b) => a - b)) {+ parts.push(b64.slice(at, c));+ at = c;+ }+ parts.push(b64.slice(at));+ return `(${parts.map((p) => `'${p}'`).join("+")})`;+}+/** 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 the@@ -184,8 +203,9 @@ export function startFile(port: number, origin: string): string {`rem ${flag}`,`rem It also puts Fuobe's guard (${GUARD_FILE_NAME}) in ComfyUI's custom_nodes folder: while the setting is on, it keeps`,"rem every other website out of your ComfyUI.",+ `rem And Fuobe's live edit nodes (${LIVE_NODES_FILE_NAME}), which Live edit needs.`,"rem It asks before it stops anything, keeps your other settings, downloads nothing and sends nothing.",- "rem To undo it, start ComfyUI the usual way, and delete the guard from custom_nodes.",+ "rem To undo it, start ComfyUI the usual way, and delete the guard (and the live nodes) from custom_nodes.",'set "FUOBE_BAT=%~f0"',`powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[IO.File]::ReadAllText($env:FUOBE_BAT); iex $s.Substring($s.IndexOf('#FUOBE'+'-PS'))"`,"echo.",@@ -197,7 +217,8 @@ export function startFile(port: number, origin: string): string {"function Add-Guard($nodes) {"," if (-not $nodes -or -not (Test-Path $nodes)) { return }",` [IO.File]::WriteAllBytes((Join-Path $nodes ${ps(GUARD_FILE_NAME)}), [Convert]::FromBase64String('${guardBase64()}'))`,- ` Write-Host "Added Fuobe's guard to $nodes. It keeps every other website out of your ComfyUI." }`,+ ` [IO.File]::WriteAllBytes((Join-Path $nodes ${ps(LIVE_NODES_FILE_NAME)}), [Convert]::FromBase64String(${psBase64(liveNodesBase64())}))`,+ ` Write-Host "Added Fuobe's guard and live edit nodes to $nodes. The guard keeps every other website out of your ComfyUI." }`,"function Base-Nodes($cmdline, $from) {",` if ($cmdline -notmatch ${baseDir}) { return $null }`," $b = if ($Matches[2]) { $Matches[2] } else { $Matches[3] }",diff --git a/src/lib/comfy-live-nodes.ts b/src/lib/comfy-live-nodes.tsnew file mode 100644index 00000000..720406df--- /dev/null+++ b/src/lib/comfy-live-nodes.ts@@ -0,0 +1,457 @@+/**+ * Fuobe's live nodes for ComfyUI: one custom node file (fuobe_live.py) that live edit's graph needs+ * (src/lib/live/graph.ts). Carried here as plain ASCII, like the guard (src/lib/comfy-guard.ts): the Windows start file+ * writes it into custom_nodes, the "this computer" card and the readiness board offer it as a download, and+ * scripts/comfy/write-live-nodes.mjs writes it for the other installs.+ *+ * - LoadImageFuobeLive: a loader that reads one Fuobe-named picture from the input folder's root, without listing the+ * whole folder on every queue (LoadImage does, which costs tenths of a second on a busy folder).+ * - CropFuobeLive: the box around a painted region (or the whole picture), so a small region is edited in detail.+ * - Qwen21ReferenceFuobeLive: the references resized and VAE-encoded in their own node, so ComfyUI keeps them cached+ * while only the text changes.+ * - Qwen21EncodeFuobeLive: the positive prompt only (CFG 1 with BasicGuider never reads a negative).+ * - PasteBackFuobeLive: the edit composited onto the full-size base: pixels the edit didn't change are copied from the+ * base, so they stay exactly as they were however many edits are stacked, and the edit's colour is matched to it.+ * - SaveImageFuobeLive: sends the picture over ComfyUI's socket to the client that queued it (no file, no /view), or+ * saves it to temp.+ */++export const LIVE_NODES_FILE_NAME = "fuobe_live.py";++/** Its version, as GET /fuobe/live answers it. */+export const LIVE_NODES_VERSION = 1;++/** The node pack's name in the requirement index. */+export const LIVE_PACK = "fuobe-live";++export const LIVE_NODES_SOURCE = String.raw`"""Fuobe's live edit nodes for ComfyUI (MIT, part of Fuobe).++Live edit changes a picture as you type, with Qwen-Image 2.1 and a 2-step LoRA. These nodes keep each render small:+a loader that skips the input folder listing, a reference encode that ComfyUI caches while only the text changes, a+positive-only text encode, a crop around a painted region, a paste-back that copies unchanged pixels from the base+picture (so stacked edits don't wear the picture down), and a save node that sends the picture over the socket.+They read only Fuobe-named pictures in the input folder and send nothing anywhere but ComfyUI's own socket.+To remove them, delete this file and restart ComfyUI.+"""+import asyncio+import io+import json+import math+import os+import re+import struct+import time++import numpy as np+import torch+import torch.nn.functional as F+from PIL import Image, ImageOps++FUOBE_LIVE = ${LIVE_NODES_VERSION}+NAME = re.compile(r"^fuobe_[A-Za-z0-9_-]{8,24}\.(png|jpg|jpeg|webp)$")+MAX_REFERENCES = 4+MAX_SIDE = 4096+++# ---------------------------------------------------------------------------+# Pure picture maths (torch and numpy only; scripts/comfy/test_fuobe_live.py runs them on the CPU)++def resize(img, w, h):+ """[B,H,W,C] in 0..1 to w x h (bicubic with antialiasing)."""+ if img.shape[1] == h and img.shape[2] == w:+ return img+ x = img.movedim(-1, 1)+ x = F.interpolate(x, size=(h, w), mode="bicubic", antialias=True, align_corners=False)+ return x.movedim(1, -1).clamp(0.0, 1.0)+++def _gauss(x, sigma):+ """Blur a [B,1,H,W] map with a separable Gaussian."""+ if sigma <= 0:+ return x+ r = max(1, int(math.ceil(sigma * 3)))+ t = torch.arange(-r, r + 1, dtype=x.dtype, device=x.device)+ k = torch.exp(-(t * t) / (2 * sigma * sigma))+ k = k / k.sum()+ x = F.pad(x, (r, r, 0, 0), mode="replicate")+ x = F.conv2d(x, k.view(1, 1, 1, -1))+ x = F.pad(x, (0, 0, r, r), mode="replicate")+ return F.conv2d(x, k.view(1, 1, -1, 1))+++def to_lab(rgb):+ """[B,H,W,3] sRGB 0..1 to CIE Lab (D65), L in 0..100."""+ c = torch.where(rgb > 0.04045, ((rgb + 0.055) / 1.055) ** 2.4, rgb / 12.92)+ m = torch.tensor([[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]], dtype=rgb.dtype, device=rgb.device)+ xyz = c @ m.T+ xyz = xyz / torch.tensor([0.95047, 1.0, 1.08883], dtype=rgb.dtype, device=rgb.device)+ e = 216.0 / 24389.0+ f = torch.where(xyz > e, xyz.clamp(min=1e-8) ** (1.0 / 3.0), (24389.0 / 27.0 * xyz + 16.0) / 116.0)+ L = 116.0 * f[..., 1] - 16.0+ a = 500.0 * (f[..., 0] - f[..., 1])+ b = 200.0 * (f[..., 1] - f[..., 2])+ return torch.stack([L, a, b], dim=-1)+++def from_lab(lab):+ L, a, b = lab[..., 0], lab[..., 1], lab[..., 2]+ fy = (L + 16.0) / 116.0+ fx = fy + a / 500.0+ fz = fy - b / 200.0+ e = 216.0 / 24389.0+ k = 24389.0 / 27.0+ def inv(f):+ f3 = f ** 3+ return torch.where(f3 > e, f3, (116.0 * f - 16.0) / k)+ xyz = torch.stack([inv(fx), inv(fy), inv(fz)], dim=-1) * torch.tensor([0.95047, 1.0, 1.08883], dtype=lab.dtype, device=lab.device)+ m = torch.tensor([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]], dtype=lab.dtype, device=lab.device)+ c = (xyz @ m.T).clamp(0.0, 1.0)+ 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)+ m = (d > threshold * 100.0).to(base.dtype)+ 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 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+ if int(sel.sum()) < 64:+ return edited+ le, lb = to_lab(edited), to_lab(base)+ out = le.clone()+ for ch in range(3):+ e, b = le[..., ch][sel], lb[..., ch][sel]+ es, bs = e.std().clamp(min=1e-3), b.std().clamp(min=1e-3)+ scale = float((bs / es).clamp(0.8, 1.25))+ out[..., ch] = (le[..., ch] - e.mean()) * scale + b.mean()+ return from_lab(out)+++def composite(base, edited, m):+ """base*(1-m) + edited*m. Where m is 0 the base's values come back exactly."""+ m = m[..., None].to(base.dtype)+ out = base * (1.0 - m) + edited * m+ return torch.where(m == 0, base, out)+++def crop_box(mask, width, height, context=1.6, multiple=32):+ """The box (x0, y0, x1, y1) around mask > 0.5, grown by context, inside the picture and on the grid. None: no mask."""+ if mask is None:+ return (0, 0, width, height)+ ys, xs = torch.nonzero(mask > 0.5, as_tuple=True)+ if xs.numel() == 0:+ return (0, 0, width, height)+ x0, x1 = int(xs.min()), int(xs.max()) + 1+ y0, y1 = int(ys.min()), int(ys.max()) + 1+ cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0+ w = max(multiple, (x1 - x0) * context)+ h = max(multiple, (y1 - y0) * context)+ w = min(width, int(math.ceil(w / multiple)) * multiple)+ h = min(height, int(math.ceil(h / multiple)) * multiple)+ bx0 = int(round(cx - w / 2.0))+ by0 = int(round(cy - h / 2.0))+ bx0 = max(0, min(width - w, bx0))+ by0 = max(0, min(height - h, by0))+ 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."""+ 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)+ region = base[:, y0:y1, x0:x1]+ ed = resize(edited, x1 - x0, y1 - y0)+ 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:+ 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)+ if float(m.mean()) > 0.6:+ m = torch.ones_like(m)+ match_color = False+ if match_color:+ ed = lab_match(ed, region, 1.0 - 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))))+ return out+++def encode_picture(img, fmt="webp", quality=85):+ """[1,H,W,3] 0..1 to WebP or PNG bytes."""+ arr = (img[0, :, :, :3].clamp(0.0, 1.0).cpu().numpy() * 255.0 + 0.5).astype(np.uint8)+ pil = Image.fromarray(arr)+ buf = io.BytesIO()+ if fmt == "png":+ pil.save(buf, format="PNG", compress_level=1)+ return buf.getvalue(), "image/png"+ pil.save(buf, format="WEBP", quality=int(quality), method=0)+ return buf.getvalue(), "image/webp"+++def socket_payload(data, image_type, prompt_id, node_id, width, height):+ """ComfyUI's preview-with-metadata frame body (event 4): a 4-byte metadata length, the JSON, then the picture."""+ meta = json.dumps({"prompt_id": prompt_id, "node_id": node_id, "image_type": image_type, "width": width, "height": height, "fuobe_live": FUOBE_LIVE}).encode("utf-8")+ return struct.pack(">I", len(meta)) + meta + data+++# ---------------------------------------------------------------------------+# The nodes (not loaded when only the maths is tested)++if not os.environ.get("FUOBE_LIVE_PURE"):+ import comfy.model_management+ import comfy.utils+ import folder_paths+ import node_helpers+ import server++ def _input_path(name):+ if not isinstance(name, str) or not NAME.match(name):+ raise ValueError("Live edit reads only pictures Fuobe sent")+ root = os.path.abspath(folder_paths.get_input_directory())+ path = os.path.abspath(os.path.join(root, name))+ if os.path.commonpath([root, path]) != root or os.path.dirname(path) != root or not os.path.isfile(path):+ raise ValueError("Live edit reads only pictures Fuobe sent")+ return path++ class LoadImageFuobeLive:+ @classmethod+ def INPUT_TYPES(cls):+ return {"required": {"image": ("STRING", {"default": "", "tooltip": "A Fuobe-named picture in the input folder."})}}++ RETURN_TYPES = ("IMAGE",)+ FUNCTION = "load"+ CATEGORY = "fuobe/live"++ @classmethod+ def IS_CHANGED(cls, image):+ try:+ st = os.stat(_input_path(image))+ return "%d-%d" % (st.st_mtime_ns, st.st_size)+ except (ValueError, OSError):+ return float("nan")++ def load(self, image):+ img = node_helpers.pillow(Image.open, _input_path(image))+ img = node_helpers.pillow(ImageOps.exif_transpose, img).convert("RGB")+ return (torch.from_numpy(np.array(img).astype(np.float32) / 255.0)[None],)++ class CropFuobeLive:+ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "image": ("IMAGE",),+ "context": ("FLOAT", {"default": 1.6, "min": 1.0, "max": 4.0, "step": 0.1}),+ "multiple": ("INT", {"default": 32, "min": 8, "max": 128, "step": 8}),+ },+ "optional": {"mask_image": ("IMAGE",)},+ }++ RETURN_TYPES = ("IMAGE", "FUOBE_BOX")+ RETURN_NAMES = ("image", "box")+ FUNCTION = "crop"+ CATEGORY = "fuobe/live"++ def crop(self, image, context, multiple, mask_image=None):+ H, W = image.shape[1], image.shape[2]+ mask = None+ if mask_image is not None:+ mask = resize(mask_image[:1, :, :, :3], W, H)[0, :, :, 0]+ box = crop_box(mask, W, H, context, multiple)+ x0, y0, x1, y1 = box+ return (image[:1, y0:y1, x0:x1, :3], box)++ class Qwen21ReferenceFuobeLive:+ @classmethod+ def INPUT_TYPES(cls):+ optional = {"image_%d" % i: ("IMAGE",) for i in range(2, MAX_REFERENCES + 1)}+ return {+ "required": {"vae": ("VAE",), "resolution": ("INT", {"default": 1024, "min": 0, "max": 4096, "step": 32}), "image_1": ("IMAGE",)},+ "optional": optional,+ }++ RETURN_TYPES = ("QWEN21_REFERENCE", "IMAGE")+ RETURN_NAMES = ("reference", "image_1")+ FUNCTION = "encode"+ CATEGORY = "fuobe/live"++ def encode(self, vae, resolution, **images):+ images_vl, latents, size, first = [], [], None, None+ for name in sorted(images, key=lambda n: int(n.rsplit("_", 1)[-1])):+ image = images[name]+ if image is None:+ continue+ samples = image[:1].movedim(-1, 1)+ if resolution > 0:+ ratio = samples.shape[3] / samples.shape[2]+ width = round(math.sqrt(resolution * resolution * ratio) / 32) * 32+ height = round(math.sqrt(resolution * resolution / ratio) / 32) * 32+ else:+ width, height = round(samples.shape[3] / 32) * 32, round(samples.shape[2] / 32) * 32+ width, height = max(32, width), max(32, height)+ if (width, height) == (samples.shape[3], samples.shape[2]):+ s = image[:1]+ else:+ s = comfy.utils.common_upscale(samples, width, height, "lanczos", "disabled").movedim(1, -1)+ if size is None:+ size, first = (width, height), s+ rgb = s[:, :, :, :3]+ if s.shape[-1] > 3:+ rgb = rgb * s[:, :, :, 3:] + (1.0 - s[:, :, :, 3:])+ images_vl.append(rgb)+ latents.append(vae.encode(s[:, :, :, :3]))+ return ({"images": images_vl, "latents": latents, "size": size}, first)++ class Qwen21EncodeFuobeLive:+ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "clip": ("CLIP",),+ "prompt": ("STRING", {"multiline": True}),+ "width": ("INT", {"default": 1024, "min": 32, "max": 8192, "step": 32}),+ "height": ("INT", {"default": 1024, "min": 32, "max": 8192, "step": 32}),+ },+ "optional": {"reference": ("QWEN21_REFERENCE",)},+ }++ RETURN_TYPES = ("CONDITIONING", "LATENT")+ RETURN_NAMES = ("positive", "latent")+ FUNCTION = "encode"+ CATEGORY = "fuobe/live"++ def encode(self, clip, prompt, width, height, reference=None):+ images_vl = reference["images"] if reference else []+ latents = reference["latents"] if reference else []+ if reference and reference["size"]:+ width, height = reference["size"]+ tokens = clip.tokenize(prompt, images=images_vl, keep_vision=not latents, prevent_empty_text=True)+ positive = clip.encode_from_tokens_scheduled(tokens)+ if latents:+ positive = node_helpers.conditioning_set_values(positive, {"reference_latents": latents}, append=True)+ latent = torch.zeros([1, 64, height // 16, width // 16], device=comfy.model_management.intermediate_device())+ return (positive, {"samples": latent})++ class PasteBackFuobeLive:+ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "base": ("IMAGE",),+ "edited": ("IMAGE",),+ "mode": (["auto", "mask", "off"],),+ "threshold": ("FLOAT", {"default": 0.06, "min": 0.0, "max": 1.0, "step": 0.01}),+ "feather": ("INT", {"default": 24, "min": 0, "max": 256}),+ "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",)},+ }++ 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):+ 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))+ return (out,)++ class SaveImageFuobeLive:+ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "images": ("IMAGE",),+ "format": (["webp", "png"],),+ "quality": ("INT", {"default": 85, "min": 50, "max": 100}),+ "to": (["socket", "temp"],),+ },+ "hidden": {"unique_id": "UNIQUE_ID"},+ }++ RETURN_TYPES = ()+ FUNCTION = "save"+ OUTPUT_NODE = True+ CATEGORY = "fuobe/live"++ def save(self, images, format, quality, to, unique_id=None):+ img = images[:1, :, :, :3]+ data, image_type = encode_picture(img, format, quality)+ h, w = int(img.shape[1]), int(img.shape[2])+ ps = server.PromptServer.instance+ sid = getattr(ps, "client_id", None)+ if to == "socket" and sid:+ payload = socket_payload(data, image_type, getattr(ps, "last_prompt_id", None), str(unique_id or ""), w, h)+ fut = asyncio.run_coroutine_threadsafe(ps.send_bytes(4, payload, sid=sid), ps.loop)+ try:+ fut.result(timeout=10)+ return {"ui": {"fuobe_live": [{"sent": True, "width": w, "height": h}]}}+ except Exception:+ pass+ ext = "png" if format == "png" else "webp"+ name = "fuobe_live_%d_%06d.%s" % (int(time.time() * 1000), np.random.randint(0, 999999), ext)+ with open(os.path.join(folder_paths.get_temp_directory(), name), "wb") as f:+ f.write(data)+ return {"ui": {"images": [{"filename": name, "subfolder": "", "type": "temp"}]}}++ NODE_CLASS_MAPPINGS = {+ "LoadImageFuobeLive": LoadImageFuobeLive,+ "CropFuobeLive": CropFuobeLive,+ "Qwen21ReferenceFuobeLive": Qwen21ReferenceFuobeLive,+ "Qwen21EncodeFuobeLive": Qwen21EncodeFuobeLive,+ "PasteBackFuobeLive": PasteBackFuobeLive,+ "SaveImageFuobeLive": SaveImageFuobeLive,+ }+ NODE_DISPLAY_NAME_MAPPINGS = {+ "LoadImageFuobeLive": "Load Image (Fuobe live)",+ "CropFuobeLive": "Crop Around Region (Fuobe live)",+ "Qwen21ReferenceFuobeLive": "Qwen Image 2.1 Reference (Fuobe live)",+ "Qwen21EncodeFuobeLive": "Qwen Image 2.1 Encode, positive only (Fuobe live)",+ "PasteBackFuobeLive": "Paste Back Unchanged Pixels (Fuobe live)",+ "SaveImageFuobeLive": "Send Image (Fuobe live)",+ }++ async def _fuobe_live_status(request):+ from aiohttp import web+ return web.json_response({"version": FUOBE_LIVE})++ try:+ _ps = getattr(server.PromptServer, "instance", None)+ if _ps is not None:+ _ps.routes.get("/fuobe/live")(_fuobe_live_status)+ except Exception:+ pass+else:+ NODE_CLASS_MAPPINGS = {}+ NODE_DISPLAY_NAME_MAPPINGS = {}+`;++/** The nodes as base64 (the start file writes them with PowerShell). */+export function liveNodesBase64(): string {+ if (!/^[\x00-\x7f]*$/.test(LIVE_NODES_SOURCE)) throw new Error("The live nodes must be plain ASCII");+ 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 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/comfy-ws.ts b/src/lib/comfy-ws.tsindex 9dc13c2f..4db75235 100644--- a/src/lib/comfy-ws.ts+++ b/src/lib/comfy-ws.ts@@ -2,7 +2,8 @@* ComfyUI's live socket (/ws?clientId=…), as the Fuobe tab reads it: JSON events (status, execution_start, progress,* executing, execution_success / error / interrupted, execution_cached) and binary preview frames. A binary frame is a* 4-byte big-endian event type, then: type 1, a 4-byte image type (1 JPEG, 2 PNG) and the image; type 4, a 4-byte- * metadata length, its JSON (prompt_id, node_id, image_type) and the image. Anything else, or anything malformed, is+ * metadata length, its JSON (prompt_id, node_id, image_type; Fuobe's live save node adds width, height and fuobe_live)+ * and the image. Anything else, or anything malformed, is* ignored. Pure.*/@@ -60,11 +61,17 @@ export function parseComfyText(text: string): ComfyEvent | null {}export interface ComfyPreview {- /** image/jpeg or image/png. */+ /** image/jpeg, image/png, or (type 4) image/webp. */type: string;data: Uint8Array;/** Set on type-4 frames (a newer ComfyUI): whose preview it is. */promptId?: string;+ /** Type 4: the node that sent it, and the picture's size when the node says. */+ node?: string;+ width?: number;+ height?: number;+ /** Sent by Fuobe's live save node (a finished picture, not a sampling preview). */+ live?: boolean;}/** The longest preview metadata read (a few hundred bytes in practice). */@@ -84,15 +91,22 @@ export function parseComfyBinary(buf: ArrayBuffer | Uint8Array): ComfyPreview |if (event === 4) {const len = view.getUint32(4);if (len > MAX_META || 8 + len >= b.length) return null;- let meta: { prompt_id?: unknown; image_type?: unknown };+ let meta: { prompt_id?: unknown; image_type?: unknown; node_id?: unknown; width?: unknown; height?: unknown; fuobe_live?: unknown };try {meta = JSON.parse(new TextDecoder().decode(b.subarray(8, 8 + len))) as typeof meta;} catch {return null;}- const type = meta.image_type === "image/png" ? "image/png" : meta.image_type === "image/jpeg" ? "image/jpeg" : null;+ const type = meta.image_type === "image/png" || meta.image_type === "image/jpeg" || meta.image_type === "image/webp" ? meta.image_type : null;if (!type) return null;- return { type, data: b.subarray(8 + len), ...(typeof meta.prompt_id === "string" && { promptId: meta.prompt_id }) };+ return {+ type,+ data: b.subarray(8 + len),+ ...(typeof meta.prompt_id === "string" && { promptId: meta.prompt_id }),+ ...(typeof meta.node_id === "string" && { node: meta.node_id }),+ ...(typeof meta.width === "number" && typeof meta.height === "number" && { width: meta.width, height: meta.height }),+ ...(meta.fuobe_live !== undefined && { live: true }),+ };}return null;}diff --git a/src/lib/gpu/commands.ts b/src/lib/gpu/commands.tsindex d227ece4..6d8c6f29 100644--- a/src/lib/gpu/commands.ts+++ b/src/lib/gpu/commands.ts@@ -115,6 +115,12 @@ function restartLine(inv: GpuInventory | null): string {}function packLines(shell: Shell, l: Layout, name: string, p: IndexPack, kind: StepKind): string[] {+ // A node file Fuobe ships itself: nothing to clone. Live edit's setup card and Settings → Your GPU download it.+ if (p.bundled) {+ if (!plain(p.bundled)) return [];+ const dest = l.under(shell, "custom_nodes");+ return [comment(shell, `Download ${p.bundled} from Fuobe (the setup card on Live edit, or Settings, Your GPU) into ${dest}, then restart ComfyUI`)];+ }if (!plain(name) || !plain(p.repo) || !/^[0-9a-f]{7,40}$/.test(p.commit)) return [comment(shell, `Install ${name} by hand: ${p.repo}`)];const dest = l.under(shell, "custom_nodes", name);const py = l.python(shell);diff --git a/src/lib/gpu/readiness.ts b/src/lib/gpu/readiness.tsindex 2fce0c73..fb4bc317 100644--- a/src/lib/gpu/readiness.ts+++ b/src/lib/gpu/readiness.ts@@ -78,7 +78,7 @@ export function fileLabel(folder: string, kind?: string): string {}/** "ComfyUI-KJNodes" → "KJNodes". */-export const packLabel = (name: string) => name.replace(/^ComfyUI[-_]/i, "").replace(/[-_]/g, " ");+export const packLabel = (name: string) => (name === "fuobe-live" ? "Fuobe live nodes" : name.replace(/^ComfyUI[-_]/i, "").replace(/[-_]/g, " "));export interface ReadinessContext {/** An account's own GPU (isolated workflows aren't supported there yet). */@@ -168,6 +168,7 @@ export function workflowReadiness(id: string, inv: GpuInventory, idx: Requiremenif (gone.length < classes.length) need = { key: `pack:${name}`, kind: "pack-update", label: `Update add-on: ${packLabel(name)}`, detail: `${name} is an older version. Missing: ${gone.join(", ")}`, pack: name };else if (listed?.importError) need = { key: `pack:${name}`, kind: "pack-repair", label: `Repair add-on: ${packLabel(name)}`, detail: `${name} is installed but didn't start.`, pack: name, remote: listed.importError };else if (listed && listed.enabled) need = { key: `restart:${name}`, kind: "restart", label: "Restart ComfyUI", detail: `${name} was installed since ComfyUI last started.`, pack: name };+ else if (idx.packs[name]?.bundled) need = { key: `pack:${name}`, kind: "pack-install", label, detail: `${idx.packs[name].bundled}, a file Fuobe ships: download it into ComfyUI's custom_nodes folder.`, pack: name };else need = { key: `pack:${name}`, kind: "pack-install", label, detail: `${name} (${idx.packs[name]?.repo ?? "custom node pack"})`, pack: name };out.needs.push(need);if (need.kind !== "restart") packNeeds.add(name);diff --git a/src/lib/gpu/types.ts b/src/lib/gpu/types.tsindex 7a57ea93..b29fdbf9 100644--- a/src/lib/gpu/types.ts+++ b/src/lib/gpu/types.ts@@ -34,6 +34,8 @@ export interface RequirementIndex {export interface IndexPack {repo: string;commit: string;+ /** A node file Fuobe ships itself (fuobe_live.py): Fuobe writes it into custom_nodes, nothing is cloned. */+ bundled?: string;/** Comfy Registry id; `version` is set only once the validator ran on that exact release (empty until then: manual). */registry?: { id: string; version: string };/** The node classes the library uses from it. */diff --git a/src/lib/licences.ts b/src/lib/licences.tsindex a3254e78..29ffce63 100644--- a/src/lib/licences.ts+++ b/src/lib/licences.ts@@ -452,6 +452,7 @@ export const NODE_PACKS: NodePack[] = [pack("ComfyUI-Whisper", "https://github.com/yuvraj108c/ComfyUI-Whisper", { name: "CC BY-NC-SA 4.0", class: "non-commercial", url: SPDX("CC-BY-NC-SA-4.0"), note: "Word-timed captions in one job; non-commercial code (the author asks to be contacted for commercial use). The Whisper weights are MIT" }),pack("ComfyUI-LatentSyncWrapper", "https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper", NO_FILE("; the LatentSync 1.6 weights are CreativeML OpenRAIL++-M"), "isolated"),pack("ComfyUI-ThinkSound_Wrapper", "https://github.com/ShmuelRonen/ComfyUI-ThinkSound_Wrapper", NO_FILE("; the ThinkSound weights are Apache-2.0"), "isolated"),+ pack("fuobe-live", "https://github.com/workingprototype/Fuobe", { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "Fuobe's own live edit nodes (fuobe_live.py, shipped with Fuobe): a loader, a cached reference encode, a crop, a paste-back and a socket save. The Qwen-Image 2.1 weights and the DMD2 LoRA they run are non-commercial" }),pack("ausboss-nodes", "https://github.com/ausboss/ComfyUI-AusBoss", { name: "MIT", class: "commercial", url: SPDX("MIT"), note: "Crop For Inpaint, Stitch Inpaint and Crop + Rotate + Pad for Qwen-Image 2.1's inpaint and expand; MIT code. The Qwen-Image 2.1 weights they run are non-commercial" }),// Genjutsu's Character swap (docs/research/openjutsu-6.md §7): Akatz Labs' packs, pinned in install-comfyui.sh.pack("h3_character_swap", "https://github.com/akatz-labs/h3-character-swap-tool/tree/0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b/worker_nodes/h3_character_swap", {diff --git a/src/lib/live/frames.ts b/src/lib/live/frames.tsnew file mode 100644index 00000000..a9f13b18--- /dev/null+++ b/src/lib/live/frames.ts@@ -0,0 +1,117 @@+/**+ * The live render stream (POST /api/live/render answers with it, `application/x-fuobe-live`). Each frame is one type+ * byte, a 4-byte big-endian length and the payload:+ *+ * - `J`: a JSON event ({ type: "queued", pos } · { type: "started" } · { type: "progress", value, max } ·+ * { type: "dropped", why } · { type: "error", message } · { type: "reconnecting" });+ * - `I`: a picture: a 4-byte header length, the JSON header (FrameHeader), then the image bytes.+ *+ * Pure, so the route, the tab and the tests share it.+ */++export const LIVE_STREAM_TYPE = "application/x-fuobe-live";++/** The largest frame read (a 4096² PNG master fits). */+export const MAX_FRAME_BYTES = 96 * 2 ** 20;++export interface FrameHeader {+ seq: number;+ slot: string;+ key: string;+ w: number;+ h: number;+ /** image/webp, image/png or image/jpeg. */+ type: string;+ /** ComfyUI's time for the render, from start to picture. */+ ms: number;+ sha256?: string;+ /** A kept master saved by the server, and its input name in ComfyUI. */+ masterId?: string;+ url?: string;+ name?: string;+}++export type LiveEvent =+ | { type: "queued"; pos: number }+ | { type: "started" }+ | { type: "progress"; value: number; max: number }+ | { type: "dropped"; why: string }+ | { type: "error"; message: string; code?: string }+ | { type: "reconnecting" };++export type Frame = { kind: "event"; event: LiveEvent } | { kind: "image"; header: FrameHeader; data: Uint8Array };++const enc = new TextEncoder();+const dec = new TextDecoder();++function wrap(type: number, payload: Uint8Array): Uint8Array {+ const out = new Uint8Array(5 + payload.length);+ out[0] = type;+ new DataView(out.buffer).setUint32(1, payload.length);+ out.set(payload, 5);+ return out;+}++export const eventFrame = (e: LiveEvent): Uint8Array => wrap(0x4a, enc.encode(JSON.stringify(e)));++export function imageFrame(header: FrameHeader, data: Uint8Array): Uint8Array {+ const h = enc.encode(JSON.stringify(header));+ const payload = new Uint8Array(4 + h.length + data.length);+ new DataView(payload.buffer).setUint32(0, h.length);+ payload.set(h, 4);+ payload.set(data, 4 + h.length);+ return wrap(0x49, payload);+}++export class FrameError extends Error {}++/** Reads frames from chunks as they arrive (a chunk may hold several frames, or part of one). */+export class FrameReader {+ private buf = new Uint8Array(0);++ push(chunk: Uint8Array): Frame[] {+ const joined = new Uint8Array(this.buf.length + chunk.length);+ joined.set(this.buf);+ joined.set(chunk, this.buf.length);+ this.buf = joined;+ const out: Frame[] = [];+ for (;;) {+ if (this.buf.length < 5) break;+ const view = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength);+ const type = this.buf[0];+ const len = view.getUint32(1);+ if (type !== 0x4a && type !== 0x49) throw new FrameError(`Unknown frame type ${type}`);+ if (len > MAX_FRAME_BYTES) throw new FrameError("Frame too large");+ if (this.buf.length < 5 + len) break;+ const payload = this.buf.slice(5, 5 + len);+ this.buf = this.buf.slice(5 + len);+ out.push(parse(type, payload));+ }+ return out;+ }++ /** Bytes left over: a stream that ended inside a frame. */+ get pending(): number {+ return this.buf.length;+ }+}++function parse(type: number, payload: Uint8Array): Frame {+ if (type === 0x4a) {+ try {+ return { kind: "event", event: JSON.parse(dec.decode(payload)) as LiveEvent };+ } catch {+ throw new FrameError("Bad event");+ }+ }+ if (payload.length < 4) throw new FrameError("Bad picture frame");+ const hl = new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint32(0);+ if (4 + hl > payload.length) throw new FrameError("Bad picture header");+ let header: FrameHeader;+ try {+ header = JSON.parse(dec.decode(payload.subarray(4, 4 + hl))) as FrameHeader;+ } catch {+ throw new FrameError("Bad picture header");+ }+ return { kind: "image", header, data: payload.slice(4 + hl) };+}diff --git a/src/lib/live/graph.ts b/src/lib/live/graph.tsnew file mode 100644index 00000000..c4a91aab--- /dev/null+++ b/src/lib/live/graph.ts@@ -0,0 +1,223 @@+/**+ * Live edit's ComfyUI graph (pure, shared by the server and the tab). Qwen-Image 2.1 (int8) with the 2-step DMD2 LoRA+ * at strength 1: BasicGuider (CFG 1, positive only), euler, ManualSigmas "1.0, 0.5, 0.0" (the LoRA's own schedule, no+ * shift), on Fuobe's live nodes (fuobe_live.py, src/lib/comfy-live-nodes.ts):+ *+ * 10 LoadImageFuobeLive (base) ─ 15 CropFuobeLive ─ 20 Qwen21ReferenceFuobeLive ─ 30 Qwen21EncodeFuobeLive ─┐+ * 11–13 (refs) ────────────────────────────────┘ 14 (mask) ─ 15, 40 │+ * 1 UNETLoader ─ 4 LoraLoaderModelOnly ─ 71 BasicGuider ─ 32 SamplerCustomAdvanced ─ 33 VAEDecode ─ 34 Split ┘+ * ─ 40 PasteBackFuobeLive (unchanged pixels back from the base, colour matched) ─ 90 SaveImageFuobeLive+ *+ * Text to image leaves out 10–15, 20 and 40. `liveGraphProblem` is the tab's check before a graph goes to the person's+ * own ComfyUI: the graph must be exactly what buildLiveGraph makes from its own bound values.+ */+import { MAX_LIVE_TEXT } from "./text";+import { GRAPH_RESOLUTIONS, isAspect, sizeFor, type Aspect, ASPECT_NAMES } from "./sizes";+import { LIVE_INPUT } from "./names";++export const LIVE_WORKFLOW_ID = "qwen-image-21-live-edit";+export const LIVE_MODEL_ID = "oss-qwen-image-21-live";++export const LIVE_FILES = {+ unet: "qwen_image_2.1_int8_convrot.safetensors",+ clip: "qwen3vl_8b_int8_convrot.safetensors",+ vae: "qwen_image_2.1_vae_bf16.safetensors",+ lora: "Qwen-Image-2.1-DMD2-2steps.safetensors",+} as const;++/** The LoRA's trained schedule plus the terminal 0 (explicit sigmas bypass the model's shift). */+export const LIVE_SIGMAS = "1.0, 0.5, 0.0";++/** The node that sends the picture. */+export const LIVE_OUTPUT = "90";++/** The longest prompt a graph may carry (compose joins the kept texts). */+export const MAX_GRAPH_PROMPT = 2000;++export const PACK_LIVE_CLASSES = ["LoadImageFuobeLive", "CropFuobeLive", "Qwen21ReferenceFuobeLive", "Qwen21EncodeFuobeLive", "PasteBackFuobeLive", "SaveImageFuobeLive"] as const;+export const CORE_LIVE_CLASSES = ["UNETLoader", "CLIPLoader", "VAELoader", "LoraLoaderModelOnly", "RandomNoise", "BasicGuider", "KSamplerSelect", "ManualSigmas", "SamplerCustomAdvanced", "VAEDecode", "SplitImageWithAlpha"] as const;+export const LIVE_CLASSES: ReadonlySet<string> = new Set<string>([...CORE_LIVE_CLASSES, ...PACK_LIVE_CLASSES]);++export type PasteMode = "auto" | "mask" | "off";+export type LiveFormat = "webp" | "png";+export type LiveTo = "socket" | "temp";++export interface LiveGraphParams {+ prompt: string;+ seed: number;+ /** The model's resolution: an edit's area (res²), or text to image's size at `aspect`. */+ res: number;+ /** Text to image only. */+ aspect?: Aspect;+ /** The base picture's input name (a master or the original); none for text to image. */+ base?: string;+ /** Pictures 2–4. */+ refs?: string[];+ /** A painted region (white = change). */+ mask?: string;+ paste: PasteMode;+ /** The composite's long side: 0 = the base's full size. */+ outMaxSide: number;+ format: LiveFormat;+ quality?: number;+ to: LiveTo;+}++export type GraphNode = { class_type: string; inputs: Record<string, unknown>; _meta?: { title: string } };+export type LiveGraph = Record<string, GraphNode>;++const link = (id: string, out = 0) => [id, out];++/** The graph for one render, and the input names it reads. */+export function buildLiveGraph(p: LiveGraphParams): { graph: LiveGraph; outputNode: string; staged: string[] } {+ const g: LiveGraph = {+ "1": { class_type: "UNETLoader", inputs: { unet_name: LIVE_FILES.unet, weight_dtype: "default" } },+ "2": { class_type: "CLIPLoader", inputs: { clip_name: LIVE_FILES.clip, type: "qwen_image", device: "default" } },+ "3": { class_type: "VAELoader", inputs: { vae_name: LIVE_FILES.vae } },+ "4": { class_type: "LoraLoaderModelOnly", inputs: { model: link("1"), lora_name: LIVE_FILES.lora, strength_model: 1 } },+ };+ const staged: string[] = [];+ const refs = (p.refs ?? []).slice(0, 3);+ if (p.base) {+ g["10"] = { class_type: "LoadImageFuobeLive", inputs: { image: p.base } };+ staged.push(p.base);+ refs.forEach((r, i) => {+ g[String(11 + i)] = { class_type: "LoadImageFuobeLive", inputs: { image: r } };+ staged.push(r);+ });+ if (p.mask) {+ g["14"] = { class_type: "LoadImageFuobeLive", inputs: { image: p.mask } };+ staged.push(p.mask);+ }+ g["15"] = { class_type: "CropFuobeLive", inputs: { image: link("10"), context: 1.6, multiple: 32, ...(p.mask && { mask_image: link("14") }) } };+ g["20"] = {+ class_type: "Qwen21ReferenceFuobeLive",+ inputs: { vae: link("3"), resolution: p.res, image_1: link("15"), ...Object.fromEntries(refs.map((_, i) => [`image_${i + 2}`, link(String(11 + i))])) },+ };+ }+ const [w, h] = p.base ? [p.res, p.res] : sizeFor(p.aspect ?? "1:1", p.res);+ g["30"] = { class_type: "Qwen21EncodeFuobeLive", inputs: { clip: link("2"), prompt: p.prompt, width: w, height: h, ...(p.base && { reference: link("20") }) } };+ g["70"] = { class_type: "RandomNoise", inputs: { noise_seed: p.seed } };+ g["71"] = { class_type: "BasicGuider", inputs: { model: link("4"), conditioning: link("30") } };+ g["72"] = { class_type: "KSamplerSelect", inputs: { sampler_name: "euler" } };+ g["73"] = { class_type: "ManualSigmas", inputs: { sigmas: LIVE_SIGMAS } };+ g["32"] = { class_type: "SamplerCustomAdvanced", inputs: { noise: link("70"), guider: link("71"), sampler: link("72"), sigmas: link("73"), latent_image: link("30", 1) } };+ g["33"] = { class_type: "VAEDecode", inputs: { samples: link("32"), vae: link("3") } };+ g["34"] = { class_type: "SplitImageWithAlpha", inputs: { image: link("33") } };+ if (p.base) {+ g["40"] = {+ class_type: "PasteBackFuobeLive",+ inputs: {+ base: link("10"),+ edited: link("34"),+ box: link("15", 1),+ ...(p.mask && { mask_image: link("14") }),+ mode: p.paste,+ threshold: 0.06,+ feather: 24,+ match_color: true,+ out_max_side: p.outMaxSide,+ },+ };+ }+ g[LIVE_OUTPUT] = { class_type: "SaveImageFuobeLive", inputs: { images: link(p.base ? "40" : "34"), format: p.format, quality: p.quality ?? 85, to: p.to } };+ return { graph: g, outputNode: LIVE_OUTPUT, staged };+}++/** What each kind of render asks for (spec §5.2). */+export type RenderSlot = "live" | "settle" | "keep" | "warm";++export function slotBindings(+ slot: RenderSlot,+ o: { liveSize: number; keepRes: number; hasMask: boolean; to: LiveTo; liveLongSide?: number },+): Pick<LiveGraphParams, "res" | "paste" | "outMaxSide" | "format" | "to"> {+ if (slot === "warm") return { res: 384, paste: "off", outMaxSide: 384, format: "webp", to: o.to };+ const paste: PasteMode = o.hasMask ? "mask" : "auto";+ if (slot === "live") return { res: o.liveSize, paste, outMaxSide: roundOut(o.liveLongSide ?? o.liveSize), format: "webp", to: o.to };+ return { res: o.keepRes, paste, outMaxSide: 0, format: "png", to: o.to };+}++const roundOut = (n: number) => Math.min(1536, Math.max(256, Math.round(n / 32) * 32));++const isLink = (v: unknown, id?: string): v is [string, number] => Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number" && (id === undefined || v[0] === id);++/** JSON with sorted keys (comparison). */+function canonical(v: unknown): string {+ if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;+ if (v && typeof v === "object") {+ const o = v as Record<string, unknown>;+ return `{${Object.keys(o)+ .filter((k) => k !== "_meta" && o[k] !== undefined)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`)+ .join(",")}}`;+ }+ return JSON.stringify(v);+}++/** Two graphs are the same (titles aside). */+export const sameGraph = (a: unknown, b: unknown) => canonical(a) === canonical(b);++/**+ * The tab's check of a live graph before it goes to ComfyUI: only live classes, exactly buildLiveGraph's shape for its+ * own bound values, and only these free values: a prompt of at most 2,000 characters, an integer seed, a resolution+ * and size from the table, input names Fuobe made (and staged), and the output's format, quality and place. A changed+ * model, LoRA, schedule, link or extra node is refused. Returns the problem, or null.+ */+export function liveGraphProblem(graph: unknown, staged: string[]): string | null {+ if (!graph || typeof graph !== "object" || Array.isArray(graph)) return "No graph";+ const g = graph as Record<string, GraphNode>;+ for (const [id, n] of Object.entries(g)) {+ if (!n || typeof n !== "object" || typeof n.class_type !== "string" || !LIVE_CLASSES.has(n.class_type)) return `Node ${id} isn't a live edit node`;+ }+ const s = (id: string, k: string) => g[id]?.inputs?.[k];+ const prompt = s("30", "prompt");+ const seed = s("70", "noise_seed");+ if (typeof prompt !== "string" || prompt.length > MAX_GRAPH_PROMPT) return "The prompt is missing or too long";+ if (typeof seed !== "number" || !Number.isSafeInteger(seed) || seed < 0) return "Bad seed";+ const base = s("10", "image");+ const name = (v: unknown) => typeof v === "string" && LIVE_INPUT.test(v) && staged.includes(v);+ let p: LiveGraphParams;+ const save = g[LIVE_OUTPUT]?.inputs ?? {};+ const format = save.format;+ const quality = save.quality;+ const to = save.to;+ if (format !== "webp" && format !== "png") return "Bad format";+ if (typeof quality !== "number" || !Number.isInteger(quality) || quality < 50 || quality > 100) return "Bad quality";+ if (to !== "socket" && to !== "temp") return "Bad output";+ if (base !== undefined) {+ if (!name(base)) return "The base isn't a picture this tab sent";+ const res = s("20", "resolution");+ if (typeof res !== "number" || !GRAPH_RESOLUTIONS.includes(res)) return "Bad resolution";+ const refs: string[] = [];+ for (const id of ["11", "12", "13"]) {+ if (!g[id]) break;+ const r = s(id, "image");+ if (!name(r)) return "A reference isn't a picture this tab sent";+ refs.push(r as string);+ }+ const mask = s("14", "image");+ if (mask !== undefined && !name(mask)) return "The mask isn't a picture this tab sent";+ const paste = s("40", "mode");+ const outMaxSide = s("40", "out_max_side");+ if (paste !== "auto" && paste !== "mask" && paste !== "off") return "Bad paste mode";+ if (typeof outMaxSide !== "number" || !Number.isInteger(outMaxSide) || outMaxSide < 0 || outMaxSide > 4096 || outMaxSide % 32) return "Bad output size";+ p = { prompt, seed, res, base: base as string, refs, ...(mask !== undefined && { mask: mask as string }), paste, outMaxSide, format, quality, to };+ } else {+ const w = s("30", "width");+ const h = s("30", "height");+ const match = GRAPH_RESOLUTIONS.flatMap((res) => ASPECT_NAMES.map((aspect) => ({ res, aspect, size: sizeFor(aspect, res) }))).find((x) => x.size[0] === w && x.size[1] === h);+ if (!match || !isAspect(match.aspect)) return "Bad size";+ p = { prompt, seed, res: match.res, aspect: match.aspect, paste: "off", outMaxSide: 0, format, quality, to };+ }+ const want = buildLiveGraph(p);+ if (!sameGraph(want.graph, g)) return "The graph isn't Fuobe's live edit graph";+ for (const n of want.staged) if (!staged.includes(n)) return "A loader reads a picture this tab didn't send";+ for (const k of Object.keys(g)) if (isLink(g[k]?.inputs?.image) && !g[isLinkTarget(g[k].inputs.image)]) return "A broken link";+ return null;+}++const isLinkTarget = (v: unknown) => (isLink(v) ? v[0] : "");++/** The live text that a graph may carry (for callers that build one). */+export const fitsPrompt = (s: string) => s.length <= MAX_LIVE_TEXT;diff --git a/src/lib/live/names.ts b/src/lib/live/names.tsnew file mode 100644index 00000000..f5fd474f--- /dev/null+++ b/src/lib/live/names.ts@@ -0,0 +1,44 @@+/**+ * The name a picture gets in ComfyUI's input folder: "fuobe_lv" and 20 characters of its sha256 (base64url). The same+ * bytes always get the same name, so ComfyUI's cache keeps the loader and the reference encode while only the text+ * changes, and nothing is uploaded twice. WebCrypto, so the tab and the server share it.+ */++export const LIVE_INPUT = /^fuobe_lv[A-Za-z0-9_-]{20}\.(png|jpg|webp)$/;++export type PictureExt = "png" | "jpg" | "webp";++const b64url = (bytes: Uint8Array) => {+ let s = "";+ for (const b of bytes) s += String.fromCharCode(b);+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+};++const hex = (d: Uint8Array) => [...d].map((b) => b.toString(16).padStart(2, "0")).join("");++export async function sha256Hex(bytes: Uint8Array): Promise<string> {+ return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes as BufferSource)));+}++/** The input name of these bytes, and their sha256 (hex). */+export async function inputName(bytes: Uint8Array, ext: PictureExt): Promise<{ name: string; sha256: string }> {+ const d = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes as BufferSource));+ return { name: `fuobe_lv${b64url(d).slice(0, 20)}.${ext}`, sha256: hex(d) };+}++/** The extension of a picture by its first bytes, or null. */+export function pictureExt(b: Uint8Array): PictureExt | null {+ if (b.length > 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) return "png";+ if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "jpg";+ if (b.length > 12 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) return "webp";+ return null;+}++export const PICTURE_TYPES: Record<PictureExt, string> = { png: "image/png", jpg: "image/jpeg", webp: "image/webp" };++/** A PNG's size from its IHDR, or null. */+export function pngSize(b: Uint8Array): { w: number; h: number } | null {+ if (pictureExt(b) !== "png" || b.length < 24) return null;+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);+ return { w: v.getUint32(16), h: v.getUint32(20) };+}diff --git a/src/lib/live/scheduler.ts b/src/lib/live/scheduler.tsnew file mode 100644index 00000000..cb9e7abb--- /dev/null+++ b/src/lib/live/scheduler.ts@@ -0,0 +1,213 @@+/**+ * Live edit's scheduler (pure: the transport is injected). One render of ours is in ComfyUI at a time, and nothing+ * piles up behind the typing:+ *+ * - `keep` renders (the picture a person chose to keep) go first, in order, and typing never cancels them;+ * - `live` keeps only the newest request: a newer one drops the waiting one ("replaced");+ * - `settle` (the full-quality render of the text on screen, after a pause) keeps only the newest, and any live request+ * cancels it, waiting or running;+ * - `warm` (a throwaway render that loads the model) runs only when nothing else waits.+ *+ * An urgent live request (the person paused, or changed a control) also stops a running live or settle render of other+ * text, which answers "superseded" (a drop, not an error). `hurry(seq)` makes a waiting request urgent. While paused+ * (the GPU is busy with another job, the connection is down, the tab is hidden), requests wait, newest only.+ */++export type Slot = "keep" | "live" | "settle" | "warm";++/** Slots by priority. */+export const SLOTS: readonly Slot[] = ["keep", "live", "settle", "warm"];++export interface LiveJob<P> {+ /** Per tab, only grows. */+ seq: number;+ slot: Slot;+ /** What the render makes (renderKey): two jobs with one key make the same picture. */+ key: string;+ urgent?: boolean;+ payload: P;+}++export type DropReason = "replaced" | "superseded" | "cancelled" | "closed";++export type Outcome<R> = { ok: true; result: R } | { ok: false; dropped: DropReason } | { ok: false; error: string };++export interface SchedulerIo<P, R> {+ /** Run one render. Abort `signal` to take it off ComfyUI (the transport deletes it if queued, interrupts it if running). */+ run(job: LiveJob<P>, signal: AbortSignal): Promise<R>;+ /** Told when a job starts, for status. */+ onStart?(job: LiveJob<P>): void;+}++interface Entry<P, R> {+ job: LiveJob<P>;+ resolve: (o: Outcome<R>) => void;+}++interface Current<P, R> extends Entry<P, R> {+ ctrl: AbortController;+ dropped?: DropReason;+}++export class LiveScheduler<P, R> {+ private keeps: Entry<P, R>[] = [];+ private waiting: { live?: Entry<P, R>; settle?: Entry<P, R>; warm?: Entry<P, R> } = {};+ private current: Current<P, R> | null = null;+ private paused = false;+ private closed = false;+ private lastSeq = -Infinity;++ private readonly io: SchedulerIo<P, R>;+ constructor(io: SchedulerIo<P, R>) {+ this.io = io;+ }++ /** Queue a job; the promise answers once it is done, dropped or failed. */+ submit(job: LiveJob<P>): Promise<Outcome<R>> {+ return new Promise((resolve) => {+ if (this.closed) return resolve({ ok: false, dropped: "closed" });+ // A job older than one already seen in its slot comes too late (a reordered request).+ if (job.seq <= this.lastSeq && job.slot !== "keep") {+ const newer = this.newestSeqIn(job.slot);+ if (newer !== undefined && newer > job.seq) return resolve({ ok: false, dropped: "replaced" });+ }+ this.lastSeq = Math.max(this.lastSeq, job.seq);+ const entry: Entry<P, R> = { job, resolve };+ if (job.slot === "keep") {+ this.keeps.push(entry);+ } else {+ const slot = job.slot;+ const prior = this.waiting[slot];+ if (prior) prior.resolve({ ok: false, dropped: "replaced" });+ this.waiting[slot] = entry;+ if (slot === "live") {+ // Typing cancels the settle render, waiting or running.+ if (this.waiting.settle) {+ this.waiting.settle.resolve({ ok: false, dropped: "replaced" });+ this.waiting.settle = undefined;+ }+ if (this.current?.job.slot === "settle" && this.current.job.key !== job.key) this.stop(this.current, "superseded");+ if (job.urgent) this.preemptFor(job);+ }+ }+ this.pump();+ });+ }++ /** The person wants this waiting live request now: stop a running live or settle render of other text. */+ hurry(seq: number): void {+ const w = this.waiting.live;+ if (w && w.job.seq === seq) this.preemptFor(w.job);+ }++ /** Drop every waiting job that matches, and stop the running one if it matches. */+ cancel(match: (job: LiveJob<P>) => boolean): void {+ for (const slot of ["live", "settle", "warm"] as const) {+ const w = this.waiting[slot];+ if (w && match(w.job)) {+ w.resolve({ ok: false, dropped: "cancelled" });+ this.waiting[slot] = undefined;+ }+ }+ this.keeps = this.keeps.filter((k) => (match(k.job) ? (k.resolve({ ok: false, dropped: "cancelled" }), false) : true));+ if (this.current && match(this.current.job)) this.stop(this.current, "cancelled");+ }++ /** Hold every waiting job (newest only per slot) until resume(). A running render finishes. */+ pause(): void {+ this.paused = true;+ }++ resume(): void {+ this.paused = false;+ this.pump();+ }++ get isPaused(): boolean {+ return this.paused;+ }++ /** The job running now, if any. */+ get running(): LiveJob<P> | null {+ return this.current?.job ?? null;+ }++ /** The jobs waiting, by slot (for status and tests). */+ get queued(): LiveJob<P>[] {+ return [...this.keeps.map((k) => k.job), ...(["live", "settle", "warm"] as const).flatMap((s) => (this.waiting[s] ? [this.waiting[s]!.job] : []))];+ }++ /** Take everything off: waiting jobs answer "closed", the running one is stopped. */+ close(): void {+ this.closed = true;+ this.cancelAll("closed");+ }++ /** Drop everything (a lost connection: the newest is sent again by the caller). */+ cancelAll(reason: DropReason = "cancelled"): void {+ for (const k of this.keeps) k.resolve({ ok: false, dropped: reason });+ this.keeps = [];+ for (const slot of ["live", "settle", "warm"] as const) {+ this.waiting[slot]?.resolve({ ok: false, dropped: reason });+ this.waiting[slot] = undefined;+ }+ if (this.current) this.stop(this.current, reason);+ }++ private newestSeqIn(slot: Slot): number | undefined {+ if (slot === "keep") return undefined;+ const w = this.waiting[slot];+ const c = this.current?.job.slot === slot ? this.current.job.seq : undefined;+ return Math.max(w?.job.seq ?? -Infinity, c ?? -Infinity);+ }++ private preemptFor(job: LiveJob<P>) {+ const c = this.current;+ if (c && (c.job.slot === "live" || c.job.slot === "settle") && c.job.key !== job.key && c.job.seq < job.seq) this.stop(c, "superseded");+ }++ private stop(c: Current<P, R>, why: DropReason) {+ if (c.dropped) return;+ c.dropped = why;+ c.ctrl.abort(why);+ }++ private next(): Entry<P, R> | undefined {+ if (this.keeps.length) return this.keeps.shift();+ for (const slot of ["live", "settle", "warm"] as const) {+ const w = this.waiting[slot];+ if (w) {+ this.waiting[slot] = undefined;+ return w;+ }+ }+ return undefined;+ }++ private pump() {+ if (this.current || this.paused || this.closed) return;+ const entry = this.next();+ if (!entry) return;+ const cur: Current<P, R> = { ...entry, ctrl: new AbortController() };+ this.current = cur;+ this.io.onStart?.(entry.job);+ let settled = false;+ const done = (o: Outcome<R>) => {+ if (settled) return;+ settled = true;+ if (this.current === cur) this.current = null;+ cur.resolve(o);+ this.pump();+ };+ let p: Promise<R>;+ try {+ p = this.io.run(entry.job, cur.ctrl.signal);+ } catch (e) {+ p = Promise.reject(e);+ }+ p.then(+ (result) => done({ 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/sizes.ts b/src/lib/live/sizes.tsnew file mode 100644index 00000000..edc42a21--- /dev/null+++ b/src/lib/live/sizes.ts@@ -0,0 +1,101 @@+/**+ * Picture sizes for live edit (pure). The aspect table is defined at 2048 and scaled, on the 32 grid, as the live+ * model's reference Space does. The live size adapts to the GPU: it steps down when frames come slowly and back up+ * when there is room.+ */++export const ASPECTS = {+ "1:1": [2048, 2048],+ "4:3": [2400, 1792],+ "3:4": [1792, 2400],+ "3:2": [2528, 1696],+ "2:3": [1696, 2528],+ "16:9": [2752, 1536],+ "9:16": [1536, 2752],+} as const;+export type Aspect = keyof typeof ASPECTS;+export const ASPECT_NAMES = Object.keys(ASPECTS) as Aspect[];+export const isAspect = (a: unknown): a is Aspect => typeof a === "string" && Object.hasOwn(ASPECTS, a);++const round32 = (n: number) => Math.max(32, Math.round(n / 32) * 32);++/** Text to image: the latent size of an aspect at a resolution. */+export function sizeFor(aspect: Aspect, res: number): [number, number] {+ const [w, h] = ASPECTS[aspect];+ const s = res / 2048;+ return [round32(w * s), round32(h * s)];+}++/** The nearest aspect of a picture. */+export function aspectOf(w: number, h: number): Aspect {+ const r = Math.log(w / h);+ const off = (a: Aspect) => Math.abs(Math.log(ASPECTS[a][0] / ASPECTS[a][1]) - r);+ return ASPECT_NAMES.reduce((best, a) => (off(a) < off(best) ? a : best), "1:1" as Aspect);+}++/** An edit: the model's size for a picture at a resolution (same area as res², the picture's shape, on the 32 grid). */+export function editSize(res: number, w: number, h: number): [number, number] {+ const ratio = w / h;+ return [round32(Math.sqrt(res * res * ratio)), round32(Math.sqrt((res * res) / ratio))];+}++/** Live sizes, smallest first. */+export const LIVE_LADDER = [384, 512, 640, 768] as const;+export type LiveSize = (typeof LIVE_LADDER)[number];+export const isLiveSize = (n: unknown): n is LiveSize => (LIVE_LADDER as readonly unknown[]).includes(n);++/** Keep (master) resolutions the person can pick. */+export const KEEP_LADDER = [1024, 1536, 2048] as const;+export type KeepRes = (typeof KEEP_LADDER)[number];+export const isKeepRes = (n: unknown): n is KeepRes => (KEEP_LADDER as readonly unknown[]).includes(n);++/** Every resolution a live graph may carry: the warm-up's 384, the live ladder and the keep ladder. */+export const GRAPH_RESOLUTIONS: readonly number[] = [...new Set<number>([...LIVE_LADDER, ...KEEP_LADDER])];++/** "Auto" keep detail: the base's long side, between 1024 and 1536. */+export function keepAuto(baseLongSide: number | undefined): KeepRes {+ if (!baseLongSide || baseLongSide < 1536) return 1024;+ return 1536;+}++/** The largest master side Fuobe keeps. */+export const MAX_MASTER_SIDE = 4096;++const median = (xs: number[]) => {+ const s = [...xs].sort((a, b) => a - b);+ const m = s.length >> 1;+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;+};++/**+ * Auto live size, with hysteresis: down a rung when the median of the last 5 frames is over 1.1 s, up a rung when the+ * median of the last 8 is under 0.45 s. The window starts again after each change, so one slow frame never flips it.+ */+export class AutoSize {+ static readonly SLOW_MS = 1100;+ static readonly FAST_MS = 450;+ private times: number[] = [];+ size: LiveSize;+ private readonly cap: LiveSize;+ constructor(size: LiveSize = 512, cap: LiveSize = 768) {+ this.size = size;+ this.cap = cap;+ }++ /** A frame's render time; returns the size for the next frame. */+ record(ms: number): LiveSize {+ if (!Number.isFinite(ms) || ms <= 0) return this.size;+ this.times.push(ms);+ if (this.times.length > 8) this.times.shift();+ const at = LIVE_LADDER.indexOf(this.size);+ if (this.times.length >= 5 && median(this.times.slice(-5)) > AutoSize.SLOW_MS && at > 0) return this.move(LIVE_LADDER[at - 1]);+ if (this.times.length >= 8 && median(this.times) < AutoSize.FAST_MS && at < LIVE_LADDER.length - 1 && LIVE_LADDER[at + 1] <= this.cap) return this.move(LIVE_LADDER[at + 1]);+ return this.size;+ }++ private move(to: LiveSize): LiveSize {+ this.size = to;+ this.times = [];+ return to;+ }+}diff --git a/src/lib/live/steps.ts b/src/lib/live/steps.tsnew file mode 100644index 00000000..7179da61--- /dev/null+++ b/src/lib/live/steps.ts@@ -0,0 +1,203 @@+/**+ * Live edit's kept steps (pure). A step is one change the person chose to keep, with its own lossless master. The+ * stack is a tree: Undo moves to the parent, Redo to the newest child, and a Keep after an Undo starts a new branch+ * (the old one stays). Every render's base is a master or the original, never a live frame:+ *+ * 1. the base of a render is the head's master (hybrid, chain) or the original (compose);+ * 2. every kept master is a PNG at least as large as its base (for text to image, 1024 or more on the long side);+ * 3. no name used as a base was ever a live frame's bytes;+ * 4. a kept master is the settled picture that was on screen, byte for byte, when Keep came after the settle.+ */++export type Method = "hybrid" | "chain" | "compose";+export const METHODS: readonly Method[] = ["hybrid", "chain", "compose"];++export interface Master {+ /** A Fuobe file URL (/api/files/…), when the server keeps it. */+ url?: string;+ /** This browser's copy (IndexedDB key), when the server couldn't keep it. */+ idb?: string;+ /** Its name in ComfyUI's input folder (inputName). */+ name: string;+ w: number;+ h: number;+ sha256: string;+ format: "png" | "jpg" | "webp";+}++export interface Step {+ id: string;+ parent: string | null;+ /** What the person typed, and as the model read it. */+ text: string;+ norm: string;+ seed: number;+ method: Method;+ keepRes: number;+ mask?: { name: string; url?: string };+ master: Master;+ /** The render's time. */+ ms: number;+ at: number;+ /** Kept only in this browser (the account's space was full). */+ local?: boolean;+}++export interface StackState {+ steps: Step[];+ head: string | null;+}++export class StepError extends Error {}++export class StepStack {+ private steps: Step[];+ private headId: string | null;+ /** sha256 of every live frame shown in this session: none may become a base. */+ private readonly liveShas = new Set<string>();+ private n: number;++ constructor(state: StackState = { steps: [], head: null }) {+ this.steps = state.steps.map((s) => ({ ...s, master: { ...s.master } }));+ this.headId = state.head && this.steps.some((s) => s.id === state.head) ? state.head : (this.steps.at(-1)?.id ?? null);+ this.n = this.steps.reduce((m, s) => Math.max(m, Number(/^s(\d+)$/.exec(s.id)?.[1] ?? 0)), 0);+ }++ /** Start from a picture (step 0, the original: its bytes as they came, JPEG allowed). */+ static from(original: Master, at = Date.now()): StepStack {+ return new StepStack({ steps: [{ id: "s0", parent: null, text: "", norm: "", seed: 0, method: "hybrid", keepRes: 0, master: original, ms: 0, at }], head: "s0" });+ }++ get empty(): boolean {+ return this.steps.length === 0;+ }++ get head(): Step | null {+ return this.steps.find((s) => s.id === this.headId) ?? null;+ }++ get original(): Step | null {+ return this.steps.find((s) => s.parent === null) ?? null;+ }++ get all(): readonly Step[] {+ return this.steps;+ }++ byId(id: string): Step | undefined {+ return this.steps.find((s) => s.id === id);+ }++ /** The steps from the original to the head. */+ path(): Step[] {+ const out: Step[] = [];+ for (let s = this.head; s; s = s.parent ? (this.byId(s.parent) ?? null) : null) out.unshift(s);+ return out;+ }++ /** The step before the head, if any. */+ previous(): Step | null {+ const h = this.head;+ return h?.parent ? (this.byId(h.parent) ?? null) : null;+ }++ /** What the next render edits (invariant 1): null for text to image. */+ base(method: Method): Master | null {+ const m = method === "compose" ? this.original?.master : this.head?.master;+ if (m && this.liveShas.has(m.sha256)) throw new StepError("A live frame can't be a base");+ return m ?? null;+ }++ /** compose: the kept texts on the path, then the live text, as one instruction. */+ composePrompt(live: string): string {+ return [...this.path().map((s) => s.norm).filter(Boolean), live].filter(Boolean).join(". ");+ }++ /** A live frame was shown: its bytes may never become a base (invariant 3). */+ sawLive(sha256: string): void {+ this.liveShas.add(sha256);+ }++ isLive(sha256: string): boolean {+ 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 {+ const base = this.head;+ 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");+ if (!base && Math.max(s.master.w, s.master.h) < 1024) throw new StepError("A first picture is kept at 1024 or more");+ const step: Step = { ...s, id: `s${++this.n}`, parent: base?.id ?? null, at: s.at ?? Date.now(), master: { ...s.master } };+ this.steps.push(step);+ this.headId = step.id;+ return step;+ }++ canUndo(): boolean {+ return !!this.head?.parent;+ }++ canRedo(): boolean {+ return this.children(this.headId).length > 0;+ }++ undo(): Step | null {+ const p = this.previous();+ if (!p) return null;+ this.headId = p.id;+ return p;+ }++ redo(): Step | null {+ const kids = this.children(this.headId);+ const next = kids.sort((a, b) => b.at - a.at || Number(b.id.slice(1)) - Number(a.id.slice(1)))[0];+ if (!next) return null;+ this.headId = next.id;+ return next;+ }++ jump(id: string): Step | null {+ const s = this.byId(id);+ if (s) this.headId = s.id;+ return s ?? null;+ }++ /** Update a step's master where it lives (the server saved it, or only this browser has it). */+ place(id: string, where: Partial<Pick<Master, "url" | "idb">> & { local?: boolean }): void {+ const s = this.byId(id);+ if (!s) return;+ if (where.url) s.master.url = where.url;+ if (where.idb) s.master.idb = where.idb;+ if (where.local !== undefined) s.local = where.local;+ }++ private children(id: string | null): Step[] {+ return id ? this.steps.filter((s) => s.parent === id) : [];+ }++ toJSON(): StackState {+ return { steps: this.steps.map((s) => ({ ...s, master: { ...s.master } })), head: this.headId };+ }+}++/** A stored stack, checked: anything malformed gives an empty stack. */+export function restoreStack(raw: unknown): StepStack {+ const st = raw as StackState;+ if (!st || !Array.isArray(st.steps)) return new StepStack();+ const ok = st.steps.every(+ (s) =>+ s &&+ typeof s.id === "string" &&+ (s.parent === null || typeof s.parent === "string") &&+ typeof s.text === "string" &&+ typeof s.seed === "number" &&+ s.master &&+ typeof s.master.name === "string" &&+ typeof s.master.sha256 === "string" &&+ typeof s.master.w === "number" &&+ typeof s.master.h === "number",+ );+ return ok ? new StepStack({ steps: st.steps, head: typeof st.head === "string" ? st.head : null }) : new StepStack();+}diff --git a/src/lib/live/text.ts b/src/lib/live/text.tsnew file mode 100644index 00000000..2eaa6aac--- /dev/null+++ b/src/lib/live/text.ts@@ -0,0 +1,47 @@+/**+ * Live edit's text rules (pure, shared by the tab and the server). A render is keyed by what the text means to the+ * model, not by every keystroke: runs of spaces, invisible characters and a trailing full stop change nothing, so they+ * cost no render. Case is kept, because quoted lettering depends on it.+ */++/** The longest live text (the graph check refuses more). */+export const MAX_LIVE_TEXT = 600;++const ZERO_WIDTH = /[-]/g;+const LEADING = /^[\s.,;:!?…\-–—·•*]+/u;+const TRAILING = /[\s.,;:!?…]+$/u;++/** What the model is asked: NFC, no invisible characters, single spaces, no leading or trailing punctuation. */+export function normalize(s: string): string {+ return s.normalize("NFC").replace(ZERO_WIDTH, "").replace(/\s+/g, " ").trim().replace(LEADING, "").replace(TRAILING, "").slice(0, MAX_LIVE_TEXT);+}++/** The text up to its last word boundary: what can render while a word is still being typed. */+export function completedWords(s: string): string {+ const t = s.replace(ZERO_WIDTH, "");+ if (/[\s.,;:!?…]$/u.test(t)) return t;+ const at = Math.max(t.lastIndexOf(" "), t.lastIndexOf("\n"), t.lastIndexOf("\t"));+ return at < 0 ? "" : t.slice(0, at);+}++/** A typed character that ends a word: the moment to render the words so far. */+export const endsWord = (ch: string) => /^[\s.,;:!?…]$/u.test(ch);++export interface KeyParts {+ /** The base picture's input name (a master or the original), or "" for text to image. */+ base: string;+ refs?: string[];+ mask?: string;+ text: string;+ seed: number;+ size: number;+ aspect?: string;+ method?: string;+ /** "live" frames and "keep" masters of the same text are different pictures. */+ quality?: "live" | "keep";+}++/** A stable key for one render: equal keys make the same picture. */+export function renderKey(p: KeyParts): string {+ return JSON.stringify([p.base, p.refs ?? [], p.mask ?? "", normalize(p.text), p.seed >>> 0, p.size, p.base ? "" : (p.aspect ?? "1:1"), p.method ?? "hybrid", p.quality ?? "live"]);+}diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsindex ce06a32e..b018f482 100644--- a/src/lib/local-comfy.ts+++ b/src/lib/local-comfy.ts@@ -50,7 +50,7 @@ export function readPath(path: string): string {if (query) throw new LocalComfyError(`No query on ${p}`);return path;};- if (["/system_stats", "/api/system_stats", "/object_info", "/models", "/embeddings", "/queue", "/api/jobs", "/fuobe/guard"].includes(p)) return noQuery();+ if (["/system_stats", "/api/system_stats", "/object_info", "/models", "/embeddings", "/queue", "/api/jobs", "/fuobe/guard", "/fuobe/live"].includes(p)) return noQuery();if (p.startsWith("/object_info/") && NODE_CLASS.test(decodeURIComponent(p.slice(13)))) return noQuery();if (p.startsWith("/models/") && MODEL_FOLDER.test(p.slice(8))) return noQuery();if (p.startsWith("/history/") && UUID.test(p.slice(9))) return noQuery();@@ -72,7 +72,10 @@ export function readPath(path: string): string {/** The /view path of a wanted file. */export const viewPath = (f: Pick<WantedFile, "filename" | "subfolder" | "type">) => `/view?${new URLSearchParams({ filename: f.filename, subfolder: f.subfolder, type: f.type })}`;-/** A POST the tab may send: an input under a name the server chose, the prompt, and taking its own prompts off. */+/**+ * A POST the tab may send: an input under a name the server chose (or, for live edit, the tab named by its content),+ * the prompt, taking its own prompts off, and taking its own finished prompts out of the history.+ */export function writePath(path: string, body: unknown, own: { promptIds: string[]; names?: string[] }): string {const ownId = (id: unknown) => typeof id === "string" && UUID.test(id) && own.promptIds.includes(id);if (path === "/upload/image") {@@ -92,6 +95,12 @@ export function writePath(path: string, body: unknown, own: { promptIds: string[if (!Array.isArray(del) || !del.length || !del.every(ownId) || Object.keys(body as object).length !== 1) throw new LocalComfyError("Only the run's own prompts");return path;}+ // Live edit takes its own finished prompts out of the history (hundreds of live renders would pile up there).+ if (path === "/history") {+ const del = (body as { delete?: unknown })?.delete;+ if (!Array.isArray(del) || !del.length || !del.every(ownId) || Object.keys(body as object).length !== 1) throw new LocalComfyError("Only the run's own prompts");+ return path;+ }if (path === "/interrupt") {if (!ownId((body as { prompt_id?: unknown })?.prompt_id)) throw new LocalComfyError("Only the run's own prompt");return path;@@ -106,6 +115,8 @@ const FILE_LOADERS: Record<string, string[]> = {LoadImage: ["image"],LoadImageMask: ["image"],LoadImageOutput: ["image"],+ // Live edit's loader (fuobe_live.py): one Fuobe-named picture in the input folder.+ LoadImageFuobeLive: ["image"],LoadVideo: ["file"],LoadAudio: ["audio"],VHS_LoadVideo: ["video"],diff --git a/tests/comfy-library-4.test.ts b/tests/comfy-library-4.test.tsindex 12def167..3d8edffe 100644--- a/tests/comfy-library-4.test.ts+++ b/tests/comfy-library-4.test.ts@@ -102,6 +102,7 @@ describe("round-4 ComfyUI workflows", () => {"qwen-image-21-t2i","qwen-image-21-edit","qwen-image-21-turbo-edit",+ "qwen-image-21-live-edit","qwen-image-21-inpaint","qwen-image-21-outpaint","ideogram4-t2i",diff --git a/tests/fixtures/live-type4.bin b/tests/fixtures/live-type4.binnew file mode 100644index 00000000..34361dbeBinary files /dev/null and b/tests/fixtures/live-type4.bin differdiff --git a/tests/gpu-requirements.test.ts b/tests/gpu-requirements.test.tsindex 68e5c42c..9f4d3bb9 100644--- a/tests/gpu-requirements.test.ts+++ b/tests/gpu-requirements.test.ts@@ -109,8 +109,9 @@ describe("requirements.json", () => {});// 26 KB gzipped since Clean up voice (its pack, two weight files and two graphs: about 0.5 KB).- it("stays within its size budget (200 KB, 26 KB gzipped)", () => {- expect(Buffer.byteLength(text)).toBeLessThanOrEqual(200 * 1024);+ // 210 KB since Live edit (its node file, LoRA and graph: about 1.6 KB).+ it("stays within its size budget (210 KB, 26 KB gzipped)", () => {+ expect(Buffer.byteLength(text)).toBeLessThanOrEqual(210 * 1024);expect(zlib.gzipSync(text).length).toBeLessThanOrEqual(26 * 1024);});});diff --git a/tests/helpers/fake-live.ts b/tests/helpers/fake-live.tsnew file mode 100644index 00000000..0151d81f--- /dev/null+++ b/tests/helpers/fake-live.ts@@ -0,0 +1,212 @@+/**+ * What the ComfyUI stand-in (fake-local-comfy.ts) makes of a live edit graph (src/lib/live/graph.ts): real pixels, so+ * 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).+ */+import { createHash } from "node:crypto";+import sharpLib from "sharp";++type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;++export interface LiveRender {+ data: Buffer;+ type: "image/webp" | "image/png";+ width: number;+ height: number;+ /** 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. */+ touched: [number, number, number, number] | null;+ base?: string;+}++export const isLiveGraph = (g: Graph) => Object.values(g).some((n) => n?.class_type === "SaveImageFuobeLive");++/** The model's size of a live graph, without decoding anything (for the stand-in's timing). */+export function liveModelSize(g: Graph, inputSize: (name: string) => { w: number; h: number } | null): { w: number; h: number } {+ const enc = g["30"]?.inputs ?? {};+ if (!g["10"]) return { w: Number(enc.width) || 512, h: Number(enc.height) || 512 };+ const res = Number(g["20"]?.inputs?.resolution) || 512;+ const s = inputSize(String(g["10"].inputs.image)) ?? { w: res, h: res };+ const r = s.w / s.h;+ return { w: Math.max(32, Math.round(Math.sqrt(res * res * r) / 32) * 32), h: Math.max(32, Math.round(Math.sqrt((res * res) / r) / 32) * 32) };+}++const hashInts = (s: string, n: number) => {+ const d = createHash("sha256").update(s).digest();+ return Array.from({ length: n }, (_, i) => d.readUInt16BE((i * 2) % 30));+};++/** A seeded noise generator (mulberry32). */+function rng(seed: number) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const sharp = async () => sharpLib;++async function decode(bytes: Buffer): Promise<{ data: Buffer; w: number; h: number }> {+ const s = await sharp();+ const { data, info } = await s(bytes).removeAlpha().raw().toBuffer({ resolveWithObject: true });+ return { data, w: info.width, h: info.height };+}++async function resize(data: Buffer, w: number, h: number, tw: number, th: number): Promise<Buffer> {+ if (w === tw && h === th) return Buffer.from(data);+ const s = await sharp();+ return s(data, { raw: { width: w, height: h, channels: 3 } }).resize(tw, th, { kernel: "lanczos3", fit: "fill" }).raw().toBuffer();+}++async function encode(data: Buffer, w: number, h: number, format: string, quality: number): Promise<Buffer> {+ const s = await sharp();+ const img = s(data, { raw: { width: w, height: h, channels: 3 } });+ return format === "png" ? img.png({ compressionLevel: 1 }).toBuffer() : img.webp({ quality }).toBuffer();+}++/** 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 ?? "");+ const seed = Number(g["70"]?.inputs?.noise_seed ?? 0);+ const save = g["90"]?.inputs ?? {};+ const format = save.format === "png" ? "png" : "webp";+ const quality = Number(save.quality) || 85;+ const [hx, hy, hw, hh, r, gr, b] = hashInts(`${prompt}\u0000${seed}`, 7);+ const colour = [r % 256, gr % 256, b % 256];++ if (!g["10"]) {+ // Text to image: a gradient and a rectangle, at the latent's size.+ const w = Number(g["30"].inputs.width);+ const h = Number(g["30"].inputs.height);+ const px = Buffer.alloc(w * h * 3);+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++) {+ const i = (y * w + x) * 3;+ px[i] = (colour[0] + (x * 128) / w) & 255;+ px[i + 1] = (colour[1] + (y * 128) / h) & 255;+ px[i + 2] = (colour[2] + ((x + y) * 64) / (w + h)) & 255;+ }+ return { data: await encode(px, w, h, format, quality), type: format === "png" ? "image/png" : "image/webp", width: w, height: h, modelW: w, modelH: h, touched: null };+ }++ const read = (id: string) => {+ const name = String(g[id]?.inputs?.image ?? "");+ const bytes = inputs.get(name);+ if (!bytes) throw Object.assign(new Error("Live edit reads only pictures Fuobe sent"), { nodeType: "LoadImageFuobeLive", node: id });+ return bytes;+ };+ const base = await decode(read("10"));+ const mask = g["14"] ? await decode(read("14")) : null;+ const { w: W, h: H } = base;+ const res = Number(g["20"]?.inputs?.resolution) || 512;+ const ratio = W / H;+ const mw = Math.max(32, Math.round(Math.sqrt(res * res * ratio) / 32) * 32);+ const mh = Math.max(32, Math.round(Math.sqrt((res * res) / ratio) / 32) * 32);+ const mode = String(g["40"]?.inputs?.mode ?? "auto");+ const outMax = Number(g["40"]?.inputs?.out_max_side ?? 0);++ // The changed rectangle, in the base's pixels.+ let rect: [number, number, number, number];+ let maskFull: Buffer | null = null;+ if (mode === "mask" && mask) {+ const m = await resize(mask.data, mask.w, mask.h, W, H);+ maskFull = m;+ let x0 = W, y0 = H, x1 = 0, y1 = 0;+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++)+ if (m[(y * W + x) * 3] > 127) {+ x0 = Math.min(x0, x);+ y0 = Math.min(y0, y);+ x1 = Math.max(x1, x + 1);+ y1 = Math.max(y1, y + 1);+ }+ rect = x1 > x0 ? [x0, y0, x1, y1] : [0, 0, 0, 0];+ } else {+ const area = 0.08 + ((hw % 1000) / 1000) * 0.12;+ const aspect = 0.6 + ((hh % 1000) / 1000) * 0.8;+ const rw = Math.max(8, Math.round(Math.sqrt(area * W * H * aspect)));+ const rh = Math.max(8, Math.round((area * W * H) / rw));+ const x0 = Math.round(((hx % 1000) / 1000) * Math.max(1, W - rw));+ const y0 = Math.round(((hy % 1000) / 1000) * Math.max(1, H - rh));+ rect = [x0, y0, Math.min(W, x0 + rw), Math.min(H, y0 + rh)];+ }++ // The model's frame: the base at the model's size, the rectangle painted, a lossy round trip, back to full size.+ let model = await resize(base.data, W, H, mw, mh);+ const sx = mw / W;+ const sy = mh / H;+ for (let y = Math.floor(rect[1] * sy); y < Math.ceil(rect[3] * sy); y++)+ for (let x = Math.floor(rect[0] * sx); x < Math.ceil(rect[2] * sx); x++) {+ if (x < 0 || y < 0 || x >= mw || y >= mh) continue;+ if (maskFull && maskFull[(Math.min(H - 1, Math.floor(y / sy)) * W + Math.min(W - 1, Math.floor(x / sx))) * 3] <= 127) continue;+ const i = (y * mw + x) * 3;+ model[i] = colour[0];+ model[i + 1] = colour[1];+ model[i + 2] = colour[2];+ }+ if (opts.lossy) {+ const rand = rng(seed ^ 0x9e3779b9);+ for (let i = 0; i < model.length; i++) model[i] = Math.max(0, Math.min(255, model[i] + Math.round(rand() * 4 - 2)));+ const s = await sharp();+ model = await s(model, { raw: { width: mw, height: mh, channels: 3 } }).blur(0.5).raw().toBuffer();+ }+ const edited = await resize(model, mw, mh, W, H);++ // Paste back: the base where nothing changed.+ const out = Buffer.from(base.data);+ let touched: [number, number, number, number] | null = null;+ 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);+ }+ 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);+ }+ }++ // The output size (a live frame is the composite made small).+ let ow = W;+ let oh = H;+ let data: Buffer = out;+ if (outMax && Math.max(W, H) > outMax) {+ const s = outMax / Math.max(W, H);+ ow = Math.max(32, Math.round(W * s));+ oh = Math.max(32, Math.round(H * s));+ 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) };+}++/** A picture's size from its header (PNG, JPEG or WebP via sharp's metadata), for timing. */+export async function pictureSize(bytes: Buffer): Promise<{ w: number; h: number } | null> {+ try {+ const s = await sharp();+ const m = await s(bytes).metadata();+ return m.width && m.height ? { w: m.width, h: m.height } : null;+ } catch {+ return null;+ }+}diff --git a/tests/helpers/fake-local-comfy.ts b/tests/helpers/fake-local-comfy.tsindex aca71443..737a2eef 100644--- a/tests/helpers/fake-local-comfy.ts+++ b/tests/helpers/fake-local-comfy.ts@@ -16,6 +16,8 @@ import { readFileSync } from "node:fs";import http from "node:http";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";export interface LocalComfyOptions {/** "off": ComfyUI's own check (other sites get 403); an origin, or "*". */@@ -47,6 +49,24 @@ export interface LocalComfyOptions {* classes, with the loaders listing its files, and its model files. Without it, this ComfyUI has nothing.*/has?: IndexLike;+ /**+ * Live edit (graphs with SaveImageFuobeLive, tests/helpers/fake-live.ts): each of the 2 steps takes this long at+ * 512 x 512, scaled by the model's area. Unset: stepMs.+ */+ stepMsAt512?: number;+ /** Live renders get a lossy round trip over the whole frame (noise and a slight blur), as a VAE's would. */+ lossy?: boolean;+ /** The live nodes aren't installed (object_info leaves out the *FuobeLive classes; /fuobe/live is 404). */+ noLiveNodes?: boolean;+}++/** One live render the stand-in made (for the bookkeeping checks). */+export interface LiveRenderLog extends Omit<LiveRender, "data"> {+ id: string;+ clientId?: string;+ sha256: string;+ bytes: Buffer;+ ms: number;}/** The parts of a requirement index (src/lib/gpu/types.ts) the stand-in reads. */@@ -80,8 +100,11 @@ export interface LocalComfyLog {path: string;origin?: string;status?: number;+ at?: number;upload?: { name: string; bytes: Buffer };- prompt?: { prompt_id?: string; prompt?: Record<string, { class_type: string; inputs: Record<string, unknown> }>; extra_data?: Record<string, unknown>; client_id?: string };+ prompt?: { prompt_id?: string; prompt?: Record<string, { class_type: string; inputs: Record<string, unknown> }>; extra_data?: Record<string, unknown>; client_id?: string; front?: boolean };+ /** POST /queue, /interrupt and /history: what it asked. */+ body?: unknown;}type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;@@ -93,6 +116,8 @@ interface Job {preview: boolean;fail?: LocalComfyOptions["failNext"];pass?: number;+ /** Another client's long job (foreign): how long it runs. */+ ms?: number;}type Entry = { prompt: unknown[]; outputs: Record<string, Record<string, unknown>>; status: { status_str: string; completed: boolean; messages: [string, Record<string, unknown>][] } };@@ -105,8 +130,12 @@ export interface LocalComfy {history: Map<string, Entry>;/** Prompts posted (a resumed task must not post twice). */posts: () => number;- /** ComfyUI restarted: its queue, history and sockets are gone, the inputs folder stays. */- restart: (o?: Partial<LocalComfyOptions>) => void;+ /** ComfyUI restarted: its queue, history and sockets are gone, the inputs folder stays (unless wipeInputs). */+ restart: (o?: Partial<LocalComfyOptions> & { wipeInputs?: boolean }) => void;+ /** Queue a long job from another client (someone else's run on the same GPU). */+ foreign: (ms: number) => string;+ /** Live renders made, in order. */+ renders: LiveRenderLog[];/** Stop listening (ComfyUI closed), and start again on the same port. */stop: () => Promise<void>;start: (o?: Partial<LocalComfyOptions>) => Promise<void>;@@ -166,6 +195,9 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loclet posts = 0;let timer: NodeJS.Timeout | undefined;const sockets = new Map<string, Set<Duplex>>();+ const renders: LiveRenderLog[] = [];+ const temps = new Map<string, { data: Buffer; type: string }>();+ const sizes = new Map<string, { w: number; h: number }>();let server: http.Server;let generation = 0;@@ -208,11 +240,68 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loctick();}+ function runLive(job: Job) {+ running = job;+ const gen = generation;+ const alive = () => gen === generation && running === job;+ const started = Date.now();+ 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);+ const stepMs = (opts.stepMsAt512 ?? opts.stepMs ?? 20) * ((size.w * size.h) / (512 * 512));+ let step = 0;+ const fail = (message: string, nodeType: string, node = "10") => {+ const err = { prompt_id: job.id, node_id: node, node_type: nodeType, exception_message: message, exception_type: "ValueError" };+ event(job.clientId, "execution_error", err);+ finish(job, { prompt: [job.number, job.id, job.graph, {}, []], outputs: {}, status: { status_str: "error", completed: false, messages: [["execution_error", err]] } });+ };+ const next = () => {+ if (!alive()) return;+ if (step < 2) {+ step++;+ event(job.clientId, "progress", { value: step, max: 2, prompt_id: job.id, node: "32" });+ timer = setTimeout(next, stepMs);+ return;+ }+ renderLive(job.graph, inputs, { lossy: opts.lossy }).then(+ (r) => {+ if (!alive()) return;+ const to = job.graph["90"]?.inputs?.to;+ const sha256 = createHash("sha256").update(r.data).digest("hex");+ const { data, ...rest } = r;+ renders.push({ ...rest, id: job.id, clientId: job.clientId, sha256, bytes: data, ms: Date.now() - started });+ let ui: Record<string, unknown>;+ if (to === "socket" && job.clientId && sockets.get(job.clientId)?.size) {+ const meta = Buffer.from(JSON.stringify({ prompt_id: job.id, node_id: "90", image_type: r.type, width: r.width, height: r.height, fuobe_live: 1 }));+ const len = Buffer.alloc(4);+ len.writeUInt32BE(meta.length);+ send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, data]), true);+ ui = { fuobe_live: [{ sent: true, width: r.width, height: r.height }] };+ } else {+ const name = `fuobe_live_${job.number}.${r.type === "image/png" ? "png" : "webp"}`;+ temps.set(name, { data, type: r.type });+ ui = { images: [{ filename: name, subfolder: "", type: "temp" }] };+ }+ 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 });+ 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 }]] } });+ },+ (e: Error & { nodeType?: string; node?: string }) => {+ if (alive()) fail(e.message, e.nodeType ?? "SaveImageFuobeLive", e.node);+ },+ );+ };+ timer = setTimeout(next, opts.latencyMs);+ }+function run(job: Job) {+ if (isLiveGraph(job.graph)) return runLive(job);running = job;const gen = generation;const alive = () => gen === generation && running === job;const steps = opts.steps ?? 4;+ const stepMs = job.ms !== undefined ? job.ms / steps : opts.stepMs;const node = Object.keys(job.graph).find((k) => /KSampler|Sampler/.test(job.graph[k].class_type)) ?? Object.keys(job.graph)[0] ?? "1";event(job.clientId, "execution_start", { prompt_id: job.id });event(job.clientId, "executing", { node, prompt_id: job.id });@@ -229,7 +318,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loclen.writeUInt32BE(meta.length);send(job.clientId, Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, FAKE_PNG]), true);}- timer = setTimeout(next, opts.stepMs);+ timer = setTimeout(next, stepMs);return;}if (job.fail === "oom") {@@ -286,7 +375,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst body = Buffer.concat(chunks);const url = new URL(req.url ?? "/", "http://fake");const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;- const entry: LocalComfyLog = { method: req.method ?? "GET", path: url.pathname + url.search, ...(origin && { origin }) };+ const entry: LocalComfyLog = { method: req.method ?? "GET", path: url.pathname + url.search, at: Date.now(), ...(origin && { origin }) };log.push(entry);const headers: Record<string, string> = {};if (opts.cors !== "off") {@@ -327,16 +416,19 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locif (p === "/models/loras") return opts.loras ? reply(200, opts.loras) : reply(404, { error: "not found" });if (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 === "/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) {const files = has.folders.get(decodeURIComponent(p.slice(19)));return files ? reply(200, files.map((f) => ({ name: f.name, pathIndex: 0, size: f.size }))) : reply(404, { error: "not found" });}- if (p === "/object_info") return reply(200, has?.info ?? {});+ const hidden = (cls: string) => !!opts.noLiveNodes && /FuobeLive$/.test(cls);+ if (p === "/object_info") return reply(200, Object.fromEntries(Object.entries(has?.info ?? {}).filter(([c]) => !hidden(c))));if (p.startsWith("/object_info/")) {const cls = decodeURIComponent(p.slice(13));- return reply(200, has?.info[cls] ? { [cls]: has.info[cls] } : {});+ return reply(200, has?.info[cls] && !hidden(cls) ? { [cls]: has.info[cls] } : {});}if (p === "/embeddings") return reply(200, []);if (p === "/upload/image" && req.method === "POST") {@@ -346,6 +438,7 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locif (!image || !name || /[\\/]|\.\./.test(name)) return reply(400, { error: "bad name" });inputs.set(name, Buffer.from(image.data));entry.upload = { name, bytes: Buffer.from(image.data) };+ void pictureSize(Buffer.from(image.data)).then((sz) => sz && sizes.set(name, sz));return reply(200, { name, subfolder: "", type: parts.get("type")?.data.toString() ?? "input" });}if (p === "/prompt" && req.method === "POST") {@@ -379,14 +472,24 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locreturn reply(200, { prompt_id: id, number: ++number, node_errors: {} });}if (fail === "gone") return reply(200, { prompt_id: id, number: ++number, node_errors: {} });+ if (opts.noLiveNodes && isLiveGraph(json.prompt ?? {})) {+ return reply(400, {+ error: { type: "missing_node_type", message: "Node 'SaveImageFuobeLive' not found. The custom node may not be installed.", details: "Node ID '#90'", extra_info: { node_id: "90", class_type: "SaveImageFuobeLive", node_title: "SaveImageFuobeLive" } },+ node_errors: {},+ });+ }const job: Job = { id, number: ++number, graph: json.prompt ?? {}, clientId: json.client_id, preview: !!json.extra_data?.preview_method && json.extra_data.preview_method !== "none", fail };- queue.push(job);+ // front: ComfyUI puts it ahead of everything waiting.+ if (json.front === true) queue.unshift(job);+ else queue.push(job);setImmediate(tick);return reply(200, { prompt_id: id, number: job.number, node_errors: {} });}if (p === "/queue") {if (req.method === "POST") {- const del = (JSON.parse(body.toString("utf8") || "{}") as { delete?: string[] }).delete ?? [];+ const asked = JSON.parse(body.toString("utf8") || "{}") as { delete?: string[] };+ entry.body = asked;+ const del = asked.delete ?? [];queue = queue.filter((j) => !del.includes(j.id));return reply(200, {});}@@ -394,7 +497,9 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locreturn reply(200, { queue_running: running ? [row(running)] : [], queue_pending: queue.map(row) });}if (p === "/interrupt" && req.method === "POST") {- const id = (JSON.parse(body.toString("utf8") || "{}") as { prompt_id?: string }).prompt_id;+ const asked = JSON.parse(body.toString("utf8") || "{}") as { prompt_id?: string };+ entry.body = asked;+ const id = asked.prompt_id;if (id && running?.id === id) cancel(id);return reply(200, {});}@@ -403,6 +508,13 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locconst h = history.get(id);return reply(200, h ? { [id]: h } : {});}+ if (p === "/history" && req.method === "POST") {+ const asked = JSON.parse(body.toString("utf8") || "{}") as { delete?: string[]; clear?: boolean };+ entry.body = asked;+ if (asked.clear) history.clear();+ for (const id of asked.delete ?? []) history.delete(id);+ return reply(200, {});+ }if (p === "/history") {const max = Number(url.searchParams.get("max_items") ?? 64);return reply(200, Object.fromEntries([...history.entries()].slice(-max)));@@ -416,6 +528,13 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Loc}if (p === "/view") {const name = url.searchParams.get("filename") ?? "";+ const temp = url.searchParams.get("type") === "temp" ? temps.get(name) : undefined;+ if (temp) return reply(200, temp.data, temp.type);+ // The input folder: what was uploaded, nothing else.+ if (url.searchParams.get("type") === "input") {+ const got = inputs.get(name);+ return got ? reply(200, got, "application/octet-stream") : reply(404, { error: "no file" });+ }const kind = (opts.outputs ?? ["image"])[Math.max(0, Number(/_(\d{5})_\./.exec(name)?.[1] ?? 1) - 1)];if (kind === "fake-png") return reply(200, Buffer.from("<!doctype html><script>alert(document.cookie)</script>".padEnd(200, " ")), "image/png");if (name.endsWith(".png")) return reply(200, FAKE_PNG, "image/png");@@ -491,16 +610,27 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Locsockets.clear();};- const restart = (o: Partial<LocalComfyOptions> = {}) => {+ const restart = ({ wipeInputs, ...o }: Partial<LocalComfyOptions> & { wipeInputs?: boolean } = {}) => {generation++;clearTimeout(timer);queue = [];running = null;history.clear();closeSockets();+ if (wipeInputs) {+ inputs.clear();+ sizes.clear();+ }Object.assign(opts, o);};+ const foreign = (ms: number) => {+ const id = randomUUID();+ queue.push({ id, number: ++number, graph: { "1": { class_type: "KSampler", inputs: {} }, "9": { class_type: "SaveImage", inputs: { filename_prefix: "someone" } } }, clientId: "someone-else", preview: false, ms });+ setImmediate(tick);+ return id;+ };+return listen(port).then((at) => {const fake: LocalComfy = {port: at,@@ -511,6 +641,8 @@ export function startLocalComfy(given: LocalComfyOptions, port = 0): Promise<Lochistory,posts: () => posts,restart,+ foreign,+ renders,stop: () =>new Promise<void>((done) => {restart();diff --git a/tests/helpers/image-metrics.ts b/tests/helpers/image-metrics.tsnew file mode 100644index 00000000..accede3c--- /dev/null+++ b/tests/helpers/image-metrics.ts@@ -0,0 +1,81 @@+/**+ * Picture measures for live edit's drift checks: SSIM (grayscale, 8 x 8 windows) and the variance of the Laplacian+ * (sharpness), each over a region (the pixels no edit touched). Decoding through sharp; plain TypeScript.+ */+import sharp from "sharp";++export interface Gray {+ w: number;+ h: number;+ px: Float64Array;+}++export async function gray(bytes: Buffer, size?: { w: number; h: number }): Promise<Gray> {+ let img = sharp(bytes).removeAlpha();+ if (size) img = img.resize(size.w, size.h, { kernel: "lanczos3", fit: "fill" });+ const { data, info } = await img.raw().toBuffer({ resolveWithObject: true });+ const px = new Float64Array(info.width * info.height);+ for (let i = 0; i < px.length; i++) px[i] = 0.299 * data[i * 3] + 0.587 * data[i * 3 + 1] + 0.114 * data[i * 3 + 2];+ return { w: info.width, h: info.height, px };+}++/** A region: true where a pixel counts. */+export type Region = (x: number, y: number) => boolean;++export const outside =+ (rects: [number, number, number, number][]): Region =>+ (x, y) =>+ !rects.some(([x0, y0, x1, y1]) => x >= x0 && x < x1 && y >= y0 && y < y1);++/** Mean SSIM over the 8 x 8 windows that lie wholly in the region. */+export function ssim(a: Gray, b: Gray, region: Region = () => true): number {+ if (a.w !== b.w || a.h !== b.h) throw new Error("SSIM needs pictures of one size");+ const C1 = (0.01 * 255) ** 2;+ const C2 = (0.03 * 255) ** 2;+ let sum = 0;+ let n = 0;+ for (let y = 0; y + 8 <= a.h; y += 8)+ for (let x = 0; x + 8 <= a.w; x += 8) {+ if (!region(x, y) || !region(x + 7, y) || !region(x, y + 7) || !region(x + 7, y + 7)) continue;+ let ma = 0, mb = 0;+ for (let j = 0; j < 8; j++) for (let i = 0; i < 8; i++) {+ const k = (y + j) * a.w + x + i;+ ma += a.px[k];+ mb += b.px[k];+ }+ ma /= 64;+ mb /= 64;+ let va = 0, vb = 0, cov = 0;+ for (let j = 0; j < 8; j++) for (let i = 0; i < 8; i++) {+ const k = (y + j) * a.w + x + i;+ const da = a.px[k] - ma;+ const db = b.px[k] - mb;+ va += da * da;+ vb += db * db;+ cov += da * db;+ }+ va /= 63;+ vb /= 63;+ cov /= 63;+ sum += ((2 * ma * mb + C1) * (2 * cov + C2)) / ((ma * ma + mb * mb + C1) * (va + vb + C2));+ n++;+ }+ return n ? sum / n : 1;+}++/** Variance of the 4-neighbour Laplacian over the region (higher is sharper). */+export function laplacianVariance(a: Gray, region: Region = () => true): number {+ let sum = 0, sq = 0, n = 0;+ for (let y = 1; y < a.h - 1; y++)+ for (let x = 1; x < a.w - 1; x++) {+ if (!region(x, y)) continue;+ const k = y * a.w + x;+ const l = a.px[k - 1] + a.px[k + 1] + a.px[k - a.w] + a.px[k + a.w] - 4 * a.px[k];+ sum += l;+ sq += l * l;+ n++;+ }+ if (!n) return 0;+ const mean = sum / n;+ return sq / n - mean * mean;+}diff --git a/tests/live-core.test.ts b/tests/live-core.test.tsnew file mode 100644index 00000000..b4e9a375--- /dev/null+++ b/tests/live-core.test.ts@@ -0,0 +1,186 @@+/**+ * Live edit's pure core: text keys, sizes and the auto ladder, input names, the render stream's framing, and the kept+ * step stack with its no-degradation invariants (src/lib/live).+ */+import { describe, expect, it } from "vitest";+import { completedWords, normalize, renderKey } from "@/lib/live/text";+import { aspectOf, AutoSize, editSize, keepAuto, sizeFor, ASPECT_NAMES } from "@/lib/live/sizes";+import { inputName, LIVE_INPUT, pictureExt, pngSize } from "@/lib/live/names";+import { eventFrame, FrameError, FrameReader, imageFrame } from "@/lib/live/frames";+import { restoreStack, StepError, StepStack, type Master } from "@/lib/live/steps";+import { INPUT_NAME } from "@/lib/relay";++describe("text", () => {+ it("normalizes what doesn't change the meaning, and keeps case", () => {+ expect(normalize(" add gold hoop earrings. ")).toBe("add gold hoop earrings");+ expect(normalize("add gold hoop earrings!!")).toBe("add gold hoop earrings");+ expect(normalize("add\ngold\thoop earrings")).toBe("add gold hoop earrings");+ expect(normalize('a sign that says "OPEN"')).toBe('a sign that says "OPEN"');+ expect(normalize("Red")).not.toBe(normalize("red"));+ expect(normalize("...red scarf")).toBe("red scarf");+ });+ it("completed words stop at the last boundary", () => {+ expect(completedWords("add gold ho")).toBe("add gold");+ expect(completedWords("add gold ")).toBe("add gold ");+ expect(completedWords("add")).toBe("");+ expect(completedWords("add gold,")).toBe("add gold,");+ });+ it("render keys are stable over no-op changes and differ on real ones", () => {+ const k = (text: string, o: Partial<Parameters<typeof renderKey>[0]> = {}) => renderKey({ base: "b", text, seed: 7, size: 512, ...o });+ expect(k("add gold hoop earrings.")).toBe(k("add gold hoop earrings"));+ expect(k("add gold")).not.toBe(k("add silver"));+ expect(k("x", { seed: 8 })).not.toBe(k("x"));+ expect(k("x", { size: 640 })).not.toBe(k("x"));+ expect(k("x", { quality: "keep" })).not.toBe(k("x"));+ expect(k("x", { base: "c" })).not.toBe(k("x"));+ });+});++describe("sizes", () => {+ // The original's table: 7 ratios x 5 sizes, defined at 2048 on the 32 grid.+ const table: Record<string, [number, number]> = { "1:1": [2048, 2048], "4:3": [2400, 1792], "3:4": [1792, 2400], "3:2": [2528, 1696], "2:3": [1696, 2528], "16:9": [2752, 1536], "9:16": [1536, 2752] };+ it("matches the reference size table for every ratio and size", () => {+ for (const a of ASPECT_NAMES)+ for (const res of [512, 768, 1024, 1536, 2048]) {+ const [bw, bh] = table[a];+ const want = [Math.max(32, Math.round((bw * res) / 2048 / 32) * 32), Math.max(32, Math.round((bh * res) / 2048 / 32) * 32)];+ expect(sizeFor(a, res)).toEqual(want);+ }+ });+ it("edit sizes keep the area and the shape on the grid", () => {+ const [w, h] = editSize(512, 1536, 2048);+ expect(w % 32).toBe(0);+ expect(h % 32).toBe(0);+ expect(Math.abs(w * h - 512 * 512) / (512 * 512)).toBeLessThan(0.1);+ expect(aspectOf(1536, 2048)).toBe("3:4");+ expect(aspectOf(1920, 1080)).toBe("16:9");+ });+ it("keep auto follows the base's long side, 1024 to 1536", () => {+ expect(keepAuto(undefined)).toBe(1024);+ expect(keepAuto(800)).toBe(1024);+ expect(keepAuto(1400)).toBe(1024);+ expect(keepAuto(2048)).toBe(1536);+ });+ it("auto size steps down on slow frames and up on fast ones, with hysteresis", () => {+ const a = new AutoSize(512);+ for (let i = 0; i < 4; i++) expect(a.record(1500)).toBe(512);+ expect(a.record(1500)).toBe(384);+ // One fast frame doesn't flip it back.+ expect(a.record(200)).toBe(384);+ for (let i = 0; i < 6; i++) a.record(200);+ expect(a.record(200)).toBe(512);+ for (let i = 0; i < 8; i++) a.record(300);+ expect(a.size).toBe(640);+ const capped = new AutoSize(640, 640);+ for (let i = 0; i < 10; i++) capped.record(100);+ expect(capped.size).toBe(640);+ });+});++describe("names", () => {+ it("names bytes by their hash, within Fuobe's input rule", async () => {+ const a = await inputName(new Uint8Array([1, 2, 3]), "png");+ const b = await inputName(new Uint8Array([1, 2, 3]), "png");+ const c = await inputName(new Uint8Array([1, 2, 4]), "png");+ expect(a).toEqual(b);+ expect(a.name).not.toBe(c.name);+ expect(a.name).toMatch(LIVE_INPUT);+ expect(a.name).toMatch(INPUT_NAME);+ expect(a.sha256).toMatch(/^[0-9a-f]{64}$/);+ });+ it("sniffs pictures and reads a PNG's size", () => {+ const png = Uint8Array.from(Buffer.from("89504e470d0a1a0a0000000d494844520000000200000003080600000072b60d24", "hex"));+ expect(pictureExt(png)).toBe("png");+ expect(pngSize(png)).toEqual({ w: 2, h: 3 });+ expect(pictureExt(Uint8Array.from([0xff, 0xd8, 0xff, 0xe0]))).toBe("jpg");+ expect(pictureExt(Uint8Array.from(Buffer.from("RIFF0000WEBPVP8 ")))).toBe("webp");+ expect(pictureExt(Uint8Array.from(Buffer.from("<html>")))).toBeNull();+ });+});++describe("frames", () => {+ it("round-trips events and pictures, across any chunking", () => {+ const pic = Uint8Array.from({ length: 1000 }, (_, i) => i % 251);+ const all = new Uint8Array([...eventFrame({ type: "queued", pos: 2 }), ...imageFrame({ seq: 4, slot: "live", key: "k", w: 512, h: 512, type: "image/webp", ms: 210 }, pic), ...eventFrame({ type: "dropped", why: "replaced" })]);+ for (const size of [1, 3, 7, 64, all.length]) {+ const r = new FrameReader();+ const out = [];+ for (let i = 0; i < all.length; i += size) out.push(...r.push(all.subarray(i, i + size)));+ expect(out).toHaveLength(3);+ expect(out[0]).toEqual({ kind: "event", event: { type: "queued", pos: 2 } });+ expect(out[1].kind === "image" && out[1].header.seq === 4 && out[1].data.length === 1000 && out[1].data[999] === 999 % 251).toBe(true);+ expect(out[2]).toEqual({ kind: "event", event: { type: "dropped", why: "replaced" } });+ expect(r.pending).toBe(0);+ }+ });+ it("keeps a truncated frame pending and refuses garbage", () => {+ const f = eventFrame({ type: "started" });+ const r = new FrameReader();+ expect(r.push(f.subarray(0, f.length - 1))).toEqual([]);+ expect(r.pending).toBe(f.length - 1);+ expect(() => new FrameReader().push(Uint8Array.from([0x58, 0, 0, 0, 1, 0]))).toThrow(FrameError);+ expect(() => new FrameReader().push(Uint8Array.from([0x4a, 0xff, 0xff, 0xff, 0xff]))).toThrow(/too large/);+ expect(() => new FrameReader().push(Uint8Array.from([0x49, 0, 0, 0, 2, 0, 1]))).toThrow(FrameError);+ });+});++describe("steps", () => {+ const master = (n: number, o: Partial<Master> = {}): Master => ({ name: `fuobe_lv${String(n).padStart(20, "0")}.png`, w: 1536, h: 2048, sha256: `sha${n}`, format: "png", ...o });+ const keep = (s: StepStack, n: number, text = `edit ${n}`, o: Partial<Master> = {}) => s.keep({ text, norm: text, seed: n, method: "hybrid", keepRes: 1536, master: master(n, o), ms: 900 });++ it("keeps, undoes, redoes and branches, and picks the base per method", () => {+ const s = StepStack.from(master(0, { format: "jpg" }));+ keep(s, 1);+ keep(s, 2);+ expect(s.path().map((x) => x.text)).toEqual(["", "edit 1", "edit 2"]);+ expect(s.base("hybrid")?.sha256).toBe("sha2");+ expect(s.base("chain")?.sha256).toBe("sha2");+ expect(s.base("compose")?.sha256).toBe("sha0");+ expect(s.composePrompt("live")).toBe("edit 1. edit 2. live");+ expect(s.undo()?.text).toBe("edit 1");+ expect(s.canRedo()).toBe(true);+ expect(s.redo()?.text).toBe("edit 2");+ s.undo();+ keep(s, 3, "branch");+ expect(s.path().map((x) => x.text)).toEqual(["", "edit 1", "branch"]);+ expect(s.all).toHaveLength(4);+ s.undo();+ // Redo goes to the newest child.+ expect(s.redo()?.text).toBe("branch");+ expect(s.jump("s2")?.text).toBe("edit 2");+ expect(s.previous()?.text).toBe("edit 1");+ while (s.undo());+ expect(s.head?.id).toBe("s0");+ expect(s.canUndo()).toBe(false);+ });++ it("refuses a master that isn't PNG, is smaller than its base, or was a live frame", () => {+ const s = StepStack.from(master(0));+ expect(() => keep(s, 1, "x", { format: "webp" })).toThrow(StepError);+ expect(() => keep(s, 1, "x", { w: 384, h: 512 })).toThrow(/smaller/);+ s.sawLive("live-sha");+ expect(() => keep(s, 1, "x", { sha256: "live-sha" })).toThrow(/live frame/);+ expect(s.all).toHaveLength(1);+ });++ it("text to image starts empty and keeps a first picture of 1024 or more", () => {+ const s = new StepStack();+ expect(s.base("hybrid")).toBeNull();+ expect(() => keep(s, 1, "x", { w: 512, h: 512 })).toThrow(/1024/);+ keep(s, 1, "a portrait", { w: 1024, h: 1024 });+ expect(s.original?.text).toBe("a portrait");+ });++ it("survives a round trip through storage, and refuses junk", () => {+ const s = StepStack.from(master(0));+ keep(s, 1);+ keep(s, 2);+ s.undo();+ const back = restoreStack(JSON.parse(JSON.stringify(s)));+ expect(back.head?.id).toBe("s1");+ expect(back.all).toHaveLength(3);+ expect(keep(back, 3).id).toBe("s3");+ expect(restoreStack({ steps: [{ id: 1 }] }).empty).toBe(true);+ expect(restoreStack(null).empty).toBe(true);+ });+});diff --git a/tests/live-drift.test.ts b/tests/live-drift.test.tsnew file mode 100644index 00000000..cb450818--- /dev/null+++ b/tests/live-drift.test.ts@@ -0,0 +1,169 @@+/**+ * 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.+ *+ * - 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 %);+ * - 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.+ */+import { randomUUID } from "node:crypto";+import sharp from "sharp";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { buildLiveGraph, slotBindings, type LiveGraphParams } from "@/lib/live/graph";+import { inputName, pngSize } from "@/lib/live/names";+import { LiveScheduler } from "@/lib/live/scheduler";+import { StepStack, type Master, type Method } from "@/lib/live/steps";+import { renderKey } from "@/lib/live/text";+import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";+import { gray, laplacianVariance, outside, ssim } from "./helpers/image-metrics";++const W = 1536;+const H = 2048;+const EDITS = ["gold hoop earrings", "a red silk scarf", "a black leather bag", "puffed sleeves", "a sign that says OPEN", "copper hair", "a pearl necklace", "deep red lipstick", "a velvet ribbon", "a silver brooch"];++let fake: LocalComfy;+let original: Buffer;++beforeAll(async () => {+ fake = await startLocalComfy({ cors: "off", stepMsAt512: 1, latencyMs: 1, lossy: true });+ // A detailed picture: fine texture over smooth shapes (a 512 round trip loses the texture).+ const px = Buffer.alloc(W * H * 3);+ let s = 1;+ for (let y = 0; y < H; y++)+ for (let x = 0; x < W; x++) {+ s = (s * 1103515245 + 12345) >>> 0;+ const n = (s >>> 24) % 48;+ const i = (y * W + x) * 3;+ px[i] = (60 + ((x * 140) / W) + n) & 255;+ px[i + 1] = (50 + ((y * 120) / H) + n) & 255;+ px[i + 2] = (90 + (((x + y) % 256) >> 2) + n) & 255;+ }+ original = await sharp(px, { raw: { width: W, height: H, channels: 3 } }).png({ compressionLevel: 1 }).toBuffer();+}, 60_000);++afterAll(() => fake?.close());++async function upload(bytes: Buffer): Promise<string> {+ const { name } = await inputName(bytes, "png");+ const form = new FormData();+ form.append("image", new Blob([new Uint8Array(bytes)], { type: "image/png" }), name);+ form.append("type", "input");+ form.append("overwrite", "true");+ const r = await fetch(`${fake.url}/upload/image`, { method: "POST", body: form });+ expect(r.ok).toBe(true);+ return name;+}++/** One render through the stand-in (the link path: saved to temp, read from /view). */+async function render(p: LiveGraphParams, signal: AbortSignal): Promise<Buffer> {+ const id = randomUUID();+ const { graph } = buildLiveGraph({ ...p, to: "temp" });+ const r = await fetch(`${fake.url}/prompt`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt: graph, prompt_id: id, client_id: "drift-test", front: true }) });+ expect(r.ok).toBe(true);+ for (;;) {+ if (signal.aborted) throw new Error("aborted");+ const h = (await (await fetch(`${fake.url}/history/${id}`)).json()) as Record<string, { outputs: Record<string, { images?: { filename: string }[] }> }>;+ const img = h[id]?.outputs?.["90"]?.images?.[0];+ if (img) {+ await fetch(`${fake.url}/history`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ delete: [id] }) });+ return Buffer.from(await (await fetch(`${fake.url}/view?filename=${img.filename}&subfolder=&type=temp`)).arrayBuffer());+ }+ if (h[id]) throw new Error("render failed");+ await new Promise((res) => setTimeout(res, 3));+ }+}++const master = async (bytes: Buffer, name: string): Promise<Master> => {+ const size = pngSize(bytes)!;+ const { sha256 } = await inputName(bytes, "png");+ return { name, w: size.w, h: size.h, sha256, format: "png" };+};++/**+ * 10 kept edits, each after two live frames, by a method: "hybrid" (paste-back), "chain" (no paste-back, whole-picture+ * edits), or "preview" (the reference app's: the shown 512 live frame becomes the next base).+ */+async function session(method: Method | "preview") {+ const sched = new LiveScheduler<LiveGraphParams, Buffer>({ run: (job, signal) => render(job.payload, signal) });+ const first = await upload(original);+ const stack = StepStack.from(await master(original, first));+ const bases: string[] = [];+ const touched: [number, number, number, number][] = [];+ let seq = 0;+ let previewBase: { name: string; bytes: Buffer } | null = null;+ for (const [k, text] of EDITS.entries()) {+ const seed = 1000 + k;+ const baseName = method === "preview" && previewBase ? previewBase.name : stack.base(method === "preview" ? "hybrid" : method)!.name;+ const paste = method === "chain" ? ("off" as const) : ("auto" as const);+ // Two live frames while typing: small WebP, never a base.+ let lastLive: Buffer | null = null;+ for (const words of [text.split(" ").slice(0, -1).join(" ") || text, text]) {+ const o = await sched.submit({ seq: ++seq, slot: "live", key: renderKey({ base: baseName, text: words, seed, size: 512 }), payload: { prompt: words, seed, base: baseName, ...slotBindings("live", { liveSize: 512, keepRes: 1536, hasMask: false, to: "temp" }), paste } });+ expect(o.ok).toBe(true);+ if (o.ok) {+ lastLive = o.result;+ stack.sawLive((await inputName(o.result, "png")).sha256);+ stack.sawLive((await inputName(o.result, "webp")).sha256);+ }+ }+ if (method === "preview") {+ // The reference app kept the live frame it showed (a 512 PNG) as the next base.+ const png = await sharp(lastLive!).png().toBuffer();+ previewBase = { name: await upload(png), bytes: png };+ bases.push(previewBase.name);+ continue;+ }+ const o = await sched.submit({ seq: ++seq, slot: "keep", key: renderKey({ base: baseName, text, seed, size: 1536, quality: "keep" }), payload: { prompt: text, seed, base: baseName, ...slotBindings("keep", { liveSize: 512, keepRes: 1536, hasMask: false, to: "temp" }), paste } });+ expect(o.ok).toBe(true);+ if (!o.ok) throw new Error("keep failed");+ const name = await upload(o.result);+ 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 (r.touched) touched.push(r.touched);+ }+ const final = method === "preview" ? previewBase!.bytes : fake.inputs.get(stack.head!.master.name)!;+ return { stack, bases, touched, 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");+ 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);+ expect(prompts.length).toBe(30);+ for (const l of prompts) {+ const name = String(l.prompt!.prompt!["10"].inputs.image);+ const bytes = fake.inputs.get(name)!;+ expect(pngSize(bytes)).toEqual({ w: W, h: H });+ const { sha256 } = await inputName(bytes, "png");+ expect(stack.isLive(sha256)).toBe(false);+ }+ const a = await gray(original);+ const b = await gray(final);+ 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);+ }, 120_000);++ it("chain without the paste-back drifts (the reason for it)", async () => {+ const { touched, final } = await session("chain");+ expect(touched).toHaveLength(0);+ const score = ssim(await gray(original), await gray(final));+ console.log(`chain without paste-back: SSIM after 10 edits = ${score.toFixed(4)}`);+ expect(score).toBeLessThan(0.98);+ }, 120_000);++ it("negative control: kept 512 previews as the base wear the picture down", async () => {+ const { final } = await session("preview");+ const score = ssim(await gray(original), await gray(final, { w: W, h: H }));+ console.log(`512 preview as base: SSIM after 10 edits = ${score.toFixed(4)}`);+ expect(score).toBeLessThan(0.9);+ }, 120_000);+});diff --git a/tests/live-graph.test.ts b/tests/live-graph.test.tsnew file mode 100644index 00000000..eda0742e--- /dev/null+++ b/tests/live-graph.test.ts@@ -0,0 +1,105 @@+/**+ * Live edit's graph (src/lib/live/graph.ts): the canonical graph equals the library's hand-built file, the variants+ * wire up as they should, and the tab's check accepts every graph Fuobe builds and refuses anything else.+ */+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { buildLiveGraph, liveGraphProblem, sameGraph, slotBindings, LIVE_CLASSES, LIVE_FILES, LIVE_SIGMAS, type LiveGraphParams } from "@/lib/live/graph";+import { graphProblem } from "@/lib/local-comfy";++const NAME = (n: number) => `fuobe_lv${String(n).padStart(20, "A")}.png`;+const base: LiveGraphParams = { prompt: "add gold hoop earrings", seed: 42, res: 512, base: NAME(1), paste: "auto", outMaxSide: 512, format: "webp", to: "socket" };+const hand = JSON.parse(fs.readFileSync(path.join(process.cwd(), "scripts/comfy/hand-built/qwen-image-21-live-edit.json"), "utf8"));++describe("buildLiveGraph", () => {+ it("is the library's hand-built graph, its bound fields filled", () => {+ const filled = structuredClone(hand);+ const g = buildLiveGraph({ prompt: filled["30"].inputs.prompt, seed: filled["70"].inputs.noise_seed, res: filled["20"].inputs.resolution, base: filled["10"].inputs.image, refs: [filled["11"].inputs.image, filled["12"].inputs.image, filled["13"].inputs.image], mask: filled["14"].inputs.image, paste: filled["40"].inputs.mode, outMaxSide: filled["40"].inputs.out_max_side, format: filled["90"].inputs.format, quality: filled["90"].inputs.quality, to: filled["90"].inputs.to }).graph;+ expect(sameGraph(g, filled)).toBe(true);+ // The model, LoRA and schedule match the reference app's.+ expect(g["1"].inputs.unet_name).toBe(LIVE_FILES.unet);+ expect(g["4"].inputs).toMatchObject({ lora_name: LIVE_FILES.lora, strength_model: 1 });+ expect(g["73"].inputs.sigmas).toBe(LIVE_SIGMAS);+ expect(g["72"].inputs.sampler_name).toBe("euler");+ expect(g["71"].class_type).toBe("BasicGuider");+ });++ it("text to image leaves out the base nodes and takes the table's size", () => {+ const { graph, staged } = buildLiveGraph({ ...base, base: undefined, aspect: "16:9", res: 512 });+ for (const id of ["10", "11", "14", "15", "20", "40"]) expect(graph[id]).toBeUndefined();+ expect(graph["30"].inputs).toMatchObject({ width: 704, height: 384 });+ expect(graph["30"].inputs.reference).toBeUndefined();+ expect(graph["90"].inputs.images).toEqual(["34", 0]);+ expect(staged).toEqual([]);+ });++ it("wires references and a mask", () => {+ const { graph, staged } = buildLiveGraph({ ...base, refs: [NAME(2), NAME(3)], mask: NAME(4), paste: "mask" });+ expect(graph["20"].inputs.image_2).toEqual(["11", 0]);+ expect(graph["20"].inputs.image_3).toEqual(["12", 0]);+ expect(graph["13"]).toBeUndefined();+ expect(graph["15"].inputs.mask_image).toEqual(["14", 0]);+ expect(graph["40"].inputs).toMatchObject({ mask_image: ["14", 0], mode: "mask", box: ["15", 1] });+ expect(staged).toEqual([NAME(1), NAME(2), NAME(3), NAME(4)]);+ });++ it("live frames are small WebP; settle and keep are full-size PNG masters", () => {+ const o = { liveSize: 512, keepRes: 1536, hasMask: false, to: "socket" as const };+ expect(slotBindings("live", o)).toEqual({ res: 512, paste: "auto", outMaxSide: 512, format: "webp", to: "socket" });+ expect(slotBindings("keep", o)).toEqual({ res: 1536, paste: "auto", outMaxSide: 0, format: "png", to: "socket" });+ expect(slotBindings("settle", { ...o, hasMask: true })).toMatchObject({ paste: "mask", outMaxSide: 0, format: "png" });+ expect(slotBindings("warm", o)).toMatchObject({ res: 384, paste: "off", format: "webp" });+ });+});++describe("liveGraphProblem", () => {+ const staged = [NAME(1), NAME(2), NAME(3), NAME(4)];+ const variants: LiveGraphParams[] = [+ base,+ { ...base, refs: [NAME(2)], mask: NAME(4), paste: "mask" },+ { ...base, refs: [NAME(2), NAME(3), NAME(4)] },+ { ...base, res: 1536, outMaxSide: 0, format: "png" },+ { ...base, base: undefined, aspect: "3:4", res: 1024, format: "png" },+ { ...base, base: undefined, aspect: "1:1", res: 384, paste: "off" },+ { ...base, to: "temp" },+ ];+ it("accepts every graph Fuobe builds, and the relay's loader check accepts them too", () => {+ for (const v of variants) {+ const { graph } = buildLiveGraph(v);+ expect(liveGraphProblem(graph, staged)).toBeNull();+ expect(graphProblem(graph, staged)).toBeNull();+ }+ });++ const bad = (change: (g: Record<string, { class_type: string; inputs: Record<string, unknown> }>) => void, staging = staged) => {+ const { graph } = buildLiveGraph(base);+ change(graph as never);+ return liveGraphProblem(graph, staging);+ };+ it("refuses anything else", () => {+ expect(bad((g) => (g["99"] = { class_type: "VAEDecode", inputs: { samples: ["32", 0], vae: ["3", 0] } }))).toMatch(/isn't Fuobe/);+ expect(bad((g) => (g["99"] = { class_type: "LoadImage", inputs: { image: "secret.png" } }))).toMatch(/isn't a live/);+ expect(bad((g) => (g["1"].class_type = "CheckpointLoaderSimple"))).toMatch(/isn't a live/);+ expect(bad(() => {}, [NAME(2)])).toMatch(/base/);+ expect(bad((g) => (g["10"].inputs.image = "fuobe_other.png"), [...staged, "fuobe_other.png"])).toMatch(/base/);+ expect(bad((g) => (g["10"].inputs.image = "../secret.png"))).toMatch(/base/);+ expect(bad((g) => (g["30"].inputs.prompt = "x".repeat(2001)))).toMatch(/prompt/);+ expect(bad((g) => (g["20"].inputs.resolution = 4096))).toMatch(/resolution/);+ expect(bad((g) => (g["4"].inputs.lora_name = "other.safetensors"))).toMatch(/isn't Fuobe/);+ expect(bad((g) => (g["4"].inputs.strength_model = 2))).toMatch(/isn't Fuobe/);+ expect(bad((g) => (g["73"].inputs.sigmas = "1.0, 0.0"))).toMatch(/isn't Fuobe/);+ expect(bad((g) => (g["32"].inputs.latent_image = ["10", 0]))).toMatch(/isn't Fuobe/);+ expect(bad((g) => (g["70"].inputs.noise_seed = -1))).toMatch(/seed/);+ expect(bad((g) => (g["90"].inputs.to = "output"))).toMatch(/output/);+ expect(bad((g) => (g["40"].inputs.out_max_side = 333))).toMatch(/size/);+ const t2i = buildLiveGraph({ ...base, base: undefined, aspect: "1:1" }).graph;+ t2i["30"].inputs.width = 1000;+ expect(liveGraphProblem(t2i, staged)).toMatch(/size/);+ expect(liveGraphProblem(null, staged)).toBe("No graph");+ });++ it("every class is a live class", () => {+ for (const n of Object.values(buildLiveGraph({ ...base, refs: [NAME(2)], mask: NAME(4) }).graph)) expect(LIVE_CLASSES.has(n.class_type)).toBe(true);+ });+});diff --git a/tests/live-nodes.test.ts b/tests/live-nodes.test.tsnew file mode 100644index 00000000..1140e50a--- /dev/null+++ b/tests/live-nodes.test.ts@@ -0,0 +1,86 @@+/**+ * Live edit's ComfyUI plumbing: the node file Fuobe ships (src/lib/comfy-live-nodes.ts), the type-4 socket frame its+ * save node sends (as comfy-ws.ts reads it), and the tab's allow-lists for the browser-direct path (local-comfy.ts).+ */+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 { startFile } from "@/lib/comfy-install";+import { parseComfyBinary } from "@/lib/comfy-ws";+import { PACK_LIVE_CLASSES } from "@/lib/live/graph";+import { graphProblem, LocalComfyError, readPath, writePath } from "@/lib/local-comfy";++const ID = "11111111-2222-4333-8444-555555555555";+const OTHER = "99999999-2222-4333-8444-555555555555";++describe("fuobe_live.py", () => {+ it("is plain ASCII, versioned, and defines every live class", () => {+ expect(LIVE_NODES_FILE_NAME).toBe("fuobe_live.py");+ expect(() => liveNodesBase64()).not.toThrow();+ expect(atob(liveNodesBase64())).toBe(LIVE_NODES_SOURCE);+ expect(LIVE_NODES_SOURCE).toContain(`FUOBE_LIVE = ${LIVE_NODES_VERSION}`);+ for (const c of LIVE_NODE_CLASSES) {+ expect(LIVE_NODES_SOURCE).toContain(`class ${c}:`);+ expect(LIVE_NODES_SOURCE).toContain(`"${c}": ${c},`);+ expect(c).toMatch(/FuobeLive$/);+ }+ expect([...LIVE_NODE_CLASSES].sort()).toEqual([...PACK_LIVE_CLASSES].sort());+ // Neutral: no machine paths.+ expect(LIVE_NODES_SOURCE).not.toMatch(/[A-Z]:\\\\|\/home\/|Projects/);+ });+ it("loads only Fuobe-named pictures from the input folder's root", () => {+ expect(LIVE_NODES_SOURCE).toContain('NAME = re.compile(r"^fuobe_[A-Za-z0-9_-]{8,24}\\.(png|jpg|jpeg|webp)$")');+ expect(LIVE_NODES_SOURCE).toContain("os.path.commonpath([root, path]) != root");+ });+ it("the Windows start file writes them next to the guard", () => {+ const bat = startFile(8188, "https://studio.example");+ // In parts ('…'+'…'), so no run of letters reads as a download command.+ 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);+ expect(isLiveNodes(null)).toBe(false);+ });+});++describe("type-4 frames from the live save node", () => {+ it("reads the frame the node writes (fixture made by scripts/comfy/test_fuobe_live.py)", () => {+ const bytes = fs.readFileSync(path.join(process.cwd(), "tests/fixtures/live-type4.bin"));+ const p = parseComfyBinary(bytes);+ expect(p).toMatchObject({ type: "image/webp", promptId: ID, node: "90", width: 192, height: 256, live: true });+ expect(Buffer.from(p!.data.subarray(0, 4)).toString()).toBe("RIFF");+ });+ it("still refuses an unknown image type", () => {+ const meta = Buffer.from(JSON.stringify({ prompt_id: ID, image_type: "text/html" }));+ const len = Buffer.alloc(4);+ len.writeUInt32BE(meta.length);+ expect(parseComfyBinary(Buffer.concat([Buffer.from([0, 0, 0, 4]), len, meta, Buffer.from("x")]))).toBeNull();+ });+});++describe("the tab's allow-lists for live edit", () => {+ const own = { promptIds: [ID], names: ["fuobe_lvAAAAAAAAAAAAAAAAAAAA.png"] };+ it("may take its own prompts out of the history, and nothing else", () => {+ expect(writePath("/history", { delete: [ID] }, own)).toBe("/history");+ expect(() => writePath("/history", { delete: [OTHER] }, own)).toThrow(LocalComfyError);+ expect(() => writePath("/history", { delete: [ID, OTHER] }, own)).toThrow(LocalComfyError);+ expect(() => writePath("/history", { delete: [] }, own)).toThrow(LocalComfyError);+ expect(() => writePath("/history", { clear: true }, own)).toThrow(LocalComfyError);+ expect(() => writePath("/history", { delete: [ID], clear: true }, own)).toThrow(LocalComfyError);+ });+ it("reads the live nodes' version", () => {+ expect(readPath("/fuobe/live")).toBe("/fuobe/live");+ expect(() => readPath("/fuobe/live?x=1")).toThrow(LocalComfyError);+ });+ it("checks the live loader like any other", () => {+ expect(graphProblem({ "10": { class_type: "LoadImageFuobeLive", inputs: { image: "fuobe_lvAAAAAAAAAAAAAAAAAAAA.png" } } }, own.names)).toBeNull();+ expect(graphProblem({ "10": { class_type: "LoadImageFuobeLive", inputs: { image: "private.png" } } }, own.names)).toMatch(/didn't send/);+ });+ it("uploads only names it made", () => {+ expect(writePath("/upload/image", { name: own.names[0], type: "input", overwrite: "true" }, own)).toBe("/upload/image");+ expect(() => writePath("/upload/image", { name: "fuobe_lvBBBBBBBBBBBBBBBBBBBB.png", type: "input", overwrite: "true" }, own)).toThrow(LocalComfyError);+ });+});diff --git a/tests/live-scheduler.test.ts b/tests/live-scheduler.test.tsnew file mode 100644index 00000000..c0ce493c--- /dev/null+++ b/tests/live-scheduler.test.ts@@ -0,0 +1,173 @@+/**+ * Live edit's scheduler (src/lib/live/scheduler.ts), with a stand-in transport: the cases of the reference live+ * server's session (newest only per slot, keeps first and never cancelled by typing, urgent preempts an older running+ * live render, hurry), and settle and warm.+ */+import { describe, expect, it } from "vitest";+import { LiveScheduler, type LiveJob, type Outcome, type Slot } from "@/lib/live/scheduler";++interface Run {+ job: LiveJob<string>;+ signal: AbortSignal;+ finish: () => void;+ aborted: boolean;+}++function harness() {+ const runs: Run[] = [];+ const s = new LiveScheduler<string, string>({+ run: (job, signal) =>+ new Promise<string>((resolve, reject) => {+ const r: Run = { job, signal, finish: () => resolve(`pic:${job.payload}`), aborted: false };+ signal.addEventListener("abort", () => {+ r.aborted = true;+ // The transport learns ComfyUI stopped it a moment later.+ queueMicrotask(() => reject(new Error("interrupted")));+ });+ runs.push(r);+ }),+ });+ let seq = 0;+ const submit = (slot: Slot, text: string, urgent = false) => {+ const job = { seq: ++seq, slot, key: text, urgent, payload: text };+ return { job, p: s.submit(job) };+ };+ const tick = () => new Promise((r) => setTimeout(r, 0));+ return { s, runs, submit, tick };+}++const outcome = (o: Outcome<string>) => ("result" in o ? o.result : "dropped" in o ? `dropped:${o.dropped}` : `error:${o.error}`);++describe("live scheduler", () => {+ it("keeps only the newest live request waiting", async () => {+ const { runs, submit, tick } = harness();+ const a = submit("live", "a");+ const b = submit("live", "b");+ const c = submit("live", "c");+ expect(runs.map((r) => r.job.payload)).toEqual(["a"]);+ expect(outcome(await b.p)).toBe("dropped:replaced");+ runs[0].finish();+ expect(outcome(await a.p)).toBe("pic:a");+ await tick();+ expect(runs.map((r) => r.job.payload)).toEqual(["a", "c"]);+ runs[1].finish();+ expect(outcome(await c.p)).toBe("pic:c");+ });++ it("runs keeps first, in order, and typing never cancels them", async () => {+ const { runs, submit, tick } = harness();+ const live = submit("live", "a");+ const k1 = submit("keep", "k1");+ const k2 = submit("keep", "k2");+ submit("live", "b", true);+ submit("live", "c", true);+ // The running live render of other text was superseded by the urgent one.+ expect(outcome(await live.p)).toBe("dropped:superseded");+ await tick();+ expect(runs[1].job.payload).toBe("k1");+ // An urgent live request doesn't stop a keep.+ submit("live", "d", true);+ expect(runs[1].aborted).toBe(false);+ runs[1].finish();+ expect(outcome(await k1.p)).toBe("pic:k1");+ await tick();+ expect(runs[2].job.payload).toBe("k2");+ runs[2].finish();+ await k2.p;+ await tick();+ expect(runs[3].job.payload).toBe("d");+ });++ it("an urgent request doesn't stop a running render of the same text", async () => {+ const { runs, submit } = harness();+ submit("live", "same");+ submit("live", "same", true);+ expect(runs[0].aborted).toBe(false);+ });++ it("hurry stops the running render for a waiting one", async () => {+ const { s, runs, submit, tick } = harness();+ const a = submit("live", "a");+ const b = submit("live", "b");+ expect(runs[0].aborted).toBe(false);+ s.hurry(b.job.seq);+ expect(outcome(await a.p)).toBe("dropped:superseded");+ await tick();+ expect(runs[1].job.payload).toBe("b");+ // hurry of a seq that isn't waiting changes nothing.+ s.hurry(999);+ expect(runs[1].aborted).toBe(false);+ });++ it("any live request cancels the settle render, waiting or running", async () => {+ const { runs, submit, tick } = harness();+ const settle = submit("settle", "a");+ expect(runs[0].job.slot).toBe("settle");+ const live = submit("live", "b");+ expect(outcome(await settle.p)).toBe("dropped:superseded");+ await tick();+ expect(runs[1].job.payload).toBe("b");+ const s2 = submit("settle", "b");+ submit("live", "c");+ expect(outcome(await s2.p)).toBe("dropped:replaced");+ runs[1].finish();+ expect(outcome(await live.p)).toBe("pic:b");+ });++ it("warm runs only when nothing else waits", async () => {+ const { runs, submit, tick } = harness();+ submit("live", "a");+ submit("warm", "w");+ submit("settle", "s");+ runs[0].finish();+ await tick();+ await tick();+ expect(runs[1].job.slot).toBe("settle");+ runs[1].finish();+ await tick();+ await tick();+ expect(runs[2].job.slot).toBe("warm");+ });++ it("only one render of ours runs at a time", async () => {+ const { runs, submit, tick } = harness();+ for (let i = 0; i < 5; i++) submit(i % 2 ? "keep" : "live", `x${i}`);+ await tick();+ expect(runs.filter((r) => !r.aborted)).toHaveLength(1);+ });++ it("waits while paused (newest only) and drops a late, older request", async () => {+ const { s, runs, submit, tick } = harness();+ s.pause();+ const a = submit("live", "a");+ const b = submit("live", "b");+ expect(runs).toHaveLength(0);+ expect(outcome(await a.p)).toBe("dropped:replaced");+ s.resume();+ expect(runs.map((r) => r.job.payload)).toEqual(["b"]);+ // A request with an older seq than one already waiting in its slot is dropped.+ const c = submit("live", "c");+ const late = s.submit({ seq: c.job.seq - 1, slot: "live", key: "late", payload: "late" });+ expect(outcome(await late)).toBe("dropped:replaced");+ runs[0].finish();+ await b.p;+ await tick();+ });++ it("cancel and close drop what matches and stop what runs", async () => {+ const { s, runs, submit } = harness();+ const a = submit("live", "a");+ const k = submit("keep", "k");+ s.cancel((j) => j.slot === "live");+ expect(outcome(await a.p)).toBe("dropped:cancelled");+ expect(runs[0].aborted).toBe(true);+ s.close();+ expect(outcome(await k.p)).toBe("dropped:closed");+ expect(outcome(await s.submit({ seq: 99, slot: "live", key: "z", payload: "z" }))).toBe("dropped:closed");+ });++ 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");+ });+});diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex 1b742fc5..dfb7ec3f 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -10460,6 +10460,120 @@"validated": false,"notes": "The Qwen-Image 2.1 turbo image-edit workflow, as the site's fast preview edits run it: turbo int8 model, the fixed 8-step ManualSigmas schedule, KSamplerSelect euler, CFGGuider cfg 1, RandomNoise, SamplerCustomAdvanced on the encoder's latent; references as qwen-image-21-edit (2048 lanczos, resolution 0, up to 4, optional ones dropped). No steps binding: the sigmas are the schedule. Removed: the prompt enhancer branch (Qwen3.5 9B PE model, off in the workflow), the custom-size switch, compare and notes. In a blind test it matched 25 steps (21 vs 22 of 48 outfit edits) and was weaker only on hard camera turns and product rotations (use qwen-image-21-edit there)."},+ {+ "id": "qwen-image-21-live-edit",+ "title": "Qwen-Image 2.1 Live Edit (2-step DMD2 LoRA, as you type)",+ "capability": "edit",+ "file": "qwen-image-21-live-edit.json",+ "source": "hand-built (scripts/comfy/hand-built/qwen-image-21-live-edit.json)",+ "bindings": {+ "prompt": [+ {+ "node": "30",+ "input": "prompt"+ }+ ],+ "image": [+ {+ "node": "10",+ "input": "image"+ }+ ],+ "image2": [+ {+ "node": "11",+ "input": "image"+ }+ ],+ "image3": [+ {+ "node": "12",+ "input": "image"+ }+ ],+ "image4": [+ {+ "node": "13",+ "input": "image"+ }+ ],+ "mask": [+ {+ "node": "14",+ "input": "image"+ }+ ],+ "seed": [+ {+ "node": "70",+ "input": "noise_seed"+ }+ ],+ "width": [+ {+ "node": "30",+ "input": "width"+ }+ ],+ "height": [+ {+ "node": "30",+ "input": "height"+ }+ ]+ },+ "outputs": [+ {+ "node": "90",+ "kind": "image"+ }+ ],+ "defaults": {+ "width": 512,+ "height": 512+ },+ "limits": {+ "maxWidth": 2048,+ "maxHeight": 2048,+ "dimensionMultiple": 32+ },+ "models": [+ {+ "file": "qwen_image_2.1_int8_convrot.safetensors",+ "folder": "diffusion_models",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/diffusion_models/qwen_image_2.1_int8_convrot.safetensors",+ "sizeGb": 7.26+ },+ {+ "file": "qwen3vl_8b_int8_convrot.safetensors",+ "folder": "text_encoders",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors",+ "sizeGb": 9.35+ },+ {+ "file": "qwen_image_2.1_vae_bf16.safetensors",+ "folder": "vae",+ "url": "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors",+ "sizeGb": 0.68+ },+ {+ "file": "Qwen-Image-2.1-DMD2-2steps.safetensors",+ "folder": "loras",+ "url": "https://huggingface.co/linoyts/Qwen-Image-2.1-DMD2-2steps/resolve/5bae28369ecea3232405c17a53c04d35d15796b8/pytorch_lora_weights.safetensors",+ "sizeGb": 0.07+ }+ ],+ "customNodes": [+ {+ "name": "fuobe-live",+ "repo": "https://github.com/workingprototype/Fuobe"+ }+ ],+ "vramGb": 20,+ "license": "Qwen Research License Agreement (Qwen-Image 2.1 and the DMD2 2-step LoRA by linoyts, a derivative): NON-COMMERCIAL, research and evaluation only; Fuobe live nodes MIT",+ "validated": false,+ "notes": "Live editing as you type (Fuobe builds this graph in code; this file is its canonical form): the int8 Qwen-Image 2.1 model with the DMD2 2-step LoRA at 1, BasicGuider (CFG 1, positive only), euler, ManualSigmas \"1.0, 0.5, 0.0\" (the LoRA card's schedule, no shift), on Fuobe's live nodes (fuobe_live.py): a loader that skips the input-folder listing, the references resized and VAE-encoded in their own node (cached while only the text changes), a positive-only encode, a crop around a painted region, a paste-back of unchanged pixels with colour matching, and a save node that sends the picture over the socket. Live frames at 384-768, kept steps at 1024-2048 composited onto a full-size lossless master. References 2-4 and the mask are optional."+ },{"id": "qwen-image-21-inpaint","title": "Qwen-Image 2.1 Inpaint (crop around the mask, paste back)",diff --git a/workflows/comfyui/model-pins.json b/workflows/comfyui/model-pins.jsonindex 8ae1eea5..97d3d01f 100644--- a/workflows/comfyui/model-pins.json+++ b/workflows/comfyui/model-pins.json@@ -912,6 +912,11 @@"sizeBytes": 849608296,"sha256": "2a32ce938ec71db2b49a817b4844ae86995569518dea56ee0ddc209cbe8e1377"},+ "https://huggingface.co/linoyts/Qwen-Image-2.1-DMD2-2steps/resolve/5bae28369ecea3232405c17a53c04d35d15796b8/pytorch_lora_weights.safetensors": {+ "revision": "5bae28369ecea3232405c17a53c04d35d15796b8",+ "sizeBytes": 67144520,+ "sha256": "3a50c28d2f70170a06011e7b5d93a12418edbc4a0fc4de4acee8d9d227a38c21"+ },"https://huggingface.co/lovis93/next-scene-qwen-image-lora-2509/resolve/main/next-scene_lora-v2-3000.safetensors": {"revision": "9b9da698b8a5370efd875f18b1727cc1119f3863","sizeBytes": 295146176,diff --git a/workflows/comfyui/packs.json b/workflows/comfyui/packs.jsonindex 58ec05e8..e7518d34 100644--- a/workflows/comfyui/packs.json+++ b/workflows/comfyui/packs.json@@ -232,5 +232,15 @@"isolated": false,"subdir": null,"folders": []+ },+ "fuobe-live": {+ "bundled": "fuobe_live.py",+ "repo": "https://github.com/workingprototype/Fuobe",+ "commit": "",+ "registry": null,+ "requirementsTxt": false,+ "isolated": false,+ "subdir": null,+ "folders": []}}diff --git a/workflows/comfyui/qwen-image-21-live-edit.json b/workflows/comfyui/qwen-image-21-live-edit.jsonnew file mode 100644index 00000000..a8677278--- /dev/null+++ b/workflows/comfyui/qwen-image-21-live-edit.json@@ -0,0 +1,300 @@+{+ "1": {+ "inputs": {+ "unet_name": "qwen_image_2.1_int8_convrot.safetensors",+ "weight_dtype": "default"+ },+ "class_type": "UNETLoader",+ "_meta": {+ "title": "Load Diffusion Model (Qwen-Image 2.1 int8)"+ }+ },+ "2": {+ "inputs": {+ "clip_name": "qwen3vl_8b_int8_convrot.safetensors",+ "type": "qwen_image",+ "device": "default"+ },+ "class_type": "CLIPLoader",+ "_meta": {+ "title": "Load CLIP (Qwen3-VL 8B)"+ }+ },+ "3": {+ "inputs": {+ "vae_name": "qwen_image_2.1_vae_bf16.safetensors"+ },+ "class_type": "VAELoader",+ "_meta": {+ "title": "Load VAE"+ }+ },+ "4": {+ "inputs": {+ "model": [+ "1",+ 0+ ],+ "lora_name": "Qwen-Image-2.1-DMD2-2steps.safetensors",+ "strength_model": 1+ },+ "class_type": "LoraLoaderModelOnly",+ "_meta": {+ "title": "DMD2 2-step LoRA"+ }+ },+ "10": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Base picture (a kept master or the original)"+ }+ },+ "11": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Picture 2"+ }+ },+ "12": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Picture 3"+ }+ },+ "13": {+ "inputs": {+ "image": "fuobe_validate.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Picture 4"+ }+ },+ "14": {+ "inputs": {+ "image": "fuobe_validate_mask.png"+ },+ "class_type": "LoadImageFuobeLive",+ "_meta": {+ "title": "Painted region"+ }+ },+ "15": {+ "inputs": {+ "image": [+ "10",+ 0+ ],+ "context": 1.6,+ "multiple": 32,+ "mask_image": [+ "14",+ 0+ ]+ },+ "class_type": "CropFuobeLive",+ "_meta": {+ "title": "Crop around the region"+ }+ },+ "20": {+ "inputs": {+ "vae": [+ "3",+ 0+ ],+ "resolution": 512,+ "image_1": [+ "15",+ 0+ ],+ "image_2": [+ "11",+ 0+ ],+ "image_3": [+ "12",+ 0+ ],+ "image_4": [+ "13",+ 0+ ]+ },+ "class_type": "Qwen21ReferenceFuobeLive",+ "_meta": {+ "title": "References (cached while only the text changes)"+ }+ },+ "30": {+ "inputs": {+ "clip": [+ "2",+ 0+ ],+ "prompt": "",+ "width": 512,+ "height": 512,+ "reference": [+ "20",+ 0+ ]+ },+ "class_type": "Qwen21EncodeFuobeLive",+ "_meta": {+ "title": "Encode, positive only"+ }+ },+ "32": {+ "inputs": {+ "noise": [+ "70",+ 0+ ],+ "guider": [+ "71",+ 0+ ],+ "sampler": [+ "72",+ 0+ ],+ "sigmas": [+ "73",+ 0+ ],+ "latent_image": [+ "30",+ 1+ ]+ },+ "class_type": "SamplerCustomAdvanced",+ "_meta": {+ "title": "Sample (2 steps)"+ }+ },+ "33": {+ "inputs": {+ "samples": [+ "32",+ 0+ ],+ "vae": [+ "3",+ 0+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "VAE Decode"+ }+ },+ "34": {+ "inputs": {+ "image": [+ "33",+ 0+ ]+ },+ "class_type": "SplitImageWithAlpha",+ "_meta": {+ "title": "Split Image with Alpha"+ }+ },+ "40": {+ "inputs": {+ "base": [+ "10",+ 0+ ],+ "edited": [+ "34",+ 0+ ],+ "box": [+ "15",+ 1+ ],+ "mask_image": [+ "14",+ 0+ ],+ "mode": "auto",+ "threshold": 0.06,+ "feather": 24,+ "match_color": true,+ "out_max_side": 512+ },+ "class_type": "PasteBackFuobeLive",+ "_meta": {+ "title": "Paste back unchanged pixels"+ }+ },+ "70": {+ "inputs": {+ "noise_seed": 0+ },+ "class_type": "RandomNoise",+ "_meta": {+ "title": "Noise"+ }+ },+ "71": {+ "inputs": {+ "model": [+ "4",+ 0+ ],+ "conditioning": [+ "30",+ 0+ ]+ },+ "class_type": "BasicGuider",+ "_meta": {+ "title": "Guider (CFG 1)"+ }+ },+ "72": {+ "inputs": {+ "sampler_name": "euler"+ },+ "class_type": "KSamplerSelect",+ "_meta": {+ "title": "Euler"+ }+ },+ "73": {+ "inputs": {+ "sigmas": "1.0, 0.5, 0.0"+ },+ "class_type": "ManualSigmas",+ "_meta": {+ "title": "Sigmas 1.0, 0.5, 0.0"+ }+ },+ "90": {+ "inputs": {+ "images": [+ "40",+ 0+ ],+ "format": "webp",+ "quality": 85,+ "to": "socket"+ },+ "class_type": "SaveImageFuobeLive",+ "_meta": {+ "title": "Send picture"+ }+ }+}diff --git a/workflows/comfyui/requirements.json b/workflows/comfyui/requirements.jsonindex be875def..6773ec25 100644--- a/workflows/comfyui/requirements.json+++ b/workflows/comfyui/requirements.json@@ -1,9 +1,9 @@{"v": 1,- "hash": "005e4f6ceb29cc90b565a3da20550620076f6a92e7cb2198530b7829d35e88d1",+ "hash": "69b24eb1d7e2efeda4718931967b4fa66c79daf55af85843ca4125d2d4e4c70f","comfyui": {"min":"0.42.0","testedCommit":"5841c187"},"folders": ["audio_encoders","background_removal","checkpoints","clip_vision","dbs","diffusion_models","facerestore_models","foley","frame_interpolation","geometry_estimation","insightface","latent_upscale_models","loras","mmaudio","model_patches","optical_flow","reuse","text_encoders","thinksound","upscale_models","vae"],- "sentinels": ["AILab_Qwen3ASRSubtitle","AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint","Add Subtitles To Frames","Apply Whisper","CFGOverride","ClothesSegment","ComfyMathExpression","DBSLoader","DBSSeparate","DownloadAndLoadWav2VecModel","DualModelGuider","FL_ChatterboxDialogTTS","FL_ChatterboxMultilingualTTS","FL_ChatterboxVC","GetImageRangeFromBatch","GetImageSizeAndCount","GrowMaskWithBlur","H3AdaLNLoRAFix","H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan","H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan","H3SLAAttention","HunyuanDependenciesLoader","HunyuanFoleySampler","HunyuanModelLoader","INTConstant","Ideogram4Scheduler","ImageBatchExtendWithOverlap","ImageGridtoBatch","ImageResizeKJv2","IndexTTS2Simple","Krea2EditGroundedEncode","Krea2EditModelPatch","Krea2OstrisEditModelPatch","LTXAVTextEncoderLoader","LTXVAddGuide","LTXVAudioVAEDecode","LTXVAudioVAELoader","LTXVConcatAVLatent","LTXVConditioning","LTXVCropGuides","LTXVDualCFGGuider","LTXVEmptyLatentAudio","LTXVImgToVideoInplace","LTXVLatentUpsampler","LTXVPreprocess","LTXVScheduler","LTXVSeparateAVLatent","LatentSyncNode","LoadBackgroundRemovalModel","LoadVideoDepthAnythingModel","MMAudioFeatureUtilsLoader","MMAudioModelLoader","MMAudioSampler","MelBandRoFormerModelLoader","MelBandRoFormerSampler","MiniMaxH3TurboLoRA","MiniMaxH3TurboSampler","MultiTalkModelLoader","MultiTalkWav2VecEmbeds","QwenImage21Cache","REUSEEnhance","REUSELoader","RIFE VFI","RMBG","ReActorFaceSwap","RemoveBackground","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SeedVR2Conditioning","SeedVR2PostProcessing","SeedVR2Preprocess","TS_ImageToSVGStringColor_Vtracer","TS_SVGStringToSVGBytesIO","TextEncodeFibo2","TextEncodeKrea2OstrisEdit","TextEncodeQwenImage21","ThinkSoundFeatureUtilsLoader","ThinkSoundModelLoader","ThinkSoundSampler","Trellis2Conditioning","Trellis2ShapeStage","Trellis2TextureStage","Trellis2UpsampleStage","VHS_BatchManager","VHS_LoadAudioUpload","VHS_LoadVideo","VHS_SelectEveryNthImage","VHS_VideoCombine","VHS_VideoInfo","VHS_VideoInfoLoaded","VideoDepthAnythingOutput","VideoDepthAnythingProcess","VideoLengthAdjuster","WanVideoBlockSwap","WanVideoClipVisionEncode","WanVideoDecode","WanVideoEncode","WanVideoImageToVideoMultiTalk","WanVideoLoraSelect","WanVideoModelLoader","WanVideoPassImagesFromSamples","WanVideoSampler","WanVideoTextEncodeCached","WanVideoVAELoader"],+ "sentinels": ["AILab_Qwen3ASRSubtitle","AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint","Add Subtitles To Frames","Apply Whisper","CFGOverride","ClothesSegment","ComfyMathExpression","CropFuobeLive","DBSLoader","DBSSeparate","DownloadAndLoadWav2VecModel","DualModelGuider","FL_ChatterboxDialogTTS","FL_ChatterboxMultilingualTTS","FL_ChatterboxVC","GetImageRangeFromBatch","GetImageSizeAndCount","GrowMaskWithBlur","H3AdaLNLoRAFix","H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan","H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan","H3SLAAttention","HunyuanDependenciesLoader","HunyuanFoleySampler","HunyuanModelLoader","INTConstant","Ideogram4Scheduler","ImageBatchExtendWithOverlap","ImageGridtoBatch","ImageResizeKJv2","IndexTTS2Simple","Krea2EditGroundedEncode","Krea2EditModelPatch","Krea2OstrisEditModelPatch","LTXAVTextEncoderLoader","LTXVAddGuide","LTXVAudioVAEDecode","LTXVAudioVAELoader","LTXVConcatAVLatent","LTXVConditioning","LTXVCropGuides","LTXVDualCFGGuider","LTXVEmptyLatentAudio","LTXVImgToVideoInplace","LTXVLatentUpsampler","LTXVPreprocess","LTXVScheduler","LTXVSeparateAVLatent","LatentSyncNode","LoadBackgroundRemovalModel","LoadImageFuobeLive","LoadVideoDepthAnythingModel","MMAudioFeatureUtilsLoader","MMAudioModelLoader","MMAudioSampler","MelBandRoFormerModelLoader","MelBandRoFormerSampler","MiniMaxH3TurboLoRA","MiniMaxH3TurboSampler","MultiTalkModelLoader","MultiTalkWav2VecEmbeds","PasteBackFuobeLive","Qwen21EncodeFuobeLive","Qwen21ReferenceFuobeLive","QwenImage21Cache","REUSEEnhance","REUSELoader","RIFE VFI","RMBG","ReActorFaceSwap","RemoveBackground","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SaveImageFuobeLive","SeedVR2Conditioning","SeedVR2PostProcessing","SeedVR2Preprocess","TS_ImageToSVGStringColor_Vtracer","TS_SVGStringToSVGBytesIO","TextEncodeFibo2","TextEncodeKrea2OstrisEdit","TextEncodeQwenImage21","ThinkSoundFeatureUtilsLoader","ThinkSoundModelLoader","ThinkSoundSampler","Trellis2Conditioning","Trellis2ShapeStage","Trellis2TextureStage","Trellis2UpsampleStage","VHS_BatchManager","VHS_LoadAudioUpload","VHS_LoadVideo","VHS_SelectEveryNthImage","VHS_VideoCombine","VHS_VideoInfo","VHS_VideoInfoLoaded","VideoDepthAnythingOutput","VideoDepthAnythingProcess","VideoLengthAdjuster","WanVideoBlockSwap","WanVideoClipVisionEncode","WanVideoDecode","WanVideoEncode","WanVideoImageToVideoMultiTalk","WanVideoLoraSelect","WanVideoModelLoader","WanVideoPassImagesFromSamples","WanVideoSampler","WanVideoTextEncodeCached","WanVideoVAELoader"],"packs": {"ComfyUI-DBS": {"repo":"https://github.com/hiroki-abe-58/ComfyUI-DBS","commit":"f656e53434b5485c148a2866fbd6ddc6b6152ed6","registry":{"id":"dbs-soundtrack-separation","version":""},"classes":["DBSLoader","DBSSeparate"],"folders":["dbs"],"isolated":false,"requirementsTxt":true,"install":"manual"},"ComfyUI-Frame-Interpolation": {"repo":"https://github.com/Fannovel16/ComfyUI-Frame-Interpolation","commit":"26545cc2dd95bc3d27f056016300673bdeee78f5","registry":{"id":"comfyui-frame-interpolation","version":""},"classes":["RIFE VFI"],"folders":[],"isolated":false,"requirementsTxt":false,"install":"manual"},@@ -28,6 +28,7 @@"ComfyUI_Fill-ChatterBox": {"repo":"https://github.com/filliptm/ComfyUI_Fill-ChatterBox","commit":"f7d7a16187430abcaf91a3039b9c83aa9960816a","registry":{"id":"comfyui_fill-chatterbox","version":""},"classes":["FL_ChatterboxDialogTTS","FL_ChatterboxMultilingualTTS","FL_ChatterboxVC"],"folders":[],"isolated":false,"requirementsTxt":true,"install":"manual"},"ausboss-nodes": {"repo":"https://github.com/ausboss/ComfyUI-AusBoss","commit":"bce780f2598f47c239cbf6503ea0984f96229391","registry":{"id":"ausboss-nodes","version":""},"classes":["AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint"],"folders":[],"isolated":false,"requirementsTxt":false,"install":"manual"},"comfyui-krea2edit": {"repo":"https://github.com/lbouaraba/comfyui-krea2edit","commit":"13ef60f20828949becada815d3cbc371eb5ccaab","registry":{"id":"comfyui-krea2edit","version":""},"classes":["Krea2EditGroundedEncode","Krea2EditModelPatch"],"folders":[],"isolated":false,"requirementsTxt":false,"install":"manual"},+ "fuobe-live": {"repo":"https://github.com/workingprototype/Fuobe","commit":"","bundled":"fuobe_live.py","classes":["CropFuobeLive","LoadImageFuobeLive","PasteBackFuobeLive","Qwen21EncodeFuobeLive","Qwen21ReferenceFuobeLive","SaveImageFuobeLive"],"folders":[],"isolated":false,"requirementsTxt":false,"install":"manual"},"h3-relay": {"repo":"https://github.com/akatz-ai/h3-relay","commit":"e2a7665b6eb8ea37a88c0de2c9c6b69a8f7c9220","registry":{"id":"h3-relay","version":""},"classes":["H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan"],"folders":[],"isolated":false,"requirementsTxt":false,"install":"manual"},"h3_character_swap": {"repo":"https://github.com/akatz-labs/h3-character-swap-tool","commit":"0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b","classes":["H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan"],"folders":[],"isolated":false,"subdir":"worker_nodes/h3_character_swap","requirementsTxt":true,"install":"manual"},"plaguekind-nodes": {"repo":"https://github.com/PlagueKind/ComfyUI-PlagueKind-Nodes","commit":"d58d006a4ea32c25c06499f2ff104f0852a045a6","registry":{"id":"plaguekind-nodes","version":""},"classes":["H3AdaLNLoRAFix","H3SLAAttention"],"folders":[],"isolated":false,"requirementsTxt":false,"install":"manual"}@@ -127,6 +128,7 @@"loras/Flux_2-Turbo-LoRA_comfyui.safetensors": {"folder":"loras","file":"Flux_2-Turbo-LoRA_comfyui.safetensors","url":"https://huggingface.co/ByteZSzn/Flux.2-Turbo-ComfyUI/resolve/main/Flux_2-Turbo-LoRA_comfyui.safetensors","pinnedUrl":"https://huggingface.co/ByteZSzn/Flux.2-Turbo-ComfyUI/resolve/57231752b9c5632e42911c73ee0ed138d381a6d4/Flux_2-Turbo-LoRA_comfyui.safetensors","sizeBytes":2760814880,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},"loras/H3-Person-Remover-V1.safetensors": {"folder":"loras","file":"H3-Person-Remover-V1.safetensors","url":"https://huggingface.co/akatz-ai/MiniMax-H3-Person-Remover-LoRA/resolve/fe136b3dc93aea993b9f194d48ea9859fdc2de14/H3-Person-Remover-V1.safetensors","pinnedUrl":"https://huggingface.co/akatz-ai/MiniMax-H3-Person-Remover-LoRA/resolve/fe136b3dc93aea993b9f194d48ea9859fdc2de14/H3-Person-Remover-V1.safetensors","sizeBytes":155110584,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},"loras/Krea2-realism-V2.safetensors": {"folder":"loras","file":"Krea2-realism-V2.safetensors","url":"https://huggingface.co/RudySen/Krea2-realism-V2/resolve/main/Krea2-realism-V2.safetensors","pinnedUrl":"https://huggingface.co/RudySen/Krea2-realism-V2/resolve/ad6f07e426303e7087d215362dbc057b0073dca3/Krea2-realism-V2.safetensors","sizeBytes":1562410344,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},+ "loras/Qwen-Image-2.1-DMD2-2steps.safetensors": {"folder":"loras","file":"Qwen-Image-2.1-DMD2-2steps.safetensors","url":"https://huggingface.co/linoyts/Qwen-Image-2.1-DMD2-2steps/resolve/5bae28369ecea3232405c17a53c04d35d15796b8/pytorch_lora_weights.safetensors","pinnedUrl":"https://huggingface.co/linoyts/Qwen-Image-2.1-DMD2-2steps/resolve/5bae28369ecea3232405c17a53c04d35d15796b8/pytorch_lora_weights.safetensors","sizeBytes":67144520,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},"loras/Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors": {"folder":"loras","file":"Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors","url":"https://huggingface.co/lightx2v/Qwen-Image-2512-Lightning/resolve/main/Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors","pinnedUrl":"https://huggingface.co/lightx2v/Qwen-Image-2512-Lightning/resolve/4609161e308ce82018a42c2a0c9b107e865bb751/Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors","sizeBytes":1698951104,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},"loras/Qwen-Image-Edit-2509-Light-Migration.safetensors": {"folder":"loras","file":"Qwen-Image-Edit-2509-Light-Migration.safetensors","url":"https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI/resolve/main/split_files/loras/Qwen-Image-Edit-2509-Light-Migration.safetensors","pinnedUrl":"https://huggingface.co/Comfy-Org/Qwen-Image-Edit_ComfyUI/resolve/f68ace85e60b4a02a323e394253731947657b7d2/split_files/loras/Qwen-Image-Edit-2509-Light-Migration.safetensors","sizeBytes":236117032,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},"loras/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors": {"folder":"loras","file":"Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors","url":"https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/main/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors","pinnedUrl":"https://huggingface.co/lightx2v/Qwen-Image-Lightning/resolve/d468c534b360e0754c6bf9e38ed49e1e09cd2e2a/Qwen-Image-Edit-2509/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors","sizeBytes":849608296,"gated":false,"presence":"loader","loaders":[["LoraLoaderModelOnly","lora_name"]]},@@ -298,6 +300,7 @@"product-shot-qwen-edit-2509": {"core":["CFGNorm","CLIPLoader","EmptyImage","FluxKontextImageScale","GetImageSize","ImageCompositeMasked","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","LoraLoaderModelOnly","ModelSamplingAuraFlow","PrimitiveFloat","PrimitiveInt","RemoveBackground","SaveImageAdvanced","StringConcatenate","TextEncodeQwenImageEditPlus","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{},"files":["background_removal/birefnet.safetensors","diffusion_models/qwen_image_edit_2509_fp8_e4m3fn.safetensors","loras/Qwen-Image-Edit-2509-Lightning-4steps-V1.0-bf16.safetensors","loras/Qwen-Image-Edit-2509-White_to_Scene.safetensors","text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},"qwen-image-21-edit": {"core":["CLIPLoader","ImageScaleToMaxDimension","KSampler","LoadImage","QwenImage21Cache","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-inpaint": {"core":["CLIPLoader","GrowMask","KSampler","LoadImage","LoadImageMask","QwenImage21Cache","SaveImage","SetLatentNoiseMask","SplitImageWithAlpha","StringFormat","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{"ausboss-nodes":["AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_StitchInpaint"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},+ "qwen-image-21-live-edit": {"core":["BasicGuider","CLIPLoader","KSamplerSelect","LoraLoaderModelOnly","ManualSigmas","RandomNoise","SamplerCustomAdvanced","SplitImageWithAlpha","UNETLoader","VAEDecode","VAELoader"],"packs":{"fuobe-live":["CropFuobeLive","LoadImageFuobeLive","PasteBackFuobeLive","Qwen21EncodeFuobeLive","Qwen21ReferenceFuobeLive","SaveImageFuobeLive"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/Qwen-Image-2.1-DMD2-2steps.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-outpaint": {"core":["CLIPLoader","GetImageSize","ImageCompositeMasked","ImageScale","InvertMask","KSampler","LoraLoaderModelOnly","QwenImage21Cache","RegexReplace","SaveImage","SplitImageWithAlpha","StringConcatenate","TextEncodeQwenImage21","TextGenerate","UNETLoader","VAEDecode","VAELoader"],"packs":{"ausboss-nodes":["AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_StitchInpaint"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","loras/qwen-image-2.1-outpaint-v2.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-t2i": {"core":["CLIPLoader","EmptyLatentImage","KSampler","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},"qwen-image-21-turbo-edit": {"core":["CFGGuider","CLIPLoader","ImageScaleToMaxDimension","KSamplerSelect","LoadImage","ManualSigmas","QwenImage21Cache","RandomNoise","SamplerCustomAdvanced","SaveImage","SplitImageWithAlpha","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/qwen_image_2.1_turbo_int8_convrot.safetensors","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},