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
Merge main's newer work (runs on your own GPU or key: waits that survive a restart or a deploy, Run with your key, smaller copies)
Adarshad1898f8ec51
diff --cc docs/gpu-workers.mdindex ad717a3f,e16fc0c1..e434c587--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@@ -500,224 -193,15 +500,227 @@@ a workflow or a node pack that workers1. Every node type is on the allowlist that is built into the worker (`bin/lib/worker/dist/allowed-nodes.json`, madeby `scripts/build-worker.mjs` from the catalog's workflows and the graph builders). For your own workflows, passa file with `allowNodesFile` in `worker.json`. The studio can never send a file like that.-2. Every file that the graph reads was sent with the job.-3. No string input names a path (an absolute path, a drive letter, a network share or a `..` step).-4. Every model file that the graph names is one that the worker verified.--After each job, the worker deletes the job's inputs and results from its folders and deletes the prompt from its-ComfyUI's history. At start, it empties its folders.--Pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). Clips and sound go to workers-only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default; `image,video,audio` for all).+2. Every file that the graph reads was sent with the job, under the name the studio gave it.+3. Every input keeps to its rule (`bin/lib/worker/dist/input-rules.json`). The build gives a rule to each input that+ could name a file, a folder, a download or code, from the values in the catalog's own workflows:+ - a fixed value, or one of a list (a subtitle node writes no file; a timeline node reads no clip by path; a format+ string, a download name and a save folder stay the catalog's);+ - a number range;+ - a file that this job sent;+ - a save name that the studio makes (plain name parts, no path);+ - a model file that the worker verified, in the model folder that its loader reads.++ No link from another node may reach an input that has a rule, so a value cannot be built from pieces. A node that+ has such an input takes only the inputs that the catalog gives it.+4. Inputs with no rule that do not take free text hold no path. A name is refused if it has a `:`, `%`, `~` or `..`.+ Any value is refused if it starts with `/`, `\`, `~` or a drive (`C:`), or if it holds an address (`://`), an+ encoded or variable part (`%2e`, `%TEMP%`), a `..` step or a Windows device name (`CON`, `NUL`, `COM1`…).+ Prompts, lyrics and captions keep any text. Other text (a size, a colour, settings written as text or as JSON) is+ read only for the shape of a path, in each key and string of its JSON too. A drive path, a share, a rooted or home+ path, a `..` step, an address or a variable is refused. `16:9` and `Scene 2: 50% faster` stay as they are.+5. Every model file that the graph names is one that the worker verified, by its exact name, whatever the name ends+ with. A file with the same name in another folder does not count. A model input takes no other value, except the+ catalog's own values for that input that name no file.++The worker reports a model file only when its SHA-256 matches the hash that the catalog pins for it+(`bin/lib/worker/dist/file-pins.json`, from `requirements.json` and `model-pins.json`). A file that has no pinned hash+is not reported, so no job that needs it comes to the worker. The worker keeps the hashes it computed, so a restart+does not read the files again. The catalog's files that still have no pin are listed in `UNPINNED_FILES`+(`scripts/lib/worker-catalog.mjs`), the one list of them. A test fails when a catalog file has no pin and is not on+that list, and when a file on the list gets a pin, so the list only gets shorter.++The worker checks the copy that its ComfyUI loads:++- Its ComfyUI looks in the worker's model folders first, in the order that `worker.json` gives (`is_default` in the+ worker's `extra_model_paths.yaml`), and takes the first folder that has the file. So the worker checks only that+ first copy. If that copy has the wrong size or hash, the file is not reported, even when a later folder has a good+ copy.+- Some node packs read ComfyUI's own `models` folder directly. And an older ComfyUI that does not know `is_default`+ looks in its own folders first. So a copy with the same name in ComfyUI's own `models` folder (`unet` and `clip`+ count for `diffusion_models` and `text_encoders`), or in a folder that ComfyUI's own `extra_model_paths.yaml` adds,+ must be the same file too. If it is not, the file is not reported.++After each job, however it ended, nothing of it stays in its ComfyUI: the worker empties the queue, stops a prompt that+still runs, and clears the whole history (a meta-batch's passes too). It also deletes the job's inputs and results from+its folders, and its copies of the inputs. At start, and whenever it stops, it empties these folders too. Before it+starts a job that its ComfyUI did not have last, it clears its ComfyUI the same way.++The owner's pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). An account's+pictures go to the worker without being decoded, and the worker makes each one again from its pixels before its+ComfyUI or a finishing job reads it (see "Pictures of an account's run"). Before they leave, the studio sends only the+picture itself: it blanks what a picture carries besides its pixels, in place (EXIF and GPS, XMP, comments,+thumbnails, a JPEG's other application segments before and between its scans, every PNG chunk but its pixels' and+colours', a WebP's EXIF and XMP), and cuts off anything after the picture's end (a second picture, a phone's+motion-photo clip and its sound). A JPEG keeps only its orientation. A kind of picture that the studio can't clean+that way (a GIF, an SVG, an animated WebP, say) is made again from its pixels on the studio instead. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default;+`image,video,audio` for all); an account's run with a kind it doesn't allow is refused before it is queued. The worker+then makes each one again before its ComfyUI reads it (see "Clips and sound"). Every VideoHelperSuite save node of a+graph for the workers is sent with `save_metadata` off, so no prompt rides inside a result. An account's run is shaped+by the worker that takes it (see "Job tickets and the PC's ceiling"), never by the account's own computer.++### Clips and sound++Set `ffmpeg` in `worker.json` to the path of ffmpeg (setup asks for it). The worker then makes every clip and every+sound that a job sends again, into a fresh file, before its ComfyUI sees it:++- a clip keeps its first picture stream and its first sound stream, encoded again in the format that its name says+ (H.264 and AAC in MP4 for most names, VP9 and Opus for WebM);+- a sound keeps its first sound stream, in the format that its name says (WAV for any other name);+- nothing else of the file is kept: no metadata, chapters, subtitles, attachments or data streams.++The worker knows a clip or a sound by its type, by its name, or by the loader that reads it in the graph. ffmpeg runs+in its own process, at low priority, for at most 20 minutes. It reads the file only as a local file+(`-protocol_whitelist file`), and only as one of these container formats (`-format_whitelist`): MP4 and MOV (with M4A+and 3GP), Matroska and WebM, AVI, GIF, MPEG-TS, MPEG-PS, FLV, ASF, WAV, MP3, FLAC, Ogg, AAC and AIFF. A playlist, a+list or any other format that would make ffmpeg open other files or addresses is refused.++What ffmpeg writes has limits too: at most one hour, at most 4096 pixels on the long side (a bigger picture is made+smaller, in the same shape), and at most 8 times the input's size (at least 256 MB, at most 2 GB). A result that+reaches the size cap is refused before the worker reads it. If ffmpeg cannot read a file, or its result is too big,+the job fails with plain words ("A clip or sound in this run couldn't be read.").++Without `ffmpeg`, the worker takes pictures only. Its inventory says so (`media: ["image"]`), and the studio sends it no+workflow that reads a clip or a sound. If such a job comes anyway, the worker gives it back to the line.++### Pictures of an account's run++A worker (protocol 3) makes every picture of an account's job ticket, and of a finishing job, again from its pixels+before anything on the PC reads it. A short-lived process at low priority reads the picture as it came (with sharp, at+most 64 megapixels, for at most 2 minutes), turns it upright by its EXIF orientation and writes a fresh PNG. Nothing+else of the file stays: no EXIF, no GPS, no XMP, no comment. If the picture can't be read, the job fails with plain+words. The studio sizes the picture as it shows (turned by its orientation), so a clip in the picture's own shape keeps+that shape.++The worker needs sharp for this, which `pnpm install` puts in its checkout. Without it, the worker logs so and says+protocol 2 in its beat, so the studio sends it only the owner's own jobs. Only a worker of protocol 3 or newer takes an+account's job ticket or a finishing job. While accounts' runs may come to the install's GPUs, an older one reads **Update the worker**.++### The CPU slot++Set `"cpuSlot": true` in `worker.json` (setup asks) and the worker runs one CPU task at a time beside its GPU's job:++- **Light CPU work.** Catalog workflows that the requirements index marks `cpu` (no model file, no graphics memory, no+ particular card): joins, trims, adding sound, loops, Ken Burns moves and filters. They run on a second ComfyUI of the+ worker's own, started with `--cpu` and with no GPU visible to it. It has its own folders, port and key, behind the+ same guard and the same checks as the GPU's ComfyUI. `cpuComfyCommand` in `worker.json` starts it another way, as+ `comfyCommand` does for the GPU's.+- **Finishing jobs.** The CPU work that follows an account's run on the install's GPUs runs here, never on the studio's+ server. The worker runs them with its own code, in a process of its own at low priority, in an emptied folder that it+ deletes after the job, with a short environment (never its token):+ - `model3d`, the finish of an image-to-3D model. The worker first checks that the GLB is self-contained: every buffer+ and picture is inside the file. A GLB that names any other file is refused and never read further, and the run+ keeps its model as it is. Then it writes the web GLB and renders the turntable and its poster on the CPU. With no+ browser or ffmpeg for the turntable, the model comes back without one. This needs `pnpm install` in its checkout.+ - `path`, a camera path drawn through a still and its depth picture (the guide of a camera move), encoded by ffmpeg.+ This needs ffmpeg.++ A finishing job comes as a finish ticket (`src/lib/finish-ticket.ts`): its kind, typed settings, and its input+ files by slot, name and SHA-256. The worker checks it the same way the studio does, and sends back only the files its+ kind makes (`web`, `turntable` and `poster`; or `path`). The studio stores them, and checks the web GLB is+ self-contained again before it keeps it. The owner's own runs, and runs on an account's own GPU or keys, keep the+ studio's own finish, as before.++On the studio, a worker holds at most one GPU job and one CPU task. Each slot claims for itself (`slot: "cpu"` in the+claim), so a CPU task never waits for the GPU's job, nor holds it up. The line counts each slot apart: a CPU task never+stands ahead of a GPU job on a worker with a CPU slot, and the place and the wait say so. A worker with no CPU slot takes+light CPU work in its GPU's slot, as before, and no finishing job. A finishing job goes only to a CPU slot that runs its+kind, in the run's class and at the run's place in line. Light CPU work has its lane's run limits in either slot. A+finishing job's run limit is its lane's run ceiling, which the owner sets in the queue settings. Another program on the+GPU stops only the GPU's job; a pause now by hand stops both. A 3D run of an account on the install's GPUs is taken+only while a worker heard from in the last few minutes, built for this studio's catalog, has a CPU slot that runs the+3D finish, and only for a model whose GLB gets that finish (an image-to-3D model, or Hi3D's refine of one). Then the+billing policy's `kinds.model3d` says, as for any other kind.++A finishing job is queued once for its run (and step), even when two app processes ask at the same time, and its+results are stored once. It waits for a CPU slot as long as its run may wait in line. If no CPU slot takes it by then,+a 3D model keeps its raw GLB and a camera path's step ends with one plain sentence. While it waits, the run's place in+line is the finishing job's. A camera path for a run on the workers is always queued for a CPU slot, even while no+worker with one is about, and is never drawn on the studio's server. (A run on the install's own ComfyUI, on the+studio's machine, has its path drawn there, as the install's own runs do.)++A chain's later step (sent once the steps before it are done) keeps its run's class and place in line: the place of+the first job a step of the same run had on the workers, or else the time the run was made. Once a worker took any of+the run's jobs, the step has no wait limit, since the wait limit applies only before the run's first start. Only steps+of the same press of Run count (the same billing hold; with none, the same batch). A result kept from an earlier run+gives a new step neither that run's place nor its start. When two app processes run on one database (a deploy's- overlap), only the one that takes a step's turn sends it, so each step is sent once. When the run is canceled or deleted, its finishing jobs end too: one in line at once,++overlap), only the one that takes a step's turn sends it, so each step is sent once. A step is marked just before its++job is made; when the process that was sending it stopped part way, the next one looks for the step's job: none++made, and the step is sent now (in its run's place); one made, and the step ends in the one plain sentence and that++job stops, so it is never run twice. When the run is canceled or deleted, its finishing jobs end too: one in line at once,+with its files, and one that a CPU slot runs at its next progress report (the worker sends one at least every 10+seconds). A 3D model finished this way waits for the output check when the run asked for one, as any run's outputs do.+The time a CPU task runs is never counted as GPU time.++Each slot claims on its own count (60 claims a minute each). After a claim that found nothing, a slot asks again 3+seconds later, or 1.5 seconds later while the beat says that a person's job waits for it.++### Live previews++When a job's run shows live previews (never one whose results are checked before anyone sees them), the claim says+`reportPreview: true`. The worker then sends its ComfyUI's latest preview with its progress: a JPEG of at most 64 KB,+at most one every 2 seconds. A JPEG preview of 64 KB or less goes as it is. A PNG preview, or a larger JPEG, is made+again with ffmpeg first: at most 512 pixels on its long side, from a local PNG or JPEG file only, with no metadata.+Without ffmpeg, only small JPEG previews go; a picture that still doesn't fit in 64 KB is not sent. The studio keeps a+preview only from the attempt that holds the job, and drops a larger one (the progress stays).++### When something goes wrong++The worker keeps its jobs going by itself:++- **Results are kept until the studio has them.** When its ComfyUI finishes a job, the worker copies every result into+ `hold/<job>/` in the worker folder before it tells the studio. The copy stays until the studio has every file. If+ the worker or its ComfyUI stops in between, the next claim gives the job back to this worker, and it uploads the+ kept files from where the studio's copy got to. The job never runs twice. Kept results go up even while the worker+ is paused, because they need no GPU. Each beat names the jobs whose results the worker keeps (`held`), so a pause,+ even a pause now, leaves those jobs with this worker instead of sending them back in line. Kept results are deleted+ when the studio has them all, when the worker takes another job, when the studio no longer has the job, or after a+ day. A claim that finds nothing for the worker keeps them: their job may still come back to it.+- **One retry policy for the studio.** A studio that restarts, a proxy that answers 502, 503 or 52x, a network that+ drops, or a busy studio that says when to come back is waited out. The pause grows from 1 second to at most 30+ seconds. The worker waits up to 2 minutes for a call, and up to an hour for a part of a result. It sends a call+ again only when that is safe. A proxy's page in place of the studio's answer (a 403 that is not JSON) never stops+ the worker.+- **A job that stalls goes back to the line.** If a job makes no progress for its stall limit, or runs past the run+ limit that the claim gives, the worker takes its prompt off its ComfyUI and gives the job back. The job keeps its+ place in the line. If its ComfyUI does not let go of the prompt within 15 seconds, the worker stops ComfyUI and+ starts it again. A job that is given back counts as an attempt; the third time, it fails.+- **The stall limit** comes with each claim (`stallMs`). The studio gives 10 minutes for every lane now, never more+ than the lane's run ceiling. `stallMin` in `worker.json` has no default; when you set it, its minutes win over the+ claim's limit on that PC.+- **The run limit** counts from when its ComfyUI starts running the job (the model load included), not while the job+ waits. The studio gives 3 times the lane's 90th-percentile time on that worker plus the lane's model load, at least+ 10 minutes and at most the lane's run ceiling (the queue's `runCeilingS`, 45 minutes unless the owner sets another).+ For a lane with no times on that worker yet, it gives the run ceiling, so a first long job can finish. A job given+ back once for running past its limit gets the whole run ceiling on its next try; past that, it fails. The worker+ ignores a run limit under 10 minutes.+- **A ComfyUI that stops answering** for `hungMin` minutes (3) is stopped and started again.+- **A job that the studio took back** (its token for the job no longer works, for example after the worker was out of+ touch) is stopped in its ComfyUI at once, so it never keeps the GPU busy for nothing.+- **Out of memory.** The worker frees its ComfyUI's memory (`/free`) and sends the job once more. Only a second time+ fails the job. The execution time that it reports is the retry's only.+- **Inputs are read once.** The worker keeps a copy of each input (by its SHA-256) while its job runs, so a job that+ is sent again reads nothing from the studio twice. If the studio will not send an input again (429 with no+ `Retry-After`), the job fails at once instead of looping. The copies go when the job ends, and also when a claim+ brings another job or none, however the last job ended.+- **The PC stays awake** while the worker holds a job, has results to send, or waits for work. A small helper asks the+ system to stay awake (`SetThreadExecutionState` on Windows, `caffeinate` on macOS, `systemd-inhibit` on Linux). The+ screen may still turn off. While the worker is paused or outside its hours, the PC sleeps as usual.+- **A PC that slept anyway** (a lid closed, the power button) is noticed when it wakes: a one-second wait in the+ worker's loop took over a minute. The next beat says how long the PC slept (`slept`, in ms). A job that the studio+ took back from the worker for going quiet during that sleep then counts no attempt, and the worker may take it again+ at once. This happens once per job at most.+- **Its model folders are read again** every 10 minutes, and whenever a job needs a model file that the worker has not+ found yet. A drive that comes back after a restart is noticed, and the studio gets the new list.+- **A model folder that isn't there yet** (a drive that is still locked or not connected after a restart) pauses the+ worker by itself (`local.why: "models-not-ready"`). Settings → Workers shows "Waiting for its model folders", and+ the worker's lanes stay as they were: the studio asks for no list of files meanwhile, and refuses one with 409. The+ worker checks its folders every minute. Once they are all there, it reads them again, sends the new list, and takes+ jobs again. A job already running goes on.+- **When the studio stops the worker.** If the studio no longer knows the worker's token, `fuobe worker run` ends with+ exit code 3; any other stop that you did not ask for ends with exit code 1. The sign-in task that+ `fuobe worker install` adds then starts the worker again after a minute. Ctrl+C ends with 0. On Ctrl+C, and on a+ stop from the system (SIGTERM), the worker stops its ComfyUI and empties its folders before it ends. Kept results+ stay for its next start.### The protocoldiff --cc docs/public-signup.mdindex d6bd505e,54f3fe59..ad40130b--- a/docs/public-signup.md+++ b/docs/public-signup.md@@@ -591,46 -595,139 +610,142 @@@ owner's own runs, and runs on this stud- **Settings → Your GPU.** Test and Connect say what is wrong with the address: a RunPod pod that isstopped ("Your RunPod pod isn't running, or ComfyUI isn't on port 8188", with **Start your pod**,- a link to RunPod's pods page), a GPU starting up, no answer, a password that is missing or wrong,- a sign-in page in front, or another app on that address. `PUT /api/account/gpu` answers 422 with- `error` (the sentence) and `trouble` (`cause`, `details`, `actions`, `retryable`). An address- pasted without `https://` gets it added, and a `?…` or `#…` part is left out; the answer's `note`- says so. A GPU that is off or starting up is checked again by itself (5, 10, 20, 30 seconds, for 3- to 5 minutes), and **Save anyway** (`{ "anyway": true }`) keeps its address: runs wait for it. Too- many checks (429) count down and check again by themselves. The saved address's card says- **Offline** with the reason, and **Check now** (`{ "saved": true }`) asks it again.+ a link to RunPod's pods page), a pod that is on while ComfyUI starts, a GPU starting up, no+ answer, a password that is missing or wrong, a sign-in page in front, or another app on that+ address. `PUT /api/account/gpu` answers 422 with `error` (the sentence) and `trouble` (`cause`,+ `details`, `actions`, `retryable`). An address pasted without `https://` gets it added, and a+ `?…` or `#…` part is left out; the answer's `note` says so. An `http://` address that sends to+ the same host's `https://` is followed to the port it named. A GPU that is off or starting up is+ checked again by itself (5, 10, 20, 30 seconds, for 3 to 5 minutes). After Test, which saves+ nothing, the words say to press **Connect** once it answers; when the checks stop, they say so,+ with **Check again** and **Save anyway** (`{ "anyway": true }`, which keeps the address: runs wait+ for it). Too many checks (429) count down and check again by themselves. The saved address's card+ says **Offline** with the reason, and **Check now** (`{ "saved": true }`) asks it again. A local+ address (`localhost`, a home network) offers **Use this computer** where this browser can reach+ its ComfyUI, and **Pair with a code**. Where it can't, a line says why instead ("Use this computer+ works in Chrome, Edge or Firefox. Safari doesn't let a website reach programs on your Mac.", or on+ a phone or tablet, or a page the browser marks as not secure).+ - **Settings → Your keys.** A key whose provider account has no balance left shows **Add credit**+ (a link to the provider's billing page) instead of **Ready**, with the day it ran out. A saved key+ has **Check again** (`PUT /api/account/keys/<provider>` with `{ "recheck": true }`): the provider's+ free check, run on the saved key, which clears a refusal or an empty balance once the provider+ takes the key. A check that finds the provider busy or out of reach (429 or 5xx) asks twice more+ by itself, then says "fal.ai is busy right now, so we couldn't check your key. Try again in a+ minute." with the status in `details`. A run the provider takes on the key clears both marks too.- **Before Run.** When the account's GPU didn't answer its last status check, the composer showsthe reason and its buttons above Generate. It reads the status the strip already has (every 30- seconds), so the GPU is never asked more often. When one of the account's keys runs the tool's- cloud version (a preset's cloud route, or a Fuobe Original on the cloud engine), **Run with your- fal.ai key** switches to Cloud and runs it there, billed to that key. A run started anyway waits.- The account menu says why the GPU is offline: "pod stopped", "starting up", "needs a password".+ seconds), so the GPU is never asked more often. Its words say what happens to runs ("Start your+ pod, and your runs start as soon as it answers. A run you start now waits for it."); a problem+ waiting can't fix (a password, another app on the address) says "Runs can't reach your GPU until+ this is fixed." When one of the account's keys runs the tool's cloud version (a preset's cloud+ route, or a Fuobe Original on the cloud engine), **Run with your fal.ai key** sits right after the+ first fix. It runs this one run there, billed to that key, and leaves the engine switch where it+ was: the next run goes to the GPU again. A key the provider refused, or whose balance ran out, is+ not offered. A paid model on a key whose balance is empty (found on a run, or by a check of the+ key) says so above Generate ("Your fal.ai balance is empty. Add credit there, then run."), with+ **Add credit**. A graph that needs a second ComfyUI (ThinkSound, LatentSync 1.6) says so before Run, with+ **Run with your key** when one runs its cloud version, and **Pick another model**. The account+ menu says why the GPU is offline: "pod stopped", "starting up", "needs a password".- **A run that waits.** A run whose GPU is off, starting up or out of reach waits and tries again by- itself, with a growing wait (up to a minute between tries). Its tile says what it waits for- ("Waiting for your RunPod pod to start", "Waiting for your GPU to start up"). A GPU that is off- waits up to 30 minutes, one starting up 10 minutes. Before the run fails, the GPU is asked once- more. A run whose account saves another address while it waits stops and says so. A provider- that is busy (429) or down (503) at submit is tried again for 1 to 3 minutes; a 502 or 504 at- submit is not, because the job may have started. Waiting never retries what it can't fix: a- refused key, an empty balance, a missing add-on or file, or an input the model refuses. A 403- that isn't about the key (a model the key may not run) says to pick another model; the key- stays as it is.+ itself, with a growing wait (up to a minute between tries, or what the other side asked for).+ Before each try it asks the GPU's `/system_stats` only; its files go once the GPU answers, and a+ file already sent is never sent twice. Its tile says what it waits for ("Your RunPod pod is off.+ Start it, and this run goes on by itself", "Waiting for your GPU to start up"), until when it+ waits, and the buttons that help (**Start your pod**, **Check my GPU**, **Run with your fal.ai+ key**, which moves this run to the key: it stops waiting and the cloud run takes its place). A run+ that made several jobs (a batch) moves as one: the press stops every job of it not handed over yet+ and the cloud run makes their outputs, never the whole batch again; while it is on its way the+ batch's other tiles don't offer the button, and a later press on one of them answers 409 "This run+ has already started or stopped, so nothing new was run." (`replaces` beside the request names the+ run). A step of a longer run (a relight and then its clip, a film's shot, a Mixed Media step), or a+ job of a batch whose other waiting job a later step waits for, doesn't offer it: moved alone, the+ step would stop and the rest of the run would go without it. Its wait goes on, and `replaces` on it+ answers 409 "This step is part of a longer run, so it can't move to your key on its own. It goes on+ by itself, or cancel it and run the tool again with your key." (`chained-run`). Nor does a run a+ tool made for one of the account's projects (a Cinema take, a Storyboard board, a short, a Faceless+ or Content Factory run), even a take of one step: moved alone, it would leave its project, where it+ would show Canceled. `replaces` on it answers 409 "This run is part of one of your projects, so it+ can't move to your key on its own. It goes on by itself, or cancel it and run it again in its+ project with your key." (`project-run`). Only a run made on its own (`POST /api/generations`, as a+ studio's Generate makes it, or Image to 3D) moves: the server marks it so when it makes it, and the+ tile offers the button only where a press can act. The Library's card shows the same buttons. Each cause has its own time from when it was first seen: a+ GPU that is off 30 minutes, one starting up 10 minutes, and 40 minutes in all. Before the run+ fails, the GPU is asked once more. When the account saves a new address (or password) while a+ run waits, the run goes there; when it disconnects its GPU, the run stops and says so, with+ **Connect your GPU**. A provider that is busy (429) or down (503) at submit is tried again for 1+ to 3 minutes; a 502 or 504 at submit is not, because the job may have started. The same holds on+ the GPU: a failure at ComfyUI's `/prompt` is tried again only when it proves nothing arrived+ (nothing listening, no such name, a stopped pod, a tunnel that is down). Waiting never retries+ what it can't fix: a refused key, an empty balance, a missing add-on or file, or an input the+ model refuses. A 403 that isn't about the key (a model the key may not run) says to pick another+ model; the key stays as it is. A wait is kept with the run (`external_meta_json`), and the server- that waits renews its hold on it: after a restart, or when a deploy's new instance takes over,- the run goes on with what is left of its wait (its tries and its time), on one instance only; so- does a step of a longer run. A server that is stopping- sends no more tries and lets go of its waiting runs at once, for the next instance. A run that++ that waits holds the run's turn to send it (`submit_turns`, the same turn every run has; each++ app process says every 5 seconds that it still runs, and the turn of one that has said nothing for++ 20 seconds is free): after a restart, or when a deploy's new instance takes over, the run goes on++ with what is left of its wait (its tries and its time), on one instance only; so does a step of a++ longer run. Another instance never fails, takes or sends a run whose turn a running instance++ holds. A server that is stopping sends no more tries and gives its waiting runs' turns back at++ once, for the next instance. A run that+ waited, and a step of a longer run on any try (its first too), is marked just before the try sends+ the job itself: a server cut off in the middle of that send leaves a job the GPU or provider may+ already have, so the next instance doesn't send it again, and the run fails with "This run was+ interrupted while it was being sent. Press Retry." Its tile doesn't say **Not billed**, because+ the provider may have the job. A try the provider turned down as it was sent (a refused key, an+ empty balance, a model gone: a 4xx answer) still says **Not billed**. A run planned for+ another provider by then stops in plain words. Runs that wait for the GPU count apart from the 4+ runs at once (up to 4 more wait); a fifth waiting run answers 429 "You have 4 runs waiting for+ your GPU. Cancel one, or run one with your key, to start another." Runs that wait on a key (its+ provider busy or down) count among the 4 runs at once.- **A paired ComfyUI.** A run for a ComfyUI paired with a code (Fuobe Connect) that is off says"Waiting for your paired ComfyUI. Start ComfyUI there (or start your pod), and this run goes on- by itself." It doesn't ask for a Fuobe tab, because a paired ComfyUI needs none.+ by itself." It doesn't ask for a Fuobe tab, because a paired ComfyUI needs none. A Fuobe tab+ that runs this computer's ComfyUI and is signed out says so, with **Log in**.- **While it runs.** A GPU or provider that stops answering mid-run is asked again with a growing- wait, and after 3 misses the tile says "Your GPU stopped answering. Waiting for it to come back".- It stops after 15 minutes (10 for a key's provider) in plain words. A key refused or a balance- gone while a run is polled fails it at once, and the job is stopped there. A ComfyUI that- restarted and lost a run gets it sent once more. A run whose account moved to another address- says so. A result that can't be copied is tried 3 times first. A graph that needs a second- ComfyUI (ThinkSound, LatentSync 1.6) is refused before anything is sent.- - **A failed run.** The tile shows the sentence, the details line, and up to three buttons: **Start- your pod**, **Check my GPU** (the Test above, on the saved address), **Open Settings → Your GPU**- or **Your keys** (**Replace key**), **Add credit on fal.ai** (or Replicate), **Run with your- Replicate key** when the other key runs the same model, and **Retry**. The Library's card shows- the same sentence with up to two of them. The run keeps them in `trouble`- (`GET /api/generations/<id>`), next to `fix` for **Fix it**.+ wait (what it asked for in `Retry-After` up to 2 minutes, never past the run's own time), and+ after 3 misses the tile says "Your GPU stopped answering. Waiting for it to come back".+ On the account's GPU it stops after 15 minutes in plain words. On a key the job is accepted (and+ paid), so it waits on until the run's own time limit; a call to fal.ai or Replicate that hangs is+ given up after 20 seconds (60 for a submit or a result) and asked again. A key refused or a+ balance gone while a run is polled fails it at once, and the job is stopped there. A ComfyUI that+ restarted and lost a run gets it sent once more, as the same job of its batch (its own seed). A+ run whose account moved to another address says so. A job in the GPU's queue waits as long as+ the queue keeps moving (2 hours at most): its place gets nearer the front (the jobs before it are+ the ones with a lower number in ComfyUI's queue), or the GPU starts another job ahead of it. It+ stops when nothing has moved for 30 minutes (45 while a job runs ahead of it, the time one job+ may take), saying the GPU was busy. A made result whose copy breaks off (a connection dropped, a 5xx) is+ copied again at later looks for up to 15 minutes ("Your result is made. Copying it from your+ GPU"), never made again. Sending a file to the GPU may take as long as its size needs at 128 KB/s+ plus a minute (5 to 30 minutes).+ - **A failed run.** The tile shows the sentence, the details line, and up to three buttons (two on+ a narrow tile; the ones that help least go first): **Start your pod**, **Run with your fal.ai+ key** right after it, **Check my GPU** (the Test above, on the saved address), **Open Settings →+ Your GPU** or **Your keys** (**Replace key**), **Add credit on fal.ai** (or Replicate), **Run with+ your Replicate key** when the other key runs the same model (on that key, never back on fal.ai),+ **Pick another model** (it opens the studio's model picker), **Try one size smaller** after a+ run ran out of graphics memory or took too long, **Send a smaller copy** after a file was too big+ for the address (`POST /api/generations/<id>/smaller` makes a smaller copy of the run's biggest+ picture or clip as a new file of the account's, and the run starts again with it), and **Retry**.+ A copy is real work, so an account makes one at a time and the server two at once (429 "Smaller+ copies are busy right now. Try again in a minute."), a clip's encode uses two cores, files that+ are full say so before any work, and a run gets 3 copies an hour (12 for the account). When no+ smaller copy can be made, the message offers **Try one size smaller** (or **Pick another model**).+ A button that starts a run stays pressed until it has, so a second click starts nothing. The+ Library's card shows the same sentence with up to two of them (one in the list), and they act+ there too: **Pick another model** opens the run's studio with the run loaded and its model picker+ open (`?reuse=<id>&pick=1`). The run keeps them in `trouble` (`GET /api/generations/<id>`), next+ to `fix` for **Fix it**.+ - **For the owner.** Each wait, heal and failure of an account's run on its own GPU or key writes+ one JSON line to the server's log (`"evt":"own-run"`: the run, the account, the place, provider,+ model, stage, status or network code, the kind of address, the cause, the try and the time+ waited). A run that stops in this server's own words writes one too, with its cause: cut off by a+ restart (`interrupted`, or `interrupted-sending` in the middle of its send), refused as its+ account runs now (`connect-gpu`, `add-key`, `switched-off`…), its keys changed while it waited+ (`keys-changed`), or a step whose earlier step didn't finish (`earlier-step`: the first step after+ the failure only; the steps after it, which stop for the same reason, write none). It never holds+ a prompt, a key, a token, an address or a file's name. A failed run also+ keeps, for the owner only, the cause, stage, code, kind of address and the provider's own words+ (cleaned, 2 KB at most): `ownRunNote(id)` in `src/server/run-events.ts` reads it, and no account+ or visitor answer carries it.## Hosted runsdiff --cc src/app/api/generations/route.tsindex bca150d7,9bd9accc..7acd51b9--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@@ -13,9 -13,13 +13,10 @@@ import { ANY_ANGLE } from "@/lib/cataloimport { relightRunTitle } from "@/lib/relight/engine";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { accountInputProblem } from "@/server/account-inputs";-import { db } from "@/server/db";import { findView, requestViewKey } from "@/server/any-angle";- import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, captureRun, createGenerations, getGeneration, listGenerations, outputKind, previewGeneration, stepsOf, type AccountRunRefusal } from "@/server/generations";-import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, cancelGeneration, CHAINED_RUN, createGenerations, getGeneration, keyMoveBlock, listGenerations, outputKind, previewGeneration, PROJECT_RUN, type AccountRunRefusal, type KeyMoveBlock } from "@/server/generations";++import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, captureRun, CHAINED_RUN, createGenerations, getGeneration, keyMoveBlock, listGenerations, outputKind, previewGeneration, PROJECT_RUN, stepsOf, stopReplaced, type AccountRunRefusal, type KeyMoveBlock } from "@/server/generations";+import { accountActiveRuns, AdmitRefused, admitRun, clientAddress, poolLimitRefusal } from "@/server/pool-limits";++import { db } from "@/server/db";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { hit, unhit } from "@/server/rate";import { GenerationRequestSchema } from "@/server/request-schema";@@@ -45,6 -47,98 +46,67 @@@ export async function GET(request: Requreturn Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: viewer.kind === "account" ? viewer.account.id : undefined }) });}-/**- * A run waiting for the account's own GPU to come back: no job yet, its wait kept with it (generations.ts `heal`). A run- * waiting on a key (its provider busy or down) isn't one: it counts among the runs going now, so a provider that is down- * can't gather more of them than that.- */-const WAITING = "(provider = 'comfyui' AND external_id IS NULL AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.heal') IS NOT NULL)";--/** Leave out the runs a new one takes the place of (a JSON list of ids). */-const NOT_REPLACED = "id NOT IN (SELECT value FROM json_each(?))";--/**- * An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. Runs- * waiting for its own GPU are counted apart (`waiting`): they use nothing while they wait. `except`: the runs the new one- * takes the place of ("Run with your key" on a waiting run).- */-function activeRuns(accountId: string, except: readonly string[] = []): number {- const r = db()- .prepare(- `SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ? AND NOT ${WAITING} AND ${NOT_REPLACED}`,- )- .get(accountId, JSON.stringify(except)) as { n: number };- return r.n;-}--function waitingRuns(accountId: string, except: readonly string[] = []): number {- const r = db()- .prepare(`SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status = 'queued' AND json_extract(request_json, '$.account') = ? AND ${WAITING} AND ${NOT_REPLACED}`)- .get(accountId, JSON.stringify(except)) as { n: number };- return r.n;-}-+ /** What a new run takes the place of: the rows that stop once it is made, and how many outputs they were to make. */+ interface Replaced {+ ids: string[];+ /** The outputs the stopped rows were to make (none: the request's own count stays). */+ outputs?: number;+ }++ /** A `replaces` for a run that can't be taken over any more: started on its GPU meanwhile, or stopped already. */+ const NOT_REPLACEABLE = "This run has already started or stopped, so nothing new was run.";++ /** What a `replaces` on a waiting run Run with your key can't move on its own answers (409, in plain words). */+ const BLOCKED: Record<KeyMoveBlock, { error: string; code: string }> = {+ chained: { error: CHAINED_RUN, code: "chained-run" },+ project: { error: PROJECT_RUN, code: "project-run" },+ };++ /** A `replaces` that names a waiting run Run with your key can't move on its own: why (generations.ts keyMoveBlock). */+ interface Blocked {+ blocked: KeyMoveBlock;+ }++ /**+ * Beside the request: the account's own run (waiting for its GPU or key, or failed) this one takes the place of ("Run+ * with your fal.ai key" on it). A waiting run takes its whole batch with it: every job of the same request not handed+ * over yet stops once this one is made, and this one makes their outputs (never the whole batch again). Undefined: no+ * `replaces`; null: one that can't be taken over any more (asked again just before the run is made, nothing awaited);+ * Blocked: a waiting run never moved alone (a step of a longer run, or a run of one of the account's projects), the same+ * check its tile makes before it offers the button.+ */+ function replacedRun(body: unknown, accountId: string): Replaced | Blocked | null | undefined {+ const id = (body as { replaces?: unknown } | null)?.replaces;+ if (id === undefined || id === null) return undefined;+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,40}$/.test(id)) return null;+ const row = db()+ .prepare("SELECT status, external_id, batch_id, request_json, depends_on FROM generations WHERE id = ? AND json_extract(request_json, '$.account') = ?")+ .get(id, accountId) as { status: string; external_id: string | null; batch_id: string | null; request_json: string; depends_on: string | null } | undefined;+ if (!row) return null;+ if (row.status === "failed") return { ids: [id] };+ if (row.status !== "queued" || row.external_id) return null;+ const blocked = keyMoveBlock({ id, depends_on: row.depends_on, batch_id: row.batch_id, request_json: row.request_json });+ if (blocked) return { blocked };+ if (!row.batch_id) return { ids: [id] };+ // Its batch's jobs (the same request; a chain's later steps have their own), and those not handed over yet.+ const jobs = db()+ .prepare("SELECT id, status, external_id FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS NULL")+ .all(row.batch_id, row.request_json) as { id: string; status: string; external_id: string | null }[];+ const ids = jobs.filter((j) => j.status === "queued" && !j.external_id).map((j) => j.id);+ if (!ids.includes(id)) ids.push(id);+ let asked = 1;+ try {+ asked = Math.max(1, Number((JSON.parse(row.request_json) as { params?: { numOutputs?: unknown } }).params?.numOutputs) || 1);+ } catch {}+ // Each job made its share of the outputs asked for.+ const outputs = Math.min(asked, ids.length * Math.ceil(asked / Math.max(1, jobs.length)));+ return { ids, ...(outputs !== asked && { outputs }) };+ }++ /** The request with the outputs of the runs it takes the place of (their count, not the whole batch's again). */+ const withReplacedOutputs = <R extends { params?: { numOutputs?: number } }>(req: R, r: Replaced | undefined): R =>+ r?.outputs ? { ...req, params: { ...req.params, numOutputs: r.outputs } } : req;+/** What the sign-in proxy passes on of a request body (next.config.ts proxyClientMaxBodySize). */const PROXY_BODY_BYTES = 4 * 1024 * 1024;const BODY_TOO_BIG = "That request is over 4 MB. Upload pictures and clips first (POST /api/uploads), then send their /api/files/ paths.";@@@ -52,27 -146,6 +114,30 @@@const refuse = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store", ...headers } });+/** An answer as its parts: its status, body and headers. */+interface Answer {+ status: number;+ body: { error: string; code?: string; provider?: string };+ headers: Record<string, string>;+}++/** The answer to an account's run that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */+const accountRunAnswer = (r: AccountRunRefusal): Answer => ({+ status: 403,+ body: { error: r.error, code: r.code, ...(r.provider && { provider: r.provider }) },+ headers: r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {},+});+- /** The answer to a run the limits refuse as it is made (admitRun), or one with a step this install's GPUs don't take. */++/**++ * The answer to a run the limits refuse as it is made (admitRun), one with a step this install's GPUs don't take, or one++ * whose run it takes the place of was taken meanwhile.++ */+const limitAnswer = (r: AdmitRefused["refusal"]): Answer => ({+ status: r.status,+ body: { error: r.error, code: r.code },- headers: r.code === "not-offered" ? { [BILLING_HEADER]: "not-offered" } : { "Retry-After": String(r.retryAfterS ?? 30) },++ headers: r.code === "not-offered" ? { [BILLING_HEADER]: "not-offered" } : r.status === 429 ? { "Retry-After": String(r.retryAfterS ?? 30) } : {},+});+/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */export async function POST(request: Request) {const viewer = requestViewer(request);@@@ -127,20 -208,21 +192,29 @@@if (account) unhit(`run:${account.id}`);return refuse(r.status, r.body.error, r.body, r.headers);};+ // With hosted runs on, an account's press of Run whose run goes to this install's GPUs is made once however often the+ // page sends it (run-requests.ts): a resend gets the run the first one made. A run on its own GPU or key notes nothing.+ const pressId = account && !preview && hostedRunsOn() ? readPressId(body) : null;+ const madeAlready = (ids: string[]) => Response.json({ items: ids.map((id) => getGeneration(id)).filter((g) => !!g) }, { status: 201 });+ if (account && pressId) {+ const made = pressRun(account.id, pressId);+ if (made) return madeAlready(made.ids);+ }const notes: string[] = [];+ const replacing = account && !preview ? replacedRun(body, account.id) : undefined;+ // A run that started or stopped meanwhile (another tile's press took it already): nothing new runs.+ if (replacing === null) return refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });+ // A waiting step of a longer run, or a run of one of the account's projects: it goes on as it is (moved alone, the rest+ // of the run would go without it, or the project would lose it).+ if (replacing && "blocked" in replacing) return refuse(409, BLOCKED[replacing.blocked].error, { code: BLOCKED[replacing.blocked].code });+ let replaces = replacing;+ // It makes the outputs of the jobs it stops, not its whole batch's again.+ req = withReplacedOutputs(req, replaces);if (account && !preview) {// Room on the server, room in the account's files, and a fair share of runs.if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);if (accountUsage(account.id).total >= accountTotalBytes(account.id)) return refuse(413, filesFullMessage(account.id));- if (accountActiveRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });- if (activeRuns(account.id, replaces?.ids) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });++ if (accountActiveRuns(account.id, { except: replaces?.ids, waitingApart: true }) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });const rate = hit(`run:${account.id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {@@@ -277,55 -352,34 +354,83 @@@stamp = held.stamp;} else if (mod.checkOutputs) stamp = { checkOutputs: true };}- // The run this one takes the place of, asked again with nothing awaited from here until it stops: a press on another++ // The run this one takes the place of, asked again with nothing awaited from here until it is made: a press on another+ // of its batch's tiles meanwhile took it already (or it started on its GPU), so nothing new runs.+ if (replaces && account) {+ const now = replacedRun(body, account.id);+ if (!now || "blocked" in now) {+ unhit(`run:${account.id}`);+ if (stamp?.hold) queueRelease(stamp.hold);+ return now ? refuse(409, BLOCKED[now.blocked].error, { code: BLOCKED[now.blocked].code }) : refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });+ }+ // Fewer of its jobs left to stop (one was handed over meanwhile): fewer outputs. A run on this install's GPUs keeps+ // the count it was priced and set aside for.+ if (!onPool && now.outputs !== undefined && now.outputs !== replaces.outputs) req = { ...req, params: { ...req.params, numOutputs: Math.min(now.outputs, req.params?.numOutputs ?? now.outputs) } };+ replaces = now;+ }- // Counted again just before the run is stored, with nothing awaited in between: requests that arrived together all- // passed the first count while the checks above waited.- const waitingFull = !onPool && goesTo === "comfyui" && waitingRuns(account?.id ?? "", replaces?.ids) >= ACCOUNT_LIMITS.waitingRuns;- if (account && (activeRuns(account.id, replaces?.ids) >= ACCOUNT_LIMITS.activeRuns || waitingFull)) {- unhit(`run:${account.id}`);- if (stamp?.hold) queueRelease(stamp.hold);- return refuse(429, waitingFull ? ACCOUNT_MESSAGES.waitingRuns : ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });- }const make = () => createGenerations(req);- const inScope = <T,>(fn: () => T): T => (account && onPool ? runOnPool(account.id, () => withRunStamp(stamp ?? { place: "pool" }, fn)) : stamp ? onOwn(() => withRunStamp(stamp, fn)) : onOwn(fn));+ // An account's run made here is its own, in no tool's project: Run with your key may take its place while it waits.+ const alone = (s: RunStamp): RunStamp => ({ ...s, standalone: true });++ const inScope = <T,>(fn: () => T): T =>++ account && onPool ? runOnPool(account.id, () => withRunStamp(alone(stamp ?? { place: "pool" }), fn)) : account ? onOwn(() => withRunStamp(alone(stamp ?? {}), fn)) : stamp ? onOwn(() => withRunStamp(stamp, fn)) : onOwn(fn);let items: ReturnType<typeof createGenerations>;try {- items = account && onPool ? runOnPool(account.id, () => withRunStamp(alone(stamp ?? { place: "pool" }), make)) : account ? onOwn(() => withRunStamp(alone(stamp ?? {}), make)) : onOwn(make);+ if (account) {+ // Counted again as the run is made, in one transaction (admitRun): requests that arrived together all passed the+ // first counts while the checks above waited, and a second server may be making runs too. The run's rows are made+ // and checked step by step (every step of a chain on this install's GPUs is one the policy allows); nothing is+ // sent until they are kept.+ const pool = onPool;+ const admitted = inScope(() => {+ const r = admitRun(+ {+ accountId: account.id,+ pool: pool && !pool.light ? { policy: pool.policy, addr } : null,++ // The studio's own limits as a run made here meets them: runs waiting for the account's own GPU are counted++ // apart (a run for its GPU meets their limit too), and the runs this one takes the place of are left out.++ studio: { except: replaces?.ids ?? [], mayWait: !onPool && goesTo === "comfyui" },+ // A send of this press that got here first made the run, or ended this try (its hold is going back):+ // nothing is made twice, and nothing against a hold that went back.+ ...(poolTry !== null && { prior: () => pressPrior(account.id, pressId!, poolTry) }),+ // Refused after its hold was made: the hold goes back, so the press's next send is a new try with a hold+ // of its own, never a run against this one. Noted in the same transaction, before any send can look.+ ...(poolTry !== null && stamp?.hold && { refused: () => void endTry(account.id, pressId!, poolTry) }),+ },+ () => {++ // The run this one takes the place of, asked once more in the same step: a press that reached another app++ // process first took it already, so nothing new runs.++ const still = replaces ? replacedRun(body, account.id) : undefined;++ if (still === null) throw new AdmitRefused({ status: 409, error: NOT_REPLACEABLE, code: "not-replaceable" });++ if (still && "blocked" in still) throw new AdmitRefused({ status: 409, ...BLOCKED[still.blocked] });+ const run = captureRun(make);+ const problem = pool && stepsProblem(pool.policy, stepsOf(run.ids));+ if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });++ // The runs this one takes the place of stop in the same step (they were waiting, or it failed): never two of++ // the same, whichever app process a second press reaches.++ if (still) stopReplaced(still.ids);+ if (poolTry !== null) notePressRun(account.id, pressId!, poolTry, run.value.map((g) => g.id), stamp?.hold ?? null);+ return run;+ },+ );+ if (r.ok) r.value.start();+ return r;+ });+ if (!admitted.ok && "prior" in admitted) {+ unhit(`run:${account.id}`);+ const prior = admitted.prior;+ // The service gives one try of a press one hold; a different one (a service that made a second) goes back, and+ // so does the hold of a try another send ended.+ if (stamp?.hold && (prior === "ended" || stamp.hold !== prior.hold)) queueRelease(stamp.hold);+ return prior === "ended" ? refuse(503, BILLING_WAIT.run, { code: "paused" }, { [BILLING_HEADER]: "paused" }) : madeAlready(prior.ids);+ }+ if (!admitted.ok) {+ unhit(`run:${account.id}`);+ if (stamp?.hold) queueRelease(stamp.hold);+ const a = limitAnswer(admitted.refusal);+ return refuse(a.status, a.body.error, a.body, a.headers);+ }+ items = admitted.value.value;+ } else items = make();} catch (e) {// Nothing was made: what was set aside goes back.if (stamp?.hold) queueRelease(stamp.hold);diff --cc src/app/api/image-to-3d/route.tsindex 1e95ddf5,94952620..de5e8ef2--- a/src/app/api/image-to-3d/route.ts+++ b/src/app/api/image-to-3d/route.ts@@@ -4,9 -4,10 +4,10 @@@ import type { GenerationRequest } fromimport { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";import { accountInputProblem } from "@/server/account-inputs";import { accountEngineMode } from "@/server/account-keys";-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer, toolWishes } from "@/server/account-tool-run";import { createGenerations } from "@/server/generations";import { GenerationRequestSchema } from "@/server/request-schema";+ import { runStamp, withRunStamp } from "@/server/run-stamp";/*** Image to 3D's runs: a model from a photo, several photos, words or an object in a photo, a splat, and a finished@@@ -57,10 -57,10 +58,11 @@@ export async function POST(request: Req() =>runAccountTool(request, account, {tool: "image-to-3d",+ ...wishes,files,plan: () => [{ request: run }],- start: () => createGenerations(run),+ // A model made on its own, as in a studio (no project keeps it): Run with your key may take its place while it waits.+ start: () => withRunStamp({ ...runStamp(), standalone: true }, () => createGenerations(run)),skipGpuCheck: extra.gpuCheck === "skip",}),({ value, gpuWarning }) => {diff --cc src/components/studio/composer.tsxindex d33da033,e06c27a0..571a874d--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@@ -1021,13 -942,11 +1030,15 @@@ export function Composer({ docked }: {// On the open engine every run is free on the GPU: said even before the run can be planned (no voice sample, no clip yet).// Said with "your GPU" only off a hosted studio: there the run may use the studio's GPUs, and the chip or hint says where.const gpuRun = saysYourGpu(engine, hostedHere);- const ownCostText = costLabel({ demo, cost: cost ?? (engine === "open" && model ? 0 : null), unknown: loraPriceUnknown, gpu: gpuRun }, formatCost);+ // A cloud model that runs on a visitor's own key only (Mureka Extend on Audio → Extend & remix): never "Free · your GPU",+ // its key in the label's words.+ const keyOnly = setupViewer && !demo ? keyOnlySetup(model, engine) : null;+ const freeHere = engine === "open" && model && !keyOnly ? 0 : null;+ const ownCostText = keyOnly && cost == null ? ownSetupLabel(keyOnly) : costLabel({ demo, cost: cost ?? freeHere, unknown: loraPriceUnknown, gpu: gpuRun }, formatCost);// An account's paid run is billed to its own provider account (Your keys), or still needs that key.const payer = paidThrough(model, status);+ // Its provider account's balance ran out on a run: said before the next one, with Add credit.+ const emptyPayer = payer && status?.viewer?.emptyKeys?.includes(payer) ? payer : null;const missingKey = needsKey(model, status)?.[0];const ownPayerText = payer && cost ? ` · ${billedTo(payer)}` : missingKey ? ` · ${addKeyLabel(missingKey).toLowerCase()}` : "";// On this studio's GPUs: the quote's words (none from the server: free, as the open engine always is).diff --cc src/components/studio/feed.tsxindex 6acb2fb4,ed6ff011..c15622fd--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@@ -18,9 -16,10 +18,10 @@@ import} from "@/components/ui/dropdown-menu";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";- import { onCloudKey } from "@/lib/before-run";- import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";+ import { useOptionalCatalog } from "./catalog";+ import { TroubleDetails } from "@/components/gpu/trouble";+ import { RunTroubleActions } from "@/components/gpu/run-trouble-actions";-import { useCreateGeneration, useGenerationActions, useStatus } from "@/lib/api";+import { useCreateGeneration, useGenerationActions, useMakingPoolRuns, useStatus } from "@/lib/api";import { placeholdersOn } from "@/lib/demo-mode";import { useSoulFinish } from "./soul-finish";import { elapsed, formatCost, leftLabel, notePace, ratioValue, timeAgo, timeLeft } from "@/lib/format";@@@ -107,8 -71,9 +108,11 @@@ export function PendingTile({ g, ratio// The bar: the steps, or how much of the result has reached the studio.const bar = saving ? Math.round((local.job.phase === "done" ? 1 : (local.job.saved ?? 0)) * 100) : pct;const where = local ? (local.here ? "Keep this tab open" : "Running in another Fuobe tab") : null;+ // A live frame: from the ComfyUI on this computer, or (Working on the workers) the latest preview picture.+ const frame = local?.preview ?? (g.status === "running" ? g.preview : undefined);+ // Waiting for its own GPU or key to come back: what helps meanwhile, and until when it waits.+ const waiting = g.status === "queued" ? g.waiting : undefined;+ const until = waiting?.until && waiting.until > now ? new Date(waiting.until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : null;return (// max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would// otherwise make the tile wider than its column and spill over the next card.@@@ -166,35 -134,40 +173,48 @@@);}+ /** A failed tile narrower than this (in px, at the feed's 224 px height) shows two trouble buttons, not three. */+ const NARROW_TILE_PX = 260;+export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {const create = useCreateGeneration();+ const feed = useContext(FeedCtx);+ const catalog = useOptionalCatalog();const trouble = g.status === "failed" ? g.trouble : undefined;+ // A run on this studio's GPUs that couldn't finish: one plain sentence (the server's), nothing technical.+ const poolFailed = g.place === "pool" && g.status === "failed";+ const shape = Math.max(ratio, 0.8);+ const narrow = shape * 224 < NARROW_TILE_PX;+ const [retrying, setRetrying] = useState(false);return (- <div className="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: Math.max(ratio, 0.8) }}>- <div className="min-h-0 space-y-1 overflow-hidden">+ <div className="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: shape }}>+ <div className="flex min-h-0 flex-col gap-1 overflow-hidden">- <p className="shrink-0 text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>- {g.error && <p className={cn("shrink-0 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error}</p>}- {/* An account's own GPU or key: what came back, small, for the curious (the first thing cut when room is short). */}- <TroubleDetails details={trouble?.details} className="min-h-0" />+ {poolFailed ? (- <p className="line-clamp-5 text-[13px] leading-snug font-medium break-words">{g.error || POOL_WORDS.failed}</p>++ <p className={cn("shrink-0 text-[13px] leading-snug font-medium break-words", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error || POOL_WORDS.failed}</p>+ ) : (+ <>- <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>- {g.error && <p className="line-clamp-5 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground">{g.error}</p>}- {/* An account's own GPU or key: what came back, small, for the curious. */}- <TroubleDetails details={trouble?.details} />++ <p className="shrink-0 text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>++ {g.error && <p className={cn("shrink-0 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error}</p>}++ {/* An account's own GPU or key: what came back, small, for the curious (the first thing cut when room is short). */}++ <TroubleDetails details={trouble?.details} className="min-h-0" />+ </>+ )}</div>+ {/* In a studio, Pick another model brings its settings back into the composer and opens its model picker. */}{trouble && (- <TroubleActions- className="mt-2"+ <RunTroubleActions+ g={g}+ reuse={feed?.reuse}+ model={catalog?.getModel(g.modelId)}+ className="mt-2 shrink-0"actions={trouble.actions}skip={["retry"]}- max={3}- handlers={{ onRunWithKey: (a) => create.mutate(onCloudKey(g.request, a), { onError: (e) => toastError(e) }) }}+ max={narrow ? 2 : 3}+ compact+ context="run"/>)}- <div className="mt-2 flex flex-wrap gap-1.5">+ <div className="mt-2 flex shrink-0 flex-wrap gap-1.5">{g.status === "failed" && g.fix && (// Something was missing on the GPU: the guided fix shows what, and how to add it.<buttondiff --cc src/components/studio/model-picker.tsxindex 275b2667,bec28416..dc7e3d54--- a/src/components/studio/model-picker.tsx+++ b/src/components/studio/model-picker.tsx@@@ -4,9 -4,8 +4,10 @@@ import { ChevronDown, Cloud, Cpu, Searcimport Link from "next/link";import { useEffect, useMemo, useRef, useState } from "react";import { KEY_ADDED_EVENT, openAddKey } from "@/components/keys/your-keys";+ import { OPEN_MODEL_PICKER_EVENT } from "@/lib/open-model-picker";import { Badge } from "@/components/ui/badge";+import { OwnSetupChip } from "@/components/own-setup";+import type { OwnSetup } from "@/lib/own-setup";import { Button } from "@/components/ui/button";import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";import { RowDot } from "@/components/gpu/readiness-chip";diff --cc src/lib/catalog/types.tsindex cb73e4ad,2d29bc50..9604ee04--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@@ -1196,12 -1185,11 +1196,17 @@@ export interface GenerationRequestcheckOutputs?: boolean;/** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */waitMs?: number;+ /** Server-only: the run's class in the line on this install's GPUs ("paid" goes before "free"), from the billing service. */+ class?: "paid" | "free";+ /** Server-only: a head start in line within its class (ms), from the billing service. */+ boostMs?: number;+ /** Server-only: a run on this install's GPUs made of light work only (joins, trims), free and never counted. */+ light?: boolean;+ /**+ * Server-only too: an account's run made on its own in a studio, not by a tool for one of its projects (a Cinema take,+ * a storyboard). Only such a run can move to the account's key while it waits (Run with your key).+ */+ standalone?: boolean;feature: string;presetId?: string;modelId: string;diff --cc src/lib/guest-access.tsindex 5a637b3a,d29165e3..84b7bbd4--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@@ -181,12 -170,9 +181,12 @@@ const GENERATION = /^\/api\/generations/** The generation an account's request is about (its own runs: the proxy checks it made it), or undefined. */export function accountGeneration(method: string, pathname: string): string | undefined {- // Cancel, and Fuobe Soul's finished picture for its own result.- const step = /^\/api\/generations\/([^/]+)\/(cancel|finish)$/.exec(pathname);+ // Cancel, Fuobe Soul's finished picture for its own result, and a smaller copy of its failed run's file.+ const step = /^\/api\/generations\/([^/]+)\/(cancel|finish|smaller)$/.exec(pathname);if (method === "POST" && step) return step[1];+ // A run's live preview picture while it works.+ const preview = /^\/api\/generations\/([^/]+)\/preview$/.exec(pathname);+ if ((method === "GET" || method === "HEAD") && preview) return preview[1];const one = GENERATION.exec(pathname);// PATCH: a like, a pin or a review status (all the route changes).return one && (method === "GET" || method === "HEAD" || method === "PATCH" || method === "DELETE") ? one[1] : undefined;diff --cc src/lib/relay.tsindex 5b55ec31,cfeeae39..923d0c99--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@@ -494,17 -364,8 +494,18 @@@ export function tabFailureWords(reasonreturn "The GPU that took this run refused it: it names a file path.";case "model-unverified":return "The GPU that took this run refused it: it needs a model file that GPU couldn't verify.";+ case "input-crashed":+ return "This run couldn't finish with these files or settings.";+ case "input-unreadable":+ return "A clip or sound in this run couldn't be read.";+ case "bad-ticket":+ return "This run couldn't be made with these settings.";+ case "unsafe-model":+ return "This 3D model couldn't be opened for the web, so it is kept as it is.";+ case "finish-failed":+ return "This run couldn't finish.";default:- return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;+ // An account reads no status code: its ComfyUI couldn't take the run, and what helps.+ return plain ? "Your ComfyUI couldn't take this run. Restart ComfyUI, then press Retry." : `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;}}diff --cc src/server/account-gpu.tsindex a9bfaf87,2f4a10c8..6e0312c7--- a/src/server/account-gpu.ts+++ b/src/server/account-gpu.ts@@@ -7,15 -7,15 +7,17 @@@ import { accountGpu, type Account, typimport type { OwnerGpuView } from "@/lib/connections";import { runnerFacts, type Principal } from "./computer/tasks";import { offeredSummary } from "./model-access";-import { MODELS } from "@/lib/catalog";-import { hostedUntestedSummary } from "@/lib/catalog/hosted-untested";+import { getModel, PRESETS } from "@/lib/catalog";+import { operationOutput } from "@/lib/catalog/types";import { PROVIDERS } from "./providers";import { blockedForAccounts, fetchPublic, isLoopbackGpu, peekText } from "./remote-fetch";+ import { redactKey } from "./provider-keys";+ import { networkCode, recordRunEvent } from "./run-events";import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";-import { balance as billingBalance, OPEN_POLICY, policy as billingPolicy, type Action, type Balance } from "./billing";+import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";import { poolReady } from "./hosted";+import { poolOwnModels } from "./pool-own-setup";+import { poolRulesOf, type PoolRules, type PresetModel } from "@/lib/pool-rules";import { diagnoseAddress, diagnoseGpu, gpuHostOf, type Diagnosis, type GpuFailure, type GpuPlace, type GpuStage } from "@/lib/diagnose";/** A diagnosis as the status strip sends it. */@@@ -345,17 -341,13 +358,24 @@@ export interface VisitorViewnotice?: { id: string; text: string; url?: string };}+declare global {+ var __fuobePresetModels: PresetModel[] | undefined;+}++/** Every preset with the open model it runs on and the kind it makes (for the pickers' rules): made once. */+const presetModels = (): PresetModel[] =>+ (globalThis.__fuobePresetModels ??= PRESETS.map((p) => {+ const m = p.open ? getModel(p.open.modelId) : undefined;+ return m && p.open ? { id: p.id, model: { id: m.id, kind: operationOutput(p.open.op, m.kind) } } : { id: p.id };+ }));++ /** Keys whose balance ran out on a run, as the status says them. */+ function emptyKeysOf(id: string): { emptyKeys: CloudProvider[] } | Record<string, never> {+ const info = accountKeyInfo(id);+ const empty = (Object.keys(info) as CloudProvider[]).filter((p) => info[p]?.balanceEmptyAt);+ return empty.length ? { emptyKeys: empty } : {};+ }+/** What the status strip and the composer show of a GPU that didn't answer: never more than the person's own GPU said. */export type VisitorTrouble = Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details">;diff --cc src/server/account-sweep.tsindex b7316aa3,32c0d9f7..22fe13ff--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@@ -13,9 -13,9 +13,10 @@@ import { strayAccountIds } from "./authimport { accountEvent, accountFacts } from "./billing";import { db } from "./db";import { handOversDone } from "./generations";+ import { forgetKeyNotes } from "./key-notes";import { deleteForever } from "./library";import { deleteAsset, scratchDir } from "./storage";+import { forgetAccountPresses } from "./run-requests";/*** Public sign-up: what an account keeps on this server goes in time. Its uploads after 14 days (even when a run stilldiff --cc src/server/computer/tasks.tsindex 470d059c,07bc28f6..fd1b34ba--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@@ -575,113 -394,9 +575,127 @@@ export function noteProgress(id: string}const node = str(r.node, 64);if (node) p.node = node;- progressMap().set(id, { ...progressMap().get(id), ...p });+ const d = rdb();+ d.transaction(() => {+ const cur = d.prepare(`SELECT progress_json FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json"> | undefined;+ if (!cur) return;+ d.prepare(`UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND ${STILL_HELD}`).run(JSON.stringify({ ...taskProgress(cur), ...p }), id, lease);+ }).immediate();+}++/** A task still sent to the computer or worker that holds the lease given (the query's last parameter). */+const STILL_HELD = `state IN (${SENT_STATES.map((x) => `'${x}'`).join(",")}) AND lease_hash IS ?`;++/**+ * Does this run show a preview picture while it works? Only with hosted runs on (an install without them shows what it+ * showed before), and not when the moderation service asked to see its outputs before they show (its stamp's+ * `checkOutputs`): a preview would show what the check holds back.+ */+export function previewShown(generationId: string): boolean {+ if (!hostedRunsOn()) return false;+ const g = rdb().prepare("SELECT request_json FROM generations WHERE id = ?").get(generationId) as { request_json: string } | undefined;+ if (!g) return false;+ try {+ return !(JSON.parse(g.request_json) as { checkOutputs?: boolean }).checkOutputs;+ } catch {+ return false;+ }+}+++/** A preview picture that couldn't be kept is logged once per app process. */+let previewWarned = false;++/**+ * Keep a worker's preview picture of its job (a JPEG of at most 64 KB, sent as base64 with a "running" report), in+ * place of the one before. One every 2 s at most: one that comes sooner is dropped, as is anything that isn't a JPEG+ * or is too big. Only a worker's task keeps one, and only for a run that shows previews (previewShown); a person's own+ * computer shows its own previews in its tab. Kept only while the attempt that sent it still holds the task: a picture+ * that comes after another app process sent it back in line or ended it is dropped, and no file is left behind.+ */+export function notePreview(+ t: Pick<TaskRow, "id" | "pools" | "preview" | "preview_at" | "lease_hash" | "generation_id" | "finish_json" | "extra_json">,+ base64: unknown,+ now = Date.now(),+): boolean {+ if (t.preview_at && now - t.preview_at < PREVIEW_LIMITS.everyMs - PREVIEW_SLACK_MS) return false;+ // A JPEG of at most PREVIEW_LIMITS.maxBytes (previewOf); a larger one, or anything else, is dropped.+ const jpeg = previewOf(base64);+ if (!jpeg || !showsPreview(t)) return false;+ const data = Buffer.from(jpeg, "base64");+ const file = previewFile(t.id);+ const part = `${file}.${process.pid}.part`;+ const d = rdb();+ let kept = false;+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(part, data, { mode: 0o600 });+ // The row and the file change together: dropProgress in another process waits for this, then removes both.+ kept = d+ .transaction((): boolean => {+ const changed = d.prepare("UPDATE relay_tasks SET preview_at = ? WHERE id = ? AND state IN ('queued','running') AND lease_hash IS ?").run(now, t.id, t.lease_hash).changes > 0;+ if (changed) fs.renameSync(part, file);+ return changed;+ })+ .immediate();+ } catch (e) {+ // A picture that can't be kept (a full disk, a file a reader has open) is only a picture: the report it came with+ // is taken all the same, and the next picture tries again.+ if (!previewWarned) console.warn(`[fuobe] a preview picture couldn't be kept: ${(e as Error).message}`);+ previewWarned = true;+ kept = false;+ } finally {+ if (!kept) {+ try {+ fs.rmSync(part, { force: true });+ } catch {}+ }+ }+ return kept;+}++/** Forget a task's progress and its preview picture (it ended, or went back in line, or its ComfyUI starts it again). */+export function dropProgress(id: string): void {+ rdb().prepare("UPDATE relay_tasks SET progress_json = NULL, preview_at = NULL WHERE id = ?").run(id);+ // (A picture a reader has open stays until the task's folder goes; nothing serves it once preview_at is gone.)+ try {+ fs.rmSync(previewFile(id), { force: true });+ } catch {}+}++/**+ * The latest preview picture of a run's job on the workers while it works, and when it came; null when there is none.+ * The caller has checked that the run is the viewer's own.+ */+export function runPreview(generationId: string): { path: string; at: number } | null {+ const t = previewTask(generationId);+ if (!t) return null;+ const file = previewFile(t.id);+ return fs.existsSync(file) ? { path: file, at: t.preview_at } : null;+}++const previewTask = (generationId: string) =>+ rdb()+ .prepare("SELECT id, preview_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state IN ('queued','running') AND preview_at IS NOT NULL ORDER BY created_at DESC LIMIT 1")+ .get(generationId) as { id: string; preview_at: number } | undefined;++/** When a run's latest preview picture came (null: it has none now), for the address its tile loads it from. */+export const runPreviewAt = (generationId: string): number | null => previewTask(generationId)?.preview_at ?? null;+++/**++ * A run's own job was made here (a task for it, in any state; a finishing job's, such as a camera path drawn for it,++ * isn't one). On this install's GPUs the job is a row of this database, so a send that was cut off either made it or not.++ */++export const hasJobFor = (generationId: string): boolean => !!rdb().prepare("SELECT 1 FROM relay_tasks WHERE generation_id = ? AND finish_json IS NULL LIMIT 1").get(generationId);++++/** A run that ended before it noted its job (a send cut off): that job stops too, in line or on a worker. */++export function stopJobsOf(generationId: string): void {++ const rows = rdb()++ .prepare(`SELECT id FROM relay_tasks WHERE generation_id = ? AND finish_json IS NULL AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`)++ .all(generationId, ...ACTIVE_STATES) as { id: string }[];++ for (const r of rows) endTask(r.id, "canceled", { error: "Stopped" });+ }+/*** A computer asks for work: first a task it took before and lost track of (a reload: not in `running`), then, when it is* the runner, the oldest waiting task. Null when there is none. The claim gets a new lease each time.diff --cc src/server/generations.tsindex 0651467a,b785ca1b..a82dd47e--- a/src/server/generations.ts+++ b/src/server/generations.ts@@@ -124,15 -128,8 +132,15 @@@ import { convertMask, decodePng, encodeimport { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";import { accountSend } from "./account-send";-import { stamped, stampOf, withRunStamp } from "./run-stamp";-import { placeInLine, poolWaitMs, runOnPool } from "./hosted";+import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";+import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";+import { placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";+import { hostedRunsOn } from "./hosted-switch";+import { catalogVersion } from "./computer/catalog-version";+import { poolLane, queueOfGeneration } from "./computer/pool";+import { noteCatalogProcess, processStart } from "./computer/ticket-refresh";- import { runPreviewAt } from "./computer/tasks";++import { hasJobFor, runPreviewAt, stopJobsOf } from "./computer/tasks";+import { runCeilingMs } from "./queue-settings";import { sweepBilling } from "./billing-outbox";import { inDemoScope, outsideDemo } from "./demo-scope";import { moderationConfigured } from "./moderation";@@@ -238,10 -229,13 +246,13 @@@ export function toGeneration(r: Row): GfolderId: lib.folder_id ?? null,pinnedAt: r.pinned_at ?? null,review: isReviewStatus(r.review) ? r.review : null,- ...(r.status === "failed" && r.fix_json && { fix: parseFix(r.fix_json) }),- ...(r.status === "failed" && r.fix_json && parseTrouble(r.fix_json)),+ ...(r.status === "failed" && r.fix_json && !pool && { fix: parseFix(r.fix_json) }),+ ...(r.status === "failed" && r.fix_json && !pool && parseTrouble(r.fix_json)),- // Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed.- ...((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && { notBilled: true as const }),+ // Waiting for its own GPU or key to come back: why, the buttons that help, and until when (never the owner's note).- ...(r.status === "queued" && !r.external_id && r.external_meta_json && waitingOf(r)),++ ...(r.status === "queued" && !r.external_id && r.external_meta_json && !pool && waitingOf(r)),+ // Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed. Not+ // said of a run whose send was under way when it stopped: the provider may have the job.+ ...((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && !maybeSent(r) && { notBilled: true as const }),// On this install's GPUs (hosted runs): what it cost, or that it cost nothing....(stored.place === "pool" && { place: "pool" as const }),...(stored.charge && r.status === "succeeded" && { charge: stored.charge }),@@@ -346,6 -272,191 +357,144 @@@ function parseTrouble(json: string): {}}+ /**+ * A waiting run's diagnosis (external_meta_json `heal`), as the Generation field. A run Run with your key can't move on+ * its own (keyMoveBlock: a step of a longer run, or a tool's run for one of the account's projects) never offers it,+ * also when its wait was kept before.+ */+ function waitingOf(r: Pick<Row, "id" | "depends_on" | "batch_id" | "request_json" | "external_meta_json">): { waiting: RunTrouble & { until?: number } } | Record<string, never> {+ const h = readMeta(r.external_meta_json).heal;+ if (!h?.trouble || typeof h.trouble.cause !== "string" || !Array.isArray(h.trouble.actions)) return {};+ const t = h.trouble.actions.some((a) => a.kind === "run-with-key") && keyMoveBlock(r) ? withoutKeyOffer(h.trouble) : h.trouble;+ return { waiting: { ...t, ...(h.deadline && { until: h.deadline }) } };+ }++ /** A run whose job was being sent when it stopped (a server cut off in the middle of the send): its provider may have it. */+ const maybeSent = (r: Pick<Row, "error" | "external_meta_json">): boolean => r.error === CUT_OFF_SENDING || typeof readMeta(r.external_meta_json).heal?.sending === "number";++ /**+ * A run that is one step of a longer one: it waits for an earlier step, or a later step (queued or running) waits for it.+ * Run with your key can't move such a step alone (the route answers 409 CHAINED_RUN, and its tile doesn't offer it).+ */+ function inChain(r: string | Pick<Row, "id" | "depends_on">): boolean {+ const id = typeof r === "string" ? r : r.id;+ const dependsOn = typeof r === "string" ? (db().prepare("SELECT depends_on FROM generations WHERE id = ?").pluck().get(id) as string | null | undefined) : r.depends_on;+ if (dependsOn) return true;+ return !!db().prepare(`SELECT 1 FROM generations WHERE status IN ('queued', 'running') AND ${DEPENDENTS_OF} LIMIT 1`).get({ id, quoted: JSON.stringify(id) });+ }++ /** Why Run with your key can't take a waiting run's place on its own: a step of a longer run, or a run of a project. */+ export type KeyMoveBlock = "chained" | "project";++ /**+ * Whether Run with your key can take this waiting run's place on its own (null), and why not. One check for its tile,+ * its next try's words and the route (POST /api/generations with `replaces`), so a button that shows can always act.+ *+ * - "chained": a step of a longer run (it waits for an earlier step, or a later step waits for it), or a job of a batch+ * whose other waiting job a later step waits for (the press moves the whole batch). Moved alone, the rest of the run+ * would go without it.+ * - "project": a run a tool made for one of the account's projects (a Cinema take, a storyboard, a short), even a take of+ * one step. The project keeps the run it made: a run made in its place would be outside it, and the take would show+ * Canceled. Only a run made on its own in a studio (stamped `standalone`, run-stamp.ts) moves.+ */+ export function keyMoveBlock(r: string | Pick<Row, "id" | "depends_on" | "batch_id" | "request_json">): KeyMoveBlock | null {+ const row =+ typeof r === "string" ? (db().prepare("SELECT id, depends_on, batch_id, request_json FROM generations WHERE id = ?").get(r) as Pick<Row, "id" | "depends_on" | "batch_id" | "request_json"> | undefined) : r;+ if (!row) return null;+ if (inChain(row)) return "chained";+ if (row.batch_id) {+ // The batch's other jobs the press would stop with it (the same request, not handed over yet).+ const jobs = db()+ .prepare("SELECT id FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS NULL AND status = 'queued' AND external_id IS NULL AND id != ?")+ .pluck()+ .all(row.batch_id, row.request_json, row.id) as string[];+ if (jobs.some((j) => inChain(j))) return "chained";+ }+ let standalone = false;+ try {+ standalone = (JSON.parse(row.request_json) as GenerationRequest).standalone === true;+ } catch {}+ return standalone ? null : "project";+ }++ /** What a step of a longer run that can't move to a key alone says (POST /api/generations with `replaces` on it). */+ export const CHAINED_RUN = "This step is part of a longer run, so it can't move to your key on its own. It goes on by itself, or cancel it and run the tool again with your key.";++ /** What a run of one of the account's projects says the same way (a Cinema take, a storyboard, a short). */+ export const PROJECT_RUN = "This run is part of one of your projects, so it can't move to your key on its own. It goes on by itself, or cancel it and run it again in its project with your key.";++ /** A trouble's buttons without Run with your key (a run that can't move to a key on its own). */+ const withoutKeyOffer = <T extends { actions: TroubleAction[] }>(t: T): T => ({ ...t, actions: t.actions.filter((a) => a.kind !== "run-with-key") });++ /**- * What a run keeps in external_meta_json before its provider has it (external_id NULL): which instance is handing it- * over or waiting on it (`lease`, renewed while it does), and, while it waits for its own GPU or key, how the wait goes- * (`heal`), so another instance (a restart, a deploy) goes on with it instead of failing it. Once handed over the column- * holds the provider's meta.++ * What a run keeps in external_meta_json before its provider has it (external_id NULL): while it waits for its own GPU++ * or key, how the wait goes (`heal`), so another app process (a restart, a deploy) goes on with it instead of failing it.++ * Which process is handing it over or waiting on it is its turn (submit_turns). Once handed over the column holds the++ * provider's meta.+ */+ interface PendingMeta {- lease?: { by: string; until: number };+ heal?: HealState;+ /** Sent again after its GPU lost it (once). */+ resent?: boolean;+ /** Which of its batch's jobs it is (its seed is the batch's + this). */+ jobIndex?: number;+ /**+ * A step of an account's longer run on its first try (nothing waited, so no `heal`): when its job began to be sent.+ * Cleared when the try fails and the step waits; gone once it is handed over (markSending).+ */+ sending?: number;+ }++ /** A run's wait for its own GPU or key, kept with it (survives a restart). */+ interface HealState {+ since: number;+ /** When it stops waiting (per cause, never past HEAL_CAP_MS from `since`). */+ deadline: number;+ /** When each cause was first seen: a change of cause (off, then starting up) gets that cause's whole budget. */+ firstSeen: Partial<Record<TroubleCause, number>>;+ tries: number;+ /** When it tries again. */+ next: number;+ index: number;+ rechecked?: boolean;+ /** The words of the last try (the run fails in them when the wait is over), and what helps meanwhile. */+ words?: string;+ trouble?: RunTrouble;+ /**+ * When a try began sending the job itself (markSending): an instance that takes the wait over later (this one cut off+ * in the middle of that send) doesn't send it again. Cleared when the try fails and the run waits again (markWaiting).+ */+ sending?: number;+ }++ const readMeta = (json: string | null | undefined): PendingMeta & Record<string, unknown> => {+ if (!json) return {};+ try {+ const m = JSON.parse(json) as unknown;+ return m && typeof m === "object" && !Array.isArray(m) ? (m as PendingMeta & Record<string, unknown>) : {};+ } catch {+ return {};+ }+ };+-declare global {- /** This process among the instances that share the database (a deploy runs two at once for a moment). */- var __fuobeInstance: string | undefined;- var __fuobeLeaseTimer: NodeJS.Timeout | undefined;-}-const instance = () => (globalThis.__fuobeInstance ??= nanoid(10));-+ /**- * How long an instance holds a run it is handing over (or waiting on) without renewing it, and how often it renews:- * past `ms`, another instance may take it (a restart, or a deploy's old instance gone). Tests make it shorter.++ * Who hands a run over: the app process that holds its turn (submit_turns, takeSubmitTurn), from the moment it begins to++ * send the run until it is handed over or stops, the wait for an account's own GPU or key included. Every app process++ * says every few seconds that it still runs (keepBeating), so a turn whose process stopped (a restart, a deploy's old++ * instance) is free once that process has gone quiet, and one it gave back (it exits, or it stops waiting on a run while++ * it drains) is free at once. One mechanism for every run: the owner's, an account's on its own GPU or key, and one on++ * this install's GPUs.+ */-export const LEASE = { ms: 60_000, renewMs: 15_000 };--/**- * Take a run that isn't handed over yet for this instance: only when no other instance holds it (its lease ran out, or- * it never had one). True when this instance holds it now.- */-function claim(id: string): boolean {- const now = Date.now();- return (- db()- .prepare(- `UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json(@lease))- WHERE id = @id AND external_id IS NULL AND status IN ('queued', 'running')- AND (NOT json_valid(external_meta_json) OR json_extract(external_meta_json, '$.lease.until') IS NULL- OR json_extract(external_meta_json, '$.lease.until') < @now OR json_extract(external_meta_json, '$.lease.by') = @me)`,- )- .run({ id, now, me: instance(), lease: JSON.stringify({ by: instance(), until: now + LEASE.ms }) }).changes > 0- );-}--/** Renew this instance's hold on every run it is handing over or waiting on (a timer; it keeps going while the server drains). */-function renewLeases(): void {- const ids = [...submitting()];- if (!ids.length) return;- const lease = JSON.stringify({ by: instance(), until: Date.now() + LEASE.ms });- const stmt = db().prepare(- `UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json(@lease))- WHERE id = @id AND external_id IS NULL AND status IN ('queued', 'running')`,- );- db().transaction(() => {- for (const id of ids) stmt.run({ id, lease });- })();-}+-/** Another instance holds this run now (its lease hasn't run out). */-function heldElsewhere(json: string | null | undefined): boolean {- const lease = readMeta(json).lease;- return !!lease && lease.by !== instance() && typeof lease.until === "number" && lease.until > Date.now();++/** Another app process took this run's turn (this one went quiet meanwhile): it is that process's to send now. */++function turnTaken(id: string): boolean {++ const held = db().prepare("SELECT held_by FROM submit_turns WHERE id = ?").pluck().get(id) as string | undefined;++ return held !== undefined && held !== runnerToken();+ }++ /** A row still waiting for its hand-over (queued or running, no job yet): only then is it changed. */+ const PENDING = "status IN ('queued', 'running') AND external_id IS NULL";+-/** Change a run only while it is still going (queued or running): a cancel or a failure written meanwhile stays. */-function updateIfGoing(id: string, fields: Partial<Row>, extra = ""): boolean {- const keys = Object.keys(fields);- return (- db()- .prepare(`UPDATE generations SET ${keys.map((k) => `${k} = @${k}`).join(", ")}${keys.length ? ", " : ""}updated_at = @__now WHERE id = @__id AND status IN ('queued', 'running')${extra}`)- .run({ ...fields, __now: Date.now(), __id: id }).changes > 0- );-}-function update(id: string, fields: Partial<Row>): void {const keys = Object.keys(fields);if (!keys.length) return;@@@ -1541,13 -1579,6 +1697,14 @@@ function chainMode(p: { demo: boolean;/** A waiting row's dependency ids as a json_each source (depends_on is one id, or a JSON list). */const DEP_IDS = "json_each(CASE WHEN substr(g.depends_on, 1, 1) = '[' AND json_valid(g.depends_on) THEN g.depends_on ELSE json_array(g.depends_on) END) d";+/**- * SQL: another app process that still runs is handing the run in `table` to its provider right now (takeSubmitTurn).- * Named parameters: @me (this process's name) and @quiet (since when a process that still runs has said so).++ * SQL: an app process that still runs holds the turn to hand the run in `table` to its provider (takeSubmitTurn: it is++ * sending it, or waiting on its own GPU or key for it); `others`: a process other than this one. Named parameters:++ * @__me (this process's name) and @__quiet (since when a process that still runs has said so).+ */- const SENT_ELSEWHERE = (table: string) =>- `EXISTS (SELECT 1 FROM submit_turns s JOIN app_processes p ON p.token = s.held_by WHERE s.id = ${table}.id AND s.held_by != @me AND p.seen_at >= @quiet)`;++const TURN_HELD = (table: string, others: boolean) =>++ `EXISTS (SELECT 1 FROM submit_turns s JOIN app_processes p ON p.token = s.held_by WHERE s.id = ${table}.id${others ? " AND s.held_by != @__me" : ""} AND p.seen_at >= @__quiet)`;+/*** Waiting steps that can move: none of their dependencies is still queued or running (so they launch), or one* failed, was canceled or is gone (so they fail now, not after the others finish). A per-frame render keeps@@@ -1561,8 -1592,7 +1718,8 @@@ const READY_DEPENDENTS = `SELECT g.* FRNOT EXISTS (SELECT 1 FROM ${DEP_IDS} JOIN generations dep ON dep.id = d.value WHERE dep.status IN ('queued', 'running'))OR EXISTS (SELECT 1 FROM ${DEP_IDS} LEFT JOIN generations dep ON dep.id = d.value WHERE dep.id IS NULL OR dep.status IN ('failed', 'canceled')))- AND NOT ${SENT_ELSEWHERE("g")}- ORDER BY g.created_at ASC LIMIT ?`;++ AND NOT ${TURN_HELD("g", true)}+ ORDER BY g.created_at ASC LIMIT @limit`;/** The error a waiting step gets when an input failed (framesProgress tells these from a step's own failure). */export const waitedOnFailure = (frame?: boolean) => `${frame ? "The previous frame" : "An earlier step"} didn't finish`;@@@ -1629,9 -1661,7 +1788,9 @@@ export const COMFY_WAIT = { ms: 60_000/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */async function advanceDependents(): Promise<void> {- const rows = db().prepare(READY_DEPENDENTS).all(50 + submitting().size) as Row[];+ const rows = db()+ .prepare(READY_DEPENDENTS)- .all({ limit: 50 + submitting().size, me: runnerToken(), quiet: Date.now() - QUIET_MS }) as Row[];++ .all({ limit: 50 + submitting().size, __me: runnerToken(), __quiet: Date.now() - QUIET_MS }) as Row[];// A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.let lookedAgain: Promise<boolean> | undefined;for (const r of rows) {@@@ -1671,9 -1708,17 +1837,25 @@@fail(`${earlier} ${short}`);continue;}- // Another instance (a deploy's other one) launching this step already: left to it.- if (!claim(r.id)) continue;+ // Every app process looks at the same waiting steps (a deploy runs two for a moment): only the one that takes the+ // step's turn sends it, so it is sent once.+ if (!takeSubmitTurn(r.id, { waiting: true })) continue;+ // A step that waited for its own GPU or key, taken over after a restart or a deploy (its wait is kept with it, as a+ // run's is: takeOver). One cut off in the middle of its send, on a later try or its first (markSending), may have- // reached its GPU or provider: never sent twice.++ // reached its GPU or provider: never sent twice. On this install's GPUs its job is a row of this database, so that is++ // known: with none made, nothing was sent and the step is sent now (in its run's place); with one made, it stops++ // with the step instead of running for nothing.+ const pending = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null);+ const heal = pending.heal;+ if ((heal && typeof heal.sending === "number") || typeof pending.sending === "number") {- fail(CUT_OFF_SENDING, "interrupted-sending");- continue;++ if (stored.place === "pool" && !hasJobFor(r.id)) notSending(r.id);++ else {++ fail(CUT_OFF_SENDING, "interrupted-sending");++ if (stored.place === "pool") stopJobsOf(r.id);++ handOverEnds(r.id);++ continue;++ }+ }submitting().add(r.id);let handedOff = false;// An account's step reads its inputs, and is planned, as its run was: as that account, on its own ComfyUI and its own@@@ -1757,11 -1789,11 +1941,11 @@@});// In the background: an upload must not hold up the runner's other polls.handedOff = true;- void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, 0, resume);} catch (e) {- fail((e as Error).message);+ fail((e as Error).message, e instanceof AccountRunError ? e.refusal.code : "chain");} finally {- if (!handedOff) submitting().delete(r.id);+ if (!handedOff) handOverEnds(r.id);}}}@@@ -1996,22 -2028,23 +2180,24 @@@ function submit(id: string, route: Modeif (!req.account) return submitNow(id, route, providerId, plan, req, index);// On this install's GPUs (hosted runs): as the account, on this install's ComfyUI server only.if (req.place === "pool") {- if (providerId !== "comfyui") {- updateIfGoing(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });- submitting().delete(id);+ // (A run is checked against the same table before it is made: hosted-run.ts stepsProblem.)+ if (!poolRunsProvider(providerId)) {- update(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });++ updateLive(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });+ handOverEnds(id);return Promise.resolve();}return runOnPool(req.account, () => withRunStamp(stampOf(req), () => submitNow(id, route, providerId, plan, req, index)));}const own = accountRun(req.account, providerId, "submit");if ("error" in own) {- update(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });- if (updateIfGoing(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null })) {++ if (updateLive(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null })) {+ ownFailed(id, req.account, { provider: providerId, model: plan.model.id, op: plan.op, stage: "submit" }, own.code);+ }// A chained step advanceDependents marked as being handed over isn't any more.- submitting().delete(id);+ handOverEnds(id);return Promise.resolve();}- return own.run(() => submitNow(id, route, providerId, plan, req, index));+ return own.run(() => submitNow(id, route, providerId, plan, req, index, resume));}/** A song's cloud tools (Mureka): the song's length and format are read before it's sent. */@@@ -2024,9 -2072,11 +2225,11 @@@ async function submitNowplan: ReturnType<typeof planGeneration>,req: GenerationRequest,index: number,+ resume?: HealState,): Promise<void> {- // Another app process that still runs is handing this run over right now: it is left to that process.- submitting().add(id);- // Another instance (a deploy's other one) holds this run: it is left to that one.- if (!claim(id)) {++ // Another app process that still runs is handing this run over, or waiting on it, right now (a deploy's overlap): it is++ // left to that process. So is a run that was cancelled, failed or handed over meanwhile.+ if (!takeSubmitTurn(id)) {submitting().delete(id);return;}@@@ -2037,46 -2086,87 +2240,87 @@@if (extra !== plan.params.extra) plan = { ...plan, params: { ...plan.params, extra } };}// An account's run on its own GPU or key (not on this install's GPUs): a passing problem (a GPU that is off or starting- // up, a busy or down provider) is waited out within a budget, the tile saying what it waits for; anything else fails- // in plain words, with what helps (src/lib/diagnose.ts). The owner's runs and runs on this install's GPUs fail at once,- // in their own words, as before.+ // up, a busy or down provider) is waited out within a budget, the tile saying what it waits for and what helps; the+ // wait is kept with the run, so a restart or a deploy goes on with it. Anything else fails in plain words, with what+ // helps (src/lib/diagnose.ts). The owner's runs and runs on this install's GPUs fail at once, in their own words.const account = req.account && req.place !== "pool" ? req.account : undefined;- const link = account && providerId === "comfyui" ? gpuLink(accountGpu(account)) : null;+ // The GPU this run was planned for (its scope read it when it began).+ const gpu = account && providerId === "comfyui" ? accountGpu(account) : null;+ const link = gpuLink(gpu);+ const pod = !!link && gpuHostOf(link.url).kind === "runpod";const started = Date.now();- let tries = 0;- let rechecked = false;+ const heal: HealState = resume ? { ...resume, firstSeen: { ...resume.firstSeen } } : { since: started, deadline: started, firstSeen: {}, tries: 0, next: 0, index };+ const facts = (more: Omit<RunFacts, "provider" | "model" | "op"> = {}): RunFacts => ({ provider: providerId, model: plan.model.id, op: plan.op, stage: "submit", ...more });+ const sent: HandOverCache = new Map();try {+ // Taken over (a restart, another instance): what is left of its wait first, then a look at its GPU.+ if (resume && resume.next > Date.now() && !(await pause(id, resume.next - Date.now()))) return;+ let lookFirst = !!resume && !!link;+ // The first try reads the GPU's last status check (never asked again here): one that is off waits at once,+ // instead of sending files to an address that answers nothing.+ const known = link && !resume ? cachedGpuState(account!, link.url) : undefined;for (;;) {+ // A try again (its wait kept with the run) while this server stops: nothing more is sent from here, and the run+ // is left as it is, for the next instance to go on with.+ if ((heal.tries > 0 || resume) && draining()) return;let error: unknown;- // The first try reads the GPU's last status check (never asked again here): one that is off waits at once,- // instead of sending files to an address that answers nothing.- const known = link && tries === 0 ? cachedGpuState(account!, link.url) : undefined;- if (known && !known.online && known.trouble?.retryable) error = troubleError(known.trouble);- else {+ if (heal.tries === 0 && !resume && known && !known.online && known.trouble?.retryable) error = troubleError(known.trouble);+ else if (link && (heal.tries > 0 || lookFirst)) {+ lookFirst = false;+ // Tried again: first a look at the GPU (its /system_stats, no files, outside the send line). Files go once it answers.+ const look = await probeGpu(account!, link);+ if (look !== "online") error = look;+ }+ if (!error) {try {- await handOver(id, route, providerId, plan, req, index);+ await handOver(id, route, providerId, plan, req, index, sent);if (link && statusOf(id) !== "failed") noteHandedOver(account!, link.url);+ if (account && heal.tries > 0) recordOwnRun({ run: id, account, ...facts({ attempt: heal.tries, waitedMs: Date.now() - heal.since }), hostKind: hostKindOf(gpu), outcome: "healed" });return;} catch (e) {+ // Another instance holds the run now, or this server is stopping: left as it is, for the instance that goes on.+ if (e instanceof LetGo) return;error = e;+ // A voice the provider cloned for this run (a billed step) is kept for the next try.+ const voice = (e as { voiceEmbedding?: unknown } | null)?.voiceEmbedding;+ if (typeof voice === "string") sent.set("voiceEmbedding", voice);}}+ // Cancelled, failed or taken by another instance, deleted, or handed over meanwhile: nothing more to do here.const status = statusOf(id);- // A cancel during the hand-over stays a cancel.- if (!status || status === "canceled") return;+ if (status !== "queued" && status !== "running") return;let trouble = account ? accountTrouble(error, account, providerId, "submit", req) : undefined;- const heal = trouble?.retryable ? retryPlan(trouble.cause) : null;- if (heal && trouble) {- tries++;- const wait = backoffMs(tries, heal, trouble.retryAfterMs) * SELF_HEAL.scale;- if (Date.now() - started + wait <= heal.budgetMs * SELF_HEAL.scale) {+ const budget = trouble?.retryable ? retryPlan(trouble.cause) : null;+ if (budget && trouble) {+ heal.tries++;+ const now = Date.now();+ // Each cause has its own budget from when it was first seen (a GPU that was off and is starting up now gets the+ // whole of starting up's), never past the cap from the first try.+ const first = (heal.firstSeen[trouble.cause] ??= now);+ heal.deadline = Math.min(heal.since + HEAL_CAP_MS * SELF_HEAL.scale, Math.max(heal.deadline, first + budget.budgetMs * SELF_HEAL.scale));+ const wait = backoffMs(heal.tries, budget, trouble.retryAfterMs) * SELF_HEAL.scale;+ if (now + wait <= heal.deadline) {if (link) noteGpuState(account!, link.url, false, { trouble: asStatus(error, trouble, link) });- update(id, { status: "queued", message: waitingWords(trouble, isCloudProvider(providerId) ? providerId : undefined) });+ // Kept with the run (another instance goes on with it after a restart or a deploy), the tile saying what it+ // waits for and showing what helps. A step of a longer run, or a run of one of the account's projects, doesn't+ // offer Run with your key: moved alone, it would leave its run or its project (keyMoveBlock).+ const shown = trouble.actions.some((a) => a.kind === "run-with-key") && keyMoveBlock(id) ? withoutKeyOffer(trouble) : trouble;+ if (!markWaiting(id, heal, shown, now + wait, waitingWords(shown, isCloudProvider(providerId) ? providerId : undefined, pod))) return;+ if (heal.tries === 1 || heal.firstSeen[trouble.cause] === now) ownEvent(id, account!, error, trouble, facts({ attempt: heal.tries, waitedMs: now - heal.since }), "waiting");if (!(await pause(id, wait))) return;- // The account moved its GPU meanwhile (another address, or this computer): this run was planned for the old one.- if (link && gpuLink(accountGpu(account!))?.url !== link.url) {- failRun(id, error, diagnoseGpuJob({ kind: "moved" }, { kind: "link", url: link.url }), req.account);- return;+ // The account changed its GPU meanwhile (a new address or password, this computer, or none): this run goes there.+ if (providerId === "comfyui" && account && gpuChanged(account, gpu)) {+ if (!accountGpu(account)) {+ failRun(id, error, diagnoseGpuJob({ kind: "disconnected" }, { kind: "link", url: link?.url ?? "" }), account, facts({ attempt: heal.tries }));+ return;+ }+ const p = replan(id, account);+ if (!p || p.providerId !== providerId) {+ failRun(id, error, diagnoseGpuJob({ kind: "moved" }, { kind: "link", url: link?.url ?? "" }), account, facts({ attempt: heal.tries }));+ return;+ }- if (!updateIfGoing(id, { message: "Your GPU has a new address, so this run goes there" }, " AND external_id IS NULL")) return;++ if (!updateLive(id, { message: "Your GPU has a new address, so this run goes there" }, " AND external_id IS NULL")) return;+ return await submit(id, p.route, p.providerId, p.plan, p.req, index, { ...heal, tries: 0, rechecked: false, next: 0 });}continue;}@@@ -2092,14 -2185,96 +2339,85 @@@return;}} finally {- submitting().delete(id);- // This server is stopping: a run still waiting here is let go of now, so the next instance takes it at its next- // look instead of after the hold runs out.- if (draining()) letGo(id);++ // Its turn goes, whatever happened: sent, failed, cancelled, or left waiting while this server stops (the next++ // process takes the wait over at once, instead of after this one has gone quiet).+ handOverEnds(id);}}-/** handOver stopped before the send: another instance holds the run, or this server is stopping while the run waited. */++/** handOver stopped before the send: another app process took the run, or this server is stopping while the run waited. */+ class LetGo extends Error {}+-/** Give up this instance's hold on a run still waiting for its hand-over (another instance may take it at once). */-function letGo(id: string): void {- db()- .prepare(- `UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.lease')- WHERE id = @id AND ${PENDING} AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.lease.by') = @me`,- )- .run({ id, me: instance() });-}-+ /**- * Just before a run's job is sent. A run that waited (its `heal` kept with it) is marked as being sent: an instance that++ * Just before a run's job is sent. A run that waited (its `heal` kept with it) is marked as being sent: a process that+ * takes the wait over later (this one cut off in the middle of the send, by a restart or a deploy) then doesn't send it- * a second time. So is a step of an account's own longer run on its first try (`own`): the instance that launches it- * after this one was cut off fails it instead of sending it again (advanceDependents). Throws LetGo when another- * instance holds the run, or when this server is stopping and the run waited (the next instance goes on with its wait,- * and sends it).++ * a second time. So is a step of an account's longer run on its first try (`step`: on its own GPU or key, or on this++ * install's GPUs): the process that launches it after this one was cut off never sends it again (advanceDependents).++ * Throws LetGo when another app process took the run's turn, or when this server is stopping and the run waited (the++ * next process goes on with its wait, and sends it).+ */-function markSending(id: string, own: boolean): void {++function markSending(id: string, step: boolean): void {+ const r = db().prepare(`SELECT external_meta_json, depends_on FROM generations WHERE id = ? AND ${PENDING}`).get(id) as Pick<Row, "external_meta_json" | "depends_on"> | undefined;+ if (!r) throw new Error("Stopped");- if (heldElsewhere(r.external_meta_json)) throw new LetGo("Held by another instance");++ if (turnTaken(id)) throw new LetGo("Taken by another app process");+ if (!readMeta(r.external_meta_json).heal) {- // A first try (nothing waited): a run's send cut off here fails at the next instance's look (sweepInterrupted).- if (own && r.depends_on) {++ // A first try (nothing waited): a run's send cut off here fails at the next process's look (sweepInterrupted).++ if (step && r.depends_on) {+ db()+ .prepare(`UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending', @now) WHERE id = @id AND ${PENDING}`)+ .run({ id, now: Date.now() });+ }+ return;+ }+ if (draining()) throw new LetGo("Stopping");+ db()+ .prepare(`UPDATE generations SET external_meta_json = json_set(external_meta_json, '$.heal.sending', @now) WHERE id = @id AND ${PENDING} AND json_type(external_meta_json, '$.heal') = 'object'`)+ .run({ id, now: Date.now() });+ }++ /** A send its provider answered with a refusal (a 4xx): the job was never taken. */+ function refusedAtSend(e: unknown): boolean {+ const status = (e as { status?: unknown } | null)?.status;+ return typeof status === "number" && status >= 400 && status < 500;+ }++ /** A send that is over without a job: the run's mark of being sent goes (it was never handed over). */+ function notSending(id: string): void {+ db()+ .prepare(`UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.heal.sending', '$.sending') WHERE id = ? AND ${PENDING} AND json_valid(external_meta_json)`)+ .run(id);+ }+/** Self-healing's clock: tests make it faster (0.001: a 30-minute wait takes 1.8 s). */export const SELF_HEAL = { scale: 1 };- /** Wait `ms`, looking every second whether the run was cancelled (false: it was, or it was deleted). */+ /** An account's job waiting in its own GPU's (or provider's) queue: how long without moving. Tests make it shorter. */+ export const OWN_QUEUE = { scale: 1 };+ /** The longest an account's job waits in its own GPU's (or provider's) queue, however it moves. */+ const OWN_QUEUE_CAP_MS = 2 * 60 * 60_000;++ /** The words a waiting run's tile shows, its wait kept with it (external_meta_json `heal`). False: it isn't waiting any more. */+ function markWaiting(id: string, heal: HealState, trouble: Diagnosis, next: number, message: string): boolean {+ heal.next = next;+ heal.words = trouble.words;+ heal.trouble = troubleOf(trouble);+ // The try that was sending failed: the next one may send.+ delete heal.sending;+ return (+ db()+ .prepare(+ `UPDATE generations SET status = 'queued', message = @message, updated_at = @now,+ external_meta_json = json_set(json_remove(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending'), '$.heal', json(@heal))+ WHERE id = @id AND ${PENDING}`,+ )+ .run({ id, message, now: Date.now(), heal: JSON.stringify(heal) }).changes > 0+ );+ }++ /**+ * Wait `ms`, looking every second whether the run still waits here. False: it was cancelled, failed, deleted or handed- * over meanwhile, another instance holds it, or this server is stopping (the next one goes on with it).++ * over meanwhile, another app process took its turn, or this server is stopping (the next one goes on with it).+ */async function pause(id: string, ms: number): Promise<boolean> {const end = Date.now() + ms;for (;;) {@@@ -2106,19 -2282,52 +2425,53 @@@const left = end - Date.now();if (left <= 0) return true;await new Promise((r) => setTimeout(r, Math.min(1000, left)));- const s = statusOf(id);- if (!s || s === "canceled") return false;- const r = db().prepare("SELECT status, external_id, external_meta_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id" | "external_meta_json"> | undefined;- if (!r || (r.status !== "queued" && r.status !== "running") || r.external_id || heldElsewhere(r.external_meta_json)) return false;++ const r = db().prepare("SELECT status, external_id FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id"> | undefined;++ if (!r || (r.status !== "queued" && r.status !== "running") || r.external_id || turnTaken(id)) return false;}}- /** A failed run in its words: an account's plain sentence (the owner's own detail as before), with what helps and "Fix it". */- function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account: string | undefined): void {- const fix = (e as { fix?: GenerationFix }).fix;+ /**+ * A failed run in its words: an account's plain sentence (the owner's own detail as before), with what helps and "Fix it".+ * Only while the run is still going: a Cancel (or another instance's failure) written meanwhile stays. `facts`: an+ * account's own run, logged and noted for the owner (run-events.ts).+ */+ function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account: string | undefined, facts?: RunFacts, own = !!facts): boolean {+ const fix = (e as { fix?: GenerationFix } | null)?.fix;const kept = keptFix(fix, trouble);// What the GPU was missing (a model, a node class) is kept, so the tile offers "Fix it", and its GPU check counts as stale.- // (Only while the run still goes: one another app process saved meanwhile stays saved.)- updateLive(id, { status: "failed", error: trouble?.words ?? (e as Error).message, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });- const done = updateIfGoing(id, { status: "failed", error: trouble?.words ?? String((e as Error | null)?.message ?? e), completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });++ // (Only while the run still goes: a Cancel, or a result another app process saved meanwhile, stays.)++ const done = updateLive(id, { status: "failed", error: trouble?.words ?? String((e as Error | null)?.message ?? e), completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ if (!done) return false;if (fix) markStale(account ? `acct:${account}` : "install");+ if (own && account && facts) ownEvent(id, account, e, trouble, facts, "failed");+ return true;+ }++ /** An account's own run (its GPU or key), never one on this install's GPUs: its account, else undefined. */+ const ownAccountOf = (req: Pick<GenerationRequest, "account" | "place"> | null | undefined): string | undefined => (req?.account && req.place !== "pool" ? req.account : undefined);++ /** ownAccountOf for a stored request (unreadable: none). */+ const ownAccountIn = (requestJson: string): string | undefined => {+ try {+ return ownAccountOf(JSON.parse(requestJson) as GenerationRequest);+ } catch {+ return undefined;+ }+ };++ /**+ * An account's own run that failed in this server's own words (cut off by a restart, refused as its account runs now, an+ * earlier step that didn't finish): the owner's log line and note, as failRun writes them for a GPU's or key's failure.+ * `cause` says which. Nothing for the owner's runs or runs on this install's GPUs (`account` undefined).+ */+ function ownFailed(id: string, account: string | undefined, f: RunFacts, cause: string): void {+ if (!account) return;+ try {+ const hostKind = f.provider === "comfyui" ? hostKindOf(accountGpu(account)) : undefined;+ recordOwnRun({ run: id, account, ...f, hostKind, cause, outcome: "failed" });+ } catch {+ // A log line never stops a run.+ }}/** generations.fix_json: what the GPU was missing (GenerationFix) and, for an account, what its GPU or key ran into. */@@@ -2254,20 -2557,22 +2701,23 @@@ function resend(r: Row, account: stringconst stored = JSON.parse(r.request_json) as GenerationRequest;const p = asAccount(account, () => prepare(stored));if (p.providerId !== r.provider) return false;+ const index = jobIndexOf(r, was);resentRuns().add(r.id);if (resentRuns().size > 5000) resentRuns().delete(resentRuns().values().next().value!);- // (Only while the run still goes: one another app process saved or ended meanwhile is left as it is.)- // (It takes its turn to be sent in the same step: a chain's step waiting to be sent again is never sent by another- // app process too.)- const again = db().transaction(() => {- const changed = db()- .prepare(- `UPDATE generations SET external_id = NULL, external_meta_json = @meta, status = 'queued', progress = NULL, message = @words, updated_at = @now- WHERE id = @id AND external_id = @ext AND status IN ('queued', 'running')`,- )- .run({ id: r.id, ext: r.external_id, meta: JSON.stringify({ resent: true, jobIndex: index }), words, now: Date.now() }).changes;- if (changed) db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);- return changed > 0;++ // (Only while the run still goes and is still the job that was lost: one another app process saved, ended or sent++ // again meanwhile is left as it is.) It takes its turn to be sent in the same step: a run waiting to be sent again is++ // never sent by another app process too.+ const again = db().transaction((): boolean => {- if (!updateLive(r.id, { external_id: null, external_meta_json: null, status: "queued", progress: null, message: words })) return false;++ const meta = JSON.stringify({ resent: true, jobIndex: index });++ if (!updateLive(r.id, { external_id: null, external_meta_json: meta, status: "queued", progress: null, message: words }, " AND external_id = @__ext", { __ext: r.external_id })) return false;+ db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);+ noteSubmitTurn(r.id);+ return true;})();- if (!again) return false;++ // (Saved, ended or sent again by another app process meanwhile: nothing more to do here, and nothing to fail.)+ if (!again) return true;submitting().add(r.id);- void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, index);return true;} catch {return false;@@@ -2638,6 -2977,12 +3122,13 @@@ async function handOver(id: string, rou// gated Restore or Detail Refine IC-LoRA) gets them downloaded too.await ensureLorasOnComfy([...(input.loras ?? []), ...graphLoras(route.endpoint, input.extra)], await comfyLoraFiles(route), (message) => update(id, { message }));}+ // A voice an earlier try had the provider clone (a billed step) is used again, not cloned twice.+ const cloned = sent?.get("voiceEmbedding");+ if (cloned && route.map?.cloneFirst && !input.voiceEmbedding) input.voiceEmbedding = cloned;+ // Nothing is sent once the run stopped being this one's to send (cancelled, failed, or taken by another instance).+ if (!going()) throw new Error("Stopped");- markSending(id, !!req.account && req.place !== "pool");++ // (Every account's step on its first try: on its own GPU or key, and on this install's GPUs.)++ markSending(id, !!req.account);const res = await adapter.submit({ generationId: id, model: plan.model, route, input });// A saved voice the cloud just cloned keeps the embedding (the owner's runs only), so its next line skips the clone.if (typeof res.meta?.voiceEmbedding === "string" && !req.account) void keepVoiceEmbedding(req.inputs?.voiceAudio, res.meta.voiceEmbedding).catch(() => {});@@@ -2683,8 -3039,8 +3188,11 @@@ const TIMEOUT_MS = 45 * 60 * 1000const WORLDCAST_TIMEOUT_MS = 3 * 60 * 60 * 1000;/** …and how long it may wait in the provider's queue first (a busy local GPU works through jobs one by one). */const QUEUE_TIMEOUT_MS = 4 * 60 * 60 * 1000;- /** A row this old with no external id, that no submit in this process is working on, was cut off by a restart. */- const STALE_SUBMIT_MS = 2 * 60 * 1000;-/** A row this old with no external id that no instance holds (LEASE) was cut off by a restart: a wait goes on, a hand-over fails. */++/**++ * A row this old with no external id whose turn no app process that still runs holds (takeSubmitTurn) was cut off by a++ * restart: a wait goes on, a hand-over fails. Tests make it shorter.++ */+ export const STALE_SUBMIT = { ms: 2 * 60 * 1000 };interface RunnerState {timer: NodeJS.Timeout;@@@ -2751,24 -3107,105 +3259,87 @@@ function startRunner(): void}/**- * Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. One another app- * process that still runs is sending (a deploy's overlap: an account's files waiting their turn to go) is left to it.- * Runs with no job yet that no instance holds any more (none renewed its hold: a restart, or a deploy's old instance gone).- * One waiting for its own GPU or key goes on here, with what is left of its wait (one instance takes it); one cut off in- * the middle of its hand-over can't be recovered, and fails. Runs at start and every tick.++ * Runs with no job yet that no app process that still runs is handing over (takeSubmitTurn: its process stopped, by a++ * restart, or a deploy's old instance gone). One waiting for its own GPU or key goes on here, with what is left of its++ * wait (one process takes it); one cut off in the middle of its hand-over can't be recovered, and fails. A run a process++ * that still runs is sending or waiting on (this one, or another in a deploy's overlap) is left to it. Runs at start and++ * every tick.*/function sweepInterrupted(): void {const now = Date.now();const rows = db()- .prepare("SELECT id, provider, model_id, op, request_json, external_meta_json FROM generations WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?")- .all(now - STALE_SUBMIT.ms) as Pick<Row, "id" | "provider" | "model_id" | "op" | "request_json" | "external_meta_json">[];+ .prepare(- `SELECT g.id FROM generations g WHERE g.status IN ('queued','running') AND g.external_id IS NULL AND g.depends_on IS NULL AND g.created_at < @before- AND NOT ${SENT_ELSEWHERE("g")}`,++ `SELECT g.id, g.provider, g.model_id, g.op, g.request_json, g.external_meta_json FROM generations g++ WHERE g.status IN ('queued','running') AND g.external_id IS NULL AND g.depends_on IS NULL AND g.created_at < @before AND NOT ${TURN_HELD("g", false)}`,+ )- .all({ before: now - STALE_SUBMIT_MS, me: runnerToken(), quiet: now - QUIET_MS }) as Pick<Row, "id">[];++ .all({ before: now - STALE_SUBMIT.ms, __me: runnerToken(), __quiet: now - QUIET_MS }) as Pick<Row, "id" | "provider" | "model_id" | "op" | "request_json" | "external_meta_json">[];const busy = submitting();for (const r of rows) {if (busy.has(r.id)) continue;- update(r.id, { status: "failed", error: "This run stopped before it started. Press Retry.", completed_at: Date.now(), message: null });+ const meta = readMeta(r.external_meta_json);- // An instance that is alive holds it (this one's renewals included).- if (meta.lease && typeof meta.lease.until === "number" && meta.lease.until > now) continue;+ if (meta.heal && takeOver(r, meta.heal)) continue;+ // A run that waited and was cut off in the middle of its send may have reached its GPU or provider: never sent twice.+ const cutOff = !!meta.heal && typeof meta.heal.sending === "number";+ const words = cutOff ? CUT_OFF_SENDING : "This run stopped before it started. Press Retry.";- if (updateIfGoing(r.id, { status: "failed", error: words, completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {++ // (Not one a process that still runs took meanwhile.)++ if (updateLive(r.id, { status: "failed", error: words, completed_at: Date.now(), message: null }, ` AND external_id IS NULL AND NOT ${TURN_HELD("generations", false)}`)) {+ ownFailed(r.id, ownAccountIn(r.request_json), factsOf(r, { stage: "submit" }), cutOff ? "interrupted-sending" : "interrupted");++ // On this install's GPUs, a job the cut-off send made stops with it (it would run for nothing).++ if (poolOf(r)) stopJobsOf(r.id);+ }+ }+ }+-/** A waiting run whose instance was cut off while it sent the job (its GPU or provider may have it): not sent again. */++/** A waiting run whose app process was cut off while it sent the job (its GPU or provider may have it): not sent again. */+ const CUT_OFF_SENDING = "This run was interrupted while it was being sent. Press Retry.";++ /**- * A waiting run no instance holds any more: taken by this one, planned again as its account runs now (its GPU, its keys),- * and its wait goes on where it was (its budget and its tries kept). False: it isn't one this can take (one cut off in- * the middle of its send among them: it fails, rather than being sent twice).++ * A waiting run whose turn no app process that still runs holds: taken by this one, planned again as its account runs now++ * (its GPU, its keys), and its wait goes on where it was (its budget and its tries kept). False: it isn't one this can++ * take (one cut off in the middle of its send among them: it fails, rather than being sent twice).+ */+ function takeOver(r: Pick<Row, "id" | "provider" | "model_id" | "op" | "request_json">, h: HealState): boolean {+ if (typeof h.sending === "number") return false;+ let stored: GenerationRequest;+ try {+ stored = JSON.parse(r.request_json) as GenerationRequest;+ } catch {+ return false;+ }+ const account = stored.account;+ if (!account || stored.place === "pool") return false;- // Another instance took it first.- if (!claim(r.id)) return true;++ // Another app process took it first.++ if (!takeSubmitTurn(r.id)) return true;+ let p: ReturnType<typeof prepare>;+ try {+ p = asAccount(account, () => prepare(stored));+ } catch (e) {+ // It can't run as the account runs now (its key removed, its model switched off): said in its own words.+ const refusal = e instanceof AccountRunError ? e.refusal.error : (e as Error).message;- if (updateIfGoing(r.id, { status: "failed", error: refusal, completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {++ if (updateLive(r.id, { status: "failed", error: refusal, completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {+ ownFailed(r.id, account, factsOf(r, { stage: "submit" }), e instanceof AccountRunError ? e.refusal.code : "refused");+ }++ handOverEnds(r.id);+ return true;+ }+ // Planned for another provider now (its GPU disconnected, another key): its polls would ask the provider it was made+ // for, so it stops, as a run whose GPU changed while it waited does.+ if (p.providerId !== r.provider) {+ if (r.provider === "comfyui") {+ const gpu = accountGpu(account);+ const end = diagnoseGpuJob({ kind: gpu ? "moved" : "disconnected" }, { kind: "link", url: gpuLink(gpu)?.url ?? "" });+ failRun(r.id, new Error("moved"), end, account, { provider: r.provider, model: p.plan.model.id, op: p.plan.op, stage: "submit" });- } else if (updateIfGoing(r.id, { status: "failed", error: "This run stopped because your keys changed while it waited. Press Retry.", completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {++ } else if (updateLive(r.id, { status: "failed", error: "This run stopped because your keys changed while it waited. Press Retry.", completed_at: Date.now(), message: null }, " AND external_id IS NULL")) {+ ownFailed(r.id, account, { provider: r.provider, model: p.plan.model.id, op: p.plan.op, stage: "submit" }, "keys-changed");+ }++ handOverEnds(r.id);+ return true;}+ submitting().add(r.id);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, typeof h.index === "number" ? h.index : 0, h);+ return true;}-declare global {- /** The renewal of this instance's holds (pointed at the newest code after a hot reload). */- var __fuobeLeaseRenew: (() => void) | undefined;-}--/**- * Renew this instance's holds every LEASE.renewMs. Not one of the runners a stopping server stops (shutdown.ts): a- * hand-over under way keeps its hold until it lands; a wait hands itself over (pause stops it).- */-function keepLeases(): void {- globalThis.__fuobeLeaseRenew = renewLeases;- if (globalThis.__fuobeLeaseTimer) return;- const next = () => {- globalThis.__fuobeLeaseTimer = setTimeout(() => {- try {- globalThis.__fuobeLeaseRenew?.();- } catch {- // A busy database: the next renewal comes well before a hold runs out.- }- next();- }, LEASE.renewMs);- globalThis.__fuobeLeaseTimer.unref?.();- };- next();-}-async function pollGuarded(r: Row): Promise<void> {const polling = (globalThis.__fuobeRunner!.polling ??= new Set());if (polling.has(r.id)) return;@@@ -2952,40 -3372,68 +3536,81 @@@ async function pollOne(r: Row): PromiserecordSubmission(r.id, res.sentAt);run = { submitted_at: res.sentAt, started_at: null };}+ // A job for the workers keeps its task's own clocks (pool.ts): its wait limit until a worker first takes it, then+ // the deadline of the attempt a worker holds, from its claim (the worker's own run limit and stall rule end an+ // attempt first). No clock of the runner's ends it, even when a poll of it fails (a busy database in a deploy's+ // overlap): the next tick asks again.+ const ownClocks = workersTask(ctx.meta, onPool) || (!!res && (res.state === "queued" || res.state === "running") && !!res.ownClocks);+ if (ownClocks && res?.state === "queued" && run.started_at) {+ db().prepare("UPDATE generation_runs SET started_at = NULL WHERE id = ?").run(r.id);+ run = { ...run, started_at: null };+ }// A job that has just left the queue gets its full running time from now.const startsNow = res?.state === "running" && !run.started_at;- const runMs = r.provider === "worldcast" ? WORLDCAST_TIMEOUT_MS : TIMEOUT_MS;+ // An account's own GPU (or its provider) whose queue keeps moving: the job waits on. Only a queue that hasn't moved+ // for the limit, or one waited in for 2 hours, ends it.+ const ownQueue = !!own && !onPool;+ let movedAt = typeof ctx.meta.queueMovedAt === "number" ? ctx.meta.queueMovedAt : run.submitted_at;+ const pos = res?.state === "queued" && typeof res.position === "number" ? res.position : undefined;+ // The job its GPU runs now (another one): a new one there is a queue that moves too.+ const busyWith = res?.state === "queued" && typeof res.busyWith === "string" ? res.busyWith : undefined;+ const wasBusyWith = typeof ctx.meta.busyWith === "string" ? ctx.meta.busyWith : undefined;+ const nearer = pos !== undefined && (typeof ctx.meta.queuePos !== "number" || pos < ctx.meta.queuePos);+ if (ownQueue && pos !== undefined && (nearer || busyWith !== wasBusyWith)) {+ // Its place first seen is where it starts; a place nearer the front, or another job running ahead of it, is a+ // queue that moves.+ if (typeof ctx.meta.queuePos === "number" && (nearer || (busyWith !== undefined && wasBusyWith !== undefined))) movedAt = now;+ const place = nearer ? pos : ctx.meta.queuePos;+ db()+ .prepare(+ "UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.queuePos', @place, '$.queueMovedAt', @movedAt, '$.busyWith', @busyWith) WHERE id = @id AND external_id IS NOT NULL",+ )+ .run({ id: r.id, place, movedAt, busyWith: busyWith ?? null });+ }+ // While a job runs ahead of it, that one job may take its own time (45 minutes) before the queue counts as stuck.+ const stillMs = ownQueue && busyWith ? Math.max(queueMs, TIMEOUT_MS) : queueMs;+ const queueOver = ownQueue+ ? now - Math.max(run.submitted_at, movedAt) > stillMs * OWN_QUEUE.scale || now - run.submitted_at > OWN_QUEUE_CAP_MS * OWN_QUEUE.scale+ : now - run.submitted_at > queueMs;- const overdue = run.started_at ? now - run.started_at > runMs : !startsNow && queueOver;+ const deadline = ownClocks && (res?.state === "queued" || res?.state === "running") ? res.deadline : undefined;+ // (Worked out only for a started job: a queued one never reads it.)+ const limitMs = ownClocks ? (deadline?.ms ?? 0) : run.started_at ? runningLimitMs(r, ctx.meta, account, onPool) : 0;- const overdue = ownClocks ? !!deadline && now > deadline.at : run.started_at ? now - run.started_at > limitMs : !startsNow && now - run.submitted_at > queueMs;++ const overdue = ownClocks ? !!deadline && now > deadline.at : run.started_at ? now - run.started_at > limitMs : !startsNow && queueOver;if (overdue) {// Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.- await adapterFor(r.provider, account)- .cancel?.(ctx)- .catch(() => {});- updateLive(r.id, {- status: "failed",- error: run.started_at || deadline+ const cancel = () =>+ adapterFor(r.provider, account)+ .cancel?.(ctx)+ .catch(() => {});- const words = run.started_at- ? `Timed out after ${runMs / 60_000} minutes`- : res?.state === "queued" && res.timeoutError- ? res.timeoutError- : onPool- ? POOL_WAITED- : account- ? `This waited over ${queueMs / 60_000} minutes to start. Press Retry.`- : "This took too long to start. Press Retry.";++ const words =++ run.started_at || deadline+ ? `Timed out after ${Math.round(limitMs / 60_000)} minutes`+ : res?.state === "queued" && res.timeoutError+ ? res.timeoutError+ : onPool+ ? POOL_WAITED+ : account+ ? `This waited over ${queueMs / 60_000} minutes to start. Press Retry.`- : "This took too long to start. Press Retry.",- completed_at: now,- message: null,- });++ : "This took too long to start. Press Retry.";+ if (ownQueue) {+ // An account's own GPU or key: why, in plain words, with what helps.+ const waited = Math.max(1, Math.round((now - run.submitted_at) / 60_000));++ const ran = Math.round(limitMs / 60_000);+ const link = r.provider === "comfyui" ? ownLink() : null;+ const ctxKey = isCloudProvider(r.provider) ? { provider: r.provider, other: otherKeyFor(own!, r.provider, r.model_id) } : null;+ const d: Diagnosis | undefined =+ res?.state === "queued" && res.timeoutError+ ? { cause: "gpu-offline", words: res.timeoutError, actions: [{ kind: "retry", label: "Retry" }, ...(/paired/i.test(res.timeoutError) ? [{ kind: "pair" as const, label: "Pair with a code", target: "/connect" }] : [])], retryable: false }+ : ctxKey- ? diagnoseKeyJob(run.started_at ? { kind: "too-long", minutes: runMs / 60_000 } : { kind: "busy", minutes: waited }, ctxKey)++ ? diagnoseKeyJob(run.started_at ? { kind: "too-long", minutes: ran } : { kind: "busy", minutes: waited }, ctxKey)+ : r.provider === "comfyui"- ? diagnoseGpuJob(run.started_at ? { kind: "too-long", minutes: runMs / 60_000 } : { kind: "busy", minutes: waited }, link ?? { kind: "computer" })++ ? diagnoseGpuJob(run.started_at ? { kind: "too-long", minutes: ran } : { kind: "busy", minutes: waited }, link ?? { kind: "computer" })+ : undefined;+ if (failRun(r.id, new Error(words), d, own, factsOf(r, { stage: "poll", waitedMs: now - run.submitted_at }))) await cancel();+ return;+ }+ await cancel();- updateIfGoing(r.id, { status: "failed", error: words, completed_at: now, message: null });++ updateLive(r.id, { status: "failed", error: words, completed_at: now, message: null });return;}if (!res) {@@@ -3012,10 -3459,13 +3637,14 @@@): undefined);// What the GPU was missing (a model, a node class): the tile offers "Fix it", and the GPU's check counts as stale.- const kept = keptFix(res.fix, own ? trouble : undefined);- updateLive(r.id, { status: "failed", error: (own && trouble?.words) || res.error, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ if (own) {+ failRun(r.id, Object.assign(new Error(res.error), { said: res.error, ...(res.fix && { fix: res.fix }) }), trouble, own, factsOf(r, { stage: "poll" }));+ return;+ }+ const kept = keptFix(res.fix, undefined);- updateIfGoing(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });- if (res.fix) markStale(account ? `acct:${account}` : "install");++ updateLive(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ // (A run on this install's GPUs says nothing about the account's own GPU.)+ if (res.fix && !onPool) markStale(account ? `acct:${account}` : "install");return;}// The Watermark Remover gave the original back (no clean repair was possible): no new result, the run says what to try.@@@ -3064,10 -3511,10 +3693,12 @@@} else {for (const o of keepMatte(res.outputs as RichOutput[], matte)) {try {- // An account's own GPU or key: a copy that breaks off is tried again a few times (the result is made, and paid).- outputs.push(await (own ? persistWithRetry(o, r.id) : persistOutput(o, r.id)));+ // An account's own GPU or key: a copy that breaks off is tried again (the result is made, and paid). The files a+ // result links to are kept once, before (never fetched again with each try of the main file).+ const linked = own ? await persistArtifacts(o.meta, r.id, o.url) : undefined;+ outputs.push(await (own ? persistWithRetry(o, r.id, linked) : persistOutput(o, r.id)));+ // Still saving: the turn is still this process's.+ claimFinish(r.id);} catch (e) {if (account) {for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);@@@ -3079,8 -3546,11 +3730,11 @@@// Its own GPU or key: why, and what helps (a file over the cap, an expired link, a GPU that went away).const trouble = own && !(e instanceof AccountFilesFull) ? saveTrouble(e, r.provider) : undefined;const why = e instanceof AccountFilesFull ? e.message : (trouble?.words ?? "We couldn't save this result. Press Retry.");- const kept = keptFix(undefined, trouble);- updateLive(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ if (own) failRun(r.id, Object.assign(new Error(why), { said: (e as Error).message }), trouble, own, factsOf(r, { stage: "result" }));+ else {+ const kept = keptFix(undefined, trouble);- updateIfGoing(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });++ updateLive(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ }return;}outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...inlineText(o.text, o.meta), ...(o.draftId ? { draftId: o.draftId } : {}) });@@@ -3149,178 -3614,6 +3803,180 @@@message: dropped ? `Kept ${ACCOUNT_LIMITS.outputsPerJob} of ${ACCOUNT_LIMITS.outputsPerJob + dropped} results` : null,completed_at: Date.now(),});+ if (!saved) dropSaved();+}++/**+ * Change a run the runner looked at, only while it still goes (queued or running, and not held for its output check) and+ * no other app process that still runs holds its turn to save its results. A look that took a while (a slow poll, a- * deploy's overlap) never takes a run another process saved, failed or canceled meanwhile back to an earlier state, and- * never fails a run another process is saving. Returns whether the change was made.++ * deploy's overlap, a wait for an account's own GPU) never takes a run another process saved, failed or canceled (or a++ * person canceled) meanwhile back to an earlier state, and never fails a run another process is saving. `extra`: more of++ * the WHERE clause (it may read @__me, @__quiet and @__now, and its own `params`). Returns whether the change was made.+ */- export function updateLive(id: string, fields: Partial<Row>, now = Date.now()): boolean {++export function updateLive(id: string, fields: Partial<Row>, extra = "", params: Record<string, unknown> = {}): boolean {+ const keys = Object.keys(fields);+ if (!keys.length) return false;++ const now = Date.now();+ return (+ db()+ .prepare(+ `UPDATE generations SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @__now WHERE id = @__id AND status IN ('queued', 'running') AND stage IS NULL+ AND NOT EXISTS (SELECT 1 FROM generation_runs t WHERE t.id = @__id AND t.finish_by IS NOT NULL AND t.finish_by != @__me AND t.finish_until >= @__now- AND NOT ${HOLDER_QUIET})`,++ AND NOT ${HOLDER_QUIET})${extra}`,+ )- .run({ ...fields, __now: now, __id: id, __me: runnerToken(), __quiet: now - QUIET_MS }).changes > 0++ .run({ ...params, ...fields, __now: now, __id: id, __me: runnerToken(), __quiet: now - QUIET_MS }).changes > 0+ );+}++/** How long an app process holds the turn to save a finished run's results (it renews it as it goes). */+const FINISH_TURN_MS = 5 * 60_000;+/** How often an app process says it still runs (keepBeating)… */+const BEAT_MS = 5_000;+/** …and how long after its last word it counts as stopped (killed, or crashed): its turns are free then, before they run out. */+export const QUIET_MS = 20_000;+/** A process quiet this long is forgotten. */+const FORGET_MS = 24 * 60 * 60_000;++/** SQL: the process holding turn `t` has been quiet since before @__quiet. A turn whose process has no row waits to run out. */+const HOLDER_QUIET = "EXISTS (SELECT 1 FROM app_processes p WHERE p.token = t.finish_by AND p.seen_at < @__quiet)";++declare global {+ /** This app process, as the runs whose results it saves name it. */+ var __fuobeRunnerToken: string | undefined;+ /** This app process's beat (keepBeating). */+ var __fuobeBeat: ReturnType<typeof setInterval> | undefined;+}++const runnerToken = () => (globalThis.__fuobeRunnerToken ??= `${process.pid}:${nanoid(12)}`);++/**+ * Say that this app process still runs, and which catalog version it makes job tickets for (ticket-refresh.ts: a newer+ * process is known from its start, before it serves any worker's claim).+ */+function beat(now = Date.now()): void {+ db()+ .prepare("INSERT INTO app_processes (token, started_at, seen_at) VALUES (?, ?, ?) ON CONFLICT(token) DO UPDATE SET seen_at = excluded.seen_at")+ .run(runnerToken(), now, now);+ noteCatalogProcess(catalogVersion(), processStart(), now);+}++/**+ * From now on, this app process says every 5 s that it still runs (in the database, so every process on it reads that,+ * wherever it runs), and another process takes a turn this one holds only once this one has been quiet for 20 s. When it+ * exits, it gives its turns back at once, so the app that starts next saves those runs straight away. Once per process:+ * the runner starts it, and so does the first turn it takes.+ */+function keepBeating(): void {+ if (globalThis.__fuobeBeat) return;+ const now = Date.now();+ try {+ beat(now);+ db().prepare("DELETE FROM app_processes WHERE seen_at < ?").run(now - FORGET_MS);+ // Turns to send a run that a process forgotten here held (it stopped part way): nobody holds them.+ db().prepare("DELETE FROM submit_turns WHERE held_by NOT IN (SELECT token FROM app_processes)").run();+ } catch (e) {+ console.warn(`[generations] app process: ${(e as Error).message}`);+ }+ const timer = setInterval(() => {+ try {+ beat();+ } catch {+ // A busy or closed database: the next beat says it.+ }+ }, BEAT_MS);+ timer.unref?.();+ globalThis.__fuobeBeat = timer;+ process.once("exit", giveTurnsBack);+}++/** This app process exits (it saves nothing more): its turns go back now, and its row with them. */+function giveTurnsBack(): void {+ try {+ const d = db();+ const me = runnerToken();+ d.transaction(() => {+ d.prepare("UPDATE generation_runs SET finish_by = NULL, finish_until = NULL WHERE finish_by = ? AND finish_until >= ?").run(me, Date.now());+ d.prepare("DELETE FROM submit_turns WHERE held_by = ?").run(me);+ d.prepare("DELETE FROM app_processes WHERE token = ?").run(me);+ })();+ } catch {+ // The database closed first: its turns are free once this process has been quiet for 20 s.+ }+}++/**+ * Take (or renew) this app process's turn to save a run's results: only while the run still goes, and only when no other+ * process holds the turn, or the one that holds it stopped part way (its turn ran out, or it has been quiet for 20 s:+ * killed, or crashed), so this one takes over. Two processes on one database (a deploy's overlap) never both save a+ * run, so a run is finished once.+ */+export function claimFinish(id: string, now = Date.now()): boolean {+ keepBeating();+ const d = db();+ return d+ .transaction((): boolean => {+ const g = d.prepare("SELECT status, stage FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "stage"> | undefined;+ // A run held for its output check was saved already.+ if (!g || (g.status !== "queued" && g.status !== "running") || g.stage) return false;+ const me = runnerToken();+ d.prepare("INSERT OR IGNORE INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, NULL)").run(id, now);+ return (+ d+ .prepare(+ `UPDATE generation_runs AS t SET finish_by = @__me, finish_until = @until WHERE t.id = @__id+ AND (t.finish_by IS NULL OR t.finish_by = @__me OR t.finish_until IS NULL OR t.finish_until < @__now OR ${HOLDER_QUIET})`,+ )+ .run({ __me: me, until: now + FINISH_TURN_MS, __id: id, __now: now, __quiet: now - QUIET_MS }).changes > 0+ );+ })+ .immediate();+}++/**- * Take this app process's turn to hand a run to its provider: only when no other app process that still runs holds it- * (one quiet for 20 s, or gone, holds nothing any more). `waiting`: only while the run still waits to be sent (queued,- * with no job at its provider yet), as a chain's next step is, which every app process looks at (advanceDependents).- * Two processes on one database (a deploy's overlap) never both send a run, and neither fails one the other is still- * sending (sweepInterrupted). handOverEnds gives the turn back.++ * Take this app process's turn to hand a run to its provider: only while the run still waits for its hand-over (queued++ * or running, with no job at its provider yet), and only when no other app process that still runs holds the turn (one++ * quiet for 20 s, or gone, holds nothing any more). The turn is held from the first look until the run is handed over or++ * stops, its wait for an account's own GPU or key included (submitNow). `waiting`: only while the run is queued, as a++ * chain's next step is, which every app process looks at (advanceDependents). Two processes on one database (a deploy's++ * overlap) never both send a run, neither fails one the other is still sending or waiting on (sweepInterrupted), and a++ * wait whose process stopped is taken over by one of them only (takeOver). handOverEnds gives the turn back.+ */+function takeSubmitTurn(id: string, o: { waiting?: boolean } = {}, now = Date.now()): boolean {+ keepBeating();+ const d = db();+ return d+ .transaction((): boolean => {- if (o.waiting) {- const g = d.prepare("SELECT status, external_id FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id"> | undefined;- if (!g || g.status !== "queued" || g.external_id) return false;- }++ const g = d.prepare("SELECT status, external_id FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id"> | undefined;++ if (!g || g.external_id || (g.status !== "queued" && (o.waiting || g.status !== "running"))) return false;+ return (+ d+ .prepare(+ `INSERT INTO submit_turns (id, held_by, held_at) VALUES (@id, @me, @now)+ ON CONFLICT(id) DO UPDATE SET held_by = excluded.held_by, held_at = excluded.held_at+ WHERE submit_turns.held_by = @me OR NOT EXISTS (SELECT 1 FROM app_processes p WHERE p.token = submit_turns.held_by AND p.seen_at >= @quiet)`,+ )+ .run({ id, me: runnerToken(), now, quiet: now - QUIET_MS }).changes > 0+ );+ })+ .immediate();+}++/** This app process holds the turn to send a run (inside a step that made the run wait to be sent again). */+function noteSubmitTurn(id: string): void {+ keepBeating();+ db()+ .prepare("INSERT INTO submit_turns (id, held_by, held_at) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET held_by = excluded.held_by, held_at = excluded.held_at")+ .run(id, runnerToken(), Date.now());+}++/** This app process has sent the run, or stopped trying: it is no longer being handed over here, and its turn goes. */+function handOverEnds(id: string): void {+ submitting().delete(id);+ try {+ db().prepare("DELETE FROM submit_turns WHERE id = ? AND held_by = ?").run(id, runnerToken());+ } catch {+ // A closed database: the turn is free once this process has been quiet for 20 s.+ }}/** Start (or keep running) the 3D finish of a job whose outputs are stored; it marks the job done when it ends. */@@@ -3691,17 -3971,6 +4348,31 @@@ export async function cancelGeneration(dropUnused(depIds(r.depends_on));}+/**+ * End a run as canceled, only while it still goes (queued or running: a run held for its output check too). A run that+ * was saved, failed or canceled since the cancel looked at it stays as it is, with its result and its report. A save+ * still under way doesn't stop it: the cancel wins, and that save ends with nothing kept (updateLive). Returns whether+ * the run was canceled.+ */+function markCanceled(id: string): boolean {+ const now = Date.now();+ return db().prepare("UPDATE generations SET status = 'canceled', completed_at = ?, message = NULL, updated_at = ? WHERE id = ? AND status IN ('queued', 'running')").run(now, now, id).changes > 0;+}+++/**++ * Stop the runs a new one takes the place of (Run with your key on a waiting run), in the same step that makes the new++ * run (POST /api/generations, inside admitRun's transaction): each one not handed over yet is canceled at once, so a press++ * on another of its batch's tiles, in this app process or another, finds nothing left to take. Its wait sees it at its++ * next look and gives its turn back; a send under way stops its job as it lands (handOver). A failed one stays as it is.++ */++export function stopReplaced(ids: readonly string[]): void {++ const pending = db().prepare("SELECT depends_on FROM generations WHERE id = ? AND status = 'queued' AND external_id IS NULL");++ for (const id of ids) {++ const r = pending.get(id) as Pick<Row, "depends_on"> | undefined;++ if (r && markCanceled(id)) dropUnused(depIds(r.depends_on));++ }++}++// ---------------------------------------------------------------------------// Fuobe Soul's post steps (the look's grade and overlay), made in the browser when the result arrives.diff --cc src/server/pool-limits.tsindex bbb8660f,00000000..3e1272bfmode 100644,000000..100644--- a/src/server/pool-limits.ts+++ b/src/server/pool-limits.ts@@@ -1,270 -1,0 +1,309 @@@+import "server-only";+import crypto from "node:crypto";+import { ACTIVE_RUNS_CODE } from "@/lib/guest-access";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "./account-files";+import { LoginGuard } from "./auth";+import type { Policy } from "./billing";+import { db } from "./db";++/**+ * The limits on an account's runs, counted in SQLite so that requests that arrive together, in one process or in two+ * (a deploy runs the old and the new server side by side for a moment), can never pass them together.+ *+ * - Every account run, wherever it goes: the studio's own limit of runs at once (ACCOUNT_LIMITS.activeRuns), as before.+ * - A run on this install's GPUs (hosted runs): also the policy's limits, counted on runs there only, never on runs on+ * the account's own GPU or its own key, nor on runs of light work only (joins, trims: free, never counted): runs at+ * once (`activeRuns`), runs waiting in line (`waiting`, no row started yet), runs made (Run pressed and admitted) in+ * the last hour (`runsPerHour`), and runs made from one client address in the last hour (`addressRunsPerHour`).+ * 0 or absent: no such limit.+ *+ * A run is one press of Run: its jobs and the steps its chains queue share a batch and count once.+ *+ * admitRun counts and makes the run's rows in one `BEGIN IMMEDIATE` transaction: SQLite lets one writer in at a time,+ * across processes, so the count it reads is the count it adds to.+ */++const HOUR = 60 * 60_000;+/** Runs made (let in) are kept this long for the hourly counts. */+const KEEP_MS = 2 * HOUR;++/** What a person reads when a limit on runs on this install's GPUs stops a run (plain words, no numbers of the studio's). */+export const POOL_LIMIT_WORDS = {+ active: (n: number) => `You have ${n} ${n === 1 ? "run" : "runs"} going. Start this one when one finishes.`,+ waiting: (n: number) => `You have ${n} ${n === 1 ? "run" : "runs"} in line. Start this one when one of them starts.`,+ hourly: "That's a lot of runs this hour. Try again later.",+ address: "That's a lot of runs from your network this hour. Try again later.",+};++export interface LimitRefusal {+ status: 429;+ error: string;+ code: string;+ retryAfterS: number;+}++/**+ * A run let in whose rows are still being made: a tool's start that awaits something (a channel, a plan) before it+ * makes its rows. It counts as one run going (and, on this install's GPUs, one in line) from the moment it is let in+ * until its rows exist (closeAdmission), so requests that arrive meanwhile meet the limits with it counted. One whose+ * process stopped before it closed counts for OPEN_ADMISSION_MS at most.+ */+export const OPEN_ADMISSION_MS = 10 * 60_000;++/**+ * Note a run let in whose rows aren't made yet (call it inside admitRun's `make`, so it is noted in the same locked step+ * as the count). `pool`: it counts against the policy's limits on runs on this install's GPUs too. Returns its key.+ */+export function openAdmission(accountId: string, pool: boolean, now = Date.now()): string {+ const key = crypto.randomBytes(12).toString("hex");+ db().prepare("INSERT INTO open_admissions (key, account, pool, at) VALUES (?, ?, ?, ?)").run(key, accountId, pool ? 1 : 0, now);+ return key;+}++/** The run's rows exist now (they count from here), or it was never made: it no longer counts as open. */+export function closeAdmission(key: string): void {+ db().prepare("DELETE FROM open_admissions WHERE key = ?").run(key);+}++/** An account's open admissions (all of them, or only those on this install's GPUs). */+function openCount(accountId: string, poolOnly: boolean, now = Date.now()): number {+ const r = db()+ .prepare(`SELECT COUNT(*) AS n FROM open_admissions WHERE account = ? AND at > ?${poolOnly ? " AND pool = 1" : ""}`)+ .get(accountId, now - OPEN_ADMISSION_MS) as { n: number };+ return r.n;+}+++/**++ * A run waiting for the account's own GPU to come back: no job yet, its wait kept with it (generations.ts `heal`). A run++ * waiting on a key (its provider busy or down) isn't one: it counts among the runs going now, so a provider that is down++ * can't gather more of them than that.++ */++const WAITING_FOR_GPU = "(provider = 'comfyui' AND external_id IS NULL AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.heal') IS NOT NULL)";++++/** Leave out the runs a new one takes the place of (a JSON list of ids). */++const NOT_REPLACED = "id NOT IN (SELECT value FROM json_each(?))";++++/** How a run made by a studio's Run (POST /api/generations) is counted against the studio's own limits. */++export interface StudioCount {++ /** The runs it takes the place of ("Run with your key" on a waiting run): they stop once it is made. */++ except?: readonly string[];++ /** Runs waiting for the account's own GPU are counted apart (accountWaitingRuns): they use nothing while they wait. */++ waitingApart?: boolean;++}+++/**+ * An account's runs going now (queued or running), wherever they run: a run's jobs and chain steps share a batch. A run- * let in whose rows are still being made counts too (openAdmission).++ * let in whose rows are still being made counts too (openAdmission). `o`: as a studio's Run counts them (StudioCount).+ */- export function accountActiveRuns(accountId: string): number {++export function accountActiveRuns(accountId: string, o: StudioCount = {}): number {++ const waiting = o.waitingApart ? ` AND NOT ${WAITING_FOR_GPU}` : "";+ const r = db()- .prepare("SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?")- .get(accountId) as { n: number };++ .prepare(++ `SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?${waiting} AND ${NOT_REPLACED}`,++ )++ .get(accountId, JSON.stringify(o.except ?? [])) as { n: number };+ return r.n + openCount(accountId, false);+}+++/** An account's runs waiting for its own GPU to come back (WAITING_FOR_GPU), but those a new run takes the place of. */++export function accountWaitingRuns(accountId: string, except: readonly string[] = []): number {++ const r = db()++ .prepare(`SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status = 'queued' AND json_extract(request_json, '$.account') = ? AND ${WAITING_FOR_GPU} AND ${NOT_REPLACED}`)++ .get(accountId, JSON.stringify(except)) as { n: number };++ return r.n;++}+++/**+ * An account's runs going now on this install's GPUs, and how many of them haven't started yet (no row of theirs has).+ * Runs of light work only (joins, trims) don't count. A run let in whose rows are still being made counts as one in line.+ */+export function poolRunCounts(accountId: string): { active: number; waiting: number } {+ const r = db()+ .prepare(+ `SELECT COUNT(*) AS active, COALESCE(SUM(CASE WHEN started = 0 THEN 1 ELSE 0 END), 0) AS waiting FROM (+ SELECT COALESCE(g.batch_id, g.id) AS k, MAX(CASE WHEN r.started_at IS NOT NULL THEN 1 ELSE 0 END) AS started+ FROM generations g LEFT JOIN generation_runs r ON r.id = g.id+ WHERE g.status IN ('queued', 'running') AND json_extract(g.request_json, '$.account') = ? AND json_extract(g.request_json, '$.place') = 'pool'+ AND json_extract(g.request_json, '$.light') IS NOT 1+ GROUP BY k)`,+ )+ .get(accountId) as { active: number; waiting: number };+ const open = openCount(accountId, true);+ return { active: r.active + open, waiting: r.waiting + open };+}++/**+ * Forget one hourly admission (admitRun noted it at `at`) of a run that made nothing: no rows, nothing sent, so it isn't+ * one of the hour's runs.+ */+export function forgetAdmission(accountId: string, at: number): void {+ db().prepare("DELETE FROM pool_admissions WHERE id = (SELECT id FROM pool_admissions WHERE account = ? AND at = ? ORDER BY id DESC LIMIT 1)").run(accountId, at);+}++declare global {+ var __fuobeAddressSalt: { db: unknown; salt: string } | undefined;+ /** When this process last forgot old admissions (prunePoolAdmissions). */+ var __fuobePoolAdmissionsPruned: number | undefined;+}++/**+ * Forget the runs (and the client addresses, kept as salted hashes) older than KEEP_MS: the hourly counts read only the+ * last hour. The runner calls this on every turn, so nothing stays longer, whether or not another run comes; it looks at+ * most once a minute in each process (`force`: now).+ */+export function prunePoolAdmissions(now = Date.now(), force = false): number {+ if (!force && now - (globalThis.__fuobePoolAdmissionsPruned ?? 0) < 60_000) return 0;+ globalThis.__fuobePoolAdmissionsPruned = now;+ db().prepare("DELETE FROM open_admissions WHERE at < ?").run(now - OPEN_ADMISSION_MS);+ return db().prepare("DELETE FROM pool_admissions WHERE at < ?").run(now - KEEP_MS).changes;+}++/**+ * The salt the client addresses are kept under: made once per install, never sent anywhere. Read (and made, the first+ * time) once per process and database, so counting an address never takes the database's write lock again.+ */+function salt(): string {+ const d = db();+ const kept = globalThis.__fuobeAddressSalt;+ if (kept?.db === d) return kept.salt;+ const read = () => (d.prepare("SELECT value FROM settings WHERE key = 'pool.addressSalt'").get() as { value: string } | undefined)?.value;+ let value = read();+ if (!value) {+ d.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES ('pool.addressSalt', ?)").run(crypto.randomBytes(32).toString("hex"));+ value = read()!;+ }+ globalThis.__fuobeAddressSalt = { db: d, salt: value };+ return value;+}++/**+ * The client's address as the hourly count keeps it (a salted hash, never the address), or null when clients can't be+ * told apart (no trusted proxy: every request would count as one client).+ */+export function clientAddress(request: Request): string | null {+ const key = LoginGuard.clientKey(request.headers);+ if (key === LoginGuard.DIRECT) return null;+ return crypto.createHmac("sha256", salt()).update(key).digest("hex").slice(0, 32);+}++const since = (column: "account" | "addr", value: string, from: number) =>+ db().prepare(`SELECT COUNT(*) AS n, MIN(at) AS oldest FROM pool_admissions WHERE ${column} = ? AND at > ?`).get(value, from) as { n: number; oldest: number | null };++/** Seconds until the oldest of an hour's runs leaves the hour. */+const retryAfter = (oldest: number | null, now: number) => Math.max(60, Math.ceil(((oldest ?? now) + HOUR - now) / 1000));++/**+ * The first of the policy's limits this run would pass, or null. `addr` may be a function: it is asked only when the+ * policy counts runs per address.+ */+export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limits">, addr: string | null | (() => string | null), now = Date.now()): LimitRefusal | null {+ const lim = policy.limits ?? ({} as Policy["limits"]);+ const positive = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);+ const activeMax = positive(lim.activeRuns);+ const waitingMax = positive(lim.waiting);+ const hourMax = positive(lim.runsPerHour);+ const addrMax = positive(lim.addressRunsPerHour);+ if (activeMax || waitingMax) {+ const c = poolRunCounts(accountId);+ if (activeMax && c.active >= activeMax) return { status: 429, error: POOL_LIMIT_WORDS.active(c.active), code: ACTIVE_RUNS_CODE, retryAfterS: 30 };+ if (waitingMax && c.waiting >= waitingMax) return { status: 429, error: POOL_LIMIT_WORDS.waiting(c.waiting), code: ACTIVE_RUNS_CODE, retryAfterS: 30 };+ }+ if (hourMax) {+ const h = since("account", accountId, now - HOUR);+ if (h.n >= hourMax) return { status: 429, error: POOL_LIMIT_WORDS.hourly, code: "limit", retryAfterS: retryAfter(h.oldest, now) };+ }+ const address = addrMax ? (typeof addr === "function" ? addr() : addr) : null;+ if (address) {+ const h = since("addr", address, now - HOUR);+ if (h.n >= addrMax) return { status: 429, error: POOL_LIMIT_WORDS.address, code: "limit", retryAfterS: retryAfter(h.oldest, now) };+ }+ return null;+}+- /** The studio's own limit of runs at once (every account run, wherever it goes), as a refusal. */- function accountLimitRefusal(accountId: string): LimitRefusal | null {- return accountActiveRuns(accountId) >= ACCOUNT_LIMITS.activeRuns ? { status: 429, error: ACCOUNT_MESSAGES.activeRuns, code: ACTIVE_RUNS_CODE, retryAfterS: 30 } : null;++/**++ * The studio's own limit of runs at once (every account run, wherever it goes), as a refusal. `studio`: a studio's Run,++ * counted as StudioCount says; with `mayWait` (a run for the account's own GPU, which may wait for it) the runs waiting++ * for that GPU meet a limit of their own too.++ */++function accountLimitRefusal(accountId: string, studio?: StudioCount & { mayWait?: boolean }): LimitRefusal | null {++ if (studio?.mayWait && accountWaitingRuns(accountId, studio.except) >= ACCOUNT_LIMITS.waitingRuns) {++ return { status: 429, error: ACCOUNT_MESSAGES.waitingRuns, code: ACTIVE_RUNS_CODE, retryAfterS: 30 };++ }++ const n = accountActiveRuns(accountId, studio ? { except: studio.except, waitingApart: true } : {});++ return n >= ACCOUNT_LIMITS.activeRuns ? { status: 429, error: ACCOUNT_MESSAGES.activeRuns, code: ACTIVE_RUNS_CODE, retryAfterS: 30 } : null;+}++/** A refusal thrown inside admitRun's transaction, so nothing `make` wrote is kept. */+export class AdmitRefused extends Error {+ constructor(readonly refusal: LimitRefusal | { status: number; error: string; code: string; retryAfterS?: number }) {+ super(refusal.error);+ }+}++/** What admitRun answers: the run made, the refusal, or (with `prior`) what this same request made already. */+export type Admitted<T, P = never> = { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | ([P] extends [never] ? never : { ok: false; prior: P });++/**+ * Count, and make the run (`make`) only if it fits: the studio's own limit for every account run, and with `pool` the+ * policy's limits on runs on this install's GPUs. All in one BEGIN IMMEDIATE transaction; a run on this install's GPUs is+ * noted for the hourly counts in the same transaction. `make` may throw AdmitRefused (or anything else) to keep nothing.+ * `prior`, looked at first in the same transaction: what this same request made already (a resend of one press of Run,+ * run-requests.ts); when it says anything, nothing is counted or made, and it is the answer. `refused`, called in the+ * same transaction when the run is not made (a limit, AdmitRefused, or another error from `make`, which is thrown again+ * once the transaction ends): what it writes is kept, while nothing `make` wrote is.+ */+export function admitRun<T, P = never>(+ o: {+ accountId: string;+ pool: { policy: Pick<Policy, "limits">; addr: string | null } | null;++ /** A studio's Run (POST /api/generations): counted as accountLimitRefusal says. */++ studio?: StudioCount & { mayWait?: boolean };+ now?: number;+ prior?: () => P | null;+ refused?: (why: AdmitRefused["refusal"] | Error) => void;+ },+ make: () => T,+): Admitted<T, P> {+ type Answer = { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P };+ const now = o.now ?? Date.now();+ const d = db();+ const refused = o.refused;+ let failed: { e: unknown } | null = null;+ let answer: Answer | null;+ try {+ answer = d+ .transaction((): Answer | null => {+ const prior = o.prior?.() ?? null;+ if (prior !== null) return { ok: false, prior };- const refusal = accountLimitRefusal(o.accountId) ?? (o.pool ? poolLimitRefusal(o.accountId, o.pool.policy, o.pool.addr, now) : null);++ const refusal = accountLimitRefusal(o.accountId, o.studio) ?? (o.pool ? poolLimitRefusal(o.accountId, o.pool.policy, o.pool.addr, now) : null);+ if (refusal) {+ refused?.(refusal);+ return { ok: false, refusal };+ }+ let value: T;+ if (!refused) value = make();+ else {+ try {+ // In a savepoint: a make that refuses or fails keeps nothing it wrote, and the refusal is still noted.+ value = d.transaction(make)();+ } catch (e) {+ refused(e instanceof AdmitRefused ? e.refusal : e instanceof Error ? e : new Error(String(e)));+ if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };+ failed = { e };+ return null;+ }+ }+ if (o.pool) {+ d.prepare("INSERT INTO pool_admissions (account, addr, at) VALUES (?, ?, ?)").run(o.accountId, o.pool.addr, now);+ prunePoolAdmissions(now, true);+ }+ return { ok: true, value };+ })+ .immediate();+ } catch (e) {+ if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };+ throw e;+ }+ if (failed) throw (failed as { e: unknown }).e;+ return answer! as Admitted<T, P>;+}diff --cc src/server/providers/comfyui.tsindex afcd4347,b420ac9e..6b41fc57--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@@ -34,13 -104,11 +34,14 @@@ import { probeAvi } from "../avi-probe"import { probeWebm } from "../webm-probe";import { adoptFile, contentTypeFor, readRef, saveFile, scratchDir } from "../storage";import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";+import { addressKind } from "@/lib/page-place";+import { graphProblem } from "@/lib/local-comfy";+import { runStamp } from "../run-stamp";import { discardBody, fetchPublic, peekText, RemoteFetchError } from "../remote-fetch";import { zipToFile } from "../zip";-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskFloorBytes, diskFreeBytes, diskHasRoom, filesFullMessage } from "../account-files";import { accountSend } from "../account-send";+ import { redactKey } from "../provider-keys";import { outsideTenant, runAsTenant, tenantAccount } from "../tenant";import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";import { ProviderError, type PollResult, type ProviderAdapter, type RemoteOutput } from "./types";diff --cc src/server/providers/types.tsindex 4a38c5ab,77e98749..a2fba474--- a/src/server/providers/types.ts+++ b/src/server/providers/types.ts@@@ -32,13 -32,21 +32,25 @@@ export interface RemoteOutput/*** What a poll found. A job on someone's own computer (comfyui.ts) also says when it reached their ComfyUI (`sentAt`: the* queue clock starts there, not while it waited for their tab), what to say if it waits too long (`timeoutError`), and- * what was missing when it failed (`fix`: the tile's "Fix it").+ * what was missing when it failed (`fix`: the tile's "Fix it"). A job for the workers keeps its task's own clocks+ * (`ownClocks`): the runner then sets no wait limit of its own, and ends it only past the deadline of the attempt a+ * worker holds now (`deadline`: when, and how long that attempt may last).*/export type PollResult =- | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; ownClocks?: true; deadline?: { at: number; ms: number } }+ | {+ state: "queued";+ progress?: number;+ message?: string;+ sentAt?: number;+ timeoutError?: string;++ ownClocks?: true;++ deadline?: { at: number; ms: number };+ /** Jobs ahead of it in the queue (0: next). */+ position?: number;+ /** The job its GPU runs now (another one): a new one there is a queue that moves, and one job may take its own time. */+ busyWith?: string;+ }- | { state: "running"; progress?: number; message?: string; sentAt?: number }+ | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true; deadline?: { at: number; ms: number } }| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }/*** `trouble`: an account's own GPU, why in plain words with what helps (src/lib/diagnose.ts). `lost`: its ComfyUIdiff --cc src/server/run-stamp.tsindex f8ee703a,2738dfd9..b78750b7--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@@ -10,12 -10,9 +10,14 @@@ import type { GenerationRequest } from* - `place: "pool"`: the run goes to this install's GPUs (hosted runs, hosted.ts), not the account's own.* - `hold`: the billing service's hold for the run (billing.ts reserve); every row reports to it once (billing-outbox.ts).* - `charge`: the words the billing service gave for the charge ("7 units"), shown on the result.+ * - `charged`: the hold set an amount aside (a free run's sets aside nothing), so a run that ends early says it wasn't+ * charged.* - `checkOutputs`: the moderation service asked to see this run's outputs before they show (moderation.ts).+ * - `class` and `boostMs`: its class in the line ("paid" before "free") and its head start inside that class.+ * - `light`: a run on this install's GPUs made of light work only (joins, trims): free, and never counted against the+ * policy's limits on runs there (pool-limits.ts).+ * - `standalone`: an account's run made on its own in a studio (POST /api/generations, Image to 3D's route), not by a+ * tool for one of its projects: Run with your key may take its place while it waits (generations.ts keyMoveBlock).*/export interface RunStamp {place?: "pool";@@@ -25,12 -21,8 +27,14 @@@checkOutputs?: boolean;/** How long it may wait in line on this install's GPUs (ms), from the billing service. */waitMs?: number;+ /** Its class in the line on this install's GPUs, from the billing service (none: "free"). */+ class?: "paid" | "free";+ /** A head start in line within its class (ms), from the billing service. */+ boostMs?: number;+ /** Light work only (hosted-run.ts lightRun): free, and not counted against the policy's limits. */+ light?: boolean;+ /** Made on its own in a studio, not by a tool for one of the account's projects. */+ standalone?: boolean;}declare global {@@@ -46,7 -38,7 +50,7 @@@ export const withRunStamp = <T,>(stampexport const runStamp = (): RunStamp | undefined => store().getStore();/** The server-only fields of a request. */- export const STAMP_FIELDS = ["place", "hold", "charge", "charged", "checkOutputs", "waitMs", "class", "boostMs", "light"] as const;-export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs", "standalone"] as const;++export const STAMP_FIELDS = ["place", "hold", "charge", "charged", "checkOutputs", "waitMs", "class", "boostMs", "light", "standalone"] as const;/** A request with the current stamp's fields, and none of a stored request's own. */export function stamped(req: GenerationRequest): GenerationRequest {@@@ -59,33 -51,13 +63,35 @@@...(s.place && { place: s.place }),...(s.hold && { hold: s.hold }),...(s.charge && { charge: s.charge }),+ ...(s.charged && { charged: true }),...(s.checkOutputs && { checkOutputs: true }),...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),+ ...(s.class === "paid" && { class: "paid" as const }),+ ...(s.boostMs && s.boostMs > 0 && { boostMs: s.boostMs }),+ ...(s.light && { light: true }),+ ...(s.standalone && { standalone: true }),};}/** A stored request's stamp, to run a later step of it (advanceDependents, polls) as it was decided. */export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[number]>): RunStamp {- return { ...(req.place === "pool" && { place: "pool" as const }), ...(req.hold && { hold: req.hold }), ...(req.charge && { charge: req.charge }), ...(req.checkOutputs && { checkOutputs: true }), ...(req.waitMs && { waitMs: req.waitMs }), ...(req.standalone && { standalone: true }) };+ return {+ ...(req.place === "pool" && { place: "pool" as const }),+ ...(req.hold && { hold: req.hold }),+ ...(req.charge && { charge: req.charge }),+ ...(req.charged && { charged: true }),+ ...(req.checkOutputs && { checkOutputs: true }),+ ...(req.waitMs && { waitMs: req.waitMs }),+ ...(req.class === "paid" && { class: "paid" as const }),+ ...(req.boostMs && req.boostMs > 0 && { boostMs: req.boostMs }),+ ...(req.light && { light: true }),++ ...(req.standalone && { standalone: true }),+ };+}++/** A request without its server-only fields: what a browser or a script is sent (and so what a retry sends back). */+export function withoutStamp<T extends Partial<Record<(typeof STAMP_FIELDS)[number], unknown>>>(req: T): Omit<T, (typeof STAMP_FIELDS)[number]> {+ const out = { ...req };+ for (const k of STAMP_FIELDS) delete out[k];+ return out;}diff --cc tests/helpers/app-process-child.tsindex 635460f6,00000000..09b62a65mode 100644,000000..100644--- a/tests/helpers/app-process-child.ts+++ b/tests/helpers/app-process-child.ts@@@ -1,126 -1,0 +1,132 @@@+/**+ * A second app process on the same data folder (tests/helpers/app-process.ts starts it): the studio's own server code,+ * with its own memory and its own database connection, as the second server of a deploy has. It answers on a random+ * high port:+ *+ * - /api/gpu/computer/*: the worker routes, as the studio serves them.+ * - GET /__app/generation/<id>: a run as GET /api/generations/<id> answers the session in the request's cookie, through+ * the sign-in proxy (src/proxy.ts) first, as a browser's request comes.+ * - POST /__app/tick: one turn of its runner (it never turns on its own), and every run that turn polls.+ * - POST /__app/billing: one sweep of its billing reports.+ * - POST /__app/pause { marker, release }: the next result it moves into the files folder waits there, with `marker`+ * written, until the file `release` exists (a test acts while this process is in the middle of saving a result).+ *+ * Run with: node --import tests/helpers/ts-register.mjs tests/helpers/app-process-child.ts+ * Requests to anything but the addresses in FUOBE_TEST_ALLOW (comma-separated) answer 599: no real network.++ * FUOBE_TEST_GPU_PORT: an account's own GPU at that port on this machine (a stand-in ComfyUI) is reached, as in vitest.++ * FUOBE_TEST_SELF_HEAL_SCALE and FUOBE_TEST_STALE_SUBMIT_MS: the clocks of a wait and of a run cut off before its send.+ */+import fs from "node:fs";+import http from "node:http";+import { register } from "node:module";+import type net from "node:net";++// next/server as the tests mock it (connection() has no request to wait for here).+register("./app-process-hooks.mjs", import.meta.url);++declare global {+ var __fuobeTestDiskFree: number | undefined;+}+globalThis.__fuobeTestDiskFree = 1e13;++const allow = (process.env.FUOBE_TEST_ALLOW ?? "").split(",").filter(Boolean);+const realFetch = globalThis.fetch;+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ if (allow.some((a) => url.startsWith(a))) return realFetch(input, init);+ return new Response("not reachable in this test", { status: 599 });+}) as typeof fetch;++// The pause point: a result's move out of the worker's upload folder.+let pause: { marker: string; release: string } | null = null;+const realRename = fs.renameSync;+fs.renameSync = ((from: fs.PathLike, to: fs.PathLike) => {+ const p = pause;+ if (p && /[\\/]relay[\\/]tasks[\\/][^\\/]+[\\/]out-\d+$/.test(String(from))) {+ pause = null;+ fs.writeFileSync(p.marker, "");+ const wait = new Int32Array(new SharedArrayBuffer(4));+ const until = Date.now() + 60_000;+ while (!fs.existsSync(p.release) && Date.now() < until) Atomics.wait(wait, 0, 0, 10);+ }+ return realRename(from, to);+}) as typeof fs.renameSync;+- const { ensureRunner } = await import("@/server/generations");++// An account's own GPU on this machine (a test's stand-in ComfyUI), and the clocks a test makes faster.++if (process.env.FUOBE_TEST_GPU_PORT) globalThis.__fuobeTestGpuPort = Number(process.env.FUOBE_TEST_GPU_PORT);++const { ensureRunner, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");++if (process.env.FUOBE_TEST_SELF_HEAL_SCALE) SELF_HEAL.scale = Number(process.env.FUOBE_TEST_SELF_HEAL_SCALE);++if (process.env.FUOBE_TEST_STALE_SUBMIT_MS) STALE_SUBMIT.ms = Number(process.env.FUOBE_TEST_STALE_SUBMIT_MS);+const { sweepBilling } = await import("@/server/billing-outbox");+const { loadRoutes, apiAs } = await import("./computer-tab");+const one = await import("@/app/api/generations/[id]/route");+const { proxy } = await import("@/proxy");+const { NextRequest } = await import("next/server");+const routes = await loadRoutes();++// Its runner turns only when asked (reading a run starts no timer of its own again: the cleared ones stay in place).+ensureRunner();+const state = globalThis.__fuobeRunner!;+clearInterval(state.timer);+if (state.fastTimer) clearInterval(state.fastTimer);++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++const read = (req: http.IncomingMessage) =>+ new Promise<Buffer>((resolve) => {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => resolve(Buffer.concat(chunks)));+ });++const server = http.createServer(async (req, res) => {+ const body = await read(req);+ const url = new URL(req.url ?? "/", "http://app");+ const send = async (r: Response) => {+ const data = Buffer.from(await r.arrayBuffer());+ res.writeHead(r.status, Object.fromEntries(r.headers));+ res.end(data);+ };+ try {+ if (url.pathname.startsWith("/api/gpu/computer/")) {+ const headers: Record<string, string> = {};+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string" && k !== "host" && k !== "content-length") headers[k] = v;+ const api = apiAs(routes, null, headers);+ return await send(await api(url.pathname + url.search, { method: req.method, headers, ...(body.length && { body: new Uint8Array(body) }) }));+ }+ const g = /^\/__app\/generation\/([^/]+)$/.exec(url.pathname);+ if (g && req.method === "GET") {+ const page = `http://localhost:3000/api/generations/${g[1]}`;+ const headers: Record<string, string> = { host: "localhost:3000", "sec-fetch-site": "same-origin", ...(req.headers.cookie && { cookie: req.headers.cookie }) };+ const passed = await proxy(new NextRequest(page, { headers }));+ if (passed.headers.get("x-middleware-next") !== "1") return await send(passed);+ return await send(await one.GET(new Request(page, { headers }), { params: Promise.resolve({ id: g[1] }) } as never));+ }+ if (url.pathname === "/__app/tick") {+ await state.tick();+ for (let i = 0; i < 2000 && state.polling?.size; i++) await sleep(5);+ return await send(Response.json({ ok: true }));+ }+ if (url.pathname === "/__app/billing") {+ await sweepBilling();+ return await send(Response.json({ ok: true }));+ }+ if (url.pathname === "/__app/pause") {+ pause = JSON.parse(body.toString("utf8")) as { marker: string; release: string };+ return await send(Response.json({ ok: true }));+ }+ if (url.pathname === "/__app/exit") {+ res.writeHead(200).end();+ setTimeout(() => process.exit(0), 10);+ return;+ }+ res.writeHead(404).end();+ } catch (e) {+ res.writeHead(500, { "content-type": "text/plain" });+ res.end(String((e as Error).stack ?? e));+ }+});++server.listen(0, "127.0.0.1", () => {+ console.log(`READY ${(server.address() as net.AddressInfo).port}`);+});diff --cc tests/helpers/fake-comfy-runner.tsindex d9f7885d,3f3c8f2c..847e0f2c--- a/tests/helpers/fake-comfy-runner.ts+++ b/tests/helpers/fake-comfy-runner.ts@@@ -206,12 -212,21 +214,21 @@@ export function startFakeComfy(opts: Fares.end(JSON.stringify(value));};const p = url.pathname;+ if (opts.hold?.(entry.method, p)) {+ if (p === "/prompt") {+ try {+ entry.prompt = (JSON.parse(body.toString("utf8")) as { prompt?: Record<string, unknown> }).prompt;+ } catch {}+ }+ held.push(res);+ return;+ }const said = opts.answer?.(entry.method, p);if (said) {- res.writeHead(said.status, { "content-type": said.contentType ?? "text/html" });+ res.writeHead(said.status, { "content-type": said.contentType ?? "text/html", ...said.headers });return res.end(said.body ?? "");}- if (p === "/system_stats") return json(200, { system: { comfyui_version: "0.3.fake", ram_total: 64 * 2 ** 30 }, devices: [{ name: "Fake GPU", vram_total: 24 * 2 ** 30 }] });+ if (p === "/system_stats") return json(200, { system: { comfyui_version: "0.3.fake", ram_total: 64 * 2 ** 30 }, devices: [{ name: "Fake GPU", vram_total: (opts.vramGb ?? 24) * 2 ** 30 }] });if (p === "/models/loras") return json(200, opts.loras ?? []);if (p === "/object_info") return json(200, {});if (p === "/upload/image" && req.method === "POST") {diff --cc tests/own-gpu-graceful.test.tsindex f6a9f6f5,d82c4417..c1c0e864--- a/tests/own-gpu-graceful.test.ts+++ b/tests/own-gpu-graceful.test.ts@@@ -30,9 -33,12 +33,12 @@@ const auth = await import("@/server/autconst generationsRoute = await import("@/app/api/generations/route");const uploadsRoute = await import("@/app/api/uploads/route");const gpuRoute = await import("@/app/api/account/gpu/route");- const { getGeneration, SELF_HEAL } = await import("@/server/generations");+ const generationRoute = await import("@/app/api/generations/[id]/route");+ const smallerRoute = await import("@/app/api/generations/[id]/smaller/route");-const { asAccount, CHAINED_RUN, cancelGeneration, createGenerations, getGeneration, LEASE, OWN_QUEUE, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");++const { asAccount, CHAINED_RUN, cancelGeneration, createGenerations, getGeneration, OWN_QUEUE, QUIET_MS, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");+ const { ownRunNote } = await import("@/server/run-events");const { cleanGpuAddress, checkGpuAddress, visitorStatus } = await import("@/server/account-gpu");- const { comfyProvider, onOwnGpu } = await import("@/server/providers/comfyui");+ const { comfyProvider, onOwnGpu, queuePlace } = await import("@/server/providers/comfyui");const { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");const { runAsTenant } = await import("@/server/tenant");@@@ -88,6 -95,13 +95,20 @@@ async function startRun(): Promise<striexpect(r.status, await r.clone().text()).toBe(201);return ((await r.json()) as { items: { id: string }[] }).items[0].id;}+ /** A later step of the run `first`: it waits for that run's result, as a relight's clip waits for its still. */+ function laterStep(first: string, pic: string): string {+ const [g] = asAccount(a, () => createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } } as Parameters<typeof createGenerations>[0], { dependsOn: first }));+ return g.id;+ }-/** A run's kept state before its job is sent (its wait, and which instance holds it). */++/** A run's kept state before its job is sent (its wait, and whether its job was being sent). */+ const setPending = (id: string, meta: object) => db().prepare("UPDATE generations SET external_meta_json = ? WHERE id = ?").run(JSON.stringify(meta), id);++/** The turn to send the run was held by an app process that has since stopped (no word from it for over 20 s). */++const heldByStopped = (id: string) => {++ db().prepare("INSERT INTO app_processes (token, started_at, seen_at) VALUES ('gone', ?, ?) ON CONFLICT(token) DO UPDATE SET seen_at = excluded.seen_at").run(Date.now() - 10 * 60_000, Date.now() - QUIET_MS - 1000);++ db().prepare("INSERT INTO submit_turns (id, held_by, held_at) VALUES (?, 'gone', ?) ON CONFLICT(id) DO UPDATE SET held_by = excluded.held_by").run(id, Date.now() - 60_000);++};++/** The app process that holds the turn to send the run (null: none does). */++const turnOf = (id: string) => (db().prepare("SELECT held_by FROM submit_turns WHERE id = ?").get(id) as { held_by: string } | undefined)?.held_by ?? null;/** Tick the runner until the row is done (or the time is up), noting every message the tile showed on the way. */async function settle(id: string, ms = 15_000, seen: string[] = []) {const end = Date.now() + ms;@@@ -349,3 -487,588 +494,587 @@@ describe("a run on an account's own GPexpect(fetched.filter((u) => u.includes("owner-comfy.test") && !u.endsWith("/system_stats"))).toEqual([]);});});++ describe("the reported case, end to end: a RunPod pod that is stopped (its address stands for the stand-in)", () => {+ const POD = "https://abc123xyz-8188.proxy.runpod.net";+ /** A stopped pod: RunPod's proxy answers 404 to everything. */+ const stopped = () => ({ status: 404, body: "404 page not found", contentType: "text/plain" });++ it("Save anyway, Generate: the run waits for the pod, says so with Start your pod, and runs once it is started", async () => {+ globalThis.__fuobeTestGpuHosts = { "abc123xyz-8188.proxy.runpod.net": fake.port };+ SELF_HEAL.scale = 0.01;+ auth.setAccountGpu(a, null);+ fake.opts.answer = stopped;+ const kept = await put({ url: "abc123xyz-8188.proxy.runpod.net", anyway: true }, false);+ expect(kept.status).toBe(200);+ expect(kept.body).toMatchObject({ offline: true, gpu: { url: POD }, trouble: { cause: "gpu-stopped", details: "RunPod pod, port 8188 · HTTP 404 · 404 page not found" } });+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ expect(getGeneration(id)?.message).toBe("Your RunPod pod is off. Start it, and this run goes on by itself");+ expect(getGeneration(id)?.waiting?.actions[0]).toMatchObject({ kind: "start-gpu" });+ // The pod is started.+ fake.opts.answer = undefined;+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ });++ it("a pod that stays off: the run stops in plain words with Start your pod first, never the raw 404 or the address", async () => {+ globalThis.__fuobeTestGpuHosts = { "abc123xyz-8188.proxy.runpod.net": fake.port };+ auth.setAccountGpu(a, { url: POD });+ fake.opts.answer = stopped;+ const g = await settle(await startRun());+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("Your RunPod pod isn't running, or ComfyUI isn't on port 8188. Start your pod, then press Retry.");+ plainWords(g?.error);+ expect(g?.trouble?.details).toBe("RunPod pod, port 8188 · HTTP 404 · 404 page not found");+ expect(kinds(g?.trouble)[0]).toBe("start-gpu");+ expect(JSON.stringify(g)).not.toMatch(/abc123xyz|proxy\.runpod|ComfyUI upload failed/);+ });+ });++ describe("what the owner learns of an account's failed run on its own GPU", () => {+ it("a GPU disconnected while its job runs: the run stops in plain words, and the owner gets its line", async () => {+ const warn = vi.spyOn(console, "warn");+ fake.opts.delayMs = 60_000;+ try {+ const id = await startRun();+ for (let i = 0; i < 500 && getGeneration(id)?.status !== "running"; i++) {+ await globalThis.__fuobeRunner?.tick();+ await new Promise((r) => setTimeout(r, 10));+ }+ auth.setAccountGpu(a, null);+ const g = await settle(id);+ expect(g?.status).toBe("failed");+ plainWords(g?.error);+ expect(ownRunNote(id)).toMatchObject({ cause: "connect-gpu", stage: "poll" });+ const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes('"evt":"own-run"') && l.includes(id));+ expect(JSON.parse(line!)).toMatchObject({ run: id, account: a, place: "own-gpu", stage: "poll", cause: "connect-gpu", outcome: "failed" });+ } finally {+ warn.mockRestore();+ }+ });++ it("a longer run broken at its first step: the next step writes the owner's line, the steps after it none", async () => {+ const warn = vi.spyOn(console, "warn");+ try {+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 401, body: "" } : undefined);+ const pic = await uploadPng();+ const first = await startRun();+ const second = laterStep(first, pic);+ const third = laterStep(second, pic);+ expect((await settle(first))?.status).toBe("failed");+ for (const id of [second, third]) expect((await settle(id))?.error).toBe("An earlier step didn't finish");+ const lines = (id: string) => warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('"evt":"own-run"') && l.includes(`"run":"${id}"`));+ expect(lines(first)).toHaveLength(1);+ expect(lines(second)).toHaveLength(1);+ expect(JSON.parse(lines(second)[0])).toMatchObject({ run: second, stage: "chain", cause: "earlier-step", outcome: "failed" });+ expect(lines(third)).toHaveLength(0);+ } finally {+ warn.mockRestore();+ }+ });++ it("keeps at most 2 KB of what the GPU said, counted in bytes, never cutting a character in two", async () => {+ const { keptText } = await import("@/server/run-events");+ const wide = "é".repeat(3000);+ const kept = keptText(wide)!;+ expect(Buffer.byteLength(kept)).toBeLessThanOrEqual(2048);+ expect(kept).toBe("é".repeat(1024));+ const emoji = "a" + "😀".repeat(1000);+ expect(Buffer.byteLength(keptText(emoji)!)).toBeLessThanOrEqual(2048);+ expect(keptText(emoji)).not.toMatch(/�/u);+ expect(keptText("short")).toBe("short");+ });++ it("one log line and a note kept with the run (no address, no token), never in the account's own answers", async () => {+ const warn = vi.spyOn(console, "warn");+ try {+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 401, body: "Unauthorized: token abc123secret from 127.0.0.1", contentType: "text/plain" } : undefined);+ const id = await startRun();+ const g = await settle(id);+ expect(g?.status).toBe("failed");+ const note = ownRunNote(id)!;+ expect(note).toMatchObject({ cause: "gpu-password", stage: "upload", code: "401", hostKind: "web" });+ expect(note.said).toMatch(/^Unauthorized/);+ expect(note.said).not.toMatch(/127\.0\.0\.1|abc123secret/);+ const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes('"evt":"own-run"') && l.includes(id));+ expect(JSON.parse(line!)).toMatchObject({ evt: "own-run", run: id, account: a, place: "own-gpu", provider: "comfyui", stage: "upload", code: "401", hostKind: "web", cause: "gpu-password", outcome: "failed" });+ expect(line).not.toMatch(/127\.0\.0\.1|localhost|abc123secret|me\.png|Unauthorized/);+ // The account's own answers never carry it.+ const list = await generationsRoute.GET(new Request("http://localhost:3000/api/generations", { headers: headers() }));+ const one = await generationRoute.GET(new Request(`http://localhost:3000/api/generations/${id}`, { headers: headers() }), { params: Promise.resolve({ id }) });+ for (const r of [list, one]) {+ const text = await r.text();+ expect(text).toContain(id);+ expect(text).not.toMatch(/ownRun|Unauthorized|abc123secret|"lease"|"heal"/);+ }+ } finally {+ warn.mockRestore();+ }+ });+ });++ describe("a busy GPU: a queue that keeps moving is waited out", () => {+ const queue = (pos: number) => ({ status: 200, body: JSON.stringify({ queue_running: [[0, "someone-else"]], queue_pending: [...Array.from({ length: pos }, (_, i) => [i + 1, `other-${i}`]), [pos + 1, "job-moving"]] }), contentType: "application/json" });+ const empty = { status: 200, body: "{}", contentType: "application/json" };++ it("waits on while its place moves up, past the queue limit, and finishes", async () => {+ OWN_QUEUE.scale = 0.0003; // 30 minutes: about half a second+ fake.opts.promptId = "job-moving";+ const started = Date.now();+ // Five ahead, one fewer every 200 ms: about a second in the queue, twice the limit, while it moves.+ fake.opts.answer = (m, p) => {+ const ahead = 5 - Math.floor((Date.now() - started) / 200);+ if (ahead < 0) return undefined;+ if (p === "/queue" && m === "GET") return queue(ahead);+ if (p.startsWith("/history/")) return empty;+ return undefined;+ };+ try {+ const g = await settle(await startRun(), 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ } finally {+ OWN_QUEUE.scale = 1;+ fake.opts.promptId = undefined;+ }+ });++ it("stops when its place hasn't moved for the limit, saying the GPU was busy", async () => {+ OWN_QUEUE.scale = 0.0003;+ fake.opts.promptId = "job-moving";+ fake.opts.answer = (m, p) => (p === "/queue" && m === "GET" ? queue(3) : p.startsWith("/history/") ? empty : undefined);+ try {+ const g = await settle(await startRun(), 20_000);+ expect(g?.status).toBe("failed");+ expect(g?.error).toMatch(/^Your GPU was busy for 1 minute, so this run stopped\./);+ expect(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu"]));+ } finally {+ OWN_QUEUE.scale = 1;+ fake.opts.promptId = undefined;+ }+ });++ it("counts its place by ComfyUI's queue numbers: the list ComfyUI answers isn't in order", async () => {+ expect(queuePlace([[1, "a"], [4, "mine"], [2, "b"], [5, "c"], [3, "d"]], "mine")).toBe(3);+ expect(queuePlace([[7, "mine"], [9, "a"]], "mine")).toBe(0);+ expect(queuePlace([[1, "a"]], "mine")).toBe(-1);+ fake.opts.promptId = "job-heap";+ const heap = { status: 200, body: JSON.stringify({ queue_running: [[0, "someone-else"]], queue_pending: [[1, "a"], [4, "job-heap"], [2, "b"], [5, "c"], [3, "d"]] }), contentType: "application/json" };+ fake.opts.answer = (m, p) => (p === "/queue" && m === "GET" ? heap : p.startsWith("/history/") ? empty : undefined);+ try {+ const id = await startRun();+ for (let i = 0; i < 500 && !/ahead/.test(getGeneration(id)?.message ?? ""); i++) {+ await globalThis.__fuobeRunner?.tick();+ await new Promise((r) => setTimeout(r, 10));+ }+ expect(getGeneration(id)?.message).toBe("In ComfyUI's queue · 3 ahead");+ await cancelGeneration(id);+ } finally {+ fake.opts.promptId = undefined;+ }+ });++ it("next in line behind one long job: waits while that job runs (up to one job's own time), then runs", async () => {+ OWN_QUEUE.scale = 0.001; // the 30 minutes without moving: 1.8 s; one job's 45 minutes: 2.7 s+ fake.opts.promptId = "job-next";+ const started = Date.now();+ // One render runs ahead of it for about 2.3 s (past the 30 minutes), then it is this job's turn.+ fake.opts.answer = (m, p) => {+ if (Date.now() - started > 2300) return undefined;+ if (p === "/queue" && m === "GET") return { status: 200, body: JSON.stringify({ queue_running: [[0, "long-render"]], queue_pending: [[1, "job-next"]] }), contentType: "application/json" };+ if (p.startsWith("/history/")) return empty;+ return undefined;+ };+ try {+ const seen: string[] = [];+ const g = await settle(await startRun(), 20_000, seen);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(seen).toContain("Next in ComfyUI's queue");+ } finally {+ OWN_QUEUE.scale = 1;+ fake.opts.promptId = undefined;+ }+ });+ });++ describe("runs that wait, and a file too big for the address", () => {+ it("runs waiting for the GPU don't fill the account's runs at once; a run that takes a waiting one's place stops it", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const ids: string[] = [];+ for (let i = 0; i < 4; i++) ids.push(await startRun());+ for (let i = 0; i < 500 && ids.some((id) => !getGeneration(id)?.waiting); i++) await new Promise((r) => setTimeout(r, 10));+ const pic = await uploadPng();+ const body = { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } };+ // A fifth for the GPU: four already wait for it.+ const fifth = await generationsRoute.POST(json("/api/generations", "POST", body));+ expect(fifth.status).toBe(429);+ expect(((await fifth.json()) as { error: string }).error).toBe("You have 4 runs waiting for your GPU. Cancel one, or run one with your key, to start another.");+ // One that takes a waiting run's place (Run with your key on its tile): accepted, and that run stops.+ const instead = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: ids[0] }));+ expect(instead.status, await instead.clone().text()).toBe(201);+ expect(getGeneration(ids[0])?.status).toBe("canceled");+ for (const id of ids) await cancelGeneration(id);+ for (const g of ((await instead.json()) as { items: { id: string }[] }).items) await cancelGeneration(g.id);+ });++ it("a run that takes the place of one tile of a waiting batch takes the batch's place, once, for the jobs not handed over", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const pic = await uploadPng();+ const body = { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] }, params: { numOutputs: 3 } };+ const first = await generationsRoute.POST(json("/api/generations", "POST", body));+ expect(first.status, await first.clone().text()).toBe(201);+ const jobs = ((await first.json()) as { items: { id: string }[] }).items.map((g) => g.id);+ expect(jobs).toHaveLength(3);+ for (let i = 0; i < 500 && jobs.some((id) => !getGeneration(id)?.waiting); i++) await new Promise((r) => setTimeout(r, 10));+ // One of its jobs reached the GPU meanwhile: it goes on there, and isn't made a second time.+ db().prepare("UPDATE generations SET external_id = 'kept-job', status = 'running', external_meta_json = '{}' WHERE id = ?").run(jobs[2]);+ const instead = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: jobs[0] }));+ expect(instead.status, await instead.clone().text()).toBe(201);+ const made = ((await instead.json()) as { items: { id: string }[] }).items.map((g) => g.id);+ // The two jobs that hadn't started: two outputs, never the batch's three again.+ expect(made).toHaveLength(2);+ expect(getGeneration(jobs[0])?.status).toBe("canceled");+ expect(getGeneration(jobs[1])?.status).toBe("canceled");+ expect(getGeneration(jobs[2])?.status).toBe("running");+ // The same button on the batch's other waiting tile, pressed a moment later: nothing new runs.+ const again = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: jobs[1] }));+ expect(again.status).toBe(409);+ expect(((await again.json()) as { error: string }).error).toBe("This run has already started or stopped, so nothing new was run.");+ for (const id of [...jobs, ...made]) await cancelGeneration(id);+ });++ it("Run with your key on a waiting step of a longer run: refused in plain words, and the whole run goes on as it was", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const first = await startRun();+ for (let i = 0; i < 500 && !getGeneration(first)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ const pic = await uploadPng();+ const second = laterStep(first, pic);+ const made = db().prepare("SELECT COUNT(*) FROM generations").pluck().get();+ const body = { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", engine: "cloud", prompt: "", inputs: { images: [pic] } };+ // The step that waits, and the one that waits for it: neither moves alone.+ for (const id of [first, second]) {+ const r = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: id }));+ expect(r.status).toBe(409);+ const said = (await r.json()) as { error: string; code: string };+ expect(said).toEqual({ error: CHAINED_RUN, code: "chained-run" });+ plainWords(said.error);+ }+ expect(CHAINED_RUN).toBe("This step is part of a longer run, so it can't move to your key on its own. It goes on by itself, or cancel it and run the tool again with your key.");+ // Nothing stopped and nothing new was made: the first step still waits, the second still waits for it.+ expect(getGeneration(first)).toMatchObject({ status: "queued", waiting: expect.anything() });+ expect(getGeneration(second)?.status).toBe("queued");+ expect(db().prepare("SELECT COUNT(*) FROM generations").pluck().get()).toBe(made);+ for (const id of [first, second]) await cancelGeneration(id);+ });++ it("a file the address refuses as too big: Send a smaller copy makes one, and the run made again with it runs", async () => {+ // A big picture (noise: it doesn't shrink as a PNG).+ const sharp = (await import("sharp")).default;+ const noise = (await import("node:crypto")).randomBytes(2400 * 2400 * 3);+ const big = await sharp(noise, { raw: { width: 2400, height: 2400, channels: 3 } }).png({ compressionLevel: 1 }).toBuffer();+ const up = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": "image/png", "x-file-name": "big.png", "content-length": String(big.length) }), body: big }));+ expect(up.status, await up.clone().text()).toBe(201);+ const pic = ((await up.json()) as { url: string }).url;+ // The tunnel's own size limit: its web page, 413.+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 413, body: "<html><title>413 Request Entity Too Large</title></html>", contentType: "text/html" } : undefined);+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } }));+ const id = ((await r.json()) as { items: { id: string }[] }).items[0].id;+ const g = await settle(id);+ expect(g?.trouble?.cause).toBe("gpu-too-big");+ expect(g?.trouble?.actions[0]).toMatchObject({ kind: "send-smaller", label: "Send a smaller copy" });+ // The proxy lets the account ask for its own run's copy, and nobody else's.+ const { proxy } = await import("@/proxy");+ const { NextRequest } = await import("next/server");+ const via = (who: string) => proxy(new NextRequest(`http://localhost:3000/api/generations/${id}/smaller`, { method: "POST", headers: { cookie: who, host: "localhost:3000" } }));+ expect(via(cookie).headers.get("x-middleware-next")).toBe("1");+ const other = auth.createAccount("[email protected]", "long enough").id;+ expect(via(`${auth.SESSION_COOKIE}=${auth.createSession(other).value}`).status).toBe(403);+ const smaller = await smallerRoute.POST(new Request(`http://localhost:3000/api/generations/${id}/smaller`, { method: "POST", headers: headers() }), { params: Promise.resolve({ id }) });+ expect(smaller.status, await smaller.clone().text()).toBe(200);+ const made = (await smaller.json()) as { request: { inputs: { images: string[] } }; note: string };+ expect(made.note).toMatch(/^Sent a smaller copy \(\d+ MB\)\.$/);+ expect(made.request.inputs.images[0]).not.toBe(pic);+ fake.opts.answer = undefined;+ const again = await generationsRoute.POST(json("/api/generations", "POST", made.request));+ expect(again.status, await again.clone().text()).toBe(201);+ expect((await settle(((await again.json()) as { items: { id: string }[] }).items[0].id))?.status).toBe("succeeded");+ const sentBytes = fake.log.filter((e) => e.path === "/upload/image").at(-1)?.upload?.length ?? 0;+ expect(sentBytes).toBeGreaterThan(0);+ expect(sentBytes).toBeLessThan(big.length * 0.8);++ // A copy is real work: one at a time for an account, a few at once on the server, a few an hour for a run.+ const ask = async () => {+ const r = await smallerRoute.POST(new Request(`http://localhost:3000/api/generations/${id}/smaller`, { method: "POST", headers: headers() }), { params: Promise.resolve({ id }) });+ return { status: r.status, error: ((await r.json()) as { error?: string }).error };+ };+ globalThis.__fuobeSmallerCopies = { total: 1, accounts: new Set([a]) };+ expect(await ask()).toEqual({ status: 429, error: "Your last smaller copy is still being made. Try again once it's done." });+ globalThis.__fuobeSmallerCopies = { total: 2, accounts: new Set(["someone-else", "another"]) };+ expect(await ask()).toEqual({ status: 429, error: "Smaller copies are busy right now. Try again in a minute." });+ globalThis.__fuobeSmallerCopies = undefined;+ // Files that are full say so before any copy is made.+ const { ACCOUNT_LIMITS } = await import("@/server/account-files");+ const limits = ACCOUNT_LIMITS as { newAccountBytes: number };+ const was = limits.newAccountBytes;+ limits.newAccountBytes = 1;+ try {+ expect(await ask()).toEqual({ status: 422, error: "Your files are full, so a smaller copy can't be kept. Delete a few results, then try again." });+ } finally {+ limits.newAccountBytes = was;+ }+ // Three for this run this hour (the busy answers aren't counted, the full one is), then none.+ expect((await ask()).status).toBe(200);+ expect((await ask()).status).toBe(429);+ expect((await ask()).error).toMatch(/^You've made a few smaller copies already\. Try again in \d+ minutes?\.$/);+ });+ });++ describe("a step of a longer run that waited, taken over after a restart", () => {+ /** The run's first step, done on the GPU, with a picture for the next step to start from. */+ async function firstStepDone(): Promise<{ first: string; pic: string }> {+ fake.opts.output = "both";+ const first = await startRun();+ expect((await settle(first))?.status).toBe("succeeded");+ return { first, pic: await uploadPng() };+ }++ it("goes on with what is left of its wait (its tries and its time), and runs once", async () => {+ const info = vi.spyOn(console, "info");+ try {+ const { first, pic } = await firstStepDone();+ fake.log.length = 0;+ const second = laterStep(first, pic);- // It waited for the GPU on an instance that is gone (its hold ran out): seven tries, two minutes.++ // It waited for the GPU in an app process that has stopped (its turn is free): seven tries, two minutes.+ const since = Date.now() - 2 * 60_000;+ setPending(second, {+ heal: { since, deadline: Date.now() + 60_000, firstSeen: { "gpu-starting": since }, tries: 7, next: 0, index: 0, words: "Waiting for your GPU to start up", trouble: { cause: "gpu-starting", actions: [] } },- lease: { by: "gone", until: Date.now() - 1 },+ });++ heldByStopped(second);+ const g = await settle(second, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ // Healed on its seventh try, its wait counted from when it began.+ const healed = info.mock.calls+ .map((c) => String(c[0]))+ .filter((l) => l.includes('"evt":"own-run"') && l.includes(`"run":"${second}"`) && l.includes('"outcome":"healed"'))+ .map((l) => JSON.parse(l) as { attempt: number; waitedMs: number });+ expect(healed).toHaveLength(1);+ expect(healed[0].attempt).toBe(7);+ expect(healed[0].waitedMs).toBeGreaterThanOrEqual(2 * 60_000);+ } finally {+ info.mockRestore();+ fake.opts.output = undefined;+ }+ });++ it("one cut off in the middle of its send is never sent again, and the owner gets its line", async () => {+ const warn = vi.spyOn(console, "warn");+ try {+ const { first, pic } = await firstStepDone();+ fake.log.length = 0;+ const second = laterStep(first, pic);- setPending(second, { heal: { since: Date.now() - 60_000, deadline: Date.now() + 60_000, firstSeen: {}, tries: 2, next: 0, index: 0, sending: Date.now() - 1000 }, lease: { by: "gone", until: Date.now() - 1 } });++ setPending(second, { heal: { since: Date.now() - 60_000, deadline: Date.now() + 60_000, firstSeen: {}, tries: 2, next: 0, index: 0, sending: Date.now() - 1000 } });++ heldByStopped(second);+ const g = await settle(second);+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("This run was interrupted while it was being sent. Press Retry.");+ expect(fake.log.filter((e) => e.path === "/prompt" || e.path === "/upload/image")).toHaveLength(0);+ expect(ownRunNote(second)).toMatchObject({ cause: "interrupted-sending", stage: "chain", hostKind: "web" });+ const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes('"evt":"own-run"') && l.includes(second));+ expect(JSON.parse(line!)).toMatchObject({ run: second, account: a, place: "own-gpu", cause: "interrupted-sending", outcome: "failed" });+ } finally {+ warn.mockRestore();+ fake.opts.output = undefined;+ }+ });++ it("one cut off in the middle of its first send (it never waited) is never sent again either", async () => {+ try {+ const { first, pic } = await firstStepDone();+ // Its first try: marked as being sent just before its job goes, with no wait of its own.+ fake.log.length = 0;+ fake.opts.hold = (m, p) => m === "POST" && p === "/prompt";+ const sending = laterStep(first, pic);+ for (let i = 0; i < 1000 && !fake.log.some((e) => e.path === "/prompt"); i++) {+ await globalThis.__fuobeRunner?.tick();+ await new Promise((r) => setTimeout(r, 10));+ }+ const meta = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(sending))) as { sending?: unknown; heal?: unknown };+ expect(typeof meta.sending).toBe("number");+ expect(meta.heal).toBeUndefined();+ await cancelGeneration(sending);+ fake.opts.hold = undefined;+ fake.dropHeld();- // The next instance finds such a step once the cut-off one's hold has run out: it fails, and nothing is sent.++ // The next app process finds such a step once the cut-off one has gone quiet: it fails, and nothing is sent.+ fake.log.length = 0;+ const second = laterStep(first, pic);- setPending(second, { sending: Date.now() - 1000, lease: { by: "gone", until: Date.now() - 1 } });++ setPending(second, { sending: Date.now() - 1000 });++ heldByStopped(second);+ const g = await settle(second);+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("This run was interrupted while it was being sent. Press Retry.");+ expect(fake.log.filter((e) => e.path === "/prompt" || e.path === "/upload/image")).toHaveLength(0);+ expect(ownRunNote(second)).toMatchObject({ cause: "interrupted-sending", stage: "chain" });+ } finally {+ fake.opts.hold = undefined;+ fake.dropHeld();+ fake.opts.output = undefined;+ }+ });+ });+++/**++ * The app process stops (its timers, its runs in hand, its beat, its name), and a new one starts on the same database:++ * the runner's module loaded again, with the faster clocks.++ */++async function newInstance() {++ const old = globalThis.__fuobeRunner;++ if (old) {++ clearInterval(old.timer);++ if (old.fastTimer) clearInterval(old.fastTimer);++ }++ globalThis.__fuobeRunner = undefined;++ if (globalThis.__fuobeBeat) clearInterval(globalThis.__fuobeBeat);++ globalThis.__fuobeBeat = undefined;++ globalThis.__fuobeSubmitting = new Set();++ globalThis.__fuobeRunnerToken = undefined;++ globalThis.__fuobeResent = undefined;++ vi.resetModules();++ const fresh = await import("@/server/generations");++ fresh.SELF_HEAL.scale = 0.01;++ fresh.STALE_SUBMIT.ms = 0;++ return fresh;++}+++ // Last: the server's own state is replaced here (a new instance of the runner's module on the same database).+ describe("a wait survives a restart or a deploy", () => {+ it("another instance's look while this one holds a waiting run leaves it alone", async () => {+ SELF_HEAL.scale = 0.01;+ STALE_SUBMIT.ms = 0;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ try {+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));++ // This app process holds the turn to send it while it waits (tests/own-run-turns.test.ts has a second process look).++ expect(turnOf(id)).toBe(globalThis.__fuobeRunnerToken);+ // Another instance's sweep: its own (empty) list of runs in hand, the same database.+ const mine = globalThis.__fuobeSubmitting;+ globalThis.__fuobeSubmitting = new Set();+ await globalThis.__fuobeRunner?.tick();+ globalThis.__fuobeSubmitting = mine;+ expect(getGeneration(id)?.status).toBe("queued");++ expect(turnOf(id)).toBe(globalThis.__fuobeRunnerToken);+ fake.opts.answer = undefined;+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ } finally {+ STALE_SUBMIT.ms = 2 * 60_000;+ }+ });++ it("a waiting run another instance takes over is never sent to a provider other than the one it was made for", async () => {+ SELF_HEAL.scale = 0.01;+ STALE_SUBMIT.ms = 0;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const shut = (globalThis.__fuobeShutdown ??= { stops: new Set(), draining: false, hooked: false });+ try {+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ // This instance stops waiting on it (as when it stops), and the run's row says another provider made it.+ shut.draining = true;+ for (let i = 0; i < 500 && globalThis.__fuobeSubmitting?.has(id); i++) await new Promise((r) => setTimeout(r, 10));+ shut.draining = false;+ db().prepare("UPDATE generations SET provider = 'fal' WHERE id = ?").run(id);+ fake.opts.answer = undefined;+ fake.log.length = 0;+ const g = await settle(id, 5_000);+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("This run stopped because your keys changed while it waited. Press Retry.");+ expect(fake.log.filter((e) => e.path === "/prompt" || e.path === "/upload/image")).toHaveLength(0);+ expect(ownRunNote(id)).toMatchObject({ cause: "keys-changed", stage: "submit" });+ } finally {+ shut.draining = false;+ STALE_SUBMIT.ms = 2 * 60_000;+ }+ });++ it("a deploy's old instance hands its waiting run to the new one, which goes on with it and runs it once", async () => {+ SELF_HEAL.scale = 0.01;- LEASE.ms = 400;- LEASE.renewMs = 100;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ expect(getGeneration(id)?.message).toBe("Waiting for your GPU to start up");+ // The old instance starts stopping: its wait lets go of the run, without failing it.+ const shut = (globalThis.__fuobeShutdown ??= { stops: new Set(), draining: false, hooked: false });+ shut.draining = true;+ for (let i = 0; i < 500 && globalThis.__fuobeSubmitting?.has(id); i++) await new Promise((r) => setTimeout(r, 10));+ expect(globalThis.__fuobeSubmitting?.has(id)).toBe(false);+ expect(getGeneration(id)?.status).toBe("queued");- // It let go of its hold at once (the new instance needn't wait for it to run out), and kept the wait.- const kept = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id))) as { lease?: unknown; heal?: unknown };- expect(kept.lease).toBeUndefined();++ // It gave its turn back at once (the new instance needn't wait for it to go quiet), and kept the wait.++ expect(turnOf(id)).toBeNull();++ const kept = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id))) as { heal?: unknown };+ expect(kept.heal).toBeTruthy();- // It is gone: its timers, its runs in hand, its name. A new instance starts on the same database.- const old = globalThis.__fuobeRunner;- if (old) {- clearInterval(old.timer);- if (old.fastTimer) clearInterval(old.fastTimer);- }- globalThis.__fuobeRunner = undefined;- if (globalThis.__fuobeLeaseTimer) clearTimeout(globalThis.__fuobeLeaseTimer);- globalThis.__fuobeLeaseTimer = undefined;- globalThis.__fuobeSubmitting = new Set();- globalThis.__fuobeInstance = undefined;- globalThis.__fuobeResent = undefined;++ // It is gone. A new instance starts on the same database; the GPU is back.+ shut.draining = false;- vi.resetModules();- const fresh = await import("@/server/generations");- fresh.SELF_HEAL.scale = 0.01;- fresh.STALE_SUBMIT.ms = 0;- fresh.LEASE.ms = 400;- // The old hold runs out; the GPU is back.- await new Promise((r) => setTimeout(r, 500));++ const fresh = await newInstance();+ fake.opts.answer = undefined;+ fake.log.length = 0;+ fresh.ensureRunner();+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(g?.error ?? "").not.toMatch(/stopped before it started/);+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ });++ it("an instance cut off while it sends a run that waited: the next one never sends it a second time", async () => {+ // The module the runner runs now (the test above started another instance of it): its knobs and the first one's.+ const now = await import("@/server/generations");- for (const m of [{ SELF_HEAL, LEASE, STALE_SUBMIT }, now]) {++ for (const m of [{ SELF_HEAL, STALE_SUBMIT }, now]) {+ m.SELF_HEAL.scale = 0.01;- m.LEASE.ms = 400;- m.LEASE.renewMs = 100;+ m.STALE_SUBMIT.ms = 0;+ }+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ expect(getGeneration(id)?.waiting).toBeTruthy();+ // The GPU is back: the run's next try sends its job, and the GPU takes it; the answer never comes back to this+ // instance, which is cut off (a restart, a deploy's old instance) before it can note the job.+ fake.log.length = 0;+ fake.opts.hold = (m, p) => m === "POST" && p === "/prompt";+ fake.opts.answer = undefined;+ for (let i = 0; i < 1000 && !fake.log.some((e) => e.path === "/prompt"); i++) await new Promise((r) => setTimeout(r, 10));+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ const meta = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id))) as { heal?: { sending?: number } };+ expect(typeof meta.heal?.sending).toBe("number");- const old = globalThis.__fuobeRunner;- if (old) {- clearInterval(old.timer);- if (old.fastTimer) clearInterval(old.fastTimer);- }- globalThis.__fuobeRunner = undefined;- if (globalThis.__fuobeLeaseTimer) clearTimeout(globalThis.__fuobeLeaseTimer);- globalThis.__fuobeLeaseTimer = undefined;- globalThis.__fuobeSubmitting = new Set();- globalThis.__fuobeInstance = undefined;- vi.resetModules();- const next = await import("@/server/generations");- next.SELF_HEAL.scale = 0.01;- next.STALE_SUBMIT.ms = 0;- next.LEASE.ms = 400;++ // The instance is cut off (killed: it says nothing more, and its turn stays where it was). A new one starts.++ const cut = globalThis.__fuobeRunnerToken;++ expect(turnOf(id)).toBe(cut);++ const next = await newInstance();+ try {- // The cut-off instance's hold runs out; the next instance looks.- await new Promise((r) => setTimeout(r, 500));+ next.ensureRunner();++ // While the cut-off one may still be running (not yet quiet for 20 s), the run is left to it.++ await globalThis.__fuobeRunner?.tick();++ expect(getGeneration(id)?.status).toBe("queued");++ // 20 s with no word from it: the next instance's look.++ db().prepare("UPDATE app_processes SET seen_at = ? WHERE token = ?").run(Date.now() - QUIET_MS - 1000, cut);+ const g = await settle(id, 10_000);+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("This run was interrupted while it was being sent. Press Retry.");+ // The owner's note says why: a server cut off in the middle of the send.+ expect(ownRunNote(id)).toMatchObject({ cause: "interrupted-sending", stage: "submit" });+ // Exactly one job across both instances, also once the first instance's send ends.+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ fake.dropHeld();+ await new Promise((r) => setTimeout(r, 200));+ await settle(id, 1_000);+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ expect(getGeneration(id)?.status).toBe("failed");+ } finally {+ fake.opts.hold = undefined;+ fake.dropHeld();+ }+ });+ });diff --cc tests/own-run-turns.test.tsindex 00000000,00000000..e268a39enew file mode 100644--- /dev/null+++ b/tests/own-run-turns.test.ts@@@ -1,0 -1,0 +1,248 @@@++import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { runnerByHand, startAppProcess, tick, type AppProcess } from "./helpers/app-process";++import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";++import { tempDir } from "./helpers/temp-dir";++++/**++ * An account's run on its own GPU across two app processes on one database, as a deploy runs them for a moment: this++ * test process is one, and a second one (tests/helpers/app-process.ts) shares its data folder. One turn decides who++ * sends a run (submit_turns): the process that holds it sends it, or waits on its GPU for it, and the other leaves it++ * alone (never fails it, never takes it, never sends it). A process that stops gives its turns back at once, so the++ * other goes on with the wait where it was (its tries and its time); one cut off in the middle of a send leaves a run++ * the other never sends again. Against a stand-in ComfyUI on this machine: no real GPU is called.++ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++vi.setConfig({ testTimeout: 90_000, hookTimeout: 180_000 });++++const dir = tempDir("fuobe-own-run-turns-");++process.env.FUOBE_DATA_DIR = dir;++process.env.COMFYUI_URL = "http://owner-comfy.test:8188";++process.env.FUOBE_PUBLIC_SIGNUP = "1";++for (const k of ["FUOBE_PASSWORD", "FUOBE_ALLOW_PRIVATE_URLS", "FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_MODERATION_URL"]) delete process.env[k];++globalThis.__fuobeTestDiskFree = 1e13;++++// Plain fetch is the install's own ComfyUI: an account's runs never reach it.++const realFetch = globalThis.fetch;++globalThis.fetch = (async () => new Response("not stubbed", { status: 599 })) as typeof fetch;++++const auth = await import("@/server/auth");++const generationsRoute = await import("@/app/api/generations/route");++const uploadsRoute = await import("@/app/api/uploads/route");++const { asAccount, createGenerations, ensureRunner, getGeneration, QUIET_MS, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");++const { db } = await import("@/server/db");++const { resetRates } = await import("@/server/rate");++++const SCALE = 0.02;++const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++++let fake: FakeComfy;++let app2: AppProcess;++/** The name the second process's turns carry. */++let theirs = "";++let a = "";++let cookie = "";++++const tokens = () => (db().prepare("SELECT token FROM app_processes").all() as { token: string }[]).map((r) => r.token);++/** This process's name, as its turns carry it. */++const mine = () => globalThis.__fuobeRunnerToken!;++++beforeAll(async () => {++ fake = await startFakeComfy({ loras: [], delayMs: 0 });++ globalThis.__fuobeTestGpuPort = fake.port;++ auth.setPassword("install password");++ a = auth.createAccount("[email protected]", "long enough").id;++ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;++ auth.setAccountGpu(a, { url: fake.url });++ ensureRunner();++ runnerByHand();++ const known = new Set(tokens());++ app2 = await startAppProcess({++ dataDir: dir,++ env: { FUOBE_PUBLIC_SIGNUP: "1", COMFYUI_URL: process.env.COMFYUI_URL, FUOBE_TEST_GPU_PORT: String(fake.port), FUOBE_TEST_SELF_HEAL_SCALE: String(SCALE), FUOBE_TEST_STALE_SUBMIT_MS: "0" },++ });++ for (let i = 0; i < 100 && !theirs; i++) {++ theirs = tokens().find((t) => !known.has(t) && t !== mine()) ?? "";++ if (!theirs) await sleep(100);++ }++ expect(theirs, "the second process says it runs").toBeTruthy();++});++afterAll(async () => {++ await app2?.kill();++ globalThis.fetch = realFetch;++ globalThis.__fuobeTestGpuPort = undefined;++ globalThis.__fuobeTestDiskFree = undefined;++ SELF_HEAL.scale = 1;++ STALE_SUBMIT.ms = 2 * 60_000;++ await fake.close();++});++beforeEach(() => {++ resetRates();++ SELF_HEAL.scale = SCALE;++ STALE_SUBMIT.ms = 0;++ Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined, hold: undefined, output: undefined });++ fake.dropHeld();++ fake.log.length = 0;++ globalThis.__fuobeAccountGpus?.clear();++ shutdown().draining = false;++ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();++});++++const shutdown = () => (globalThis.__fuobeShutdown ??= { stops: new Set(), draining: false, hooked: false });++const headers = (extra: Record<string, string> = {}) => ({ cookie, host: "localhost:3000", ...extra });++const json = (url: string, body: unknown) => {++ const text = JSON.stringify(body);++ return new Request(`http://localhost:3000${url}`, { method: "POST", headers: headers({ "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), body: text });++};++const html = (status: number) => ({ status, body: "<!DOCTYPE html><html><head><title>Bad gateway</title></head><body>…</body></html>", contentType: "text/html" });++/** The GPU is starting up: its address answers 502 (a run waits for it). */++const gpuStarting = () => (fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined));++const gpuBack = () => (fake.opts.answer = undefined);++++async function uploadPng(): Promise<string> {++ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }), body: TINY_PNG }));++ expect(r.status).toBe(201);++ return ((await r.json()) as { url: string }).url;++}++async function startRun(): Promise<string> {++ const pic = await uploadPng();++ const r = await generationsRoute.POST(json("/api/generations", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } }));++ expect(r.status, await r.clone().text()).toBe(201);++ return ((await r.json()) as { items: { id: string }[] }).items[0].id;++}++++interface Heal {++ since: number;++ tries: number;++ sending?: number;++ trouble?: unknown;++}++const row = (id: string) => db().prepare("SELECT status, error, external_id, external_meta_json FROM generations WHERE id = ?").get(id) as { status: string; error: string | null; external_id: string | null; external_meta_json: string | null };++const healOf = (id: string) => (JSON.parse(row(id).external_meta_json || "{}") as { heal?: Heal }).heal;++/** The app process that holds the turn to send the run (null: none does). */++const turnOf = (id: string) => (db().prepare("SELECT held_by FROM submit_turns WHERE id = ?").get(id) as { held_by: string } | undefined)?.held_by ?? null;++const prompts = () => fake.log.filter((e) => e.path === "/prompt").length;++++/** Turn a runner (this process's, or the other's) until `fn` says yes, or the time is up (its last answer). */++async function until<T>(fn: () => T, turn: () => Promise<void> = tick, ms = 20_000): Promise<T> {++ const end = Date.now() + ms;++ let v = fn();++ while (!v && Date.now() < end) {++ await turn();++ await sleep(20);++ v = fn();++ }++ return v;++}++const ended = (id: string) => ["succeeded", "failed", "canceled"].includes(row(id).status);++const waiting = (id: string) => row(id).status === "queued" && !!healOf(id)?.trouble;++++/** This process stops as a deploy's old instance does: its waits let go of their runs (and give their turns back). */++async function drainHere(id: string) {++ shutdown().draining = true;++ for (let i = 0; i < 500 && globalThis.__fuobeSubmitting?.has(id); i++) await sleep(10);++ expect(globalThis.__fuobeSubmitting?.has(id)).toBe(false);++}++++describe("two app processes and a run waiting for its account's own GPU", () => {++ it("the other process's turns leave a run waiting here alone, and it is sent once when its GPU is back", async () => {++ gpuStarting();++ const id = await startRun();++ expect(await until(() => waiting(id))).toBe(true);++ expect(turnOf(id), "the turn is this process's while it waits").toBe(mine());++ // The other process turns (its sweep, its chain steps, its polls) while the run waits here.++ for (let i = 0; i < 3; i++) await app2.tick();++ expect(row(id)).toMatchObject({ status: "queued", external_id: null });++ expect(getGeneration(id)?.waiting, "still waiting, with what helps").toBeTruthy();++ expect(turnOf(id)).toBe(mine());++ expect(prompts()).toBe(0);++ gpuBack();++ expect(await until(() => ended(id))).toBe(true);++ expect(row(id).status, row(id).error ?? "").toBe("succeeded");++ expect(prompts(), "sent once").toBe(1);++ expect(turnOf(id), "the turn goes once it is sent").toBeNull();++ });++++ it("a deploy mid-wait: this process stops, the other takes the wait over at once, goes on with its tries, and sends it once", async () => {++ gpuStarting();++ const id = await startRun();++ expect(await until(() => waiting(id))).toBe(true);++ const before = healOf(id)!;++ await drainHere(id);++ // It gave its turn back at once (the other needn't wait for it to go quiet), and kept the wait with the run.++ expect(turnOf(id)).toBeNull();++ expect(row(id)).toMatchObject({ status: "queued", external_id: null });++ expect(healOf(id)?.since).toBe(before.since);++ // The other process takes the wait over: its turn, the wait's start kept, its tries going on from where they were.++ expect(await until(() => turnOf(id) === theirs && (healOf(id)?.tries ?? 0) > before.tries, () => app2.tick())).toBe(true);++ expect(healOf(id)?.since).toBe(before.since);++ expect(prompts()).toBe(0);++ gpuBack();++ expect(await until(() => ended(id), () => app2.tick())).toBe(true);++ expect(row(id).status, row(id).error ?? "").toBe("succeeded");++ expect(prompts(), "sent once, by the process that went on with it").toBe(1);++ });++});++++describe("a step of a longer run that waits for its account's own GPU", () => {++ it("is left to the process waiting on it; once that process stops, the other resumes its wait where it was and sends it once", async () => {++ // The run's first step, done on the GPU, with a picture for the next step.++ fake.opts.output = "both";++ const first = await startRun();++ expect(await until(() => ended(first))).toBe(true);++ expect(row(first).status, row(first).error ?? "").toBe("succeeded");++ const pic = await uploadPng();++ gpuStarting();++ fake.log.length = 0;++ const [step] = asAccount(a, () =>++ createGenerations({ feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } } as Parameters<typeof createGenerations>[0], { dependsOn: first }),++ );++ // This process launches it; its GPU is starting up, so it waits here.++ expect(await until(() => waiting(step.id))).toBe(true);++ expect(turnOf(step.id)).toBe(mine());++ const before = healOf(step.id)!;++ // The other process's chain steps leave it alone.++ for (let i = 0; i < 3; i++) await app2.tick();++ expect(turnOf(step.id)).toBe(mine());++ expect(row(step.id)).toMatchObject({ status: "queued", external_id: null });++ // This process stops: the other launches the step again with its wait kept (the same start, more tries), not a new one.++ await drainHere(step.id);++ expect(await until(() => turnOf(step.id) === theirs && (healOf(step.id)?.tries ?? 0) > before.tries, () => app2.tick())).toBe(true);++ expect(healOf(step.id)?.since).toBe(before.since);++ expect(getGeneration(step.id)?.waiting).toBeTruthy();++ gpuBack();++ expect(await until(() => ended(step.id), () => app2.tick())).toBe(true);++ expect(row(step.id).status, row(step.id).error ?? "").toBe("succeeded");++ expect(prompts(), "the step was sent once").toBe(1);++ });++});++++// Last: the other process is killed here.++describe("a process cut off in the middle of a send", () => {++ it("the run it was sending is never sent a second time: it ends in plain words once that process has gone quiet", async () => {++ gpuStarting();++ const id = await startRun();++ expect(await until(() => waiting(id))).toBe(true);++ await drainHere(id);++ // The other process takes the wait over; its GPU is back, and the job is sent, but the answer never comes back:++ // the other process is killed before it can note the job.++ fake.opts.hold = (m, p) => m === "POST" && p === "/prompt";++ gpuBack();++ expect(await until(() => prompts() > 0, () => app2.tick())).toBe(true);++ expect(typeof healOf(id)?.sending, "marked as being sent").toBe("number");++ expect(turnOf(id)).toBe(theirs);++ await app2.kill();++ shutdown().draining = false;++ // While its process may still be running (not yet quiet for 20 s), the run is left to it.++ await tick();++ expect(row(id)).toMatchObject({ status: "queued", external_id: null });++ // 20 s with no word from it: this process's next look ends the run, and sends nothing.++ db().prepare("UPDATE app_processes SET seen_at = ? WHERE token = ?").run(Date.now() - QUIET_MS - 1000, theirs);++ expect(await until(() => ended(id))).toBe(true);++ expect(row(id)).toMatchObject({ status: "failed", error: "This run was interrupted while it was being sent. Press Retry." });++ expect(getGeneration(id)?.notBilled, "its GPU may have it").toBeUndefined();++ fake.dropHeld();++ for (let i = 0; i < 5; i++) await tick();++ expect(prompts(), "one job across both processes").toBe(1);++ expect(row(id).status).toBe("failed");++ });++});diff --cc tests/recovery-server.test.tsindex 0c8973c4,00000000..f5cf1f27mode 100644,000000..100644--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@@ -1,1946 -1,0 +1,2024 @@@+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { runnerByHand, startAppProcess, tick, type AppProcess } from "./helpers/app-process";+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";+import { plainFailure, RunWatch, type RunLike } from "./helpers/run-watch";+import { startFakeModeration } from "./helpers/fake-billing";+import { FREE_RUNS_POLICY, startStandInBilling, type StandInBilling } from "./helpers/standin-billing";+import { startStandInComfy, type StandInComfy } from "./helpers/standin-comfy";+import { tempDir } from "./helpers/temp-dir";+import { workerDriver, type WorkerDriver } from "./helpers/worker-driver";++/**+ * Recovery checks for accounts' runs on this install's GPUs, on the studio's side: a stand-in ComfyUI, the worker's+ * runner on the real worker routes with a worker token, and a stand-in billing service that makes every run free (rate+ * limits only). Each check asks the same three things of the run:+ *+ * - its output arrives exactly once (one result in the run, one file kept, one prompt where nothing went wrong);+ * - every look at it shows only "In line" with its place, "Working", then the result: a recovery shows "In line" again+ * with its place kept, and never an error or a word about the machines. The looks are a refresh, the account's+ * session and a second session on another device (each through the sign-in proxy, as a browser asks), its list, and+ * with two app processes the other one too. Each look must find the run, and another account must be refused it;+ * - nothing is charged twice (one hold, one report).+ *+ * Where the studio can't do something yet, the check is of what it does today, named for it, so that it fails the day+ * the studio learns it: then it becomes a check of the new behaviour. The worker's own scenarios are in+ * tests/recovery-worker.test.ts.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 90_000, hookTimeout: 180_000 });++const dir = tempDir("fuobe-recovery-");+process.env.FUOBE_DATA_DIR = dir;+// Nothing answers here: no test may reach a real ComfyUI.+const DEAD = "http://127.0.0.1:7";+process.env.COMFYUI_URL = DEAD;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+for (const k of ["FUOBE_PASSWORD", "FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_MODERATION_URL", "FUOBE_POOL_MEDIA_INPUTS", "FUOBE_POOL_WAIT_MIN"]) delete process.env[k];+globalThis.__fuobeTestDiskFree = 1e13;++// The server's own fetch: anything but the stand-ins answers 599 at once (no real network).+const realFetch = globalThis.fetch;+let allowed: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);+ return new Response("not reachable in this test", { status: 599 });+}) as typeof fetch;++const auth = await import("@/server/auth");+const generationsRoute = await import("@/app/api/generations/route");+const oneRoute = await import("@/app/api/generations/[id]/route");+const previewRoute = await import("@/app/api/generations/[id]/preview/route");+const { proxy } = await import("@/proxy");+const { NextRequest } = await import("next/server");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const { cancelGeneration, createGenerations, getGeneration, ensureRunner, QUIET_MS, updateLive } = await import("@/server/generations");+const { runOnPool } = await import("@/server/hosted");+const { stampOf, withRunStamp } = await import("@/server/run-stamp");+const pool = await import("@/server/computer/pool");+const { catalogVersion } = await import("@/server/computer/catalog-version");+const tasks = await import("@/server/computer/tasks");+const billing = await import("@/server/billing");+const outbox = await import("@/server/billing-outbox");+const outputChecks = await import("@/server/output-checks");+const qs = await import("@/server/queue-settings");+const { comfyProvider, loadManifest } = await import("@/server/providers/comfyui");+const { loadIndex } = await import("@/server/gpu/index-file");+const { allLanes } = await import("@/lib/lanes");+const { getModel } = await import("@/lib/catalog");+const { POOL_WORDS } = await import("@/lib/relay");+const { HOSTED_WORDS } = await import("@/server/hosted");+const { ACCOUNT_MESSAGES } = await import("@/server/account-files");++type TaskRow = import("@/server/computer/tasks").TaskRow;++const HOST = "localhost:3000";+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };+const MIN = 60_000;+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));+const IMAGE = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" };+const imageLane = () => pool.poolLane(getModel(IMAGE.modelId)!.routes.find((r) => r.provider === "comfyui")!.endpoint);++let comfy: StandInComfy;+let svc: StandInBilling;+let routes: ComputerRoutes;+let A = "";+let B = "";+/** Two sessions of account A (two devices), and one of account B. */+let a1 = "";+let a2 = "";+let b1 = "";+const drivers: WorkerDriver[] = [];++function settings() {+ setSetting("comfyWhere", "workers");+ setSetting("comfyUrl", "");+ setSetting("engineMode", "open");+ setSetting("demoMode", "off");+}++beforeAll(async () => {+ comfy = await startStandInComfy({ steps: 4, stepMs: 20 });+ svc = await startStandInBilling();+ allowed = [comfy.url];+ routes = await loadRoutes();+ auth.setPassword("install password");+ const session = (id: string) => `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;+ A = auth.createAccount("[email protected]", "long enough").id;+ B = auth.createAccount("[email protected]", "long enough").id;+ a1 = session(A);+ a2 = session(A);+ b1 = session(B);+ settings();+ ensureRunner();+ runnerByHand();+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestDiskFree = undefined;+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ await comfy.close();+ await svc.close();+});+beforeEach(async () => {+ resetRates();+ billing.resetBillingCache();+ qs.saveQueueSettings(qs.QUEUE_DEFAULTS);+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_BILLING_URL = svc.address;+ process.env.FUOBE_BILLING_TOKEN = svc.token;+ delete process.env.FUOBE_HOSTED_FREE;+ Object.assign(svc, { priced: false, slowMs: 0, slowPath: null, reserveStatus: null, gather: null, maxWaitMs: 20 * MIN, holdLifeMs: 105 * MIN, readTiming: true, policy: JSON.parse(JSON.stringify(FREE_RUNS_POLICY)) });+ await svc.start();+ await comfy.start();+ comfy.inner.restart({ stall: false, failNext: undefined, loseNext: 0, steps: 4, stepMs: 20, previewPicture: undefined });+ settings();+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ db().prepare("DELETE FROM pool_admissions").run();+});+afterEach(() => {+ vi.useRealTimers();+ for (const d of drivers.splice(0)) d.stop();+});++// ---------------------------------------------------------------------------+// The studio's side++/**+ * A worker the owner added and resumed, allowed every lane (or `lanes`), able to run every workflow, and connected (its+ * worker program beat a moment ago: `connected` false, never).+ */+function standInWorker(name = "stand-in", o: { paused?: boolean; lanes?: string[]; connected?: boolean } = {}) {+ const w = pool.addWorker(name);+ const lanes = o.lanes ?? allLanes(loadIndex(), sha).map((l) => l.lane);+ pool.patchWorker(w.id, { paused: !!o.paused, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });+ // Connected once: it said its build (one that takes this studio's job tickets).+ db()+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes, workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);+ if (o.connected !== false) db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);+ return w;+}++/** The worker program for this worker's token, against the stand-in ComfyUI. */+function driver(w: { token: string }): WorkerDriver {+ const d = workerDriver({ routes, token: w.token, comfy });+ drivers.push(d);+ return d;+}++const request = (url: string, o: { method?: string; body?: unknown; cookie?: string } = {}) => {+ const text = o.body === undefined ? undefined : JSON.stringify(o.body);+ const headers: Record<string, string> = { ...SITE_HEADERS, cookie: o.cookie ?? a1, ...(text && { "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }) };+ return new Request(`http://${HOST}${url}`, { method: o.method ?? (text ? "POST" : "GET"), headers, body: text });+};++/** Press Run (POST /api/generations) as a session. */+async function run(body: Record<string, unknown>, cookie = a1) {+ const r = await generationsRoute.POST(request("/api/generations", { body, cookie }));+ return { status: r.status, headers: r.headers, body: (await r.json()) as { items?: { id: string }[]; code?: string; error?: string } };+}++/** The price check before Run. */+async function priceCheck(body: Record<string, unknown>, cookie = a1) {+ const r = await generationsRoute.POST(request("/api/generations?preview=1", { body, cookie }));+ return { status: r.status, body: (await r.json()) as { place?: string; quote?: { allowed: boolean; text: string; code?: string; etaS?: number | null }; error?: string; code?: string } };+}++/** A GET as a browser sends it: the sign-in proxy (src/proxy.ts) first, then the route when the proxy passes it on. */+async function browserGet(url: string, cookie: string, route: (req: Request) => Promise<Response>): Promise<Response> {+ const headers = { ...SITE_HEADERS, cookie };+ const p = await proxy(new NextRequest(`http://${HOST}${url}`, { headers }));+ if (p.headers.get("x-middleware-next") !== "1") return p;+ return route(new Request(`http://${HOST}${url}`, { headers }));+}++/** GET /api/generations/<id> as a session's browser asks it: the answer's status, and the run when it was there. */+async function sessionGet(cookie: string, id: string): Promise<{ status: number; run: RunLike | null }> {+ const r = await browserGet(`/api/generations/${id}`, cookie, (req) => oneRoute.GET(req, { params: Promise.resolve({ id }) } as never));+ return { status: r.status, run: r.ok ? ((await r.json()) as RunLike) : null };+}++/** A small JPEG as a worker sends its preview picture (base64): its bytes start as a JPEG's, then `n` and filler. */+const jpegBase64 = (n: number, size = 2000) => Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from(`preview ${n} `), Buffer.alloc(size, n % 251)]).toString("base64");++/** GET a run's preview picture as a session's browser asks it: the response. */+const previewGet = (cookie: string, url: string) => {+ const id = /^\/api\/generations\/([^/]+)\/preview/.exec(url)![1];+ return browserGet(url, cookie, (req) => previewRoute.GET(req, { params: Promise.resolve({ id }) } as never));+};++/** The picture's first bytes (hex) as the session gets it, or its status when it gets none. */+async function previewOf(cookie: string, url: string): Promise<string> {+ const r = await previewGet(cookie, url);+ return r.ok ? Buffer.from(await r.arrayBuffer()).subarray(0, 12).toString("hex") : String(r.status);+}++/** A run as a session reads it (an answer that isn't OK throws: a person would see an error). */+const sessionRead = (cookie: string) => async (id: string) => {+ const { status, run } = await sessionGet(cookie, id);+ if (!run) throw new Error(`GET /api/generations/${id} answered ${status}`);+ return run;+};++/** A run as the session's list shows it (GET /api/generations, page by page), or null when the list hasn't got it. */+const listRead = (cookie: string) => async (id: string) => {+ let before = "";+ for (let page = 0; page < 20; page++) {+ const r = await browserGet(`/api/generations?limit=50${before && `&before=${before}`}`, cookie, (req) => generationsRoute.GET(req));+ if (!r.ok) throw new Error(`GET /api/generations answered ${r.status}`);+ const items = ((await r.json()) as { items: (RunLike & { id: string; createdAt: number })[] }).items;+ const g = items.find((x) => x.id === id);+ if (g) return g;+ if (items.length < 50) return null;+ const last = items[items.length - 1];+ before = `${last.createdAt}:${last.id}`;+ }+ return null;+};++/**+ * Every place the run's account looks from: a refresh, its session, a second session on another device, and its list.+ * Another account's session and list must never show it.+ */+function watchOf(id: string, extra: Record<string, () => Promise<RunLike | null>> = {}) {+ return new RunWatch(+ {+ refresh: () => getGeneration(id) as RunLike | null,+ session: () => sessionRead(a1)(id),+ "second session": () => sessionRead(a2)(id),+ list: () => listRead(a1)(id),+ ...extra,+ },+ {+ "another account": async () => (await sessionGet(b1, id)).status,+ "another account's list": async () => ((await listRead(b1)(id)) ? 200 : 404),+ },+ );+}++const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as TaskRow | undefined;+const assetsOf = (generationId: string) => (db().prepare("SELECT COUNT(*) AS n FROM assets WHERE generation_id = ?").get(generationId) as { n: number }).n;+const holdOf = (generationId: string) => (db().prepare("SELECT json_extract(request_json, '$.hold') AS hold FROM generations WHERE id = ?").get(generationId) as { hold: string | null }).hold;+/** Runs account A has made. */+const made = () => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ?").get(A) as { n: number }).n;+const done = (g: { status: string } | null | undefined) => !!g && g.status !== "queued" && g.status !== "running";++/** Turn the runner until `fn` says yes (or the tries run out: the last answer). */+async function until<T>(fn: () => T | Promise<T>, tries = 300): Promise<T> {+ let v = await fn();+ for (let i = 0; i < tries && !v; i++) {+ await tick();+ await sleep(20);+ v = await fn();+ }+ return v;+}++/** The run once it has ended (the runner turning until then). */+const ended = (id: string) => until(() => (done(getGeneration(id)) ? (getGeneration(id) as RunLike) : null));++/** Press Run and wait for the run's task in the workers' line. */+async function pressRun(body: Record<string, unknown> = IMAGE, cookie = a1) {+ const r = await run(body, cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const t = await until(() => taskOf(id));+ expect(t, "its task in the workers' line").toBeDefined();+ return { id, task: t! };+}++/**+ * The worker takes jobs and runs them until there is none (or it stops). Every beat answer must let it take jobs+ * (unless the test paused it here): a worker the studio refuses fails here, never as a run that waits.+ */+async function workAll(d: WorkerDriver, max = 10) {+ for (let i = 0; i < max; i++) {+ const a = await d.beat();+ if (a && !d.pausedHere) expect(a.runner, `the studio lets the worker take jobs: ${JSON.stringify(a.worker)}`).toBe(true);+ const r = await d.runOne();+ if (r !== true) return r;+ }+ return true;+}++/** The billing service's reports for a run, once the outbox has sent them. */+async function reportsOf(id: string, want = 1) {+ for (let i = 0; i < 100 && svc.reportsFor(id).length < want; i++) {+ await outbox.sweepBilling();+ await sleep(10);+ }+ return svc.reportsFor(id);+}++/**+ * The three checks: the run ended with its result, exactly once; every look showed only the allowed states; and it was+ * charged once (one hold, one settle).+ */+async function expectOnce(id: string, watch: RunWatch, o: { outputs?: number; prompts?: number; place?: number } = {}) {+ const g = await ended(id);+ await watch.look();+ expect(watch.problems({ place: o.place }), JSON.stringify(watch.path())).toEqual([]);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(g!.outputs!.length).toBe(o.outputs ?? 1);+ expect(assetsOf(id), "files kept for the run").toBe(g!.outputs!.length);+ if (o.prompts !== undefined) expect(comfy.postsOf(taskOf(id)!.prompt_id), "prompts its ComfyUI got").toBe(o.prompts);+ const hold = holdOf(id);+ expect(hold, "the run's hold").toBeTruthy();+ expect(svc.holds.has(hold!)).toBe(true);+ const reports = await reportsOf(id);+ expect(reports).toEqual([{ holdId: hold, kind: "settle", status: "succeeded" }]);+ expect(svc.late).toEqual([]);+ return g!;+}++/** A free run that ended without its result: in plain words, refunded once. */+async function expectFreeFailure(id: string) {+ const g = await ended(id);+ expect(plainFailure(g!, { charged: false }), JSON.stringify(g)).toEqual([]);+ expect(await reportsOf(id)).toEqual([{ holdId: holdOf(id), kind: "refund", status: "failed" }]);+ return g!;+}++// ---------------------------------------------------------------------------++describe("an account's run reaches the workers", () => {+ it("with no ComfyUI address, it becomes the account's task, a stand-in worker renders it, and it shows only In line, Working and the result", async () => {+ const w = standInWorker();+ // Every run free: the price says only "Free".+ const q = await priceCheck(IMAGE);+ expect(q.status, JSON.stringify(q.body)).toBe(200);+ expect(q.body.place).toBe("pool");+ expect(q.body.quote).toMatchObject({ allowed: true, text: "Free" });++ const { id, task } = await pressRun();+ expect(task.principal).toBe(`acct:${A}`);+ expect(task.pools).toBe("pool");+ const watch = watchOf(id);+ await watch.look();+ expect(watch.seen.length).toBe(4);+ expect(watch.seen.every((s) => s.status === "queued" && s.place === 1)).toBe(true);++ const d = driver(w);+ d.onStep(async () => {+ await tick();+ await watch.look();+ });+ expect((await d.beat())?.claimableNow).toBe(1);+ expect(await workAll(d)).toBe(false);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ expect(watch.path("session")).toEqual(["queued", "running", "succeeded"]);+ expect(watch.path("second session")).toEqual(["queued", "running", "succeeded"]);+ // The worker's ComfyUI got its prompt from the worker, under the task's own prompt id.+ expect(comfy.log().filter((e) => e.prompt?.prompt_id === task.prompt_id).map((e) => e.prompt?.client_id)).toEqual([expect.stringMatching(/^worker-/)]);+ expect(svc.holdsOf(A).filter((h) => h.reports.has(id))).toHaveLength(1);+ });+});++/**+ * Time passes on the studio's clock (Date only: everything else runs as it does), a minute at a time: each minute the+ * workers beat, the runner turns, and the run is looked at.+ */+async function pass(ms: number, ds: WorkerDriver[], watch?: RunWatch, every = MIN) {+ for (let t = 0; t < ms; t += every) {+ vi.setSystemTime(Date.now() + every);+ for (const d of ds) await d.beat();+ await tick();+ await watch?.look();+ }+}+const clock = () => vi.useFakeTimers({ toFake: ["Date"], shouldAdvanceTime: true });++/** The worker steps aside for another program at its first report that the job runs (its next beat says so). */+function stepAsideWhenRunning(d: WorkerDriver, watch: RunWatch, why = "gpu-busy:game.exe", before?: () => Promise<void>) {+ let stepped = false;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running" || stepped) return;+ stepped = true;+ await before?.();+ d.pause(why);+ await d.beat();+ });+ return () => stepped;+}++/** The worker runs on, and every step is looked at. */+function lookAtEveryStep(d: WorkerDriver, watch: RunWatch) {+ d.onStep(async () => {+ await tick();+ await watch.look();+ });+}++describe("a worker that stops and starts again", () => {+ it("stopped right after the studio heard its job finished, and started again with its ComfyUI still up, it sends the result: one prompt, one output", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const first = driver(w);+ lookAtEveryStep(first, watch);+ first.stopAfter("finished");+ await first.beat();+ expect(await first.runOne()).toBe("stopped");+ expect(first.dead).toBe(true);+ expect(taskOf(id)!.state).toBe("collecting");+ // The same worker, started again: its job is still its own, and it sends what its ComfyUI made.+ const again = driver(w);+ lookAtEveryStep(again, watch);+ expect(await workAll(again)).toBe(false);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("stopped right after its claim, its job waits for it: when it starts again within two minutes it runs it", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const first = driver(w);+ first.stopAfter("claim");+ await first.beat();+ expect(await first.runOne()).toBe("stopped");+ await tick();+ await watch.look();+ const again = driver(w);+ lookAtEveryStep(again, watch);+ expect(await workAll(again)).toBe(false);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a busy studio (429) while it sends the result is waited out: one output", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ lookAtEveryStep(d, watch);+ d.answer("part", 429, 5);+ expect(await workAll(d)).toBe(false);+ expect(d.calls.filter((c) => c.startsWith("part")).length).toBeGreaterThan(5);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });+});++describe("a refresh, a second session and the list see the same run", () => {+ it("in line behind another account's run, then working, then its result: every look shows the same state, place and step", async () => {+ const w = standInWorker();+ const theirs = await pressRun(IMAGE, b1);+ const { id } = await pressRun();+ const watch = watchOf(id);+ expect((await watch.look()).map((s) => [s.status, s.place])).toEqual(Array(4).fill(["queued", 2]));+ comfy.inner.opts.steps = 10;+ comfy.inner.opts.stepMs = 200;+ const d = driver(w);+ const together: (number | null)[][] = [];+ d.onStep(async (step) => {+ await tick();+ const now = await watch.look();+ if (step === "running" && now.every((s) => s.status === "running")) together.push(now.map((s) => s.progress));+ });+ expect(await workAll(d)).toBe(false);+ expect(getGeneration(theirs.id)?.status).toBe("succeeded");+ // It waited behind the other run, then it was first in line.+ const places = watch.seen.filter((s) => s.status === "queued").map((s) => s.place);+ expect(places).toContain(2);+ expect(places).toContain(1);+ // While it ran, every look at one moment shows the same step (within one).+ expect(together.length).toBeGreaterThan(0);+ for (const at of together) expect(Math.max(...at.map((p) => p ?? 0)) - Math.min(...at.map((p) => p ?? 0))).toBeLessThanOrEqual(1 / 10 + 1e-9);+ expect(together.some((at) => at.every((p) => (p ?? 0) > 0))).toBe(true);+ await expectOnce(id, watch, { prompts: 1, place: 2 });+ });+});++describe("a run's preview picture while it works", () => {+ it("the Working tile gets the worker's latest picture, for the run's own account only and never kept by a cache; it goes when the run ends", async () => {+ const w = standInWorker();+ const { id, task } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ let n = 0;+ d.previews(() => jpegBase64(++n));+ const seen: { session?: string; list?: string; picture: string; headers: Record<string, string | null>; other: number; guest: number }[] = [];+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running" || seen.length) return;+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ if (!g.preview) return;+ const listed = (await listRead(a1)(id)) as (RunLike & { preview?: string }) | null;+ const r = await previewGet(a2, g.preview);+ seen.push({+ session: g.preview,+ list: listed?.preview,+ picture: Buffer.from(await r.arrayBuffer()).subarray(0, 3).toString("hex"),+ headers: { type: r.headers.get("content-type"), cache: r.headers.get("cache-control"), sniff: r.headers.get("x-content-type-options") },+ other: (await previewGet(b1, g.preview)).status,+ guest: (await previewGet("", g.preview)).status,+ });+ });+ await workAll(d);+ expect(seen).toHaveLength(1);+ const [s] = seen;+ expect(s.session).toMatch(new RegExp(`^/api/generations/${id}/preview\\?at=\\d+$`));+ expect(s.list, "the list carries it too").toBe(s.session);+ expect(s.picture).toBe("ffd8ff");+ expect(s.headers).toEqual({ type: "image/jpeg", cache: "private, no-store", sniff: "nosniff" });+ expect(s.other, "another account").toBe(403);+ expect(s.guest, "a guest").toBe(401);+ // Ended: no picture is left, and its address answers nothing.+ const g = (await expectOnce(id, watch, { prompts: 1, place: 1 })) as RunLike & { preview?: string };+ expect(g.preview).toBeUndefined();+ expect((await previewGet(a1, s.session!)).status).toBe(404);+ expect(taskOf(id)!.preview_at).toBeNull();+ expect(tasks.runPreview(id)).toBeNull();+ expect(fs.existsSync(path.join(tasks.relayDir(), "tasks", task.id, "preview.jpg"))).toBe(false);+ });++ it("back in line, the run shows no picture of the attempt before", async () => {+ clock();+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ d.previews(() => jpegBase64(1));+ let had = "";+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running" || had) return;+ had = ((await sessionRead(a1)(id)) as RunLike & { preview?: string }).preview ?? "";+ if (!had) return;+ d.pause("gpu-busy:game.exe");+ await d.beat();+ });+ await workAll(d);+ expect(had).toMatch(/\/preview\?at=/);+ await tick();+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ expect(g).toMatchObject({ status: "queued", queue: { place: 1 } });+ expect(g.preview).toBeUndefined();+ expect((await previewGet(a1, had)).status).toBe(404);+ d.pause(null);+ d.previews(null);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { place: 1 });+ });++ it("a picture that isn't a JPEG, is over 64 KB or comes within 2 s of the last is dropped; a person's own computer keeps none", async () => {+ standInWorker();+ const { id, task } = await pressRun();+ db().prepare("UPDATE relay_tasks SET state = 'running', lease_hash = 'this-attempt' WHERE id = ?").run(task.id);+ const now = Date.now();+ const t = { ...taskOf(id)!, preview_at: null };+ expect(tasks.notePreview(t, Buffer.from("not a picture").toString("base64"), now)).toBe(false);+ expect(tasks.notePreview(t, jpegBase64(1, 70 * 1024), now)).toBe(false);+ expect(tasks.notePreview(t, "%%%", now)).toBe(false);+ expect(tasks.notePreview({ ...t, pools: null }, jpegBase64(1), now)).toBe(false);+ expect(tasks.notePreview({ ...t, preview: 0 }, jpegBase64(1), now)).toBe(false);+ expect(tasks.notePreview({ ...t, preview_at: now - 1000 }, jpegBase64(1), now)).toBe(false);+ expect(tasks.notePreview({ ...t, preview_at: now - 2000 }, jpegBase64(1), now)).toBe(true);+ tasks.dropProgress(t.id);+ });++ it("a step or a picture that comes after another app process sent the task back in line, or gave it to another attempt, leaves nothing behind", async () => {+ standInWorker();+ const { id, task } = await pressRun();+ const folder = path.join(tasks.relayDir(), "tasks", task.id);+ const left = () => (fs.existsSync(folder) ? fs.readdirSync(folder).filter((f) => f.startsWith("preview")) : []);+ db().prepare("UPDATE relay_tasks SET state = 'running', lease_hash = 'first-attempt' WHERE id = ?").run(task.id);+ const late = { ...taskOf(id)! };+ const now = Date.now();+ // The other process sent it back in line meanwhile.+ db().prepare("UPDATE relay_tasks SET state = 'waiting', lease_hash = NULL WHERE id = ?").run(task.id);+ tasks.noteProgress(task.id, { value: 3, max: 4 }, now, late.lease_hash);+ expect(tasks.notePreview(late, jpegBase64(1), now)).toBe(false);+ expect(taskOf(id)).toMatchObject({ progress_json: null, preview_at: null });+ expect(left()).toEqual([]);+ // Another worker took it again (a new lease): the first attempt's late report still leaves nothing.+ db().prepare("UPDATE relay_tasks SET state = 'running', lease_hash = 'second-attempt' WHERE id = ?").run(task.id);+ tasks.noteProgress(task.id, { value: 3, max: 4 }, now, late.lease_hash);+ expect(tasks.notePreview(late, jpegBase64(1), now)).toBe(false);+ expect(taskOf(id)).toMatchObject({ progress_json: null, preview_at: null });+ expect(left()).toEqual([]);+ // The attempt that holds it now is kept.+ tasks.noteProgress(task.id, { value: 1, max: 4 }, now, "second-attempt");+ expect(tasks.notePreview({ ...taskOf(id)! }, jpegBase64(2), now)).toBe(true);+ expect(tasks.taskProgress(taskOf(id)!)).toMatchObject({ value: 1, max: 4 });+ expect(left()).toEqual(["preview.jpg"]);+ // Ended: both go.+ tasks.endTask(task.id, "canceled");+ expect(left()).toEqual([]);+ });++ it("a task a worker claims again shows nothing of the attempt before it until the new one reports", async () => {+ const w = standInWorker();+ const { id, task } = await pressRun();+ const file = path.join(tasks.relayDir(), "tasks", task.id, "preview.jpg");+ db()+ .prepare("UPDATE relay_tasks SET state = 'waiting', lease_hash = NULL, worker_id = NULL, progress_json = ?, preview_at = ? WHERE id = ?")+ .run(JSON.stringify({ value: 3, max: 4, at: Date.now() }), Date.now(), task.id);+ // Left from an attempt before (a process that stopped part way never dropped it).+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, Buffer.from(jpegBase64(1), "base64"));+ const d = driver(w);+ let atClaim: { progress_json: string | null; preview_at: number | null; file: boolean } | null = null;+ d.onStep((step) => {+ if (step === "claim" && !atClaim) atClaim = { ...taskOf(id)!, file: fs.existsSync(file) };+ });+ await workAll(d);+ expect(atClaim).toMatchObject({ progress_json: null, preview_at: null, file: false });+ expect((await ended(id))?.status).toBe("succeeded");+ });++ it("a worker's preview pictures reach the Working tile: the latest shows, and the studio keeps at most one every 2 s", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 8;+ comfy.inner.opts.stepMs = 600;+ // The worker sends a picture with every progress report here (the worker program's own sender, which makes+ // ComfyUI's pictures small JPEGs and sends one every 2 s at most, is checked in worker-cpu-slot.test.ts).+ const d = driver(w);+ let n = 0;+ d.previews(() => jpegBase64(++n));+ const kept: number[] = [];+ const shown: string[] = [];+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running") return;+ const at = taskOf(id)?.preview_at ?? null;+ if (at !== null && at !== kept.at(-1)) kept.push(at);+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ if (g.preview) shown.push(Buffer.from(await (await previewGet(a1, g.preview)).arrayBuffer()).subarray(4, 12).toString("latin1"));+ });+ await workAll(d);+ expect(kept.length, "pictures kept").toBeGreaterThanOrEqual(2);+ for (let i = 1; i < kept.length; i++) expect(kept[i] - kept[i - 1]).toBeGreaterThanOrEqual(1500);+ expect(shown.length).toBeGreaterThan(0);+ for (const s of shown) expect(s).toBe("preview ");+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a run whose outputs the moderation service sees first shows no preview while it works: no address, and the picture's address answers nothing", async () => {+ const mod = await startFakeModeration();+ process.env.FUOBE_MODERATION_URL = mod.url;+ // An answer with no checkOutputs field: its outputs are checked first.+ mod.run = { allowed: true };+ try {+ const w = standInWorker();+ const { id, task } = await pressRun();+ expect(taskOf(id)!.preview, "its ComfyUI is asked for no previews").toBe(0);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 300;+ comfy.inner.opts.previewPicture = (step) => ({ type: "image/jpeg", data: Buffer.from(jpegBase64(step), "base64") });+ const d = driver(w);+ // A worker that sends a picture anyway.+ d.previews(() => jpegBase64(1));+ const looks: { preview?: string; route: number }[] = [];+ d.onStep(async (step) => {+ if (step !== "running") return;+ const g = (await sessionRead(a1)(id)) as RunLike & { preview?: string };+ looks.push({ preview: g.preview, route: (await previewGet(a1, `/api/generations/${id}/preview?at=1`)).status });+ });+ await workAll(d);+ expect(looks.length).toBeGreaterThan(0);+ expect(looks.every((l) => l.preview === undefined && l.route === 404), JSON.stringify(looks)).toBe(true);+ expect(taskOf(id)!.preview_at).toBeNull();+ expect(fs.existsSync(path.join(tasks.relayDir(), "tasks", task.id, "preview.jpg"))).toBe(false);+ // Its result shows once the check passes.+ await until(async () => (await tick(), getGeneration(id)?.status === "succeeded"));+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ await mod.close();+ }+ });++ it("a worker's report with a picture over 64 KB is taken without the picture, and the run goes on", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ d.previews(() => jpegBase64(1, 66 * 1024));+ const previews: (string | undefined)[] = [];+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step === "running") previews.push(((await sessionRead(a1)(id)) as RunLike & { preview?: string }).preview);+ });+ await workAll(d);+ expect(d.steps).toContain("running");+ expect(previews.length).toBeGreaterThan(0);+ expect(previews.every((p) => p === undefined)).toBe(true);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a picture the studio can't keep (its file is open elsewhere, or the disk is full) never fails the worker's report: the run goes on and its output arrives", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ let n = 0;+ d.previews(() => jpegBase64(++n));+ const realRename = fs.renameSync.bind(fs);+ const spy = vi.spyOn(fs, "renameSync").mockImplementation((from, to) => {+ if (String(to).endsWith("preview.jpg")) throw Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM" });+ return realRename(from, to);+ });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ // What the task's folder holds while it runs: no picture kept, and nothing half-written left beside it.+ const left: string[][] = [];+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ const dir = path.dirname(tasks.outputFile(taskOf(id)!.id, 0));+ if (step === "running" && fs.existsSync(dir)) left.push(fs.readdirSync(dir).filter((f) => f.startsWith("preview")));+ });+ try {+ await workAll(d);+ expect(d.steps).toContain("running");+ expect(spy.mock.calls.some(([, to]) => String(to).endsWith("preview.jpg")), "a picture was sent and couldn't be kept").toBe(true);+ expect(left.length).toBeGreaterThan(0);+ expect(left.flat()).toEqual([]);+ } finally {+ spy.mockRestore();+ warn.mockRestore();+ }+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });+});++describe("the owner's own job on the workers", () => {+ it("with hosted runs off, it shows no preview picture, as before: its worker is never asked for one, and one sent anyway is dropped", async () => {+ delete process.env.FUOBE_HOSTED_RUNS;+ delete process.env.FUOBE_BILLING_URL;+ try {+ const w = standInWorker();+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ const { id } = await pressRun(IMAGE, owner);+ expect(taskOf(id)!.principal).toBe("owner");+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ let n = 0;+ d.previews(() => jpegBase64(++n));+ const asked: number[] = [];+ const shown: (string | undefined)[] = [];+ d.onStep(async (step) => {+ await tick();+ if (step !== "running") return;+ asked.push(tasks.showsPreview(taskOf(id)!) ? 1 : 0);+ shown.push(((await sessionRead(owner)(id)) as RunLike & { preview?: string }).preview);+ });+ await workAll(d);+ expect(shown.length).toBeGreaterThan(0);+ expect(asked.every((x) => x === 0), "the claim asks for no picture").toBe(true);+ expect(shown.every((p) => p === undefined), "no picture shows").toBe(true);+ expect(taskOf(id)!.preview_at).toBeNull();+ await until(() => getGeneration(id)?.status === "succeeded");+ } finally {+ process.env.FUOBE_HOSTED_RUNS = "1";+ }+ });++ it("waiting, it carries its place in their line in the list as after a refresh", async () => {+ const w = standInWorker();+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ const theirs = await pressRun(IMAGE, b1);+ const { id } = await pressRun(IMAGE, owner);+ expect(taskOf(id)!.principal).toBe("owner");+ const one = (await sessionRead(owner)(id)) as RunLike & { queue?: { place: number } };+ const listed = (await listRead(owner)(id)) as (RunLike & { queue?: { place: number } }) | null;+ // People's runs go first: the owner's job is second.+ expect(one.queue?.place).toBe(2);+ expect(listed?.queue).toEqual(one.queue);+ const d = driver(w);+ lookAtEveryStep(d, watchOf(theirs.id));+ await workAll(d);+ expect((await ended(id))?.status).toBe("succeeded");+ });+});++describe("a press of Run sent twice (a network drop at submit)", () => {+ it("makes one run and one hold: the resend gets the run the first send made", async () => {+ const w = standInWorker();+ const holds = svc.holds.size;+ const rows = made();+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ const first = await run(press);+ // The answer never reached the page: it sends the same press again.+ const again = await run(press);+ expect(first.status, JSON.stringify(first.body)).toBe(201);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ const id = first.body.items![0].id;+ expect(again.body.items!.map((g) => g.id)).toEqual(first.body.items!.map((g) => g.id));+ expect(made() - rows, "runs made").toBe(1);+ expect(svc.holds.size - holds, "holds made").toBe(1);+ // The reserve names the press, as the account's own (never the page's id as it is).+ const ids = svc.callsOf("/v1/reserve").slice(-1).map((c) => (c.body as { requestId?: string }).requestId);+ expect(ids[0]).toMatch(/^r_[0-9a-f]{32}$/);+ expect(ids).not.toContain(press.requestId);+ // Another account's press under the same page id is its own press.+ const theirs = await run(press, b1);+ expect(theirs.status, JSON.stringify(theirs.body)).toBe(201);+ expect(theirs.body.items![0].id).not.toBe(id);+ expect(svc.holds.size - holds, "holds made").toBe(2);+ const d = driver(w);+ const watch = watchOf(id);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a resend that comes while the first send still waits for the billing service makes no second run or hold", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const holds = svc.holds.size;+ const rows = made();+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ await svc.downFor(3000);+ const first = run(press);+ await sleep(1000);+ // A proxy cut the first request short: the page sends the press again.+ const again = run(press);+ const [a, b] = await Promise.all([first, again]);+ expect(a.status, JSON.stringify(a.body)).toBe(201);+ expect(b.status, JSON.stringify(b.body)).toBe(201);+ expect(b.body.items!.map((g) => g.id)).toEqual(a.body.items!.map((g) => g.id));+ expect(made() - rows, "runs made").toBe(1);+ expect(svc.holds.size - holds, "holds made").toBe(1);+ });++ it("a send that stops waiting for the billing service after a resend of the same press made its run leaves that run's hold alone", async () => {+ const w = standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const was = { ...billing.RESERVE_RETRY };+ // One try for the first send, then its whole wait is over.+ Object.assign(billing.RESERVE_RETRY, { forMs: 3000, firstMs: 200 });+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ try {+ // The service answers the first send's reserve only after the app stopped waiting for it.+ Object.assign(svc, { slowMs: 2500, slowPath: "/v1/reserve" });+ const reserves = svc.callsOf("/v1/reserve").length;+ const first = run(press);+ for (let i = 0; i < 200 && svc.callsOf("/v1/reserve").length === reserves; i++) await sleep(10);+ expect(svc.callsOf("/v1/reserve").length, "the first send's reserve reached the service").toBe(reserves + 1);+ // The page sends the press again, and the service answers that one at once: it makes the run.+ Object.assign(svc, { slowMs: 0, slowPath: null });+ const again = await run(press);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ const id = again.body.items![0].id;+ // Only then does the first send stop waiting.+ expect((await first).status).toBe(503);+ expect(made() - rows, "runs made").toBe(1);+ const hold = svc.holds.get(holdOf(id)!)!;+ const requestId = hold.requestId;+ expect(db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE key = ?").get(`release:request:${requestId}`)).toEqual({ n: 0 });+ await outbox.drainOutbox(Date.now() + outbox.REQUEST_RELEASE_AFTER_MS + 1000);+ expect(hold.released, "the run's hold stays open").toBe(false);+ expect(svc.callsOf("/v1/release").some((c) => (c.body as { requestId?: string }).requestId === requestId)).toBe(false);+ // The run finishes and settles against its own hold.+ const watch = watchOf(id);+ const d = driver(w);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { place: 1 });+ expect(hold.released).toBe(false);+ } finally {+ Object.assign(billing.RESERVE_RETRY, was);+ }+ });++ it("a press refused by the limits after its hold was made gives the hold back, and a resend of it is a new try with a hold of its own, never a run against that hold", async () => {+ standInWorker();+ (svc.policy as { limits: { activeRuns: number } }).limits.activeRuns = 1;+ billing.resetBillingCache();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ // The first press's reserve is slow; meanwhile another press makes a run, so the first is over the limit once+ // its hold is made.+ Object.assign(svc, { slowMs: 800, slowPath: "/v1/reserve" });+ const reserves = svc.callsOf("/v1/reserve").length;+ const first = run(press);+ for (let i = 0; i < 200 && svc.callsOf("/v1/reserve").length === reserves; i++) await sleep(10);+ Object.assign(svc, { slowMs: 0, slowPath: null });+ const other = await run({ ...IMAGE, requestId: `press-${crypto.randomUUID()}` });+ expect(other.status, JSON.stringify(other.body)).toBe(201);+ const a = await first;+ expect(a.status, JSON.stringify(a.body)).toBe(429);+ expect(made() - rows, "runs made").toBe(1);+ const reserve = svc.callsOf("/v1/reserve").find((c, i) => i >= reserves && (c.body as { requestId?: string }).requestId !== undefined);+ const requestId = (reserve!.body as { requestId: string }).requestId;+ const hold = [...svc.holds.values()].find((h) => h.requestId === requestId)!;+ for (let i = 0; i < 100 && !hold.released; i++) {+ await outbox.sweepBilling();+ await sleep(10);+ }+ expect(hold.released, "the refused press's hold goes back").toBe(true);+ // The other run ends, so the limit lets the press through now; its answer was lost, and the page sends it again.+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(other.body.items![0].id);+ const before = svc.callsOf("/v1/reserve").length;+ const again = await run(press);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ const tried = svc.callsOf("/v1/reserve").slice(before).map((c) => (c.body as { requestId?: string }).requestId);+ expect(tried.length, "one new reserve").toBe(1);+ expect(tried[0], "under a request id of its own").not.toBe(requestId);+ const runId = again.body.items![0].id;+ expect(svc.holds.get(holdOf(runId)!)?.requestId).toBe(tried[0]);+ expect(hold.released, "the first try's hold stays given back").toBe(true);+ expect(made() - rows, "runs made").toBe(2);+ // Sent once more: the run it made, with no new reserve.+ const third = await run(press);+ expect(third.body.items!.map((g) => g.id)).toEqual([runId]);+ expect(svc.callsOf("/v1/reserve").length).toBe(before + 1);+ });++ it("with hosted runs off, a press id changes nothing: each request makes its run, as before", async () => {+ delete process.env.FUOBE_HOSTED_RUNS;+ delete process.env.FUOBE_BILLING_URL;+ try {+ standInWorker();+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ const owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ const first = await run(press, owner);+ const again = await run(press, owner);+ expect(first.status, JSON.stringify(first.body)).toBe(201);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ expect(again.body.items![0].id).not.toBe(first.body.items![0].id);+ expect((db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE request_id = ?").get(press.requestId) as { n: number }).n).toBe(0);+ } finally {+ process.env.FUOBE_HOSTED_RUNS = "1";+ }+ });+});++describe("a reserve the billing service refuses or never answers", () => {+ it("an answer that would be the same on every try (a refused request) is a refusal in plain words at once, not after the whole wait", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const reserves = svc.callsOf("/v1/reserve").length;+ svc.reserveStatus = 401;+ const t = Date.now();+ const r = await run(IMAGE);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ expect(Date.now() - t).toBeLessThan(5000);+ expect(svc.callsOf("/v1/reserve").length - reserves, "tries").toBe(1);+ expect(made()).toBe(rows);+ // Nothing was held there, so nothing is released.+ expect((db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE key LIKE 'release:request:%' AND created_at >= ?").get(t) as { n: number }).n).toBe(0);+ });++ it("a press whose tries got no answer in time is refused within the whole wait, the hold the service made meanwhile goes back, and a resend of it is a new try", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const was = { ...billing.RESERVE_RETRY };+ Object.assign(billing.RESERVE_RETRY, { forMs: 3000, firstMs: 200 });+ // The service takes each reserve, but answers only after the app stopped waiting.+ Object.assign(svc, { slowMs: 2500, slowPath: "/v1/reserve" });+ const press = { ...IMAGE, requestId: `press-${crypto.randomUUID()}` };+ try {+ const t = Date.now();+ const r = await run(press);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ expect(Date.now() - t, "within the whole wait").toBeLessThanOrEqual(3000 + 500);+ expect(made()).toBe(rows);+ await sleep(600);+ const held = [...svc.holds.values()].filter((h) => h.account === A && !h.released && h.createdAt >= t);+ expect(held.length, "the service made a hold the app never heard of").toBe(1);+ // Its release waits a minute (a reserve still on its way is answered first), then goes.+ await outbox.drainOutbox(Date.now() + 1000);+ expect(held[0].released).toBe(false);+ await outbox.drainOutbox(Date.now() + outbox.REQUEST_RELEASE_AFTER_MS + 1000);+ expect(held[0].released, "released by its request id").toBe(true);+ expect(svc.callsOf("/v1/release").some((c) => (c.body as { requestId?: string }).requestId === held[0].requestId)).toBe(true);+ // The page sends the same press again: a new try, under a request id of its own, never the hold that went back.+ Object.assign(svc, { slowMs: 0, slowPath: null });+ const reserves = svc.callsOf("/v1/reserve").length;+ const again = await run(press);+ expect(again.status, JSON.stringify(again.body)).toBe(201);+ const tried = svc.callsOf("/v1/reserve").slice(reserves).map((c) => (c.body as { requestId?: string }).requestId);+ expect(tried.length).toBe(1);+ expect(tried[0]).not.toBe(held[0].requestId);+ expect(svc.holds.get(holdOf(again.body.items![0].id)!)?.requestId).toBe(tried[0]);+ expect(made()).toBe(rows + 1);+ } finally {+ Object.assign(billing.RESERVE_RETRY, was);+ }+ });+});++describe("the worker steps aside for another program", () => {+ it("a game takes the GPU for 40 minutes from minute 15: the run goes back in line in its place, waits past its wait limit, and its output arrives with no error", async () => {+ clock();+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ // Minute 15 of a long render: a game starts, and the worker steps aside at its next beat.+ const stepped = stepAsideWhenRunning(d, watch, "gpu-busy:game.exe", () => pass(15 * MIN, [d], watch));+ await workAll(d);+ expect(stepped()).toBe(true);+ const back = taskOf(id)!;+ expect(back.state).toBe("waiting");+ expect(back.requeues, "a step aside costs no attempt").toBe(0);+ // The game runs for 40 minutes, past the run's 20 minute wait limit. Near its end, another account presses Run: with+ // the only worker stepped aside, no run is made that would wait for nothing (the price check says it starts soon).+ await pass(35 * MIN, [d], watch);+ const all = () => (db().prepare('SELECT COUNT(*) AS n FROM generations').get() as { n: number }).n;+ const rows = all();+ const holds = svc.holds.size;+ const theirs = await run(IMAGE, b1);+ expect(theirs.status, JSON.stringify(theirs.body)).toBe(503);+ expect(theirs.body).toMatchObject({ error: billing.BILLING_WAIT.run, code: "busy" });+ expect((await priceCheck(IMAGE, b1)).body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });+ expect(all()).toBe(rows);+ expect(svc.holds.size).toBe(holds);+ await pass(5 * MIN, [d], watch);+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });+ // The game ends: it runs first, in its place, and settles against the hold it was given at Run.+ const hold = holdOf(id);+ d.pause(null);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { place: 1 });+ expect(svc.reportsFor(id).map((r) => r.holdId)).toEqual([hold]);+ });++ it("with the studio's own wait limit (no billing service), the same: a run a worker took once never fails at the wait limit", async () => {+ clock();+ delete process.env.FUOBE_BILLING_URL;+ process.env.FUOBE_HOSTED_FREE = "1";+ process.env.FUOBE_POOL_WAIT_MIN = "20";+ try {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ stepAsideWhenRunning(d, watch, "gpu-busy:blender.exe");+ await workAll(d);+ await pass(40 * MIN, [d], watch);+ expect(getGeneration(id)).toMatchObject({ status: "queued", queue: { place: 1 } });+ d.pause(null);+ lookAtEveryStep(d, watch);+ await workAll(d);+ const g = await ended(id);+ await watch.look();+ expect(watch.problems({ place: 1 })).toEqual([]);+ expect(g?.status).toBe("succeeded");+ expect(g!.outputs).toHaveLength(1);+ expect(assetsOf(id)).toBe(1);+ } finally {+ delete process.env.FUOBE_POOL_WAIT_MIN;+ }+ });++ it("a look at the run that fails while it waits back in line past its wait limit changes nothing: it stays In line in its place, and its output arrives", async () => {+ clock();+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ stepAsideWhenRunning(d, watch, "gpu-busy:game.exe");+ await workAll(d);+ expect(taskOf(id)!.state).toBe("waiting");+ // The game runs 25 minutes, past the run's 20 minute wait limit.+ await pass(25 * MIN, [d], watch);+ expect(getGeneration(id)?.status).toBe("queued");+ // One look of the runner's fails (a busy database in a deploy's overlap, say).+ const spy = vi.spyOn(comfyProvider, "poll").mockRejectedValueOnce(new Error("database is locked"));+ try {+ await tick();+ expect(spy).toHaveBeenCalled();+ } finally {+ spy.mockRestore();+ }+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });+ expect(taskOf(id)!.state).toBe("waiting");+ // The game ends: it runs, and nothing was lost.+ d.pause(null);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { place: 1 });+ });+});++describe("retries", () => {+ it("its ComfyUI crashes twice, then works: back in line once with its place kept, and the output arrives once", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ let crashes = 0;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ // Its ComfyUI crashes twice while running the job (it comes back empty).+ if (step === "running" && crashes < 2) {+ crashes++;+ await comfy.crash();+ await comfy.start();+ }+ });+ await workAll(d);+ expect(crashes).toBe(2);+ expect(d.steps.filter((s) => s === "gone")).toHaveLength(2);+ // The worker's resend took the first loss; the second put it back in line, which counts once.+ expect(taskOf(id)!.requeues).toBe(1);+ await expectOnce(id, watch, { place: 1 });+ expect(watch.path("session")).toContain("queued");+ });+});++describe("a run that can never succeed here", () => {+ /** A worker that may run every lane but the picture model's. */+ const workerWithoutTheModel = () => standInWorker("without-the-model", { lanes: allLanes(loadIndex(), sha).map((l) => l.lane).filter((l) => l !== imageLane()) });++ it("no worker has the model: Run is refused and nothing is made (no run, no task, no hold)", async () => {+ workerWithoutTheModel();+ const rows = made();+ const taskCount = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;+ const holds = svc.holds.size;+ const r = await run(IMAGE);+ expect(r.status).toBe(403);+ expect(made()).toBe(rows);+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(taskCount);+ expect(svc.holds.size).toBe(holds);+ });++ it("its price check says so before Run, so Run is off and no run is made that would wait for nothing", async () => {+ workerWithoutTheModel();+ const rows = made();+ const q = await priceCheck(IMAGE);+ expect(q.status, JSON.stringify(q.body)).toBe(200);+ expect(q.body.place).toBe("pool");+ expect(q.body.quote).toMatchObject({ allowed: false, code: "not-offered" });+ expect(made()).toBe(rows);+ });+});++describe("no worker online", () => {+ it("with every worker paused, the price check says it starts soon, so Run is off", async () => {+ standInWorker("paused", { paused: true });+ const q = await priceCheck(IMAGE);+ expect(q.status, JSON.stringify(q.body)).toBe(200);+ expect(q.body.place).toBe("pool");+ expect(q.body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });+ // A guest is told the same.+ const g = await priceCheck(IMAGE, "");+ expect(g.body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });+ });++ it("Run pressed while every worker is away makes no run that would wait for nothing, and promises no start; once one is back, Run works", async () => {+ const away = [+ standInWorker("paused here", { connected: true }),+ standInWorker("never connected", { connected: false }),+ standInWorker("silent", {}),+ standInWorker("outside its hours", {}),+ ];+ db().prepare("UPDATE relay_workers SET paused_local = 1, local_why = 'gpu-busy:game.exe' WHERE id = ?").run(away[0].id);+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 3 * MIN, away[2].id);+ pool.patchWorker(away[3].id, { hours: { tz: "UTC", days: {} } });+ const rows = made();+ const holds = svc.holds.size;+ const r = await run(IMAGE);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ // Plain words that promise no start (no run was made), and no billing card: the price check, asked again, says+ // "Starting soon" with Run off.+ expect(r.body).toEqual({ error: billing.BILLING_WAIT.run, code: "busy" });+ expect(r.headers.get("x-fuobe-billing")).toBeNull();+ expect((await priceCheck(IMAGE)).body.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.startingSoon });+ expect(made()).toBe(rows);+ expect(svc.holds.size).toBe(holds);+ // The silent one beats again: Run is back on, and the run goes in line.+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now(), away[2].id);+ expect((await priceCheck(IMAGE)).body.quote).toMatchObject({ allowed: true, text: "Free" });+ const { id } = await pressRun();+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });+ });++ it("a worker making room for local work first is on: the run goes in line", async () => {+ const w = standInWorker();+ db().prepare("UPDATE relay_workers SET local_why = 'waiting-for-yield' WHERE id = ?").run(w.id);+ expect((await priceCheck(IMAGE)).body.quote).toMatchObject({ allowed: true, text: "Free" });+ });+});++describe("one job per worker", () => {+ it("a second claim while the worker holds a job gets nothing new, and a job left sending goes back in line in its place", async () => {+ clock();+ const w = standInWorker();+ const mine = await pressRun();+ const theirs = await pressRun(IMAGE, b1);+ const watch = watchOf(mine.id);+ const d = driver(w);+ await d.beat();+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });+ const claim = async (running: string[]) => {+ const r = await api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "worker", running }) });+ return r.status === 200 ? ((await r.json()) as { task: { id: string } }).task.id : r.status;+ };+ expect(await claim([])).toBe(mine.task.id);+ // It holds that one: a second claim gets nothing new, whatever it says it runs.+ expect(await claim([mine.task.id])).toBe(204);+ expect(await claim([])).toBe(mine.task.id);+ expect(taskOf(theirs.id)!.state).toBe("waiting");+ await tick();+ await watch.look();+ // It never sends the job to its ComfyUI: 15 minutes after the claim the job goes back in line, still first.+ await pass(16 * MIN, [d], watch);+ expect(taskOf(mine.id)!.state).toBe("waiting");+ expect(getGeneration(mine.id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });+ expect(getGeneration(theirs.id)?.queue?.place).toBe(2);+ // Then both run, in that order.+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(mine.id, watch, { place: 1 });+ expect(getGeneration(theirs.id)?.status).toBe("succeeded");+ });+});++describe("the billing service down or restarting", () => {+ it("a run that finishes while the service is down settles once when it is back, and its account sees no error", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ // Down from the moment the run was set aside until after it finished.+ await svc.stop();+ const d = driver(w);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await until(() => done(getGeneration(id)));+ await outbox.sweepBilling();+ expect(svc.reportsFor(id)).toEqual([]);+ await watch.look();+ await svc.start();+ // The outbox's next try.+ await outbox.drainOutbox(Date.now() + 10 * MIN);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("Run pressed while the service restarts waits for it: the run is made once, with one hold, and finishes", async () => {+ const w = standInWorker();+ // The account's policy is known from its price check.+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const holds = svc.holds.size;+ const reserves = svc.callsOf("/v1/reserve").length;+ await svc.downFor(10_000);+ const t = Date.now();+ const r = await run(IMAGE);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(Date.now() - t, "it waited for the service").toBeGreaterThanOrEqual(9_000);+ expect(made() - rows).toBe(1);+ expect(svc.holds.size - holds).toBe(1);+ // Every try was the same press: one request id.+ const ids = new Set(svc.callsOf("/v1/reserve").slice(reserves).map((c) => (c.body as { requestId?: string }).requestId));+ expect(ids.size).toBe(1);+ const id = r.body.items![0].id;+ const watch = watchOf(id);+ const d = driver(w);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a service that stays down past the wait: Run says to try again in a moment, in plain words, and nothing is made", async () => {+ standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const rows = made();+ const was = { ...billing.RESERVE_RETRY };+ Object.assign(billing.RESERVE_RETRY, { forMs: 1500, firstMs: 200 });+ try {+ await svc.stop();+ const r = await run(IMAGE);+ expect(r.status, JSON.stringify(r.body)).toBe(503);+ expect(r.body.error).toBe(billing.BILLING_WAIT.run);+ expect(r.body.error).not.toMatch(/paus|error|service|GPU|worker/i);+ expect(made()).toBe(rows);+ } finally {+ Object.assign(billing.RESERVE_RETRY, was);+ await svc.start();+ }+ });++ it("down for 30 s while one account presses Run and another's run settles: both finish, each settles once, and no error shows", async () => {+ const w = standInWorker();+ expect((await priceCheck(IMAGE)).body.quote?.allowed).toBe(true);+ const theirs = await pressRun(IMAGE, b1);+ await svc.downFor(30_000);+ // Account A presses Run during the outage; meanwhile the worker renders B's run, which finishes and can't settle yet.+ const press = run(IMAGE);+ const d = driver(w);+ d.onStep(() => tick());+ await d.beat();+ expect(await d.runOne()).toBe(true);+ await until(() => done(getGeneration(theirs.id)));+ expect(getGeneration(theirs.id)?.status).toBe("succeeded");+ await outbox.sweepBilling();+ expect(svc.reportsFor(theirs.id)).toEqual([]);+ const r = await press;+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const watch = watchOf(id);+ lookAtEveryStep(d, watch);+ await workAll(d);+ // The outbox's next try reaches the service again.+ await outbox.drainOutbox(Date.now() + 10 * MIN);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ expect(await reportsOf(theirs.id)).toEqual([{ holdId: holdOf(theirs.id), kind: "settle", status: "succeeded" }]);+ expect(svc.late).toEqual([]);+ });++ it("the last policy it gave stands for 10 minutes while it doesn't answer, then runs wait for it", async () => {+ clock();+ expect(await billing.policy(A)).toBeTruthy();+ await svc.stop();+ try {+ vi.setSystemTime(Date.now() + 9 * MIN);+ expect(await billing.policy(A), "9 minutes on").toBeTruthy();+ vi.setSystemTime(Date.now() + 2 * MIN);+ expect(await billing.policy(A), "11 minutes on").toBeNull();+ } finally {+ await svc.start();+ }+ vi.setSystemTime(Date.now() + MIN);+ expect(await billing.policy(A), "answered again").toBeTruthy();+ });+});++describe("the run ceiling per lane", () => {+ it("a run longer than 45 minutes in a lane whose ceiling is 60 minutes finishes", async () => {+ clock();+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [imageLane()]: 3600 } } });+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ let long = false;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step === "running" && !long) {+ long = true;+ await pass(50 * MIN, [d], watch);+ }+ });+ await workAll(d);+ expect(long).toBe(true);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("its hold asks to stay open for the lane's run ceiling and the time back in line: a long run that went back in line still settles against its own hold", async () => {+ clock();+ // A 3 hour lane, and an hour back in line covered. The service's own fixed rule (2 hours after the wait limit) would+ // close the hold before this run ends.+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [imageLane()]: 3 * 3600 } }, pausedBudgetS: 3600 });+ const w = standInWorker();+ const { id } = await pressRun();+ const reserve = svc.callsOf("/v1/reserve").at(-1)!.body as { timing?: { runMs: number; pausedMs: number } };+ const attempt = pool.SENDING_MS + 2 * 3 * 3_600_000 + pool.SAVING_MS;+ expect(reserve.timing).toEqual({ runMs: pool.MAX_ATTEMPTS * attempt, pausedMs: 3_600_000 });+ const hold = svc.holds.get(holdOf(id)!)!;+ expect(hold.closeBy - hold.createdAt).toBe(svc.maxWaitMs + pool.MAX_ATTEMPTS * attempt + 3_600_000);+ const watch = watchOf(id);+ comfy.inner.opts.steps = 6;+ comfy.inner.opts.stepMs = 100;+ const d = driver(w);+ // A game takes the GPU 10 minutes in, for 40 minutes: the run goes back in line in its place.+ const stepped = stepAsideWhenRunning(d, watch, "gpu-busy:game.exe", () => pass(10 * MIN, [d], watch));+ await workAll(d);+ expect(stepped()).toBe(true);+ await pass(40 * MIN, [d], watch);+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: POOL_WORDS.inLine, queue: { place: 1 } });+ // Back, it runs for two and a half hours.+ d.pause(null);+ let long = false;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step === "running" && !long) {+ long = true;+ await pass(150 * MIN, [d], watch);+ }+ });+ await workAll(d);+ expect(long).toBe(true);+ await expectOnce(id, watch, { place: 1 });+ expect(Date.now()).toBeGreaterThan(hold.createdAt + svc.maxWaitMs + svc.holdLifeMs);+ expect(svc.reportsFor(id)).toEqual([{ holdId: hold.id, kind: "settle", status: "succeeded" }]);+ expect(svc.late).toEqual([]);+ });++ it("a run past its lane's ceiling is stopped by its worker and put back in line once, with its place kept; past it again, it ends in plain words", async () => {+ clock();+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [imageLane()]: 600 } } });+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ const after: string[] = [];+ let actedThisClaim = false;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step === "claim") actedThisClaim = false;+ if (step !== "running" || actedThisClaim) return;+ actedThisClaim = true;+ // The attempt runs past the 10 minute ceiling: the studio leaves it to its worker's run limit.+ await pass(11 * MIN, [d], watch);+ after.push(getGeneration(id)!.status);+ // The worker's run limit stops it and gives it back, as the worker program does.+ tasks.report(taskOf(id)!, { event: "give-back", why: "run-limit" }, () => ({ error: "unused" }));+ await tick();+ await watch.look();+ });+ await workAll(d);+ expect(after).toEqual(["running", "running"]);+ expect(watch.path("session")).toEqual(["queued", "running", "queued", "running", "failed"]);+ // Until it truly can't finish: only In line, with its place kept, and Working.+ expect(watch.problems({ place: 1 }).filter((p) => !p.includes('"status":"failed"'))).toEqual([]);+ await expectFreeFailure(id);+ });++ it("each attempt has the lane's ceiling to itself: 7 minutes into a 10 minute ceiling its ComfyUI loses the job, the worker sends it again, and the output arrives once", async () => {+ clock();+ qs.saveQueueSettings({ ...qs.queueSettings(), runCeilingS: { default: 2700, lanes: { [imageLane()]: 600 } } });+ const w = standInWorker();+ const { id, task } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ let crashed = false;+ let resent = false;+ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running") return;+ if (!crashed) {+ // The first attempt runs 7 minutes, then its ComfyUI restarts and loses the job.+ crashed = true;+ await pass(7 * MIN, [d], watch);+ await comfy.crash();+ await comfy.start();+ } else if (!resent && d.steps.includes("gone")) {+ // The worker sent it again: 4 minutes into this attempt (11 since the first began), it is still working.+ resent = true;+ await pass(4 * MIN, [d], watch);+ expect(getGeneration(id)).toMatchObject({ status: "running", message: POOL_WORDS.working });+ }+ });+ await workAll(d);+ expect(crashed && resent).toBe(true);+ await expectOnce(id, watch, { place: 1 });+ // Its ComfyUI got the job twice (once per attempt), under the task's one prompt id.+ expect(comfy.postsOf(task.prompt_id)).toBe(2);+ });+});++describe("the server's disk is low when the result comes", () => {+ it("the run ends in the one plain sentence, never words about uploads or a pause", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ d.onStep(async (step) => {+ await tick();+ // While it renders, the server's disk drops below the free space it keeps.+ if (step === "running") globalThis.__fuobeTestDiskFree = 1;+ });+ try {+ await workAll(d);+ const g = await ended(id);+ expect(g?.status).toBe("failed");+ } finally {+ globalThis.__fuobeTestDiskFree = 1e13;+ }+ const g = await expectFreeFailure(id);+ expect(g.error).not.toBe(ACCOUNT_MESSAGES.diskLow);+ expect(db().prepare("SELECT error FROM generations WHERE id = ?").get(id)).toEqual({ error: ACCOUNT_MESSAGES.diskLow });+ });+});++describe("a deploy while results are being sent", () => {+ it("a burst of 503s while the result is sent ends the run today: the worker gives up after 3 failed parts in a row", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ d.onStep(() => tick());+ // The studio answers 503 to the next 6 parts of its result, as a deploy's proxy does for a few seconds.+ d.answer("part", 503, 6);+ await workAll(d);+ expect(d.calls.filter((c) => c.startsWith("part")).length).toBeGreaterThanOrEqual(3);+ await expectFreeFailure(id);+ });+});++describe("two app processes on one database (a deploy's overlap)", () => {+ let app2: AppProcess;+ const appEnv = () => ({ FUOBE_HOSTED_RUNS: "1", FUOBE_BILLING_URL: svc.address, FUOBE_BILLING_TOKEN: svc.token, COMFYUI_URL: DEAD, FUOBE_PUBLIC_SIGNUP: "1" });+ beforeAll(async () => {+ app2 = await startAppProcess({ dataDir: dir, env: appEnv(), allow: [comfy.url] });+ });+ afterAll(async () => {+ await app2?.stop();+ });++ /** The run as the account's session reads it from the other process. */+ const there = (id: string) => async () => (await app2.generation(id, a1)) as unknown as RunLike;++ /** When the app process that names its turns `token` last said it still runs (none: it exited, or never ran). */+ const seenAt = (token: string) => (db().prepare("SELECT seen_at FROM app_processes WHERE token = ?").get(token) as { seen_at: number } | undefined)?.seen_at;+ /** The app process that holds the turn to save the run's result. */+ const turnOf = (id: string) => (db().prepare("SELECT finish_by FROM generation_runs WHERE id = ?").get(id) as { finish_by: string | null } | undefined)?.finish_by ?? null;+ /** That process is in the middle of saving the run's result: it took the turn, minutes before its turn runs out. */+ const holdTurn = (id: string, token: string) => db().prepare("UPDATE generation_runs SET finish_by = ?, finish_until = ? WHERE id = ?").run(token, Date.now() + 4 * MIN, id);++ /** One more app process on this database, and the name its turns carry. */+ async function anotherApp(): Promise<{ app: AppProcess; token: string }> {+ const tokens = () => (db().prepare("SELECT token FROM app_processes").all() as { token: string }[]).map((r) => r.token);+ const known = new Set(tokens());+ const app = await startAppProcess({ dataDir: dir, env: appEnv(), allow: [comfy.url] });+ const token = tokens().find((t) => !known.has(t));+ if (!token) {+ await app.stop();+ throw new Error("The new app process never said it runs");+ }+ return { app, token };+ }++ it("each app process says its catalog version from its start, before it serves any worker's claim", async () => {+ const version = catalogVersion()!;+ const t0 = Date.now();+ db().prepare("DELETE FROM catalog_processes").run();+ // The other process's beat (every 5 s, from its start) says it again.+ for (let i = 0; i < 100 && !db().prepare("SELECT 1 FROM catalog_processes WHERE version = ?").get(version); i++) await sleep(100);+ const r = db().prepare("SELECT started_at, seen_at FROM catalog_processes WHERE version = ?").get(version) as { started_at: number; seen_at: number } | undefined;+ expect(r, "the catalog version of the app processes").toBeTruthy();+ expect(r!.seen_at).toBeGreaterThanOrEqual(t0);+ expect(r!.started_at).toBeLessThanOrEqual(r!.seen_at);+ });++ it("the other process serves the worker and a session: the same run, the same state", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id, { "other process": there(id) });+ const d = driver(w);+ d.via(app2.api);+ lookAtEveryStep(d, watch);+ await workAll(d);+ expect(d.calls.some((c) => c.startsWith("part"))).toBe(true);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ expect(watch.seen.filter((s) => s.where === "other process").map((s) => s.status)).toContain("succeeded");+ // The other process refuses the run to another account's session too.+ await expect(app2.generation(id, b1)).rejects.toThrow(/answered 403/);+ });++ it("a chain's next step both processes find ready at once is sent once: one job for it on the workers, run once", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ await workAll(d);+ expect((await ended(id))?.status).toBe("succeeded");+ // The run's next step, made as its run's steps are (as the account, on this install's GPUs, with the run's stamp):+ // its input, the first step's picture, is ready for both processes.+ const first = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json);+ const [step] = runOnPool(A, () => withRunStamp(stampOf(first), () => createGenerations({ feature: "image", modelId: "oss-selftest-image", op: "edit", prompt: "invert it", chainFrom: "first" }, { dependsOn: id })));+ const sent = () => (db().prepare("SELECT external_id FROM generations WHERE id = ?").get(step.id) as { external_id: string | null }).external_id;+ const jobs = () => db().prepare("SELECT id FROM relay_tasks WHERE generation_id = ?").all(step.id).length;+ // Both runners turn at the same moment.+ await Promise.all([tick(), app2.tick()]);+ for (let i = 0; i < 200 && !sent(); i++) await sleep(25);+ expect(sent(), "sent by the first turn of one of them").toBeTruthy();+ // (A second hand-over, were there one, lands in the moments after.)+ await sleep(1500);+ await Promise.all([tick(), app2.tick()]);+ expect(jobs(), "its jobs on the workers").toBe(1);++ // It waits at its run's place in line, in its run's class, whichever process sent it.++ expect(taskOf(step.id)).toMatchObject({ rank_at: taskOf(id)!.rank_at, class: taskOf(id)!.class });+ await workAll(d);+ expect((await ended(step.id))?.status).toBe("succeeded");+ expect(jobs()).toBe(1);+ const ran = db().prepare("SELECT COUNT(*) AS n FROM worker_jobs WHERE generation_id = ? AND event = 'finished'").get(step.id) as { n: number };+ expect(ran.n, "the workers ran it once").toBe(1);+ });+++ /** A finished run on the workers and its next step, made as a run's steps are (ready for both processes). */++ async function runAndNextStep() {++ const w = standInWorker();++ const { id } = await pressRun();++ const d = driver(w);++ await workAll(d);++ expect((await ended(id))?.status).toBe("succeeded");++ const first = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json);++ // (Made with the runner's look held back: a test decides who has the step's turn before either process looks.)++ const [step] = runOnPool(A, () => withRunStamp(stampOf(first), () => createGenerations({ feature: "image", modelId: "oss-selftest-image", op: "edit", prompt: "invert it", chainFrom: "first" }, { dependsOn: id })));++ return { id, step: step.id, d };++ }++ const jobsOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ?").all(generationId) as TaskRow[];++ /** An app process that said agoMs ago that it still runs, holding the turn to send the run. */++ const sendingIn = (token: string, id: string, agoMs = 0) => {++ db().prepare("INSERT INTO app_processes (token, started_at, seen_at) VALUES (?, ?, ?) ON CONFLICT(token) DO UPDATE SET seen_at = excluded.seen_at").run(token, Date.now() - 10 * MIN, Date.now() - agoMs);++ db().prepare("INSERT INTO submit_turns (id, held_by, held_at) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET held_by = excluded.held_by").run(id, token, Date.now());++ };++++ it("a chain's next step a third process is sending is left to it by both; once that process has gone quiet, one of them sends it once, at its run's place", async () => {++ const { id, step, d } = await runAndNextStep();++ sendingIn("app-sending", step);++ for (let i = 0; i < 3; i++) await Promise.all([tick(), app2.tick()]);++ expect(jobsOf(step), "no job while the process sending it still runs").toHaveLength(0);++ expect(getGeneration(step)?.status).toBe("queued");++ // It was killed part way (20 s with no word from it).++ sendingIn("app-sending", step, QUIET_MS + 1000);++ await Promise.all([tick(), app2.tick()]);++ for (let i = 0; i < 200 && !jobsOf(step).length; i++) await sleep(25);++ await sleep(1000);++ await Promise.all([tick(), app2.tick()]);++ expect(jobsOf(step), "one job for it on the workers").toHaveLength(1);++ expect(jobsOf(step)[0]).toMatchObject({ rank_at: taskOf(id)!.rank_at, class: taskOf(id)!.class });++ await workAll(d);++ expect((await ended(step))?.status).toBe("succeeded");++ expect(jobsOf(step)).toHaveLength(1);++ });++++ it("a chain's next step whose send was cut off: with no job made yet it is sent once, at its run's place, with no error", async () => {++ const { id, step, d } = await runAndNextStep();++ // Marked as being sent by a process that was killed before it made the step's job.++ db().prepare("UPDATE generations SET external_meta_json = json_object('sending', ?) WHERE id = ?").run(Date.now() - 1000, step);++ sendingIn("app-cut-off", step, QUIET_MS + 1000);++ await Promise.all([tick(), app2.tick()]);++ for (let i = 0; i < 200 && !jobsOf(step).length; i++) await sleep(25);++ await sleep(1000);++ await Promise.all([tick(), app2.tick()]);++ expect(jobsOf(step), "one job for it on the workers").toHaveLength(1);++ expect(jobsOf(step)[0]).toMatchObject({ rank_at: taskOf(id)!.rank_at, class: taskOf(id)!.class });++ await workAll(d);++ const g = await ended(step);++ expect(g?.status, g?.error ?? "").toBe("succeeded");++ expect(jobsOf(step)).toHaveLength(1);++ });++++ it("a chain's next step whose send was cut off after its job was made is never sent twice: it ends in the plain sentence, and that job stops", async () => {++ const { step } = await runAndNextStep();++ // The killed process made the step's job, in the step's place, before it could note it on the step.++ const lane = imageLane();++ const made = tasks.createTask({++ principal: `acct:${A}`,++ generationId: step,++ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },++ pool: { pools: ["pool"], account: A, class: "free", rankAt: Date.now() - MIN, lane, needs: { workflowId: loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 } },++ });++ db().prepare("UPDATE generations SET external_meta_json = json_object('sending', ?) WHERE id = ?").run(Date.now() - 1000, step);++ sendingIn("app-cut-off-2", step, QUIET_MS + 1000);++ await Promise.all([tick(), app2.tick()]);++ const g = await ended(step);++ expect(plainFailure(g!, { charged: false }), JSON.stringify(g)).toEqual([]);++ expect(db().prepare("SELECT error FROM generations WHERE id = ?").get(step)).toEqual({ error: "This run was interrupted while it was being sent. Press Retry." });++ await Promise.all([tick(), app2.tick()]);++ expect(jobsOf(step).map((t) => t.id), "nothing more was sent").toEqual([made.id]);++ expect(jobsOf(step)[0].state, "the job it made stops with it").toBe("canceled");++ });+++ it("a step and a preview picture the worker reports to the other process are seen here too: a refresh, both sessions, the list and the other process show the same step", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id, { "other process": there(id) });+ comfy.inner.opts.steps = 10;+ comfy.inner.opts.stepMs = 200;+ const d = driver(w);+ // The worker's calls reach the other process; this one's runner turns.+ d.via(app2.api);+ let n = 0;+ d.previews(() => jpegBase64(++n));+ const steps: (number | null)[][] = [];+ const pictures: (string | null)[] = [];+ d.onStep(async (step, _path, report) => {+ if (step !== "running" || Number(report?.value ?? 0) < 2) return;+ await tick();+ steps.push((await watch.look()).map((s) => s.progress));+ const g = (await sessionRead(a2)(id)) as RunLike & { preview?: string };+ pictures.push(g.preview ? await previewOf(a2, g.preview) : null);+ });+ await workAll(d);+ expect(steps.length, "looks while the worker said it was past step 2").toBeGreaterThan(0);+ for (const at of steps) {+ for (const p of at) expect(p ?? 0, "the step a look shows").toBeGreaterThan(0);+ expect(Math.max(...at.map((p) => p ?? 0)) - Math.min(...at.map((p) => p ?? 0)), "every look at one moment, the same step").toBeLessThanOrEqual(1 / 10 + 1e-9);+ }+ // The second device loads the picture from this process, though the other one took it.+ expect(pictures.some((p) => p && p.startsWith("ffd8ff"))).toBe(true);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("while one process saves a finished run's result, the other leaves it to that process: the result is saved once, and the run settles once", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id, { "other process": there(id) });+ const d = driver(w);+ // This process's runner turns at every step but the result's parts: the result is saved below.+ d.onStep(async (step) => {+ if (step === "part") return;+ await tick();+ await watch.look();+ });+ await d.beat();+ expect(await d.runOne()).toBe(true);+ expect(taskOf(id)!.state).toBe("done");+ expect(getGeneration(id)?.status).toBe("running");+ // The other process starts saving the result, and is in the middle of moving its file when this one's runner turns.+ const pause = await app2.pauseNextSave();+ const theirs = app2.tick();+ await pause.paused;+ await tick();+ // (Only this process is looked at now: the other one waits in the middle of its move until it is released.)+ expect(getGeneration(id)?.status, "this process leaves the run to the one saving it").toBe("running");+ expect(getGeneration(id)?.message).toBe(POOL_WORDS.working);+ pause.release();+ await theirs;+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a process that stopped while it saved a result leaves it to the other once its turn runs out", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ d.onStep(async (step) => {+ if (step === "part") return;+ await tick();+ await watch.look();+ });+ await d.beat();+ expect(await d.runOne()).toBe(true);+ expect(getGeneration(id)?.status).toBe("running");+ // Another process took the turn and stopped (a deploy ended it) before it saved anything.+ db().prepare("UPDATE generation_runs SET finish_by = 'another-process', finish_until = ? WHERE id = ?").run(Date.now() + 60_000, id);+ await tick();+ expect(getGeneration(id)?.status).toBe("running");+ // Its turn runs out: this process saves the result.+ db().prepare("UPDATE generation_runs SET finish_until = ? WHERE id = ?").run(Date.now() - 1, id);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("an app restarted while it saved a result collects it at once: the app that stopped gave its turn back as it exited", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ d.onStep(async (step) => {+ if (step === "part") return;+ await tick();+ await watch.look();+ });+ await d.beat();+ expect(await d.runOne()).toBe(true);+ expect(getGeneration(id)?.status).toBe("running");+ // The app before the restart was saving the result (it holds the turn, for minutes yet) when it was told to stop.+ const { app, token } = await anotherApp();+ try {+ holdTurn(id, token);+ for (let i = 0; i < 3; i++) await tick();+ expect(getGeneration(id)?.status, "a turn whose app still runs is left to it").toBe("running");+ expect(updateLive(id, { message: POOL_WORDS.inLine })).toBe(false);+ // While it runs, it says so every few seconds: a turn it has held longer than its quiet limit stays its own.+ const quietSince = seenAt(token)! - QUIET_MS - 1000;+ db().prepare("UPDATE app_processes SET seen_at = ? WHERE token = ?").run(quietSince, token);+ for (let i = 0; i < 150 && seenAt(token)! <= quietSince; i++) await sleep(100);+ expect(seenAt(token), "its next word").toBeGreaterThan(quietSince);+ await tick();+ expect(getGeneration(id)?.status).toBe("running");+ expect(turnOf(id)).toBe(token);+ } finally {+ await app.stop();+ }+ // It exited as an app does when it is told to stop: its turn went with it, and this app saves the result now.+ expect(seenAt(token)).toBeUndefined();+ expect(turnOf(id)).toBeNull();+ await tick();+ expect(getGeneration(id)?.status).toBe("succeeded");+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("an app killed while it saved a result leaves it to this one once it has been quiet for 20 s, minutes before its turn runs out", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ d.onStep(async (step) => {+ if (step === "part") return;+ await tick();+ await watch.look();+ });+ await d.beat();+ expect(await d.runOne()).toBe(true);+ const { app, token } = await anotherApp();+ holdTurn(id, token);+ await app.kill();+ // Killed: nothing of it ran as it ended, so its turn and its last word are still there.+ expect(turnOf(id)).toBe(token);+ await tick();+ expect(getGeneration(id)?.status, "its last word is a moment old: it may only be slow").toBe("running");+ // 20 s with no word from it: it stopped, and this app saves the result, long before its turn would run out.+ clock();+ vi.setSystemTime(Date.now() + QUIET_MS + 1000);+ await tick();+ expect(getGeneration(id)?.status).toBe("succeeded");+ expect(turnOf(id)).not.toBe(token);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a stop that lands after another process saved the result, while it waited for the workers, leaves the run saved: its file stays, and it settles once", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id, { "other process": there(id) });+ const d = driver(w);+ d.onStep(async (step) => {+ if (step === "part") return;+ await tick();+ await watch.look();+ });+ await d.beat();+ expect(await d.runOne()).toBe(true);+ expect(getGeneration(id)?.status).toBe("running");+ // The stop (a press of Stop in another tab) asks the run's workers to drop it, and waits for their answer.+ let asked!: () => void;+ const reached = new Promise<void>((r) => (asked = r));+ let answer!: () => void;+ const answered = new Promise<void>((r) => (answer = r));+ const realCancel = comfyProvider.cancel!;+ const cancel = vi.spyOn(comfyProvider, "cancel").mockImplementation(async (ctx) => {+ asked();+ await answered;+ return realCancel.call(comfyProvider, ctx);+ });+ try {+ const stopping = cancelGeneration(id);+ await reached;+ // Meanwhile the other process saves the result.+ await app2.tick();+ expect(getGeneration(id)?.status).toBe("succeeded");+ answer();+ await stopping;+ } finally {+ answer();+ cancel.mockRestore();+ }+ // The stop came too late: the run stays saved with its file, and its report is one settle, never a refund.+ expect(getGeneration(id)?.status).toBe("succeeded");+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });++ it("a run stopped while its result is saved stays stopped, and the file saved for it goes (none is left filling the account's space)", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ // The stop lands while the result is saved: as its file is kept, the run is stopped (a cancel from another tab).+ db().exec(`CREATE TEMP TRIGGER stop_while_saved AFTER INSERT ON assets WHEN NEW.generation_id = '${id}' BEGIN UPDATE generations SET status = 'canceled' WHERE id = '${id}'; END`);+ try {+ await workAll(d);+ await until(() => assetsOf(id) === 0 && getGeneration(id)?.status === "canceled");+ for (let i = 0; i < 5; i++) await tick();+ } finally {+ db().exec("DROP TRIGGER IF EXISTS stop_while_saved");+ }+ expect(getGeneration(id)).toMatchObject({ status: "canceled" });+ expect(assetsOf(id)).toBe(0);+ });++ it("with the moderation service checking outputs, a run stopped while its result is saved is never brought back to wait for its check", async () => {+ const mod = await startFakeModeration();+ process.env.FUOBE_MODERATION_URL = mod.url;+ mod.run = { allowed: true, checkOutputs: true };+ try {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ db().exec(`CREATE TEMP TRIGGER stop_while_saved AFTER INSERT ON assets WHEN NEW.generation_id = '${id}' BEGIN UPDATE generations SET status = 'canceled' WHERE id = '${id}'; END`);+ try {+ await workAll(d);+ await until(() => assetsOf(id) === 0 && getGeneration(id)?.status === "canceled");+ for (let i = 0; i < 5; i++) await tick();+ } finally {+ db().exec("DROP TRIGGER IF EXISTS stop_while_saved");+ }+ expect(getGeneration(id)).toMatchObject({ status: "canceled" });+ expect((db().prepare("SELECT stage FROM generations WHERE id = ?").get(id) as { stage: string | null }).stage).toBeNull();+ expect((db().prepare("SELECT COUNT(*) AS n FROM output_checks WHERE generation_id = ?").get(id) as { n: number }).n).toBe(0);+ expect(assetsOf(id)).toBe(0);+ expect(mod.calls_of("/v1/check-output")).toEqual([]);+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ await mod.close();+ }+ });++ it("with the moderation service checking outputs, a process whose turn runs out while it saves a result leaves it to the process that took over: nothing of its own save is held or checked", async () => {+ const mod = await startFakeModeration();+ process.env.FUOBE_MODERATION_URL = mod.url;+ mod.run = { allowed: true, checkOutputs: true };+ try {+ const w = standInWorker();+ const { id } = await pressRun();+ const d = driver(w);+ // As its file is kept, the save here has taken past its turn, and another process took the turn over.+ db().exec(`CREATE TEMP TRIGGER turn_taken AFTER INSERT ON assets WHEN NEW.generation_id = '${id}' BEGIN UPDATE generation_runs SET finish_by = 'another-process', finish_until = ${Date.now() + 10 * MIN} WHERE id = '${id}'; END`);+ try {+ await workAll(d);+ await until(() => taskOf(id)?.state === "done" && assetsOf(id) === 0);+ for (let i = 0; i < 5; i++) await tick();+ } finally {+ db().exec("DROP TRIGGER IF EXISTS turn_taken");+ }+ // Nothing of this process's save is held or checked: its file went.+ expect(getGeneration(id)?.status).toBe("running");+ expect((db().prepare("SELECT stage FROM generations WHERE id = ?").get(id) as { stage: string | null }).stage).toBeNull();+ expect((db().prepare("SELECT COUNT(*) AS n FROM output_checks WHERE generation_id = ?").get(id) as { n: number }).n).toBe(0);+ expect(assetsOf(id)).toBe(0);+ // A slow look here changes nothing while the other process saves it.+ expect(updateLive(id, { status: "failed", error: "Timed out after 45 minutes", completed_at: Date.now() })).toBe(false);+ // The process holding the turn holds its own save for the check (here a result with no file, which succeeds as it is),+ // once: a run already held for its check is never held again.+ db().prepare("UPDATE generations SET stage = 'checking' WHERE id = ?").run(id);+ expect(outputChecks.holdForCheck(id, [], { live: true, turn: "another-process" })).toBe(false);+ db().prepare("UPDATE generations SET stage = NULL WHERE id = ?").run(id);+ expect(outputChecks.holdForCheck(id, [], { live: true, turn: "a-third-process" })).toBe(false);+ expect(outputChecks.holdForCheck(id, [], { live: true, turn: "another-process" })).toBe(true);+ expect(getGeneration(id)?.status).toBe("succeeded");+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ await mod.close();+ }+ });++ it("a look at a run that comes back after another process saved it, or while another process saves it, changes nothing", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ lookAtEveryStep(d, watch);+ await workAll(d);+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ const saved = getGeneration(id)!;+ // A slow look from before the save says it still works, or that it failed: the saved run stays as it is.+ expect(updateLive(id, { status: "running", progress: 0.5, message: POOL_WORDS.working })).toBe(false);+ expect(updateLive(id, { status: "failed", error: "Timed out after 45 minutes", completed_at: Date.now() })).toBe(false);+ expect(getGeneration(id)).toMatchObject({ status: "succeeded", outputs: saved.outputs });+ // A run another process is saving now: a look here neither fails it nor moves it back.+ const next = (await pressRun()).id;+ db().prepare("UPDATE generation_runs SET finish_by = 'another-process', finish_until = ? WHERE id = ?").run(Date.now() + 60_000, next);+ expect(updateLive(next, { status: "failed", error: "Timed out after 45 minutes", completed_at: Date.now() })).toBe(false);+ expect(getGeneration(next)?.status).toBe("queued");+ // Its turn runs out (that process stopped): this one may change it again.+ db().prepare("UPDATE generation_runs SET finish_until = ? WHERE id = ?").run(Date.now() - 1, next);+ expect(updateLive(next, { message: POOL_WORDS.inLine })).toBe(true);+ await workAll(d);+ expect((await ended(next))?.status).toBe("succeeded");+ });++ it("both processes' sweeps meet over a finished run's report: one sends it, so the service gets it once", async () => {+ const w = standInWorker();+ const { id } = await pressRun();+ const watch = watchOf(id);+ const d = driver(w);+ lookAtEveryStep(d, watch);+ // While the run finishes, this process sends no report: its sweep comes below, with the other process's.+ delete process.env.FUOBE_BILLING_URL;+ try {+ await workAll(d);+ await until(() => done(getGeneration(id)));+ } finally {+ process.env.FUOBE_BILLING_URL = svc.address;+ }+ expect(outbox.queueReports()).toBeGreaterThan(0);+ // Both sweeps at once: the service answers a report only once a second one has come, or after 4 seconds.+ svc.gather = { path: "/v1/settle", count: 2, maxMs: 4000 };+ await Promise.all([outbox.drainOutbox(), app2.sweepBilling()]);+ svc.gather = null;+ const g = await ended(id);+ await watch.look();+ expect(watch.problems({ place: 1 })).toEqual([]);+ expect(g?.status).toBe("succeeded");+ const settle = { holdId: holdOf(id), kind: "settle", status: "succeeded" };+ expect(svc.reportsFor(id)).toEqual([settle]);+ expect(svc.callsOf("/v1/settle").filter((c) => (c.body as { generationId?: string }).generationId === id)).toHaveLength(1);+ });+});diff --cc workflows/comfyui/requirements.jsonindex 97e2cbc8,9f7fac2f..6baa0dea--- a/workflows/comfyui/requirements.json+++ b/workflows/comfyui/requirements.json@@@ -1,6 -1,6 +1,6 @@@{"v": 1,- "hash": "d0f15d0d1db3c528a08a3361d3a013641c7f3435d327593f77eeca3bca7fb7b7",- "hash": "e3763e4e87449c85547fbe275a5e6355072a05dff509b898d3ff078af8cd6c9e",++ "hash": "2b9696c56432c3e14e0bb16026345f5dc1fb74ac0f27c8725ab073c2d0beeb19","comfyui": {"min":"0.42.0","testedCommit":"5841c187"},"folders": ["Hi3D","RMBG","audio_encoders","background_removal","checkpoints","clip_vision","dbs","diffusion_models","facerestore_models","foley","frame_interpolation","geometry_estimation","insightface","kandinsky6_audio_vae","latent_upscale_models","loras","mmaudio","model_patches","optical_flow","reuse","sams","text_encoders","thinksound","upscale_models","vae"],"sentinels": ["AILab_FeyNoBg","AILab_Qwen3ASRSubtitle","AILab_Qwen3TTSVoiceClone_Advanced","AILab_Qwen3TTSVoiceDesign_Advanced","AILab_VRMBG","AUSBOSS_NODES_CropForInpaint","AUSBOSS_NODES_ImageCropRotatePad","AUSBOSS_NODES_MaskByTouch","AUSBOSS_NODES_StitchInpaint","Add Subtitles To Frames","Apply Whisper","AuKGenerateEdit","AuKModelLoader","CFGOverride","ClothesSegment","ComfyMathExpression","CorridorKey2","CropFuobeLive","DBSLoader","DBSSeparate","DownloadAndLoadWav2VecModel","DualModelGuider","FL_ChatterboxDialogTTS","FL_ChatterboxMultilingualTTS","FL_ChatterboxVC","GetImageRangeFromBatch","GetImageSizeAndCount","GrowMaskWithBlur","H3AdaLNLoRAFix","H3AdvancedSwapPlan","H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan","H3ClipShots","H3FaceChunks","H3FaceJoin","H3FaceMaskSAM","H3FaceStitch","H3FaceTrackCrop","H3FillShots","H3GreyMannequins","H3ObjectSwapPlan","H3PeopleMask","H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan","H3RoleMask","H3SLAAttention","H3SoundtrackOrSilence","H3SourceSlice","H3SubjectPrompt","H3TrackCrops","H3TrackRoles","Hi3DLoadMesh","Hi3DModelLoader","Hi3DRefine","HunyuanDependenciesLoader","HunyuanFoleySampler","HunyuanModelLoader","INTConstant","Ideogram4Scheduler","IdolCamera","IdolPreprocessImage","IdolPruneSplat","ImageBatchExtendWithOverlap","ImageDetailContrast","ImageGridtoBatch","ImageResizeKJv2","IndexTTS2Simple","Kandinsky6AudioVAEDecode","Kandinsky6AudioVAELoader","Kandinsky6BeautifyPrompt","Kandinsky6EmptyLatent","Kandinsky6ImageToVideoAudio","Kandinsky6LatentUpscalerLoader","Kandinsky6RemoveReferenceLatent","Kandinsky6SRVAELoader","Kandinsky6Sampler","Kandinsky6TextEncode","Kandinsky6VSRUpscale","Krea2EditGroundedEncode","Krea2EditModelPatch","Krea2OstrisEditModelPatch","LTXAVTextEncoderLoader","LTXAddVideoICLoRAGuide","LTXICLoRALoaderModelOnly","LTXVAddGuide","LTXVAudioVAEDecode","LTXVAudioVAELoader","LTXVConcatAVLatent","LTXVConditioning","LTXVCropGuides","LTXVDualCFGGuider","LTXVEmptyLatentAudio","LTXVImgToVideoInplace","LTXVLatentUpsampler","LTXVPreprocess","LTXVScheduler","LTXVSeparateAVLatent","LTXVTiledFusionSampler","LatentSyncNode","LoadBackgroundRemovalModel","LoadImageFuobeLive","LoadVideoDepthAnythingModel","MMAudioFeatureUtilsLoader","MMAudioModelLoader","MMAudioSampler","MelBandRoFormerModelLoader","MelBandRoFormerSampler","Metric3D-NormalMapPreprocessor","MiniMaxH3ChainAssemble","MiniMaxH3ChainContext","MiniMaxH3ChainCurrent","MiniMaxH3ChainLoopEnd","MiniMaxH3ChainLoopStart","MiniMaxH3ChainPlanModern","MiniMaxH3ChainReview","MiniMaxH3ChainSegmentSave","MiniMaxH3ContexMaskedTarget","MiniMaxH3FantasticVideoEditLatent","MiniMaxH3GenerationProfile","MiniMaxH3LoopTrim","MiniMaxH3SourceTimeline","MiniMaxH3TurboLoRA","MiniMaxH3TurboSampler","MultiTalkModelLoader","MultiTalkWav2VecEmbeds","NomasCameraPath","NomasWorldContinue","NomasWorldGenerate","NomasWorldPrompt","OpenH3LoadRefinedLatent","OpenH3RegenFastVAEDecode","OpenH3RegenFinish","OpenH3RegenLora","OpenH3RegenPrepareDraft","OpenH3RegenRefineLatent","OpenH3RegenSigmas","OpenH3RegenUpscale","OpenH3SaveRefinedLatent","Orion4D_FXMax_DCTLToneMapper","PasteBackFuobeLive","QWMComposite","QWMDetect","QWMFinal","QWMPrepare","QWMRefineMask","QWMResidualDetect","Qwen21EncodeFuobeLive","Qwen21ReferenceFuobeLive","QwenImage21Cache","REUSEEnhance","REUSELoader","RIFE VFI","RMBG","RTXTrueHDR","RTXVideoFrameGeneration","RTXVideoSuperResolution","ReActorFaceSwap","RemoveBackground","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SAMLoader","SaveImageFuobeLive","SeedVR2Conditioning","SeedVR2PostProcessing","SeedVR2Preprocess","SolarRendererConditioning","SolarRendererLoraLoader","SolarRendererModel","SolarRendererSigmas","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","VRAM_Debug","VideoDepthAnythingOutput","VideoDepthAnythingProcess","VideoLengthAdjuster","ViggleTurboLora","ViggleTurboSigmas","VoxCPM2_Clone","VoxCPM2_TTS","WanVideoBlockSwap","WanVideoClipVisionEncode","WanVideoDecode","WanVideoEncode","WanVideoImageToVideoMultiTalk","WanVideoLoraSelect","WanVideoModelLoader","WanVideoPassImagesFromSamples","WanVideoSampler","WanVideoTextEncodeCached","WanVideoVAELoader","ZenImage21AdapterLoader","ZenImage21TextEncode"],@@@ -374,10 -374,10 +374,10 @@@"image-to-3d-trellis2-multiview": {"core":["ApplyTextureToMesh","BakeAmbientOcclusion","BakeNormalMapFromMesh","BakeTextureFromVoxel","BatchImagesNode","CFGOverride","CLIPVisionLoader","CreateVideo","DecimateMesh","EmptyTrellis2LatentStructure","GetMeshInfo","ImageCropToMask","KSampler","LoadBackgroundRemovalModel","LoadImage","LoadMoGeModel","MeshSmoothNormals","MeshToFile3D","MoGeGeometryToFOV","MoGeInference","ModelSamplingSD3","Pixal3DMultiViewConditioning","PrimitiveInt","RemeshMesh","RemoveBackground","RenderMesh","RescaleCFG","RotateMesh","Save3DAdvanced","SaveVideo","Trellis2ShapeStage","Trellis2TextureStage","Trellis2UpsampleStage","UNETLoader","UnwrapMesh","VAELoader","VaeDecodeShapeTrellis","VaeDecodeStructureTrellis2","VaeDecodeTextureTrellis"],"packs":{},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_L_naf_fp32.safetensors","diffusion_models/pixal3d_multiview_int8_convrot.safetensors","geometry_estimation/moge_2_vitl_normal_fp16.safetensors","vae/trellis_2_shape_vae_bf16.safetensors","vae/trellis_2_texture_vae_bf16.safetensors"],"optional":[],"vramGb":16,"isolated":false,"firstRun":[],"validated":true},"image-to-mesh-idol": {"core":["CLIPVisionLoader","ComfySwitchNode","CreateCameraInfo","CreateVideo","EmptyImage","ImageCompositeMasked","ImageScale","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","RemoveBackground","RenderSplat","SaveGLB","SaveVideo","SplatToMesh","TripoSplatConditioning","TripoSplatPreprocessImage","UNETLoader","VAEDecodeTripoSplat","VAELoader"],"packs":{},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_vit_h.safetensors","diffusion_models/idol_fp16.safetensors","vae/flux2-vae.safetensors","vae/idol_decoder_fp16.safetensors"],"optional":[],"vramGb":8,"isolated":false,"firstRun":[],"validated":true},"image-to-splat-idol": {"core":["CLIPVisionLoader","ComfySwitchNode","CreateCameraInfo","CreateVideo","EmptyImage","ImageCompositeMasked","ImageScale","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","RemoveBackground","RenderSplat","SaveGLB","SaveVideo","SplatToFile3D","TripoSplatConditioning","TripoSplatPreprocessImage","UNETLoader","VAEDecodeTripoSplat","VAELoader"],"packs":{},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_vit_h.safetensors","diffusion_models/idol_fp16.safetensors","vae/flux2-vae.safetensors","vae/idol_decoder_fp16.safetensors"],"optional":[],"vramGb":8,"isolated":false,"firstRun":[],"validated":true},- "image-to-splat-idol-clean": {"core":["CLIPVisionLoader","ComfySwitchNode","CreateCameraInfo","CreateVideo","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","PreviewAny","RemoveBackground","RenderSplat","SaveGLB","SaveImage","SaveVideo","SplatToFile3D","TripoSplatConditioning","UNETLoader","VAEDecodeTripoSplat","VAELoader"],"packs":{"ComfyUI-Idol":["IdolCamera","IdolPreprocessImage","IdolPruneSplat"]},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_vit_h.safetensors","diffusion_models/idol_fp16.safetensors","vae/flux2-vae.safetensors","vae/idol_decoder_fp16.safetensors"],"optional":[],"vramGb":8,"isolated":false,"firstRun":[]},+ "image-to-splat-idol-clean": {"core":["CLIPVisionLoader","ComfySwitchNode","CreateCameraInfo","CreateVideo","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","PreviewAny","RemoveBackground","RenderSplat","SaveGLB","SaveImage","SaveVideo","SplatToFile3D","TripoSplatConditioning","UNETLoader","VAEDecodeTripoSplat","VAELoader"],"packs":{"ComfyUI-Idol":["IdolCamera","IdolPreprocessImage","IdolPruneSplat"]},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_vit_h.safetensors","diffusion_models/idol_fp16.safetensors","vae/flux2-vae.safetensors","vae/idol_decoder_fp16.safetensors"],"optional":[],"vramGb":8,"isolated":false,"firstRun":[],"validated":true},"image-to-splat-triposplat": {"core":["CLIPVisionLoader","ComfySwitchNode","CreateCameraInfo","CreateVideo","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","RemoveBackground","RenderSplat","SaveGLB","SaveVideo","SplatToFile3D","TripoSplatConditioning","TripoSplatPreprocessImage","UNETLoader","VAEDecodeTripoSplat","VAELoader"],"packs":{},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_vit_h.safetensors","diffusion_models/triposplat_fp16.safetensors","vae/flux2-vae.safetensors","vae/triposplat_vae_decoder_fp16.safetensors"],"optional":[],"vramGb":8,"isolated":false,"firstRun":[],"validated":true},"image-to-views-idol": {"core":["CLIPVisionLoader","ComfySwitchNode","InvertMask","KSampler","LoadBackgroundRemovalModel","LoadImage","RemoveBackground","RenderSplat","SaveImage","TripoSplatConditioning","UNETLoader","VAEDecodeTripoSplat","VAELoader"],"packs":{"ComfyUI-Idol":["IdolCamera","IdolPreprocessImage","IdolPruneSplat"]},"files":["background_removal/birefnet.safetensors","clip_vision/dino_v3_vit_h.safetensors","diffusion_models/idol_fp16.safetensors","vae/flux2-vae.safetensors","vae/idol_decoder_fp16.safetensors"],"optional":[],"vramGb":8,"isolated":false,"firstRun":[]},- "image-vectorize-vtracer": {"core":["LoadImage","SaveSVGNode"],"packs":{"ComfyUI-ToSVG":["TS_ImageToSVGStringColor_Vtracer","TS_SVGStringToSVGBytesIO"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},+ "image-vectorize-vtracer": {"core":["LoadImage","SaveSVGNode"],"packs":{"ComfyUI-ToSVG":["TS_ImageToSVGStringColor_Vtracer","TS_SVGStringToSVGBytesIO"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},"image-watermark-remove-qwen21": {"core":["CLIPLoader","KSampler","LoadImage","ModelAttentionBackend","PreviewAny","QwenImage21Cache","SaveImage","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{"ComfyUI-Qwen-Watermark":["QWMComposite","QWMDetect","QWMFinal","QWMPrepare","QWMRefineMask","QWMResidualDetect"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","sams/sam_vit_b_01ec64.pth","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},"image-watermark-remove-qwen21-brush": {"core":["CLIPLoader","KSampler","LoadImage","LoadImageMask","ModelAttentionBackend","PreviewAny","QwenImage21Cache","SaveImage","TextEncodeQwenImage21","UNETLoader","VAEDecode","VAELoader"],"packs":{"ComfyUI-Qwen-Watermark":["QWMComposite","QWMDetect","QWMFinal","QWMPrepare","QWMRefineMask","QWMResidualDetect"]},"files":["diffusion_models/qwen_image_2.1_int8_convrot.safetensors","sams/sam_vit_b_01ec64.pth","text_encoders/qwen3vl_8b_int8_convrot.safetensors","vae/qwen_image_2.1_vae_bf16.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},"image-watermark-scan-qwen3vl": {"core":["CLIPLoader","ComfyMathExpression","GetImageSize","ImageCrop","LoadImage","PreviewAny"],"packs":{"ComfyUI-Qwen-Watermark":["QWMDetect"]},"files":["text_encoders/qwen3vl_8b_int8_convrot.safetensors"],"optional":[],"vramGb":10,"isolated":false,"firstRun":[],"validated":true},@@@ -389,10 -389,10 +389,10 @@@"interpolate-rife-vfi": {"core":["ComfyMathExpression","PrimitiveInt"],"packs":{"ComfyUI-Frame-Interpolation":["RIFE VFI"],"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoCombine","VHS_VideoInfo"]},"files":[],"optional":[],"vramGb":2,"isolated":false,"firstRun":["RIFE VFI downloads rife49.pth into custom_nodes/ComfyUI-Frame-Interpolation/ckpts/rife on first run"],"validated":true},"kandinsky6-i2av": {"core":["CLIPLoader","CreateVideo","DualCLIPLoader","ImageScale","LoadImage","SaveVideo","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{"kandinsky6":["Kandinsky6AudioVAEDecode","Kandinsky6AudioVAELoader","Kandinsky6BeautifyPrompt","Kandinsky6EmptyLatent","Kandinsky6ImageToVideoAudio","Kandinsky6RemoveReferenceLatent","Kandinsky6Sampler","Kandinsky6TextEncode"]},"files":["audio_vae/bigvgan_vocoder/bigvgan_generator.pt","audio_vae/bigvgan_vocoder/config.json","audio_vae/v1-44.pth","diffusion_models/Kandinsky-6.0-Lite-distill-5s-Diffusers/transformer/diffusion_pytorch_model.safetensors","text_encoders/clip_l.safetensors","text_encoders/qwen_2.5_vl_7b.safetensors","vae/hunyuan_video_vae_bf16.safetensors"],"optional":["diffusion_models/Kandinsky-6.0-Pro-distill-5s-Diffusers/transformer/diffusion_pytorch_model.safetensors","text_encoders/qwen3.5_9b_bf16.safetensors"],"vramGb":24,"isolated":false,"firstRun":[]},"kandinsky6-t2av": {"core":["CLIPLoader","CreateVideo","DualCLIPLoader","SaveVideo","UNETLoader","VAEDecode","VAELoader"],"packs":{"kandinsky6":["Kandinsky6AudioVAEDecode","Kandinsky6AudioVAELoader","Kandinsky6BeautifyPrompt","Kandinsky6EmptyLatent","Kandinsky6Sampler","Kandinsky6TextEncode"]},"files":["audio_vae/bigvgan_vocoder/bigvgan_generator.pt","audio_vae/bigvgan_vocoder/config.json","audio_vae/v1-44.pth","diffusion_models/Kandinsky-6.0-Lite-distill-5s-Diffusers/transformer/diffusion_pytorch_model.safetensors","text_encoders/clip_l.safetensors","text_encoders/qwen_2.5_vl_7b.safetensors","vae/hunyuan_video_vae_bf16.safetensors"],"optional":["diffusion_models/Kandinsky-6.0-Pro-distill-5s-Diffusers/transformer/diffusion_pytorch_model.safetensors","text_encoders/qwen3.5_9b_bf16.safetensors"],"vramGb":24,"isolated":false,"firstRun":[]},- "kenburns-still": {"core":["ComfyMathExpression","ConcatenateVideo","CreateVideo","EndLoop","GetImageSize","ImageCrop","ImageScale","ImageScaleBy","LoadImage","PrimitiveFloat","PrimitiveInt","RebatchImages","SaveVideo","StartLoop"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},+ "kenburns-still": {"core":["ComfyMathExpression","ConcatenateVideo","CreateVideo","EndLoop","GetImageSize","ImageCrop","ImageScale","ImageScaleBy","LoadImage","PrimitiveFloat","PrimitiveInt","RebatchImages","SaveVideo","StartLoop"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},"krea2-edit-general": {"core":["CLIPLoader","EmptySD3LatentImage","KSampler","LoadImage","LoraLoaderModelOnly","SaveImage","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{"comfyui-krea2edit":["Krea2EditGroundedEncode","Krea2EditModelPatch"]},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","loras/krea2_general_edit_v2.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},"krea2-edit-identity": {"core":["CLIPLoader","EmptySD3LatentImage","KSampler","LoadImage","LoraLoaderModelOnly","SaveImage","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{"comfyui-krea2edit":["Krea2EditGroundedEncode","Krea2EditModelPatch"]},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","loras/krea2_identity_edit_v2.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},- "krea2-inpaint": {"core":["CLIPLoader","ConditioningZeroOut","EmptyImage","EmptyLatentImage","GetImageSize","ImageCompositeMasked","ImageScaleToTotalPixels","KSampler","LoadImage","LoadImageMask","LoraLoaderModelOnly","SaveImage","UNETLoader","VAEDecode","VAELoader"],"packs":{"ComfyUI-Krea2-Ostris-Edit":["Krea2OstrisEditModelPatch","TextEncodeKrea2OstrisEdit"]},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","loras/krea2_inpaint_edit.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},+ "krea2-inpaint": {"core":["CLIPLoader","ConditioningZeroOut","EmptyImage","EmptyLatentImage","GetImageSize","ImageCompositeMasked","ImageScaleToTotalPixels","KSampler","LoadImage","LoadImageMask","LoraLoaderModelOnly","SaveImage","UNETLoader","VAEDecode","VAELoader"],"packs":{"ComfyUI-Krea2-Ostris-Edit":["Krea2OstrisEditModelPatch","TextEncodeKrea2OstrisEdit"]},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","loras/krea2_inpaint_edit.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},"krea2-outpaint": {"core":["CLIPLoader","ConditioningZeroOut","EmptyImage","EmptyLatentImage","GetImageSize","ImageCompositeMasked","ImagePadForOutpaint","ImageScaleToTotalPixels","KSampler","LoadImage","LoraLoaderModelOnly","SaveImage","UNETLoader","VAEDecode","VAELoader"],"packs":{"ComfyUI-Krea2-Ostris-Edit":["Krea2OstrisEditModelPatch","TextEncodeKrea2OstrisEdit"]},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","loras/krea2_inpaint_edit.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[]},"krea2-realism-t2i": {"core":["CLIPLoader","CLIPTextEncode","ConditioningZeroOut","EmptyLatentImage","KSampler","LoraLoaderModelOnly","SaveImage","UNETLoader","VAEDecode","VAELoader"],"packs":{},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","loras/Krea2-realism-V2.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},"krea2-turbo-i2i": {"core":["CLIPLoader","CLIPTextEncode","ConditioningZeroOut","ImageScaleToTotalPixels","KSampler","LoadImage","SaveImage","UNETLoader","VAEDecode","VAEEncode","VAELoader"],"packs":{},"files":["diffusion_models/krea2_turbo_fp8_scaled.safetensors","text_encoders/qwen3vl_4b_fp8_scaled.safetensors","vae/qwen_image_vae.safetensors"],"optional":[],"vramGb":20,"isolated":false,"firstRun":[],"validated":true},@@@ -518,18 -518,18 +518,18 @@@"video-blockout-wan22-fun-vace": {"core":["BatchImagesNode","CLIPLoader","CLIPTextEncode","ComfyMathExpression","ComfySwitchNode","CreateVideo","GetVideoComponents","ImageFromBatch","ImageInvert","ImageScale","ImageToMask","KSamplerAdvanced","LoadImage","LoadVideo","LoraLoaderModelOnly","MaskToImage","ModelSamplingSD3","PrimitiveBoolean","PrimitiveInt","RepeatImageBatch","SaveVideo","SolidMask","TrimVideoLatent","UNETLoader","VAEDecode","VAELoader","WanVaceToVideo"],"packs":{},"files":["diffusion_models/wan2.2_fun_vace_high_noise_14B_fp8_scaled.safetensors","diffusion_models/wan2.2_fun_vace_low_noise_14B_fp8_scaled.safetensors","loras/wan2.2_t2v_lightx2v_4steps_lora_v1.1_high_noise.safetensors","loras/wan2.2_t2v_lightx2v_4steps_lora_v1.1_low_noise.safetensors","text_encoders/umt5_xxl_fp8_e4m3fn_scaled.safetensors","vae/wan_2.1_vae.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},"video-character-swap-h3": {"core":["CLIPLoader","CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","ImageFromBatch","ImageScale","LoadImage","LoadVideo","LoraLoaderModelOnly","MiniMaxH3SigmaShift","ModelAttentionBackend","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SaveVideo","SelectCLIPDevice","UNETLoader","VAELoader","Video Slice"],"packs":{"h3_character_swap":["H3CharacterSwapAssemble","H3CharacterSwapController","H3CharacterSwapExpandMask","H3CharacterSwapModels","H3CharacterSwapPrepareVideo","H3CharacterSwapRecoverMasks","H3CharacterSwapSelectSubject","H3CharacterSwapSettings","H3CharacterSwapShot","H3CharacterSwapWindowPlan"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors","loras/h3_character_swap_v1.5.safetensors","loras/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors","text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","vae/minimax_h3_audio_vae_fp32.safetensors","vae/minimax_h3_video_vae_fp16.safetensors"],"optional":["loras/h3_character_swap_pro4500_1000.safetensors"],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},"video-character-swap-h3-relay": {"core":["BasicScheduler","CFGGuider","CLIPLoader","CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","EndLoop","GetImageSize","ImageFromBatch","KSamplerSelect","LTXVSeparateAVLatent","LoadImage","LoadVideo","LoraLoaderModelOnly","MiniMaxH3AddGuide","MiniMaxH3ReferenceToVideo","MiniMaxH3SigmaShift","ModelAttentionBackend","RandomNoise","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SamplerCustomAdvanced","SaveVideo","SelectCLIPDevice","StartLoop","UNETLoader","VAEDecode","VAEEncode","VAELoader","Video Slice"],"packs":{"h3-relay":["H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors","loras/h3_character_swap_v1.5.safetensors","loras/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors","text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","vae/minimax_h3_audio_vae_fp32.safetensors","vae/minimax_h3_video_vae_fp16.safetensors"],"optional":["loras/h3_character_swap_pro4500_1000.safetensors"],"vramGb":24,"isolated":false,"firstRun":[]},- "video-character-swap-h3-segment": {"core":["BasicScheduler","CFGGuider","CLIPLoader","CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","EndLoop","GetImageSize","GetVideoComponents","ImageFromBatch","ImageScale","KSamplerSelect","LTXVSeparateAVLatent","LoadImage","LoadVideo","LoraLoaderModelOnly","MiniMaxH3AddGuide","MiniMaxH3ReferenceToVideo","MiniMaxH3SigmaShift","ModelAttentionBackend","RandomNoise","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SamplerCustomAdvanced","SaveVideo","SelectCLIPDevice","StartLoop","UNETLoader","VAEDecode","VAEEncode","VAELoader","Video Slice"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_VideoCombine"],"h3-relay":["H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors","loras/h3_character_swap_v1.5.safetensors","loras/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors","text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","vae/minimax_h3_audio_vae_fp32.safetensors","vae/minimax_h3_video_vae_fp16.safetensors"],"optional":["loras/h3_character_swap_pro4500_1000.safetensors"],"vramGb":24,"isolated":false,"firstRun":[]},+ "video-character-swap-h3-segment": {"core":["BasicScheduler","CFGGuider","CLIPLoader","CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","EndLoop","GetImageSize","GetVideoComponents","ImageFromBatch","ImageScale","KSamplerSelect","LTXVSeparateAVLatent","LoadImage","LoadVideo","LoraLoaderModelOnly","MiniMaxH3AddGuide","MiniMaxH3ReferenceToVideo","MiniMaxH3SigmaShift","ModelAttentionBackend","RandomNoise","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SamplerCustomAdvanced","SaveVideo","SelectCLIPDevice","StartLoop","UNETLoader","VAEDecode","VAEEncode","VAELoader","Video Slice"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_VideoCombine"],"h3-relay":["H3RelayAppendWindow","H3RelayApplyEditMask","H3RelayApplyHistory","H3RelayExpandMask","H3RelayFinishWindows","H3RelayPrepareSource","H3RelayRecoverMasks","H3RelaySamplingMemory","H3RelaySelectMask","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors","loras/h3_character_swap_v1.5.safetensors","loras/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors","text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","vae/minimax_h3_audio_vae_fp32.safetensors","vae/minimax_h3_video_vae_fp16.safetensors"],"optional":["loras/h3_character_swap_pro4500_1000.safetensors"],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},- "video-composite-mask": {"core":["CreateVideo","CropMask","FeatherMask","GetVideoComponents","GrowMask","ImageCompositeMasked","ImageScale","ImageToMask","LoadVideo","SaveVideo","Video Slice"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-2": {"core":["BatchImagesNode","CreateVideo","GetVideoComponents","ImageScale","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-3": {"core":["BatchImagesNode","CreateVideo","GetVideoComponents","ImageScale","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-4": {"core":["BatchImagesNode","CreateVideo","GetVideoComponents","ImageScale","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-encoded": {"core":["ConcatenateVideo","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-sound1-2": {"core":["BatchImagesNode","CreateVideo","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-sound1-3": {"core":["BatchImagesNode","CreateVideo","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-sound1-4": {"core":["BatchImagesNode","CreateVideo","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-sound2-2": {"core":["AudioConcat","BatchImagesNode","CreateVideo","EmptyAudio","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoInfoLoaded"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-sound2-3": {"core":["AudioConcat","BatchImagesNode","CreateVideo","EmptyAudio","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoInfoLoaded"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-concat-sound2-4": {"core":["AudioConcat","BatchImagesNode","CreateVideo","EmptyAudio","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoInfoLoaded"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},+ "video-composite-mask": {"core":["CreateVideo","CropMask","FeatherMask","GetVideoComponents","GrowMask","ImageCompositeMasked","ImageScale","ImageToMask","LoadVideo","SaveVideo","Video Slice"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-2": {"core":["BatchImagesNode","CreateVideo","GetVideoComponents","ImageScale","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-3": {"core":["BatchImagesNode","CreateVideo","GetVideoComponents","ImageScale","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-4": {"core":["BatchImagesNode","CreateVideo","GetVideoComponents","ImageScale","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-encoded": {"core":["ConcatenateVideo","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-sound1-2": {"core":["BatchImagesNode","CreateVideo","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-sound1-3": {"core":["BatchImagesNode","CreateVideo","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-sound1-4": {"core":["BatchImagesNode","CreateVideo","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-sound2-2": {"core":["AudioConcat","BatchImagesNode","CreateVideo","EmptyAudio","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoInfoLoaded"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-sound2-3": {"core":["AudioConcat","BatchImagesNode","CreateVideo","EmptyAudio","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoInfoLoaded"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-concat-sound2-4": {"core":["AudioConcat","BatchImagesNode","CreateVideo","EmptyAudio","ImageScale","SaveVideo"],"packs":{"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoInfoLoaded"]},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},"video-depth-da3": {"core":["ComfySwitchNode","CreateVideo","DA3Inference","DA3Render","GetImageSize","GetVideoComponents","ImageScale","ImageStitch","LoadDA3Model","LoadVideo","PrimitiveBoolean","SaveVideo"],"packs":{},"files":["geometry_estimation/depth_anything_3_mono_large.safetensors"],"optional":[],"vramGb":4,"isolated":false,"firstRun":[],"validated":true},"video-depth-vda-large": {"core":["ComfySwitchNode","CreateVideo","GetImageSize","GetVideoComponents","ImageScale","ImageStitch","LoadVideo","PrimitiveBoolean","SaveVideo"],"packs":{"ComfyUI-Video-Depth-Anything":["LoadVideoDepthAnythingModel","VideoDepthAnythingOutput","VideoDepthAnythingProcess"]},"files":[],"optional":[],"vramGb":8,"isolated":false,"firstRun":["LoadVideoDepthAnythingModel downloads depth-anything/Video-Depth-Anything-Large video_depth_anything_vitl.pth (about 1.5 GB) into models/videodepthanything on first run"],"validated":true},"video-depth-vda-small": {"core":["ComfySwitchNode","CreateVideo","GetImageSize","GetVideoComponents","ImageScale","ImageStitch","LoadVideo","PrimitiveBoolean","SaveVideo"],"packs":{"ComfyUI-Video-Depth-Anything":["LoadVideoDepthAnythingModel","VideoDepthAnythingOutput","VideoDepthAnythingProcess"]},"files":[],"optional":[],"vramGb":4,"isolated":false,"firstRun":["LoadVideoDepthAnythingModel downloads depth-anything/Video-Depth-Anything-Small video_depth_anything_vits.pth (0.12 GB) into models/videodepthanything on first run"],"validated":true},@@@ -551,11 -551,11 +551,11 @@@"video-inpaint-wan-vace-painted": {"core":["CLIPLoader","CLIPTextEncode","CheckpointLoaderSimple","ComfyMathExpression","CreateVideo","GetImageSize","GetVideoComponents","GrowMask","ImageCompositeMasked","ImageFromBatch","ImageScale","ImageToMask","InvertMask","KSampler","LoadImageMask","LoadVideo","LoraLoaderModelOnly","MaskToImage","ModelSamplingSD3","PrimitiveFloat","PrimitiveInt","SAM3_TrackToMask","SAM3_VideoTrack","SaveImage","SaveVideo","TrimAudioDuration","TrimVideoLatent","UNETLoader","VAEDecode","VAELoader","Video Slice","WanVaceToVideo"],"packs":{"ComfyUI-KJNodes":["GrowMaskWithBlur"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/wan2.1_vace_14B_fp16.safetensors","loras/lightx2v_T2V_14B_cfg_step_distill_v2_lora_rank64_bf16.safetensors","text_encoders/umt5_xxl_fp8_e4m3fn_scaled.safetensors","vae/wan_2.1_vae.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},"video-insert-wan-vace": {"core":["CLIPLoader","CLIPTextEncode","ComfyMathExpression","CreateVideo","GetImageSize","GetVideoComponents","GrowMask","ImageCompositeMasked","ImageFromBatch","ImageScale","ImageToMask","InvertMask","KSampler","LoadImage","LoadImageMask","LoadVideo","LoraLoaderModelOnly","MaskToImage","ModelSamplingSD3","PrimitiveFloat","PrimitiveInt","RepeatImageBatch","SaveVideo","TrimAudioDuration","TrimVideoLatent","UNETLoader","VAEDecode","VAELoader","Video Slice","WanVaceToVideo"],"packs":{"ComfyUI-KJNodes":["GrowMaskWithBlur"]},"files":["diffusion_models/wan2.1_vace_14B_fp16.safetensors","loras/lightx2v_T2V_14B_cfg_step_distill_v2_lora_rank64_bf16.safetensors","text_encoders/umt5_xxl_fp8_e4m3fn_scaled.safetensors","vae/wan_2.1_vae.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},"video-key-corridorkey": {"core":["MaskToImage","SaveImageAdvanced"],"packs":{"ComfyUI-CorridorKey2":["CorridorKey2"],"ComfyUI-VideoHelperSuite":["VHS_BatchManager","VHS_LoadVideo","VHS_VideoCombine","VHS_VideoInfo"]},"files":[],"optional":[],"vramGb":6,"isolated":false,"firstRun":["CorridorKey2 downloads about 5.1 GB into models/corridorkey2/ on first run: corridorkey_v2.safetensors (2.66 GB) and foundation_stats.safetensors from nikopueringer/CorridorKey2.0 (its main revision, cf44a8db when checked), NVIDIA C-RADIOv4-SO400M @ c0457f5d (1.72 GB), Microsoft MoGe-2 ViT-B @ ca5f0e07 (0.42 GB) and Google DeepMind RVM small (0.27 GB, md5-checked)"]},- "video-mask-h3-relay": {"core":["CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","GetImageSize","GetVideoComponents","ImageBatch","ImageFromBatch","ImageScale","LoadVideo","MaskToImage","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SaveVideo","Video Slice"],"packs":{"h3-relay":["H3RelayPrepareSource","H3RelayRecoverMasks","H3RelaySelectMask"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors"],"optional":[],"vramGb":6,"isolated":false,"firstRun":[]},+ "video-mask-h3-relay": {"core":["CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","GetImageSize","GetVideoComponents","ImageBatch","ImageFromBatch","ImageScale","LoadVideo","MaskToImage","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SaveVideo","Video Slice"],"packs":{"h3-relay":["H3RelayPrepareSource","H3RelayRecoverMasks","H3RelaySelectMask"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors"],"optional":[],"vramGb":6,"isolated":false,"firstRun":[],"validated":true},"video-matte-vrmbg3": {"core":["CreateVideo","GetVideoComponents","LoadVideo","SaveImageAdvanced","SaveVideo"],"packs":{"ComfyUI-RMBG":["AILab_VRMBG"],"ComfyUI-VideoHelperSuite":["VHS_VideoCombine"]},"files":["RMBG/VRMBG-3.0/model.safetensors"],"optional":[],"vramGb":6,"isolated":false,"firstRun":[]},"video-motion-transfer-h3": {"core":["BasicGuider","BasicScheduler","CLIPLoader","ImageScale","ImageScaleToMaxDimension","KSamplerSelect","LoadImage","LoraLoaderModelOnly","MiniMaxH3ReferenceToVideo","MiniMaxH3SigmaShift","ModelAttentionBackend","RandomNoise","SamplerCustomAdvanced","UNETLoader","VAEDecode","VAELoader"],"packs":{"ComfyUI-Fantastic-MiniMaxH3-PromptBuilder":[],"ComfyUI-KJNodes":["VRAM_Debug"],"ComfyUI-MiniMaxH3-Context-Loop":[],"ComfyUI-VideoHelperSuite":["VHS_LoadVideo","VHS_VideoCombine"],"comfyui-h3-oneclick-swap":["H3SoundtrackOrSilence"],"comfyui_controlnet_aux":["Metric3D-NormalMapPreprocessor"]},"files":["diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors","loras/minimax_h3_DMAD_4step_full_lora_avg_rank_39_bf16.safetensors","text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","vae/minimax_h3_audio_vae_fp32.safetensors","vae/minimax_h3_video_vae_int8_convrot.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":["Metric3D vit-small (metric_depth_vit_small_800k.pth) -> custom_nodes/comfyui_controlnet_aux/ckpts/JUGGHM/Metric3D (fetched on first run unless placed there)"]},- "video-mux-audio": {"core":["AudioAdjustVolume","AudioMerge","ConcatenateVideo","EmptyAudio","LoadAudio","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},- "video-mux-audio-replace": {"core":["ConcatenateVideo","LoadAudio","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true},+ "video-mux-audio": {"core":["AudioAdjustVolume","AudioMerge","ConcatenateVideo","EmptyAudio","LoadAudio","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},+ "video-mux-audio-replace": {"core":["ConcatenateVideo","LoadAudio","LoadVideo","SaveVideo"],"packs":{},"files":[],"optional":[],"vramGb":0,"isolated":false,"firstRun":[],"validated":true,"cpu":true},"video-person-remove-h3-mask": {"core":["CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","EmptyImage","GetImageSize","GetVideoComponents","GrowMask","ImageCompositeMasked","ImageFromBatch","LoadVideo","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SaveVideo","ThresholdMask"],"packs":{},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors"],"optional":[],"vramGb":6,"isolated":false,"firstRun":[],"validated":true},"video-person-remove-h3-relay": {"core":["BasicScheduler","CFGGuider","CLIPLoader","CLIPTextEncode","CheckpointLoaderSimple","CreateVideo","EmptyImage","EndLoop","GetImageSize","GetVideoComponents","GrowMask","ImageCompositeMasked","ImageFromBatch","ImageScale","KSamplerSelect","LTXVSeparateAVLatent","LoadImage","LoadVideo","LoraLoaderModelOnly","MiniMaxH3AddGuide","MiniMaxH3ReferenceToVideo","MiniMaxH3SigmaShift","ModelAttentionBackend","RandomNoise","SAM3_Detect","SAM3_TrackToMask","SAM3_VideoTrack","SamplerCustomAdvanced","SaveVideo","SelectCLIPDevice","StartLoop","ThresholdMask","UNETLoader","VAEDecode","VAEDecodeAudio","VAELoader"],"packs":{"h3-relay":["H3RelayAppendWindow","H3RelayApplyHistory","H3RelayFinishWindows","H3RelayReviewWindows","H3RelaySamplingMemory","H3RelayTextMemory","H3RelayWindowInputs","H3RelayWindowPlan"]},"files":["checkpoints/sam3.1_multiplex_fp16.safetensors","diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors","loras/H3-Person-Remover-V1.safetensors","text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors","vae/minimax_h3_audio_vae_fp32.safetensors","vae/minimax_h3_video_vae_fp16.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},"video-reframe-wan22-fun-vace": {"core":["CLIPLoader","CLIPTextEncode","CreateVideo","GetVideoComponents","KSamplerAdvanced","LoadVideo","LoraLoaderModelOnly","ModelSamplingSD3","SaveVideo","TrimVideoLatent","UNETLoader","VAEDecode","VAELoader","WanVaceToVideo"],"packs":{"ComfyUI-KJNodes":["ImageResizeKJv2"]},"files":["diffusion_models/wan2.2_fun_vace_high_noise_14B_fp8_scaled.safetensors","diffusion_models/wan2.2_fun_vace_low_noise_14B_fp8_scaled.safetensors","loras/wan2.2_t2v_lightx2v_4steps_lora_v1.1_high_noise.safetensors","loras/wan2.2_t2v_lightx2v_4steps_lora_v1.1_low_noise.safetensors","text_encoders/umt5_xxl_fp8_e4m3fn_scaled.safetensors","vae/wan_2.1_vae.safetensors"],"optional":[],"vramGb":24,"isolated":false,"firstRun":[],"validated":true},