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 progress and previews in SQLite, one finisher, outbox claim, policy grace, refuse before Run, hold deadline and request ids
Adarsh98d602c9be52
diff --cc docs/billing-hook.mdindex 09093c0d,29aa2f04..05b3c8b9--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@@ -79,69 -79,17 +79,70 @@@ defaults where the request names none)input's size, an upscale's times its factor, within the workflow's limits. It is null for sound, text and 3D.`steps` lists every step of the run that uses this install's GPUs, the run's own step first: a chain (a film of-several shots, a picture and then a step on it, MiniMax H3 at 2K with its finish for each take) is priced once, with one-quote and one hold, for one press of Run.+several shots, a picture and then a step on it) is priced once, with one quote and one hold, for one press of Run.Steps of CPU work are left out: they cost nothing. The requirements index marks these `cpu`: no model file, nographics memory and no card their nodes need, such as filters, trims, joins, adding sound and Ken Burns moves. A step-whose nodes run on the card (RTX Video) is GPU work. Every step must be one the policy allows (`pool`, `kinds`) and one-this install's GPUs can run (a ComfyUI step: not a text step, a step made in the browser or a cloud model), or the run-isn't offered here. It is refused before Run, never part way through.+whose nodes run on the card (RTX Video) is GPU work. A text step inside the run (a script, lyrics, a translation)+is written by the install's AI helper: it is left out too, and never counted. Every other step must be one the policy+allows (`pool`, `kinds`) and one this install's GPUs can run (a ComfyUI step: not a step made in the browser or a+cloud model), or the run isn't offered here. It is refused before Run, never part way through.++A tool's run (Shorts, Cinema Studio, Storyboard, the apps, the palette lock and every other tool an account runs) goes+through the same gate as a studio run: every step is checked, the run is priced once from every step, held once, and+counted once. Its price check answers `{ place: "pool", quote, line }` beside the tool's own answer when the run would+go to this install's GPUs, and the tool's own answer is then priced as a run there (so an account with no GPU of its+own is priced, not asked to connect one). A tool whose body has no field for the place or the price shown reads them+from the request's headers: `x-fuobe-place` (`own` or `pool`) and `x-fuobe-shown` (`{ amount, priceVersion }` as+URI-encoded JSON). A field in the body wins.++A tool makes its own requests, so each of its steps is priced as it asks. A step that asks for more outputs at once+than `outputsPerRun` allows (or Fuobe's own cap of 4) is refused before Run with words that say how many a run there+makes. It is never priced as a smaller run. The studios' own runs are cut to the cap instead, and say so. Before+anything of a tool's run is sent, Fuobe checks the rows its start made against what was priced and held: no more jobs+of any model, no more outputs at once than the cap, and only CPU work for a run held as CPU work. A run whose rows+don't match is stopped (403, `code: "not-offered"`): its rows are canceled, and their reports close its hold. A hold+gets a `release` only when none of its rows were made, never as well as its rows' reports. A tool run whose start makes+no rows at all (it kept its own error, say) sends nothing: its hold gets a `release`, and the run doesn't count toward+the hour. The palette lock spreads the pictures a person picks over separate jobs of one picture each: on this install's+GPUs it makes no more of them than `outputsPerRun` allows, as a studio run there is cut.++One press of Run is one hold and one run, however often it is sent. A tool page sends its own id for each press+(`requestId` in the body, or the `x-request-id` header for a tool whose body has no field for it). With hosted runs on,- the press is kept in the database for a day: a resend that reaches another server process, or comes after a restart,- gets the first answer and makes nothing. The reserve's `requestId` is made from the account and the press (a hash, so- one account can never name another's hold). A press refused after its hold was made gives that hold back; a resend of- it asks for a new hold under a new `requestId`.++a press whose run goes to this install's GPUs is kept in the database for a day: a resend that reaches another server++process, or comes after a restart, gets the first answer and makes nothing. The reserve's `requestId` is made from the++account and the press (a hash, so one account can never name another's hold). A press refused after its hold was made++gives that hold back; a resend of it is a new try that asks for a new hold under a new `requestId`. A run on the++account's own GPU or with its own key keeps nothing of its press in the database, as before.++The limits on runs at once and in line count a tool run from the moment it is let in. A tool whose start waits for+something (a channel, a plan) before it makes its rows still counts as one run going, and one in line, until its rows+exist, so requests sent together can't all pass the limits.++Some models, modes and options run on a visitor's own setup only (`src/lib/own-setup.ts`), and so does a workflow that+none of this install's GPUs can run right now (none holds its files, serves its kind of work, or has the memory it+needs). A run that asks for one, on any step, is refused before Run. The price check answers `allowed: false` with the+label's words as `text` and the setup itself as `ownSetup` (`{ need: "gpu", vramGb? }` or `{ need: "key", provider }`),+and Run opens that setup (Connect your GPU, or Add your key) instead of staying off. The run itself is refused with+403, `code: "connect-gpu"` or `"add-key"`. A mode whose own check refuses it while it is planned here (MiniMax H3 at+2K, Kandinsky 6.0 Pro) gets the same answer, but with no plan in it: only `modelId`, `place`, `quote` and `line`.+When the account has its own GPU, these runs go to that GPU, as before. `GET /api/status` lists the open models these+GPUs can't run right now (`viewer.pool.own`), so the pickers can label them. An item whose graphs the workflow manifest+marks validated runs here like any other, as its label leaves the pages, with no code change. Restore & colourise names+a GPU of the visitor's own only: its gated LoRA is never sent with a visitor's key.++A tool page whose price check answers `{ place: "pool", quote, line }` shows the service's words and the place in line+in its price slot, not its own words for a run on the visitor's own GPU. When the quote is refused, Run sends nothing+and says why, or opens the visitor's own setup when `ownSetup` names one.++For a visitor with no GPU of its own, the pickers never leave out what these GPUs keep off. The model picker, the preset+galleries and the camera motion, effect and Mix pickers show each such item with its label ("Runs on your own GPU ·+48 GB", "Use your own fal.ai key"). A preset card says the `cardText` ("Try free") only when these GPUs run it. An app's+own tool says the label in its place chip, and its Run opens the setup too. "Connect your GPU" says the label under+its title.A run made only of CPU work is free and never counted. Fuobe asks the service for no quote and no hold, and the run-counts against none of the policy's limits. For now it still waits in the same line on this install's GPUs as GPU work.-It does not run on the install's own CPU yet.+counts against none of the policy's limits. A worker with a CPU slot runs it beside its GPU's job, in a line of its+own ([gpu-workers.md](gpu-workers.md), "The CPU slot"). A worker with none runs it in its GPU's line, as before.3D runs (Image to 3D and the other 3D tools) aren't offered on this install's GPUs yet, whatever `kinds.model3d` says.They run on the account's own GPU, as before. An account with no GPU of its own is told the tool isn't available here@@@ -182,10 -133,18 +186,23 @@@ estimate. A quote with `allowed: falseor a chain's later step), so Run never fails on them once pressed. The page asks for a quote again by itself: every15 s while it is refused, every 30 s while it is allowed, and at once when a run starts or ends.+ `requestId` names one press of Run. The page sends an id with each press, and sends the same press again when its+ answer is lost on the way (the network dropped, or a proxy in between gave up on a slow answer). Fuobe makes the-reserve's `requestId` from the account and that id, so every send of one press reserves under one id, and no other-account's press can name it. Fuobe makes the run once: a resend gets the run the first send made. A request with no-page id (a script) reserves under an id of its own.++reserve's `requestId` from the account, that id and the press's try, so every send of one try reserves under one id,++and no other account's press can name it. Fuobe makes the run once: a resend gets the run the first send made. A try++ends when its hold goes back before a run was made (refused after the hold was made, or no answer in time): the press's++next send is a new try under a new `requestId`, so no run is ever made against a hold that went back. A request with++no page id (a script) reserves under an id of its own. Only runs on this install's GPUs reserve, so only they use it.++ A release names the hold, or, when no try of a reserve got an answer that said what happened, the reserve's+ `requestId`. The service releases whatever it holds for that id, and nothing when it holds none. Fuobe sends a release-by `requestId` a minute after it gave up, so the reserve comes first. A resend of that press is refused at once.++by `requestId` a minute after it gave up, so the reserve comes first. A resend of that press is a new try, under a new++`requestId`.+`shown` is the price the person saw before pressing Run. A service must never charge more than it: when the price wouldbe higher, it refuses with `price-changed` and the new quote, and the person sees the new price before running again.+The card that shows it offers "Run at this price": the same run is sent again with the new price in `x-fuobe-shown`, so+a run started without a price check (a result's Upscale, a retry, Run again) runs at the price the person accepted.A reserve's `text` is shown on the result once it succeeded ("7 units"). A run that fails or is removed says "Notcharged" only when its reserve answer set an amount aside (`amount` above 0). `maxWaitMs` is how long the run may waitdiff --cc docs/gpu-workers.mdindex 548a022c,95426a44..035ba5ac--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@@ -722,21 -583,23 +731,33 @@@ its target), at most once an hour eachthan once counts once: the attempt whose result was kept. The studio keeps at most the run ceiling of the job's lane,and at most the time since the job was sent to its ComfyUI (plus a minute, because ComfyUI starts a job a momentbefore the studio hears that it was sent).+ - `running` can carry `preview`: the latest preview picture of the job, a JPEG of at most 64 KB as base64, at most+ one every 2 seconds. A claim says `reportPreview: true` when the run shows one: only with hosted runs on+ (`FUOBE_HOSTED_RUNS=1`; without them, no job shows one, as before). The worker keeps the latest+ preview its ComfyUI sends on its socket and adds it to a `running` report. A PNG preview, or a JPEG over 64 KB, is+ made a smaller JPEG with ffmpeg first (at most 512 pixels on its long side); a worker without ffmpeg sends only+ ComfyUI's own small JPEGs. The studio keeps only the latest one for the job, shows it in the run's tile while the+ run works, and serves it only to the run's own account (`GET /api/generations/<id>/preview`, never cached). It+ drops the picture when the job ends, goes back in line or is claimed again. A picture that is not a JPEG, is too+ big, comes too soon or comes from an attempt that no longer holds the job is dropped, and the rest of the report+ still counts. A picture that the studio cannot keep (a full disk, a file open elsewhere) is dropped too. A run+ whose outputs the moderation service checks first shows no preview ([moderation-hook.md](moderation-hook.md)).+ Progress from reports and beats is kept in the database, so every app process sees the same step.- `give-back` with `why` (`stalled`, `run-limit` or `media`) puts the job back in line. The job keeps its place and- counts as an attempt. Only a worker's job can be given back.+ counts as an attempt. Only a worker's job can be given back. With `update-worker` (a ticket for another catalog)+ or `outside-ceiling` (more than its PC allows), that worker is not offered the job again until its build or its+ ceiling changes. Refused on the claim that took it from the line, before anything was sent, it costs no attempt+ and waits as a job no worker took (its wait limit holds, unless a worker ran it before). Refused later on (a worker+ that started again after an update and took its own job back), it counts as an attempt, and the job keeps its+ claim's time.+ - `running` may carry `preview`: a JPEG as base64, at most 64 KB, at most one every 2 seconds (see "Live+ previews"). A progress report with a preview may weigh up to about 91 KB (the preview as base64 and a few KB+ more); any other stays under the small limit.- `failed` can also give `unknown-node`, `unsafe-path` (a path, or an input outside its rule), `model-unverified`,- `input-crashed` (its ComfyUI stopped twice on the job) or `input-unreadable` (ffmpeg could not read a clip or a- sound) as the reason. The worker's own log names the node and the input, never the value. For+ `input-crashed` (its ComfyUI stopped twice on the job), `input-unreadable` (ffmpeg could not read a clip or a+ sound), `bad-ticket` (a ticket it can't use, or a graph where a ticket belongs), `unsafe-model` (a 3D model that+ isn't self-contained) or `finish-failed` (a finishing job that couldn't be made) as the reason. The worker's own log+ names the node and the input, never the value. For`input-crashed` and `input-unreadable`, and for a job that a worker gave back for the last time, the person whostarted the run sees one plain sentence with no technical detail.diff --cc src/app/api/generations/route.tsindex 41b71ddf,3769f5d9..c70d723e--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@@ -26,6 -30,8 +26,8 @@@ import { queueRelease } from "@/server/import { runOnPool } from "@/server/hosted";import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, stepsProblem, type PlaceDecision, type Refusal } from "@/server/hosted-run";import { withRunStamp, type RunStamp } from "@/server/run-stamp";+ import { hostedRunsOn } from "@/server/hosted-switch";-import { notePress, notePressRefused, pressSeen, readPressId, type PressRefusal, type PressSeen } from "@/server/run-requests";++import { endTry, notePressRun, pressPrior, pressRun, pressTries, pressTry, readPressId } from "@/server/run-requests";/*** List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,@@@ -49,6 -55,23 +51,27 @@@ const BODY_TOO_BIG = "That request is oconst 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): PressRefusal => ({++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. */-const limitAnswer = (r: AdmitRefused["refusal"]): PressRefusal => ({++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) },+ });+-/** The answer to a run whose rows couldn't be made (as the route's own catch says it, for an account's run). */-const thrownAnswer = (e: Error): PressRefusal => (e instanceof AccountRunError ? accountRunAnswer(e.refusal) : { status: 422, body: { error: e.message }, headers: {} });-/** 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);@@@ -94,15 -125,28 +117,23 @@@/** An account's run that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */const refused = (r: AccountRunRefusal) => {if (account) unhit(`run:${account.id}`);- const headers: Record<string, string> = r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {};- return refuse(403, r.error, { code: r.code, ...(r.provider && { provider: r.provider }) }, headers);+ const a = accountRunAnswer(r);+ return refuse(a.status, a.body.error, a.body, a.headers);};// Beside the request (never in it): the place the client prefers, and the price it showed (hosted runs, billing hook).- const { wish, shown } = readWishes(body);+ const { wish, shown } = readWishes(body, request.headers);const refusedBy = (r: Refusal) => {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 is made once however often the page sends it (run-requests.ts): a- // resend gets the run the first one made, and one that was refused because the billing service didn't answer is- // refused again (a new press starts afresh).++ // 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 paused = () => refuse(503, BILLING_WAIT.run, { code: "paused" }, { [BILLING_HEADER]: "paused" });+ const madeAlready = (ids: string[]) => Response.json({ items: ids.map((id) => getGeneration(id)).filter((g) => !!g) }, { status: 201 });- // The answer a press got before, for a resend of it: the same refusal, or the run it made.- const answerAgain = (seen: Exclude<PressSeen, null>) =>- seen === "gave-up" ? paused() : "refused" in seen ? refuse(seen.refused.status, seen.refused.body.error, seen.refused.body, seen.refused.headers) : madeAlready(seen.ids);+ if (account && pressId) {- const seen = pressSeen(account.id, pressId);- if (seen) return answerAgain(seen);++ const made = pressRun(account.id, pressId);++ if (made) return madeAlready(made.ids);+ }const notes: string[] = [];if (account && !preview) {// Room on the server, room in the account's files, and a fair share of runs.@@@ -160,6 -202,6 +191,8 @@@if (decision.kind === "refuse") return refusedBy(decision.refusal);}const onPool = decision.kind === "pool" ? decision : null;++ // The try of the press this send is, for a run on this install's GPUs only (run-requests.ts).++ const poolTry = account && onPool && pressId ? pressTries(account.id, pressId) : null;// The client's address, kept only as a salted hash for the policy's hourly count per address (null: no trusted proxy).const addr = account && onPool ? clientAddress(request) : null;if (account && onPool) {@@@ -233,7 -275,7 +266,7 @@@// Light work only (joins, trims): free, so nothing is set aside, and it counts against none of the policy's limits.stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };} else if (onPool) {- const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps);- const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps, pressId);++ const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs, onPool.steps, poolTry === null ? null : pressTry(account.id, pressId!, poolTry));if (!held.ok) return refusedBy(held.refusal);stamp = held.stamp;} else if (mod.checkOutputs) stamp = { checkOutputs: true };@@@ -249,15 -291,35 +282,36 @@@// 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 }, () => {- 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" });- return run;- });+ const r = admitRun(+ {+ accountId: account.id,+ pool: pool && !pool.light ? { policy: pool.policy, addr } : null,- // A resend of this press that got here first made the run (or gave up, or was refused): nothing is made twice.- ...(pressId && { prior: () => pressSeen(account.id, pressId) }),- // Refused after its hold was made: the hold goes back, so a resend gets this same answer, never a run- // against that hold. Noted in the same transaction, before any resend can look.- ...(pressId && stamp?.hold && { refused: (why: AdmitRefused["refusal"] | Error) => notePressRefused(account.id, pressId, stamp?.hold ?? null, why instanceof Error ? thrownAnswer(why) : limitAnswer(why)) }),++ // 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) }),+ },+ () => {+ 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" });- if (pressId) notePress(account.id, pressId, run.value.map((g) => g.id), stamp?.hold ?? null);++ 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 press one hold; a different one (a service that made a second) goes back, and so does- // the hold of a press that made no run.- if (stamp?.hold && (prior === "gave-up" || "refused" in prior || stamp.hold !== prior.hold)) queueRelease(stamp.hold);- return answerAgain(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);diff --cc src/lib/computer-runner.tsindex ba487687,f05cb791..289bcb3c--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@@ -477,7 -421,11 +477,8 @@@ export class ComputerRunnerif (!p) return;// A preview goes only to the prompt's own client: this tab's job (a newer ComfyUI also names the prompt).const job = this.view.jobs.find((j) => j.phase === "running" && (!p.promptId || this.events.has(p.promptId)));- if (job) this.job({ id: job.taskId, generationId: job.generationId }, { preview: new Blob([p.data as BlobPart], { type: p.type }) });+ if (!job) return;+ this.job({ id: job.taskId, generationId: job.generationId }, { preview: new Blob([p.data as BlobPart], { type: p.type }) });- // Kept for the studio too, when the run shows one (a copy: the socket's buffer is reused).- const kept = this.previewed.get(job.taskId);- if (kept && (!p.promptId || p.promptId === this.promptOf.get(job.taskId))) kept.frame = { data: new Uint8Array(p.data), type: p.type, at: this.now() };};}diff --cc src/server/account-sweep.tsindex edefcb1c,ab345ae7..b7316aa3--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@@ -15,7 -15,6 +15,7 @@@ import { db } from "./db"import { handOversDone } from "./generations";import { deleteForever } from "./library";import { deleteAsset, scratchDir } from "./storage";- import { forgetAccountPresses } from "./tool-presses";++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/account-tool-run.tsindex 8e720e11,04e0c52b..80191894--- a/src/server/account-tool-run.ts+++ b/src/server/account-tool-run.ts@@@ -26,8 -21,6 +26,8 @@@ import { hit, unhit } from "./rate"import { withRunStamp, type RunStamp } from "./run-stamp";import { once } from "./shorts-schemas";import { ShortsError } from "./shorts";+import { hostedRunsOn } from "./hosted-switch";- import { answerPress, claimPress, releasePress, toolPressId, type PressAnswer } from "./tool-presses";++import { answerPress, claimPress, pressTry, releasePress, toolPressKey, toolPressSeen, type Press, type PressAnswer, type PressClaim } from "./run-requests";/*** A tool's run for a signed-in account (public sign-up): Genjutsu first, then the other tools that plan a run as a@@@ -94,59 -85,10 +94,55 @@@ class Refused) {}}+const asAnswer = async (r: Response): Promise<PressAnswer> => ({ status: r.status, headers: [...r.headers], text: await r.text() });+const fromAnswer = (a: PressAnswer): Response => new Response(a.text, { status: a.status, headers: a.headers });++/**- * The press of Run a tool's run belongs to (onceForAccount): its id for the billing service's reserve, so every resend- * of the press asks for the same hold (hosted-run.ts reservePool). Null: a run with no id from its page.++ * The press of Run a tool's run belongs to (onceForAccount), with hosted runs on: its account and key (run-requests.ts),++ * and its try once startOnPool has claimed it for a run on this install's GPUs (`tries`). Null key: a run with no id++ * from its page. A run on the account's own GPU or key never claims it, so nothing of it is kept.+ */- const PRESS = new AsyncLocalStorage<{ pressId: string | null }>();++const PRESS = new AsyncLocalStorage<{ accountId: string; key: string | null; tries: number | null }>();++/** How long a resend waits for its press to be answered by another server process, before it says it is starting. */+const PRESS_WAIT_MS = 30_000;++/** A resend whose press another server process is still starting, after PRESS_WAIT_MS. */+const STARTING: PressAnswer = {+ status: 409,+ headers: [+ ["content-type", "application/json"],+ ["cache-control", "no-store"],+ ["retry-after", "5"],+ ],+ text: JSON.stringify({ error: "This run is starting. It shows in your runs in a moment.", code: "press-starting" }),+};++/**- * A press kept in the database (tool-presses.ts), with hosted runs on: a resend that reaches another server process, or- * comes after a restart, gets the first answer (waiting for it while that process starts it), never a second run.++ * A press of a tool's Run as another server process left it (run-requests.ts): its answer (waiting for it while that++ * process starts it), STARTING when it is still being started after PRESS_WAIT_MS, or null when there is none to give.++ * `look` reads it, or claims it for this call.+ */- async function keptPress(accountId: string, scope: string, clientId: string, attempt: (tries: number) => Promise<PressAnswer>): Promise<PressAnswer> {++async function awaitPress(look: () => PressClaim | null): Promise<Extract<PressClaim, { kind: "claimed" }> | PressAnswer | null> {+ const until = Date.now() + PRESS_WAIT_MS;- let claim = claimPress(accountId, scope, clientId);- while (claim.kind === "starting") {++ let seen = look();++ while (seen?.kind === "starting") {+ if (Date.now() > until) return STARTING;+ await new Promise((r) => setTimeout(r, 250));- claim = claimPress(accountId, scope, clientId);- }- if (claim.kind === "done") return claim.answer;- try {- const answer = await attempt(claim.tries);- answerPress(accountId, scope, clientId, answer);- return answer;- } catch (e) {- releasePress(accountId, scope, clientId, e instanceof Refused && e.held);- throw e;++ seen = look();+ }++ if (!seen) return null;++ return seen.kind === "done" ? seen.answer : seen;+}+/*** An account's tool run once per client request id (shorts-schemas.ts once): a repeat of the id (a second click that got- * through, a retried POST) gets the first run, and never another account's. With hosted runs on, the press is kept in- * the database too (keptPress), so a repeat that reaches another server process gets it as well, and its run on this- * install's GPUs asks the billing service for one hold however often it is sent. A refusal isn't kept: sent again- * (after the account connects its GPU, say), the run is checked again; one refused after its hold was made (and given- * back) asks for a new hold then. `ok` turns the started run into the route's answer.- * through, a retried POST) gets the first run, and never another account's. A refusal isn't kept: sent again (after the- * account connects its GPU, say), the run is checked again. `ok` turns the started run into the route's answer.++ * through, a retried POST) gets the first run, and never another account's. With hosted runs on, a press whose run goes++ * to this install's GPUs is kept in the database too (run-requests.ts), so a repeat that reaches another server process++ * gets it as well, and the run asks the billing service for one hold however often it is sent. A refusal isn't kept:++ * sent again (after the account connects its GPU, say), the run is checked again; one refused after its hold was made++ * (and given back) is a new try then, with a new hold. A run on the account's own GPU or key keeps nothing, as before.++ * `ok` turns the started run into the route's answer.*/export async function onceForAccount<T>(account: Account,@@@ -155,38 -97,27 +151,69 @@@fn: () => Promise<AccountToolResult<T>>,ok: (r: { value: T; gpuWarning?: string }) => Response,): Promise<Response> {- const attempt = async (tries: number): Promise<PressAnswer> => {- const out = await PRESS.run({ pressId: id ? toolPressId(scope, id, tries) : null }, fn);- if (out.ok) return asAnswer(ok(out));- throw new Refused(await asAnswer(out.response), !!out.held);++ const key = id && hostedRunsOn() ? toolPressKey(scope, id) : null;++ const attempt = async (): Promise<PressAnswer> => {++ // A press another server process answered (or is starting) is that answer.++ const before = key ? await awaitPress(() => toolPressSeen(account.id, key)) : null;++ // (Still starting there: said, and never kept as this press's answer here.)++ if (before === STARTING) throw new Refused(STARTING, false);++ if (before) return before as PressAnswer;++ const press = { accountId: account.id, key, tries: null as number | null };++ try {++ const out = await PRESS.run(press, fn);++ const answer = out.ok ? await asAnswer(ok(out)) : null;++ if (key && press.tries !== null) {++ if (answer) answerPress(account.id, key, answer);++ else releasePress(account.id, key, press.tries, !out.ok && !!out.held);++ }++ if (answer) return answer;++ throw new Refused(await asAnswer((out as Extract<AccountToolResult<T>, { ok: false }>).response), !out.ok && !!out.held);++ } catch (e) {++ if (key && press.tries !== null && !(e instanceof Refused)) releasePress(account.id, key, press.tries, false);++ throw e;++ }+ };try {- const answer = await once(`${scope}:acct:${account.id}`, id, () => (id && hostedRunsOn() ? keptPress(account.id, scope, id, attempt) : attempt(0)));- return fromAnswer(answer);- const r = await once(`${scope}:acct:${account.id}`, id, async () => {- const out = await fn();- if (!out.ok) throw new Refused(out.response.status, [...out.response.headers], await out.response.text());- return out;- });- return ok(r);++ return fromAnswer(await once(`${scope}:acct:${account.id}`, id, attempt));} catch (e) {- if (e instanceof Refused) return new Response(e.text, { status: e.status, headers: e.headers });+ if (e instanceof Refused) return fromAnswer(e.answer);throw e;}}-/** An account's runs going now (queued or running), counted as runs: a run's jobs and steps share a batch. */-export function activeAccountRuns(accountId: 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') = ?")- .get(accountId) as { n: number };- return r.n;++/**++ * Claim the tool's press for its run on this install's GPUs (startOnPool), once that is where it goes: its try for the++ * reserve, or the answer another server process gave it (or STARTING). Nothing to claim (no id, hosted runs off): null.++ */++async function claimToolPress(): Promise<{ press: Press } | { answer: PressAnswer } | null> {++ const p = PRESS.getStore();++ if (!p?.key) return null;++ const { accountId, key } = p;++ const got = await awaitPress(() => claimPress(accountId, key));++ if (!got) return null;++ if (!("kind" in got)) return { answer: got };++ p.tries = got.tries;++ return { press: pressTry(accountId, key, got.tries) };+ }++/** A page's id for a press of Run, as a tool's body carries it beside its own fields (`requestId`), or none. */+export function requestIdOf(body: unknown): string | undefined {+ const v = (body as { requestId?: unknown } | null)?.requestId;+ return typeof v === "string" && /^[A-Za-z0-9_-]{8,64}$/.test(v) ? v : undefined;+}++/** The header a page sends its id for a press of Run in, for a tool whose body has no field for it. */+export const PRESS_HEADER = "x-request-id";++/** A page's id for a press of Run, from the request's PRESS_HEADER, or none. */+export const pressIdOf = (request: Request): string | undefined => requestIdOf({ requestId: request.headers.get(PRESS_HEADER) });++/**+ * An account's runs going now (queued or running), counted as runs: a run's jobs and steps share a batch, and a run let+ * in whose rows are still being made counts too (pool-limits.ts accountActiveRuns).+ */+export const activeAccountRuns = (accountId: string): number => accountActiveRuns(accountId);+/** A request body over what an account's run may weigh (its files are uploaded first): 413 before it is read. */export function bodyTooBig(request: Request): Response | null {return Number(request.headers.get("content-length") ?? 0) > ACCOUNT_LIMITS.runBodyBytes ? refuse(413, ACCOUNT_MESSAGES.bodyTooBig) : null;@@@ -467,117 -297,3 +494,120 @@@ export async function runAccountTool<T>return back(errorResponse(e));}}++/** What the moderation service checks of a tool's run: its words (every step's, once each) and its files. */+function checkedRequest(steps: ToolStep[], files: string[]): GenerationRequest {+ const first = steps.find((s) => !s.deps) ?? steps[0];+ const words = steps.map((s) => s.request.prompt?.trim()).filter(Boolean);+ return { ...first.request, prompt: [...new Set(words)].join("\n").slice(0, 8000), inputs: filesAsInputs(files) };+}++const isThenable = (v: unknown): v is PromiseLike<unknown> => !!v && typeof (v as { then?: unknown }).then === "function";++/**+ * A tool run on this install's GPUs (placeOf said "pool"): the policy's limits on runs there (never for light work+ * only), the moderation service's check, one hold for the whole run priced from every step (none for light work: free),+ * then the run made as the account's run there (runOnPool, every row stamped with its place and hold) and counted in+ * the same transaction (admitRun). Every row it makes is checked again before anything is sent (madeRunProblem): against+ * the policy, and against what the run was priced and held for (its jobs, its outputs at once, light work only). A row+ * that doesn't match stops the whole run: its rows are stopped, and their reports close its hold (a run that made no+ * row gives its hold back). Its own GPU's checks (the pre-flight, its LoRAs) don't apply here.+ */+async function startOnPool<T>(+ request: Request,+ account: Account,+ run: AccountToolRun<T>,+ steps: ToolStep[],+ files: string[],+ pool: Extract<ToolPlace, { kind: "pool" }>,+ back: (response: Response) => AccountToolResult<T>,+): Promise<AccountToolResult<T>> {+ const id = account.id;+ const addr = clientAddress(request);+ const over = pool.light ? null : poolLimitRefusal(id, pool.policy, addr);+ if (over) return back(refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) }));+ const kind = outputKind(pool.main.planned.op, pool.main.planned.model);+ const mod = await moderateRun(account, checkedRequest(steps, files), null, "pool", { kind, place: "pool" });+ if (!mod.ok) return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));++ // The press of Run, kept from here (run-requests.ts): another server process may have started or answered it meanwhile.++ const claim = await claimToolPress();++ if (claim && "answer" in claim) return back(fromAnswer(claim.answer));+ let stamp: RunStamp;+ if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };+ else {- // One hold per press of Run: every resend of the press asks for it by the same request id.- const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, PRESS.getStore()?.pressId ?? null);++ // One hold per try of a press of Run: every send of the try asks for it by the same request id.++ const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, claim?.press ?? null);+ if (!held.ok) return back(refuse(held.refusal.status, held.refusal.body.error, held.refusal.body, held.refusal.headers));+ stamp = held.stamp;+ }+ const release = () => {+ if (stamp.hold) queueRelease(stamp.hold);+ };+ /** Refused from here on: after its hold was made, when one was (it goes back). */+ const refused = (response: Response): AccountToolResult<T> => ({ ...back(response), ...(stamp.hold && { held: true }) });+ const notOffered = (error: string) => refuse(403, error, { code: "not-offered" }, { [BILLING_HEADER]: "not-offered" });+ /** What the start made: its value, its rows (they keep coming while an awaiting start runs) and its open admission. */+ type Made = { value: T | Promise<T>; ids: string[]; start: () => void; open: string | null };+ const now = Date.now();+ let admitted: { ok: true; value: Made } | { ok: false; refusal: { status: number; error: string; code: string; retryAfterS?: number } };+ try {+ admitted = runOnPool(id, () =>+ withRunStamp(stamp, () =>+ admitRun({ accountId: id, pool: pool.light ? null : { policy: pool.policy, addr }, now }, (): Made => {+ const made = captureRun(run.start);+ // A tool that makes its rows as it goes (after an await) is checked once they are all made, below. Until then+ // it counts as a run going (and in line) for every later request, from this same locked step: requests sent+ // together can't all pass the limits while its rows aren't made yet.+ if (isThenable(made.value)) return { ...made, open: openAdmission(id, !pool.light, now) };+ const problem = madeRunProblem(pool, made.ids);+ if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });+ return { ...made, open: null };+ }),+ ),+ );+ } catch (e) {+ release();+ return refused(errorResponse(e));+ }+ if (!admitted.ok) {+ release();+ const r = admitted.refusal;+ return refused(r.code === "not-offered" ? notOffered(r.error) : refuse(r.status, r.error, { code: r.code }, { "Retry-After": String(r.retryAfterS ?? 30) }));+ }+ const made = admitted.value;+ /**+ * Stop what was made (nothing of it was sent). Each stopped row's report closes the hold (billing-outbox.ts), so the+ * hold goes back by itself only when no row was made.+ */+ const undo = () => {+ for (const g of made.ids) void cancelGeneration(g);+ if (!made.ids.length) release();+ };+ let value: T;+ try {+ value = await made.value;+ } catch (e) {+ undo();+ return refused(errorResponse(e));+ } finally {+ // Its rows exist now and count for themselves (or none will).+ if (made.open) closeAdmission(made.open);+ }+ if (isThenable(made.value)) {+ const problem = madeRunProblem(pool, made.ids);+ if (problem) {+ undo();+ return refused(notOffered(problem));+ }+ }+ // A start that made nothing (a tool that kept its own error, say): nothing runs, so its hold goes back, and it is not+ // one of the hour's runs.+ if (!made.ids.length) {+ release();+ if (!pool.light) forgetAdmission(id, now);+ unhit(`run:${id}`);+ return { ok: true, value };+ }+ made.start();+ return { ok: true, value };+}diff --cc src/server/billing-outbox.tsindex ba943fa6,708a2e0c..42751b5e--- a/src/server/billing-outbox.ts+++ b/src/server/billing-outbox.ts@@@ -140,15 -159,42 +159,51 @@@ interface OutboxRowcreated_at: number;}- /** Send the reports that are due. Returns how many the service took. */+ /** How long an app process holds a report it is sending (a send takes 5 s at most: billing.ts BILLING_TIMEOUTS.report). */+ const SEND_TURN_MS = 60_000;++ declare global {+ /** This app process, as the reports it is sending name it. */+ var __fuobeOutboxToken: string | undefined;+ }++ const outboxToken = () => (globalThis.__fuobeOutboxToken ??= `${process.pid}:${crypto.randomUUID()}`);++ /**+ * Take a report to send it: only one not sent yet, that no other app process is sending now (two processes on one+ * database during a deploy's overlap never send the same report, so the service gets each one once).+ */+ function claimReport(key: string): boolean {+ const now = Date.now();+ const me = outboxToken();+ return (+ db()+ .prepare("UPDATE billing_outbox SET sending_by = ?, sending_until = ? WHERE key = ? AND done_at IS NULL AND (sending_until IS NULL OR sending_until < ? OR sending_by = ?)")+ .run(me, now + SEND_TURN_MS, key, now, me).changes > 0+ );+ }+-/** Send the reports that are due. Returns how many the service took. */++/**++ * Send the reports that are due. Returns how many the service took. A sweep of this process that is sending now is++ * waited for first: the reports it holds are skipped below, and would otherwise still be on their way when this returns.++ */export async function drainOutbox(now = Date.now(), limit = 50): Promise<number> {++ const going = globalThis.__fuobeBillingSweep;++ if (going) await going;++ return drainDue(now, limit);++}++++async function drainDue(now: number, limit = 50): Promise<number> {const d = db();- const due = d.prepare("SELECT key, kind, hold_id, payload_json, tries, created_at FROM billing_outbox WHERE done_at IS NULL AND next_at <= ? ORDER BY next_at LIMIT ?").all(now, limit) as OutboxRow[];+ const due = d+ .prepare("SELECT key, kind, hold_id, payload_json, tries, created_at FROM billing_outbox WHERE done_at IS NULL AND next_at <= ? AND (sending_until IS NULL OR sending_until < ?) ORDER BY next_at LIMIT ?")+ .all(now, Date.now(), limit) as OutboxRow[];let sent = 0;for (const r of due) {+ if (!claimReport(r.key)) continue;try {await sendReport(r.kind, JSON.parse(r.payload_json));- d.prepare("UPDATE billing_outbox SET done_at = ?, tries = tries + 1, last_error = NULL WHERE key = ?").run(Date.now(), r.key);+ d.prepare("UPDATE billing_outbox SET done_at = ?, tries = tries + 1, last_error = NULL, sending_until = NULL, sending_by = NULL WHERE key = ?").run(Date.now(), r.key);sent++;const account = accountOfHold(r.hold_id);if (account) forgetBalance(account);@@@ -176,23 -222,23 +231,29 @@@ function accountOfHold(holdId: string)}declare global {-- var __fuobeBillingSweep: boolean | undefined;++ /** This process's outbox sweep while it runs. */++ var __fuobeBillingSweep: Promise<void> | undefined;}--/** One outbox sweep (the runner's tick): write what is due, send what is due. One at a time. */--export async function sweepBilling(now = Date.now()): Promise<void> {-- if (globalThis.__fuobeBillingSweep) return;++/** One outbox sweep (the runner's tick): write what is due, send what is due. One at a time: a call meanwhile waits for it. */++export function sweepBilling(now = Date.now()): Promise<void> {++ if (globalThis.__fuobeBillingSweep) return globalThis.__fuobeBillingSweep;// Reports wait for a service: with none set, nothing is written (a hold can only exist while one was set).-- if (!billingConfigured()) return;-- globalThis.__fuobeBillingSweep = true;-- try {-- queueReports(now);-- await drainOutbox(now);-- } catch (e) {-- console.warn(`[fuobe] billing sweep: ${(e as Error).message}`);-- } finally {-- globalThis.__fuobeBillingSweep = false;-- }++ if (!billingConfigured()) return Promise.resolve();++ const sweep: Promise<void> = (async () => {++ // (Set as this process's sweep before any of it runs.)++ await null;++ try {++ queueReports(now);++ await drainDue(now);++ } catch (e) {++ console.warn(`[fuobe] billing sweep: ${(e as Error).message}`);++ } finally {++ if (globalThis.__fuobeBillingSweep === sweep) globalThis.__fuobeBillingSweep = undefined;++ }++ })();++ globalThis.__fuobeBillingSweep = sweep;++ return sweep;}/** How many reports wait, and since when (for the admin queue view). */diff --cc src/server/computer/pool.tsindex e9d9a38d,2bbc974b..ef6c5ec4--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@@ -7,9 -5,7 +7,9 @@@ import { RELAY_TIMES, SENT_STATES, typimport { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";import { db } from "../db";import { loadIndex } from "../gpu/index-file";+import { hostedRunsOn } from "../hosted-switch";+import { catalogVersion } from "./catalog-version";- import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, type TaskRow } from "./tasks";+ import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setPoolGiveBack, setPoolLost, setTask, takeTask, taskById, type TaskRow } from "./tasks";import { queueSettings, runCeilingMs } from "../queue-settings";import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";@@@ -270,11 -204,9 +270,11 @@@ export function workerBeat(w: WorkerRowconst t = typeof r?.task === "string" ? (d.prepare("SELECT * FROM relay_tasks WHERE id = ? AND worker_id = ?").get(r.task, w.id) as TaskRow | undefined) : undefined;if (!t || !(SENT_STATES as readonly string[]).includes(t.state)) continue;setTask(t.id, { device_seen_at: now });- noteProgress(t.id, r as unknown as Record<string, unknown>, now);+ noteProgress(t.id, r as unknown as Record<string, unknown>, now, t.lease_hash);}for (const id of b.stopped) d.prepare("UPDATE relay_tasks SET stop = 0 WHERE id = ? AND device = ?").run(id, device);+ // A task its CPU slot held that ended with a stop: the CPU slot heard it in its reports and emptied its ComfyUI then.+ d.prepare("UPDATE relay_tasks SET stop = 0 WHERE device = ? AND stop = 1 AND state IN ('done','failed','canceled')").run(slotDevice(w, "cpu"));const stops = (d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE device = ? AND stop = 1").all(device) as { id: string; prompt_id: string; prefix: string | null }[]).map((s) => ({task: s.id,promptId: s.prompt_id,@@@ -889,28 -742,58 +891,65 @@@ export function poolLane(workflowId: st* Is there a worker for this workflow (any workflow: `workflowId` null): one the owner added and didn't revoke, allowed* the workflow's lane, and able to run it as its last list of files said (its verified files and node packs, the kinds* of input it takes) with the VRAM it needs, whether it is paused, outside its hours or offline right now (a run then- * waits in line for it). A run that no worker could ever take is refused before Run, never left to wait for nothing.+ * waits in line for it). Inside its PC's ceiling: the lanes or workflows that PC may ever run, and, given the job's+ * `size`, its largest picture, longest clip and most results. A run that no worker could ever take is refused before+ * it is queued, never left to wait for nothing. `tickets`: only a worker that takes job tickets now (ticketReady), as+ * an account's run needs; without it, a worker built from another catalog counts too (the owner's own jobs, and+ * whether this install's GPUs could ever run it).*/-export function workersCanRun(workflowId: string | null): boolean {- return ableWorkers(workflowId).length > 0;+export function workersCanRun(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean } = {}): boolean {++ return ableWorkers(workflowId, o).length > 0;+ }++ /** The workers that may and can run this workflow (any workflow: null), whatever their state now (workersCanRun). */-function ableWorkers(workflowId: string | null): WorkerRow[] {++function ableWorkers(workflowId: string | null, o: { size?: Needs["size"]; tickets?: boolean } = {}): WorkerRow[] {const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;const lane = workflowId ? poolLane(workflowId) : null;// (Runs made here go to the "pool" pool: poolFields.)- return poolWorkers().some((w) => {+ return poolWorkers().filter((w) => {if (w.pool !== "pool") return false;+ if (o.tickets && !ticketReady(w)) return false;const allow = allowOf(w);const cap = capableOf(w);- if (workflowId === null) return cap.workflows.some((id) => poolLane(id) in allow);- if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId)) return false;+ const ceiling = ceilingOf(w);+ if (workflowId === null) return cap.workflows.some((id) => poolLane(id) in allow && insideCeiling(ceiling, { workflowId: id, lane: poolLane(id) }));+ if (!needs || !(lane! in allow) || !cap.workflows.includes(workflowId) || ceilingProblem(ceiling, { workflowId, lane, size: o.size })) return false;return needs.minVramBytes <= (factsOf(w).vramBytes ?? 0);});}+ /**+ * Is a worker on to take work soon: connected and heard from within the silence limit, paused neither on the website+ * nor on its PC (a game or another program on its GPU counts as paused), not draining, new enough, and inside its+ * hours? A worker that makes room for local ComfyUI work first is on: people's runs keep their place and it takes them+ * next.+ */+ function onSoon(w: WorkerRow, now: number): boolean {+ return (+ !w.revoked_at &&+ !(w.expires_at && w.expires_at <= now) &&+ !w.paused_server &&+ !w.paused_local &&+ !w.drain &&+ (w.protocol ?? 0) >= MIN_PROTOCOL &&+ !!w.seen_at &&+ now - w.seen_at <= RELAY_TIMES.poolSilentMs &&+ hoursAt(hoursOf(w), now).inside+ );+ }++ /**- * Is every worker that could run this workflow (any workflow: null) away now: paused, draining, outside its hours,- * silent, or never connected? A run made then would wait for nothing until its wait limit ended it, so the price check++ * Is every worker that could run an account's job of this workflow (any workflow: null) away now: paused, draining,++ * outside its hours, silent, or never connected? Only workers that take job tickets now count (ticketReady), as an++ * account's run goes as one. A run made then would wait for nothing until its wait limit ended it, so the price check+ * says "Starting soon" (Run is off), and a press of Run makes nothing. False when no worker could run it at all+ * (workersCanRun refuses that) or one is on.+ */+ export function workersAway(workflowId: string | null, now = Date.now()): boolean {- const able = ableWorkers(workflowId);++ const able = ableWorkers(workflowId, { tickets: true });+ return able.length > 0 && !able.some((w) => onSoon(w, now));+ }+/*** What the workers allowed a lane have (any lane: `lane` null), for shaping a graph that each of them can run: the least* VRAM and RAM among those that said, and their device when they all name the same kind. Nothing known: empty.diff --cc src/server/computer/tasks.tsindex 9f27651f,9f027550..699d660a--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@@ -8,6 -8,7 +8,7 @@@ importDEVICE_ID,FACT_LIMITS,INPUT_NAME,- PREVIEW_REPORT,++ PREVIEW_LIMITS,RELAY_LIMITS,RELAY_TIMES,reportAllowed,@@@ -22,12 -23,10 +23,13 @@@type ReportEvent,type TaskInput,type WantedFile,+ previewOf,} from "@/lib/relay";+import type { FinishTicket } from "@/lib/finish-ticket";+import type { JobTicket } from "@/lib/job-ticket";import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";import { runCeilingMs } from "../queue-settings";+ import { hostedRunsOn } from "../hosted-switch";/*** "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a@@@ -68,16 -65,14 +68,17 @@@ export interface Progressat: number;}- const progressMap = () => (globalThis.__fuobeRelayProgress ??= new Map());- export const taskProgress = (id: string): Progress | undefined => progressMap().get(id);- /** A task's latest live preview from its worker: a JPEG (at most 64 KB) and when it came, or null. */- export function taskPreview(id: string): { jpeg: Buffer; at: number } | null {- const p = progressMap().get(id);- return p?.preview ? { jpeg: Buffer.from(p.preview, "base64"), at: p.previewAt ?? p.at } : null;- }+ /**+ * A task's live progress, as its last report or beat said it. Kept in the database (relay_tasks.progress_json), not in+ * one process's memory: a refresh, a second device and the other app process during a deploy all see the same step.+ */+ export const taskProgress = (t: Pick<TaskRow, "progress_json">): Progress | undefined => json<Progress | undefined>(t.progress_json, undefined);+-/** The most a preview picture may weigh, and how often one is kept (one at most every 2 s, a little early allowed). */-export const PREVIEW_LIMITS = { ...PREVIEW_REPORT, slackMs: 300 } as const;++/**++ * A preview picture that comes a little before PREVIEW_LIMITS.everyMs is kept all the same (a worker's timer and the++ * network's delay).++ */++const PREVIEW_SLACK_MS = 300;/** The relay's tables are made with the database (db.ts RELAY_TABLES). */const rdb = () => db();@@@ -543,15 -495,11 +547,19 @@@ export function beat(principal: Princip}/**- * Note a task's live progress (a report or a beat), over what it said before. Only while the task is still with the+ * Does a worker's task show live previews: a task on the workers whose run asked for previews, that isn't a finishing- * job, and whose results aren't checked before anyone sees them.++ * job, and whose results aren't checked before anyone sees them (the task's stamp, and its run's: previewShown).+ */- export function showsPreview(t: Pick<TaskRow, "pools" | "preview" | "finish_json" | "extra_json">): boolean {- return !!t.pools && !!t.preview && !t.finish_json && !json<{ checkOutputs?: boolean }>(t.extra_json, {}).checkOutputs;++export function showsPreview(t: Pick<TaskRow, "pools" | "preview" | "finish_json" | "extra_json" | "generation_id">): boolean {++ return !!t.pools && !!t.preview && !t.finish_json && !json<{ checkOutputs?: boolean }>(t.extra_json, {}).checkOutputs && previewShown(t.generation_id);+}+- /** Keep a task's live progress. A preview is kept only from a progress report (`o.preview`), never from a beat. */- export function noteProgress(id: string, r: Record<string, unknown>, now: number, o: { preview?: boolean } = {}) {++/**++ * Note a task's live progress (a report or a beat; never a preview: notePreview), over what it said before. Only while the task is still with the+ * computer or worker that said it (`lease`: the lease it held then, as read with the task): a late report from an attempt+ * another app process sent back in line, ended or gave to another worker meanwhile leaves nothing behind.+ */+ export function noteProgress(id: string, r: Record<string, unknown>, now: number, lease: string | null) {const p: Progress = { at: now };for (const k of ["value", "max", "nodesDone", "position"] as const) {const v = nonNeg(r[k]);@@@ -559,12 -507,111 +567,113 @@@}const node = str(r.node, 64);if (node) p.node = node;- // A worker's live preview: a JPEG of at most 64 KB (previewOf); a larger one, or anything else, is dropped.- const preview = o.preview ? previewOf(r.preview) : undefined;- if (preview) Object.assign(p, { preview, previewAt: now });- 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;+ }+ }+-/** Is this a JPEG picture (its first bytes)? */-const isJpeg = (b: Buffer) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff;++ /** 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">, base64: unknown, now = Date.now()): boolean {- if (!t.pools || !t.preview || typeof base64 !== "string" || !base64 || base64.length > Math.ceil(PREVIEW_LIMITS.bytes / 3) * 4 + 4) return false;- if (t.preview_at && now - t.preview_at < PREVIEW_LIMITS.everyMs - PREVIEW_LIMITS.slackMs) return false;- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) return false;- const data = Buffer.from(base64, "base64");- if (data.length > PREVIEW_LIMITS.bytes || !isJpeg(data) || !previewShown(t.generation_id)) return false;++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 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.@@@ -605,12 -652,12 +714,16 @@@ export function takeTask(t: TaskRow, de// claim (the report "gone"). Across claims, only its requeues count (pool.ts MAX_ATTEMPTS). Its sending clock starts at// the claim.setTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now, ...(fresh && t.pools && { attempts: 0, sending_since: null }), ...fields });- if (fresh) rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);+ if (fresh) {+ rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);+ // A new attempt: nothing of an earlier one shows (no step, no preview picture).+ dropProgress(t.id);+ }const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));+ // An account's task for workers hands out its job ticket, never a graph (src/lib/job-ticket.ts).+ const ticket = t.ticket_json ? json<JobTicket | null>(t.ticket_json, null) : null;+ // A finishing job hands out its finish ticket (src/lib/finish-ticket.ts): no graph and no job ticket.+ const finish = t.finish_json ? json<FinishTicket | null>(t.finish_json, null) : null;return {id: t.id,generationId: t.generation_id,@@@ -749,8 -794,10 +862,10 @@@ function reportOnce(t: TaskRow, e: Reporeturn { ok: true };case "running":setTask(t.id, { ...seen, state: "running", ...(!t.started_at && { started_at: now }), note: null });- // A live preview only from the attempt that holds the lease, for a run that shows them.- noteProgress(t.id, { ...e, position: undefined }, now, { preview: showsPreview(t) });+ noteProgress(t.id, { ...e, position: undefined }, now, t.lease_hash);- // A worker's preview picture of the job: the tile shows the latest one while the run works (as the lease that sent- // it still holds the task).++ // A worker's live preview of the job: the tile shows the latest one while the run works. Kept only from a progress++ // report of the attempt that holds the lease, for a run that shows them (notePreview, showsPreview).+ if (e.preview) notePreview({ ...(taskById(t.id) ?? t), lease_hash: t.lease_hash }, e.preview, now);return { ok: true };case "finished":case "passes": {diff --cc src/server/db.tsindex 4115084e,dcba1ab0..1755e99d--- a/src/server/db.ts+++ b/src/server/db.ts@@@ -850,10 -845,11 +850,13 @@@ export const RELAY_TABLES = `CREATE TAB/*** The optional external services' tables (billing.ts, moderation.ts). billing_outbox: every settle, refund and release- * the billing service must get, kept until it takes it (billing-outbox.ts). output_checks: each output of a run whose- * outputs the moderation service sees first, and where its check is. reports_inbox: "Report this result" when no- * moderation service is set, for the owner. Made here rather than as numbered migrations (other branches add those at- * the same time). Safe to run on every start; empty and unread while no service is set.+ * the billing service must get, kept until it takes it (billing-outbox.ts). run_requests: each press of Run an account- * made with hosted runs on, by the page's id for it, and the run it made (run-requests.ts). output_checks: each output- * of a run whose outputs the moderation service sees first, and where its check is. reports_inbox: "Report this- * result" when no moderation service is set, for the owner. Made here rather than as numbered migrations (other- * branches add those at the same time). Safe to run on every start; empty and unread while no service is set.++ * made on this install's GPUs, by a key made from the page's id for it, with its try, the run it made (a studio run's++ * rows and hold) or the answer it got (a tool's), and `starting` while a tool's press is being started; kept a day++ * (run-requests.ts). output_checks: each output of a run whose outputs the moderation service sees first, and where its++ * check is. reports_inbox: "Report this result" when no moderation service is set, for the owner. Made here rather than++ * as numbered migrations (other branches add those at the same time). Safe to run on every start; empty and unread while++ * no service is set.*/export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox (key TEXT PRIMARY KEY,@@@ -888,6 -884,17 +891,18 @@@);CREATE INDEX IF NOT EXISTS pool_admissions_account ON pool_admissions(account, at);CREATE INDEX IF NOT EXISTS pool_admissions_addr ON pool_admissions(addr, at);+ CREATE TABLE IF NOT EXISTS run_requests (+ account TEXT NOT NULL,+ request_id TEXT NOT NULL,++ tries INTEGER NOT NULL DEFAULT 0,++ starting INTEGER NOT NULL DEFAULT 0,+ ids_json TEXT,+ hold_id TEXT,- gave_up INTEGER NOT NULL DEFAULT 0,- refusal_json TEXT,++ answer_json TEXT,+ at INTEGER NOT NULL,+ PRIMARY KEY (account, request_id)+ );+ CREATE INDEX IF NOT EXISTS run_requests_at ON run_requests(at);CREATE TABLE IF NOT EXISTS reports_inbox (id TEXT PRIMARY KEY,target_json TEXT NOT NULL,@@@ -992,8 -999,33 +1007,35 @@@ const HOOK_COLUMNS: [string, string, st["assets", "held", "INTEGER NOT NULL DEFAULT 0"],// NULL, or "checking" (the tile says "Checking").["generations", "stage", "TEXT"],+ // A report one app process is sending now, until when: no other process sends it meanwhile (billing-outbox.ts).+ ["billing_outbox", "sending_until", "INTEGER"],+ ["billing_outbox", "sending_by", "TEXT"],- // The answer a press of Run got when it was refused after its hold was made (run-requests.ts).- ["run_requests", "refusal_json", "TEXT"],++ // A press of Run's try, and a tool's press being started or answered (run-requests.ts).++ ["run_requests", "tries", "INTEGER NOT NULL DEFAULT 0"],++ ["run_requests", "starting", "INTEGER NOT NULL DEFAULT 0"],++ ["run_requests", "answer_json", "TEXT"],+ ];++ /**+ * Columns the runner added to generation_runs: the app process that saves a finished run's results, and until when it+ * holds that turn (generations.ts claimFinish). Two processes on one database (a deploy's overlap) never both save it.+ */+ const RUNNER_COLUMNS: [string, string, string][] = [+ ["generation_runs", "finish_by", "TEXT"],+ ["generation_runs", "finish_until", "INTEGER"],];+ /**+ * Each app process on this database, by the name its turns carry, and when it last said it still runs (generations.ts+ * keepBeating). A turn whose process went quiet is free before it runs out. Made here rather than as a numbered+ * migration, so branches that add migrations never clash over its place.+ */+ const RUNNER_TABLES = `CREATE TABLE IF NOT EXISTS app_processes (+ token TEXT PRIMARY KEY,+ started_at INTEGER NOT NULL,+ seen_at INTEGER NOT NULL+ );`;+/** Columns of the relay tables that came later: [table, column, type]. */const RELAY_COLUMNS: [string, string, string][] = [["relay_runners", "comfy", "TEXT NOT NULL DEFAULT 'ok'"],@@@ -1129,9 -1156,6 +1176,8 @@@ function open(): Database.Database}// Admin tokens and the admin API's log.db.exec(ADMIN_TABLES);- // A tool's press of Run, kept so a resend gets its first answer (tool-presses.ts), and the runs let in whose rows are- // still being made (pool-limits.ts openAdmission): not a numbered migration either.- db.exec(TOOL_PRESS_TABLES);++ // The runs let in whose rows are still being made (pool-limits.ts openAdmission): not a numbered migration either.++ db.exec(ADMISSION_TABLES);// Skills: the runs that wait across studios. A data folder that ran claude/fuobe-parity-4's earlier build of this// feature (its numbered migration at place 27, a skill_runs with no engine column and runs kept in another shape)// keeps that table under another name, so these runs start from an empty table. Nothing is deleted.@@@ -1175,30 -1199,6 +1221,18 @@@ const ACCOUNT_CANVAS_TABLES = `CREATE T);CREATE INDEX IF NOT EXISTS account_canvases_account ON account_canvases(account_id, updated_at DESC);`;+/**- * Each press of a tool's Run an account made with hosted runs on (src/server/tool-presses.ts): by a key made from the- * account, the tool and the page's id for the press, with the answer it got once it started (`starting` while it is- * being started) and how many of its tries were refused after their hold was made. Kept a day. open_admissions: a run- * let in whose rows are still being made (a tool's start that awaits before it makes them), counted until they exist.++ * The runs let in whose rows are still being made (a tool's start that awaits before it makes them), counted until they++ * exist (pool-limits.ts openAdmission).+ */- const TOOL_PRESS_TABLES = `CREATE TABLE IF NOT EXISTS tool_presses (- account TEXT NOT NULL,- request_id TEXT NOT NULL,- answer_json TEXT,- tries INTEGER NOT NULL DEFAULT 0,- starting INTEGER NOT NULL DEFAULT 0,- at INTEGER NOT NULL,- PRIMARY KEY (account, request_id)- );- CREATE INDEX IF NOT EXISTS tool_presses_at ON tool_presses(at);- CREATE TABLE IF NOT EXISTS open_admissions (++const ADMISSION_TABLES = `CREATE TABLE IF NOT EXISTS open_admissions (+ key TEXT PRIMARY KEY,+ account TEXT NOT NULL,+ pool INTEGER NOT NULL DEFAULT 0,+ at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS open_admissions_account ON open_admissions(account, at);`;+export function db(): Database.Database {globalThis.__fuobeDb ??= open();return globalThis.__fuobeDb;diff --cc src/server/generations.tsindex 07157f9f,76019eaf..201c4941--- a/src/server/generations.ts+++ b/src/server/generations.ts@@@ -107,8 -105,10 +107,10 @@@ import { blockedForAccounts, discardBodimport { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";-import { placeInLine, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";+import { placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";- import { poolLane } from "./computer/pool";+ import { hostedRunsOn } from "./hosted-switch";+ import { poolLane, queueOfGeneration } from "./computer/pool";+ import { runPreviewAt } from "./computer/tasks";import { runCeilingMs } from "./queue-settings";import { sweepBilling } from "./billing-outbox";import { inDemoScope, outsideDemo } from "./demo-scope";@@@ -521,7 -539,8 +541,8 @@@ export const ASSET_FREE: Record<string"gpu_snapshots.report_json": "readiness built from that inventory","generations.external_meta_json": "the provider's job handles","billing_outbox.payload_json": "reports for the billing service: hold and run ids, counts and words, never a file",- "tool_presses.answer_json": "a copy of the answer one press of a tool's Run got, for a resend of it: its runs' own rows keep their files",+ "run_requests.ids_json": "the ids of the runs one press of Run made, never a file",- "run_requests.refusal_json": "the status, words and code a refused press of Run got, never a file",++ "run_requests.answer_json": "a copy of the answer one press of a tool's Run got, for a resend of it: its runs' own rows keep their files","reports_inbox.target_json": "what a report is about: a run, asset or share id, never a file","admin_tokens.scopes_json": "an admin token's scope names","admin_audit.detail_json": "small facts about an admin action: counts, ids and names, never a file's URL",@@@ -563,8 -582,7 +584,9 @@@"relay_tasks.refusal_json": "a ComfyUI refusal: node classes and model names","relay_tasks.needs_json": "what a job for the workers needs: workflow, model file names and sizes, node packs, VRAM","relay_tasks.tried_json": "the ids of the workers that lost or failed this job",+ "relay_tasks.ticket_json": "an account's job ticket for the workers: settings, and the names and SHA-256 of the job's own staged inputs",+ "relay_tasks.finish_json": "a finishing job's ticket for a worker's CPU slot: settings, and the names and SHA-256 of the job's own staged inputs",+ "relay_tasks.progress_json": "a job's live step, node name and place in its ComfyUI's queue (its preview picture is a file in the task's folder, never a Fuobe file)","relay_workers.facts_json": "what a worker said about its ComfyUI: its GPU, memory and version","relay_workers.inventory_json": "a worker's model files and node packs: names, sizes and hashes on that PC","relay_workers.lanes_json": "the lanes a worker can run: hashes of model file names",@@@ -3038,8 -3161,7 +3193,8 @@@ export async function cancelGeneration(// awaits, so it can't mark the job done in between.if ((JSON.parse(r.external_meta_json ?? "{}") as Record<string, unknown>).finishing) {stopModelFinish(id);+ stopWorkerFinish(id);- update(id, { status: "canceled", completed_at: Date.now(), message: null });+ markCanceled(id);return;}const model = getModel(r.model_id);@@@ -3060,8 -3182,8 +3215,9 @@@else if ("run" in own) await own.run(cancel);}stopModelFinish(id);+ stopWorkerFinish(id);- update(id, { status: "canceled", completed_at: Date.now(), message: null });+ // Saved meanwhile (here, or by another app process while the provider was asked to stop): it stays as it is.+ if (!markCanceled(id)) return;// Steps waiting only to feed this one are dropped too (nothing was spent on them).dropUnused(depIds(r.depends_on));}diff --cc src/server/hosted-run.tsindex 51ee3930,0708288f..511558a9--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@@ -24,25 -25,24 +24,27 @@@ importtype RunFacts,} from "./billing";import { getModel } from "@/lib/catalog";-import { PLACE_ASK_HEADER } from "@/lib/guest-access";-import { createGenerations, outputKind, plannedSteps, previewGeneration, type PlannedStep } from "./generations";+import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER } from "@/lib/guest-access";+import { db } from "./db";+import { AccountRunError, createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, stepsOf, type PlannedStep } from "./generations";import { loadIndex } from "./gpu/index-file";- import { poolLane } from "./computer/pool";- import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, outputsWords, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTicketsReady, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";+ import { attemptLimitMs, MAX_ATTEMPTS, poolLane } from "./computer/pool";+ import { holdTiming } from "./queue-settings";-import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRun, poolAway, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";++import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, outputsWords, poolAllows, poolAllowsRun, poolAway, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTicketsReady, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";import { withRunStamp } from "./run-stamp";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";+ import { queueRequestRelease } from "./billing-outbox";-import { notePressGaveUp, reserveRequestId } from "./run-requests";-import { db } from "./db";++import { reserveRequestId, type Press } from "./run-requests";import type { RunStamp } from "./run-stamp";import { readRef } from "./storage";-import { readSnapshot } from "./gpu/snapshots";import { ACCOUNT_LIMITS } from "./account-files";import { poolLimitRefusal } from "./pool-limits";import { runAsTenant } from "./tenant";+import { needsGpu, ownSetupHere, poolCardRefuses, requestOwnSetup } from "./pool-own-setup";- import { reserveRequestId } from "./tool-presses";+import { ADD_KEY_HEADER } from "@/lib/your-keys";++export { poolCardRefuses };/*** The generations route's side of hosted runs (hosted.ts), the billing hook (billing.ts) and the moderation hook@@@ -121,33 -95,15 +123,40 @@@ const OWN = { kind: "own" } as const/** What an account whose own GPU didn't answer is asked, when its run named no place (never moved and charged unasked). */export const OWN_GPU_QUIET = "Your GPU isn't answering right now. Run this on this studio's GPUs instead, or try again when your GPU is back.";+ /**+ * Run pressed while every GPU here that could run it is away (it was there when the price check before Run asked): no+ * run is made, and the answer promises no start. It is no billing refusal, so no card opens for it: the page says the+ * words and asks the price check again, which now says "Starting soon" with Run off until one of those GPUs is back.+ */+ const awayRefusal = (): Refusal => ({ status: 503, body: { error: BILLING_WAIT.run, code: "busy" }, headers: { "Retry-After": "15" } });+/** A run this install's GPUs won't take, refused in the words the price check before Run gives too. */-const notOffered = (error: string): PlaceDecision => ({ kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });+const notOffered = (error: string): { kind: "refuse"; refusal: Refusal } => ({ kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });++/**+ * A run that runs on the visitor's own setup only (own-setup.ts): refused in its label's words, with the setup itself so+ * the client opens it (Connect your GPU, or Add your key) instead of saying no.+ */+const ownSetupRefusal = (setup: OwnSetup): { kind: "refuse"; refusal: Refusal } => ({+ kind: "refuse",+ refusal: {+ status: 403,+ body: { error: ownSetupLabel(setup), code: setup.need === "key" ? "add-key" : "connect-gpu", ownSetup: setup, ...(setup.need === "key" && { provider: setup.provider }) },+ headers: setup.need === "key" ? { [ADD_KEY_HEADER]: setup.provider } : { [CONNECT_GPU_HEADER]: "1" },+ },+});++/** A gate's refusal as the run's answer: its words, with the own setup that would run it. */+function gateRefusal(gate: GateRefusal): { kind: "refuse"; refusal: Refusal } {+ if (gate.reason === "ownSetup") return ownSetupRefusal(gate.setup ?? needsGpu());+ const error = gateText(gate, false);+ // Not right now (the GPUs that could run it are being updated): refused as a busy moment, with Run off until then.+ if (gate.reason === "busy") return { kind: "refuse", refusal: billingRefusal("busy", error) };+ if (gate.reason === "model3d") return { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } };+ const r = notOffered(error);+ if (gate.setup) r.refusal.body.ownSetup = gate.setup;+ return r;+}const askPlace = (): Refusal => ({ status: 409, body: { error: OWN_GPU_QUIET, code: "own-gpu-offline" }, headers: { [PLACE_ASK_HEADER]: "1" } });@@@ -221,39 -168,16 +230,49 @@@ export function stepsProblem(p: Policyreturn null;}+/** How many outputs each row asks for (its request's numOutputs: a run split into one job per output keeps it on each). */+function rowOutputs(ids: string[]): number[] {+ const q = db().prepare("SELECT request_json FROM generations WHERE id = ?");+ return ids.map((id) => {+ const r = q.get(id) as { request_json: string } | undefined;+ try {+ const n = r ? Number((JSON.parse(r.request_json) as GenerationRequest).params?.numOutputs ?? 1) : 1;+ return Number.isFinite(n) ? n : 1;+ } catch {+ return 1;+ }+ });+}++/**+ * The rows a tool's run made on this install's GPUs, checked against what it was priced and held for, before anything+ * of it is sent: every step one the policy allows there (stepsProblem); a run held as light work (free, never counted)+ * that made light work only; no row asking for more outputs at once than a run there makes (poolOutputsCap); and no more+ * jobs of any model and operation than were priced. Null when they match; otherwise its refusal's words. A tool whose+ * start makes more than its plan said is stopped here, never run on a hold for less.+ */+export function madeRunProblem(run: { policy: Policy; steps: RunFacts["steps"]; light: boolean }, ids: string[]): string | null {+ const made = stepsOf(ids);+ const problem = stepsProblem(run.policy, made);+ if (problem) return problem;+ if (run.light) return lightRun(made) ? null : HOSTED_WORDS.notOffered;+ const cap = poolOutputsCap(run.policy);+ if (rowOutputs(ids).some((n) => n > cap)) return outputsWords(cap, false);+ const held = new Map((run.steps ?? []).map((s) => [`${s.model} ${s.op ?? ""}`, s.jobs]));+ for (const s of pricedSteps(made)) if (s.jobs > (held.get(`${s.model} ${s.op ?? ""}`) ?? 0)) return HOSTED_WORDS.notOffered;+ return null;+}++ /**+ * Are the workers that could run some GPU step of a run all away now (paused, silent, outside their hours): its own+ * model's, or a later step's of a chain? Then the run would wait for nothing at that step, so it isn't made. Light steps+ * (a join, a trim) are left out, as they cost nothing.+ */+ export function runAway(planned: Pick<Planned, "route">, steps: PlannedStep[] | null | undefined): boolean {+ if (poolAway(planned.route.endpoint)) return true;+ return (steps ?? []).some((s) => s.provider === "comfyui" && !freeStep(s) && poolAway(stepEndpoint(s)));+ }+/*** Is a run light work only: every step it makes a ComfyUI step that needs no model and no graphics memory (a filter, a* trim, a join, adding sound, a Ken Burns move)? Such a run is free and never counts against the policy's limits on runs@@@ -442,8 -345,13 +461,12 @@@ export async function decidePlace(accouconst gate = poolGate(p, planned, req, () => stepsFor(account, req));if (!gate.ok) {if (ownFallback) return OWN;- const error = gateWords(gate.reason, false);- return gate.reason === "model3d" ? { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } } : notOffered(error);+ return gateRefusal(gate);}+ // Every GPU here that could run it is off for now (paused, silent, outside its hours): a run made now would only wait+ // until its wait limit ended it. It goes to the account's own GPU as any run these GPUs can't take now, else it isn't+ // made (awayRefusal).+ if (runAway(planned, gate.steps)) return ownFallback ? OWN : { kind: "refuse", refusal: awayRefusal() };// Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.if (ownOffline) return { kind: "refuse", refusal: askPlace() };return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped, light: lightRun(gate.steps) };@@@ -514,9 -422,9 +537,10 @@@ export async function moderateRun/*** Set the run's price aside (no billing service: nothing to set aside; the run is free). Returns the stamp the run's- * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `pressId`: the press of- * Run it belongs to (a tool's scope and its page's id for the press), so every resend of that press asks for the same- * hold; none, a fresh request id.- * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `pressId`: the page's- * id for this press of Run (run-requests.ts), so every resend of it reserves under one request id; none (a script): an- * id of this request's own. A reserve given up after a try that may have made a hold releases it by its request id.++ * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `press`: the press of++ * Run it belongs to and its try (run-requests.ts), so every send of that try reserves under one request id, and a new try++ * under one of its own; none (a script): an id of this request's own. A reserve given up after a try that may have made a++ * hold releases it by its request id, unless a send of the same try owns that hold (`press.gaveUp`).*/export async function reservePool(account: Account,@@@ -525,20 -433,33 +549,34 @@@shown: { amount: number; priceVersion: string } | null,checkOutputs: boolean,steps?: RunFacts["steps"],-- pressId: string | null = null,++ press: Press | null = null,): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }) };if (!billingConfigured()) return { ok: true, stamp: base };const kind = outputKind(planned.op, planned.model);+ const run: RunFacts = { ...runOnPool(account.id, () => runFacts(req, planned, kind)), ...(steps?.length && { steps }) };- const requestId = pressId ? reserveRequestId(account.id, pressId) : nanoid(16);++ const requestId = press ? reserveRequestId(account.id, press.key, press.tries) : nanoid(16);const a = await reserve({- requestId: pressId ? reserveRequestId(account.id, pressId) : nanoid(16),+ requestId,account: accountFacts(account),- run: { ...runOnPool(account.id, () => runFacts(req, planned, kind)), ...(steps?.length && { steps }) },+ run,queue: queueFacts(account.id, planned.route.endpoint),shown: shown ?? { amount: 0, priceVersion: "" },+ // How long its hold must stay open once a worker first takes it: every attempt at its lanes' run ceilings, and the+ // time it may spend back in line (the queue's settings).+ timing: holdTiming(run.steps?.length ? run.steps : [{ lane: run.lane, jobs: run.jobs }], MAX_ATTEMPTS, attemptLimitMs),});if (!a) return { ok: true, stamp: base };if (!a.ok) {+ if (a.unsure) {- // A try may have made a hold the app never heard of: it goes back, and a resend of this press is refused at once.- // A resend of the press that got there first (it made the run, or was refused and gave its hold back) owns the- // press's one hold, so nothing is released by its request id. One statement decides, after any run it made.++ // A try may have made a hold the app never heard of: it goes back by its request id, and the press's next send is a++ // new try under a request id of its own. A send of the same try that got there first (it made the run, or was++ // refused and gave its hold back) owns that hold, so nothing is released by its request id. One statement decides,++ // after any run it made.+ db().transaction(() => {- if (!pressId || notePressGaveUp(account.id, pressId)) queueRequestRelease(requestId);++ if (!press || press.gaveUp()) queueRequestRelease(requestId);+ })();+ }return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }) }) };}forgetBalance(account.id);@@@ -565,19 -486,11 +603,22 @@@ export interface PoolLineetaSeconds: number | null;}+ /** A price check's answer while every GPU that could run it is off for now: Run is off, and the wait is said. */+ const startingSoonQuote = (): Quote => ({ allowed: false, amount: 0, priceVersion: "", text: HOSTED_WORDS.startingSoon, code: "busy", etaS: null });+/** A price check's answer for a run this install's GPUs won't take, in the words the run itself would get. */-const notOfferedQuote = (text: string): Quote => ({ allowed: false, amount: 0, priceVersion: "", text, code: "not-offered" });+/**+ * A price check refused for what this install's GPUs don't take: its words, and (`ownSetup`) the visitor's own setup+ * that runs it, so Run opens that setup (Connect your GPU, Add your key, or a guest's sign-up) instead of staying off.+ */+const notOfferedQuote = (text: string, setup?: OwnSetup): Quote & { ownSetup?: OwnSetup } => ({ allowed: false, amount: 0, priceVersion: "", text, code: "not-offered", ...(setup && { ownSetup: setup }) });++/**+ * A gate's refusal as the price check's quote (gateText: the label's words for an own setup). Busy (the GPUs that could+ * run it are being updated) is quoted as code "busy", shown like the other busy moments with Run off.+ */+const gateQuote = (gate: GateRefusal, guest: boolean): Quote & { ownSetup?: OwnSetup } =>+ gate.reason === "busy" ? { ...notOfferedQuote(gateText(gate, guest)), code: "busy" } : notOfferedQuote(gateText(gate, guest), gate.reason === "model3d" ? undefined : gate.setup);/*** A price check on this install's GPUs (hosted runs on): the plan there, the billing service's quote (no service: free,@@@ -622,7 -531,13 +663,13 @@@ export async function poolQuoteconst gate = poolGate(p, planned, req, () => stepsFor(account, req));if (!gate.ok) {if (hasGpu && wish !== "pool") return null;- return { planned, quote: notOfferedQuote(gateWords(gate.reason, !account)), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };+ return { planned, quote: gateQuote(gate, !account), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };+ }+ // Every GPU here that could run it is off for now: Run is off and says it starts soon (the price check asks again by+ // itself, and Run comes back on once one is back), never a run that would wait for nothing.+ if (runAway(planned, gate.steps)) {+ if (hasGpu && wish !== "pool") return null;+ return { planned, quote: startingSoonQuote(), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };}// Light work only (joins, trims): free, and never counted against the policy's limits, so the service isn't asked.if (lightRun(gate.steps)) {diff --cc src/server/hosted.tsindex 1db968e0,64e9e4b9..cd98643a--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@@ -84,25 -84,24 +84,37 @@@ export function poolTakes(endpoint: strreturn picks.length > 0 && picks.every((id) => workersCanRun(id));}+ /**+ * Are this install's GPUs all away for this endpoint now (on the workers: every worker that could run it paused, silent or+ * outside its hours)? Then a run waits for nothing: the price check says "Starting soon" (Run is off), and a press of+ * Run makes nothing. On this install's own ComfyUI: never.+ */+ export function poolAway(endpoint: string | undefined): boolean {+ if (!endpoint || !poolOnWorkers()) return false;+ if (!endpoint.includes("{")) return workersAway(endpoint);+ const picks = workflowPicks(endpoint);+ return picks.length > 0 && picks.every((id) => workersAway(id));+ }+/**- * The steps a run on this install's GPUs can carry out there: ComfyUI's. The price check, the run's admission and its- * submit read this one table, so a run is refused before Run when a step of it couldn't run there (a text step, a step- * made in the browser, a cloud model), never part way through.+ * Can this install's GPUs take this workflow's job tickets now (an account's run there goes as one): on the workers, one+ * built for this studio's catalog that may run it (a workflow that picks its graph at run time: every graph it may+ * pick). After an update of the studio, a worker built from the catalog before takes them once it is updated too:+ * meanwhile poolTakes still says the run could go there, and this says not yet. Not on the workers: yes.*/-const POOL_PROVIDERS: ReadonlySet<string> = new Set(["comfyui"]);+export function poolTicketsReady(endpoint: string | undefined): boolean {+ if (!endpoint || !poolOnWorkers()) return true;+ const picks = endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint];+ return picks.length > 0 && picks.every((id) => workersCanRun(id, { tickets: true }));+}++/**+ * The steps a run on this install's GPUs can carry out there: ComfyUI's, and a chain's text steps (a script, lyrics, a+ * translation), which the install's AI helper writes for free. The price check, the run's admission and its submit read+ * this one table, so a run is refused before Run when a step of it couldn't run there (a step made in the browser, a+ * cloud model), never part way through.+ */+const POOL_PROVIDERS: ReadonlySet<string> = new Set(["comfyui", "llm"]);export const poolRunsProvider = (provider: string): boolean => POOL_PROVIDERS.has(provider);/** May a run on this install's GPUs send them this kind of file (the workers take only the kinds the install allows)? */@@@ -137,7 -124,8 +149,9 @@@ export const HOSTED_WORDS =rtxCard: "This one needs an NVIDIA RTX card, and this studio's GPUs can't run it right now. Connect your own GPU in Settings, or pick another choice.",notHosted: "Runs on this studio's GPUs aren't open to this account. Connect your own GPU in Settings.",waitedTooLong: "This studio's GPUs were busy, so it didn't run. Not charged.",+ busy: "Busy right now. Try again in a little while.",+ /** Every GPU that could run it is off for now: Run opens again by itself once one is back. */+ startingSoon: "Starting soon",};/** The same refusals for a guest, who has no Settings to connect a GPU in yet. */diff --cc src/server/pool-limits.tsindex 995bbaf3,5c6d1ed7..bbb8660f--- a/src/server/pool-limits.ts+++ b/src/server/pool-limits.ts@@@ -203,20 -159,54 +203,57 @@@ export class AdmitRefused extends Erro}}++/** 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>(o: { accountId: string; pool: { policy: Pick<Policy, "limits">; addr: string | null } | null; now?: number }, make: () => T): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } {+ export function admitRun<T, P = never>(+ o: {+ accountId: string;+ pool: { policy: Pick<Policy, "limits">; addr: string | null } | null;+ now?: number;+ prior?: () => P | null;+ refused?: (why: AdmitRefused["refusal"] | Error) => void;+ },+ make: () => T,-): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } | { ok: false; prior: P } {++): 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 {- return d- .transaction((): { ok: true; value: T } | { ok: false; refusal: AdmitRefused["refusal"] } => {+ 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);- if (refusal) return { ok: false, refusal };- const value = make();+ 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);@@@ -228,4 -218,6 +265,6 @@@if (e instanceof AdmitRefused) return { ok: false, refusal: e.refusal };throw e;}+ if (failed) throw (failed as { e: unknown }).e;- return answer!;++ return answer! as Admitted<T, P>;}diff --cc src/server/providers/comfyui.tsindex fe03d934,fbd396c9..9889899d--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@@ -1690,12 -2863,11 +1690,14 @@@ export const comfyProvider: ProviderAdaprincipal: computer,generationId,graph: forPool ? withoutSaveMetadata(wf) : wf,+ ...(ticket && { ticket }),prefix: typeof meta.prefix === "string" ? meta.prefix : undefined,metaBatch,- preview: true,- // A run whose results are checked before anyone sees them sends no live previews from the workers.+ // On the workers, a run whose outputs the moderation service sees first shows no preview while it works (its+ // ComfyUI makes none). A person's own computer shows its own previews in its tab, as before.+ preview: !(forPool && runStamp()?.checkOutputs),++ // (The task keeps the stamp too: showsPreview never keeps a preview picture for such a run.)+ ...(forPool && runStamp()?.checkOutputs && { extra: { checkOutputs: true } }),workflowId: manifest.id,made: model?.kind,loras: (input.loras ?? []).map((l) => ({ file: l.file, ...(l.url && { url: l.url }) })),diff --cc src/server/run-requests.tsindex 00000000,598d21ad..f9701c8dmode 000000,100644..100644--- a/src/server/run-requests.ts+++ b/src/server/run-requests.ts@@@ -1,0 -1,93 +1,217 @@@+ import "server-only";+ import crypto from "node:crypto";+ import { db } from "./db";++ /**- * One press of Run, by the id the page sends with it (the same on every resend of that press). With hosted runs on, an- * account's press makes its run once: a resend (an answer lost on the way, a proxy that cut a slow request short) gets- * the run the first one made, and the external billing service sees one reserve request id for it, so it makes one hold.- * Without hosted runs, nothing is noted and a run is made as before.++ * One press of Run on this install's GPUs, by the id its page sends with it (the same on every resend of that press).++ * With hosted runs on, an account's press whose run goes there makes that run once: a resend (an answer lost on the way,++ * a proxy that cut a slow request short, a second server process during a deploy) gets the run the first send made, and++ * the external billing service sees one reserve request id for each try of the press, so it makes one hold for it.++ *++ * A try ends when its hold goes back before a run was made: refused after the hold was made (a limit, a step these GPUs++ * don't take, rows that couldn't be made), or its reserve got no answer in time (the hold the service may have made is++ * released by its request id). The press's next send is then a new try, under a request id of its own, so no run is++ * ever made against a hold that went back. A press refused before anything was set aside keeps its try: sent again, it++ * is checked again under the same request id.++ *++ * Only runs on this install's GPUs are noted. A run on an account's own GPU or with its own key notes nothing and is++ * made as before (a tool's press once per server process: shorts-schemas.ts once), and so is every run with hosted runs++ * off.+ */++ /** A press id as a page sends it. */+ const PRESS_ID = /^[A-Za-z0-9_-]{8,64}$/;++ /** The press id beside a run request (the body's `requestId`), or null. */+ export function readPressId(body: unknown): string | null {+ const v = (body as { requestId?: unknown } | null)?.requestId;+ return typeof v === "string" && PRESS_ID.test(v) ? v : null;+ }++ /** How long a press is remembered (a resend comes within a minute; a day is plenty). */+ export const PRESS_KEEP_MS = 24 * 3_600_000;+++/** A tool's press still starting after this long belongs to a process that stopped: a resend starts it itself. */++export const PRESS_STARTING_MS = 5 * 60_000;++++/** A tool's press key: its scope (the tool, and the project or item it runs on) and the page's id for the press. */++export const toolPressKey = (scope: string, clientId: string): string => `${scope}\n${clientId}`;+++ /**- * The reserve's request id for a press: made from the account and the page's id, so the same press always gives the- * same one and no other account's press can ever name it.++ * The reserve's request id for a try of a press: made from the account, the press's key (the page's id; a tool's scope++ * and the page's id) and the try, so every send of one try gives the same one, each try its own, and no other account's++ * press can ever name it.+ */-export const reserveRequestId = (accountId: string, pressId: string): string =>- `r_${crypto.createHash("sha256").update(`${accountId}\n${pressId}`).digest("hex").slice(0, 32)}`;++export const reserveRequestId = (accountId: string, key: string, tries = 0): string =>++ `r_${crypto.createHash("sha256").update(`${accountId}\n${key}${tries ? `\n${tries}` : ""}`).digest("hex").slice(0, 32)}`;+-/** A refusal a press got after its price was set aside, as the route answered it: a resend of the press gets it again. */-export interface PressRefusal {- status: number;- body: { error: string; code?: string; provider?: string };- headers: Record<string, string>;++/** A try of a press, as reservePool reserves for it (hosted-run.ts). */++export interface Press {++ /** The press's key: the page's id for it (a tool's: toolPressKey). */++ key: string;++ /** Its try: how many earlier tries of the press ended with their hold given back. */++ tries: number;++ /**++ * Its reserve got no answer in time: the try ends (true), and the hold the service may have made goes back by its++ * request id. False when a send of the same try made its run or ended the try first: then that hold is not this++ * send's to give back.++ */++ gaveUp: () => boolean;+ }+-/**- * What a press made already: its run's rows (the first ones, as the route answered them) and the hold they carry;- * "gave-up" when its reserve was given up (the billing service didn't answer in time and the press was refused);- * `refused` when it was refused after its hold was made (a limit, a step this install's GPUs don't take, rows that- * couldn't be made), so its hold went back; null when it is new.- */-export type PressSeen = { ids: string[]; hold: string | null } | "gave-up" | { refused: PressRefusal } | null;--export function pressSeen(accountId: string, pressId: string, now = Date.now()): PressSeen {- const r = db()- .prepare("SELECT ids_json, hold_id, gave_up, refusal_json FROM run_requests WHERE account = ? AND request_id = ? AND at > ?")- .get(accountId, pressId, now - PRESS_KEEP_MS) as { ids_json: string | null; hold_id: string | null; gave_up: number; refusal_json: string | null } | undefined;- if (!r) return null;- if (r.gave_up) return "gave-up";- if (r.refusal_json) {- try {- return { refused: JSON.parse(r.refusal_json) as PressRefusal };- } catch {- return "gave-up";- }- }++/** The press's row: by a key made from the account and the press's key, never the page's id as it was sent. */++const rowKey = (accountId: string, key: string) => reserveRequestId(accountId, key);++++interface PressRow {++ tries: number;++ starting: number;++ ids_json: string | null;++ hold_id: string | null;++ answer_json: string | null;++ at: number;++}++++function pressRow(accountId: string, key: string, now: number): PressRow | undefined {++ return db()++ .prepare("SELECT tries, starting, ids_json, hold_id, answer_json, at FROM run_requests WHERE account = ? AND request_id = ? AND at > ?")++ .get(accountId, rowKey(accountId, key), now - PRESS_KEEP_MS) as PressRow | undefined;++}++++/** Forget presses older than a day (a row past it is a new press). */++const prune = (now: number) => db().prepare("DELETE FROM run_requests WHERE at <= ?").run(now - PRESS_KEEP_MS);++++/** The try a send of this press is now (0 for a new press). */++export const pressTries = (accountId: string, key: string, now = Date.now()): number => pressRow(accountId, key, now)?.tries ?? 0;++++/** A try of a press for reservePool. */++export const pressTry = (accountId: string, key: string, tries: number): Press => ({ key, tries, gaveUp: () => endTry(accountId, key, tries) });++++/** What a studio press made: its run's rows (the first ones, as the route answered them) and the hold they carry. */++export type PressRun = { ids: string[]; hold: string | null };++++/** The run a press made already (any try), or null. */++export function pressRun(accountId: string, key: string, now = Date.now()): PressRun | null {++ const r = pressRow(accountId, key, now);++ if (!r?.ids_json) return null;+ let ids: string[] = [];+ try {- ids = JSON.parse(r.ids_json ?? "[]") as string[];++ ids = JSON.parse(r.ids_json) as string[];+ } catch {}+ return { ids, hold: r.hold_id };+ }+-/** Note the run a press made (inside the transaction that makes it), and forget presses older than a day. */-export function notePress(accountId: string, pressId: string, ids: string[], hold: string | null, now = Date.now()): void {++/**++ * What a send of a try finds just before it makes its run (inside the transaction that would make it): the run a send++ * of the press made already, "ended" when another send ended this try meanwhile (its hold is going back), or null.++ */++export function pressPrior(accountId: string, key: string, tries: number, now = Date.now()): PressRun | "ended" | null {++ const made = pressRun(accountId, key, now);++ if (made) return made;++ const r = pressRow(accountId, key, now);++ return r && r.tries !== tries ? "ended" : null;++}++++/** Note the run a try of a press made (inside the transaction that makes it). */++export function notePressRun(accountId: string, key: string, tries: number, ids: string[], hold: string | null, now = Date.now()): void {++ prune(now);++ db()++ .prepare(++ "INSERT INTO run_requests (account, request_id, tries, starting, ids_json, hold_id, answer_json, at) VALUES (?, ?, ?, 0, ?, ?, NULL, ?) ON CONFLICT (account, request_id) DO UPDATE SET tries = excluded.tries, starting = 0, ids_json = excluded.ids_json, hold_id = excluded.hold_id, at = excluded.at",++ )++ .run(accountId, rowKey(accountId, key), tries, JSON.stringify(ids), hold, now);++}++++/**++ * End a try of a press whose hold went back before a run was made (refused after the hold was made, or its reserve given++ * up): its next send is a new try. False when the try made its run (or answered), or had ended already.++ */++export function endTry(accountId: string, key: string, tries: number, now = Date.now()): boolean {+ const d = db();- d.prepare("DELETE FROM run_requests WHERE at < ?").run(now - PRESS_KEEP_MS);- d.prepare("INSERT OR REPLACE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, refusal_json, at) VALUES (?, ?, ?, ?, 0, NULL, ?)").run(accountId, pressId, JSON.stringify(ids), hold, now);++ return d++ .transaction((): boolean => {++ prune(now);++ const r = pressRow(accountId, key, now);++ if (r && (r.ids_json || r.answer_json || r.tries !== tries)) return false;++ // (A tool's press keeps its claim: the call that holds it answers or releases it.)++ d.prepare(++ "INSERT INTO run_requests (account, request_id, tries, starting, at) VALUES (?, ?, ?, 0, ?) ON CONFLICT (account, request_id) DO UPDATE SET tries = excluded.tries, at = excluded.at",++ ).run(accountId, rowKey(accountId, key), tries + 1, now);++ return true;++ })++ .immediate();++}++++/** What a tool's route answered: kept as its parts, so every resend gets its own copy. */++export interface PressAnswer {++ status: number;++ headers: [string, string][];++ text: string;+ }++ /**- * Note a press refused after its hold was made, with the answer it got (inside the transaction that refused it): its- * hold goes back, and a resend of the press gets the same answer instead of a run against that hold.++ * Where a tool's press stands: claimed by this call (`tries`: its try), being started by another call (`starting`), or++ * answered already (`done`).+ */-export function notePressRefused(accountId: string, pressId: string, hold: string | null, refusal: PressRefusal, now = Date.now()): void {- db()- .prepare("INSERT OR REPLACE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, refusal_json, at) VALUES (?, ?, NULL, ?, 0, ?, ?)")- .run(accountId, pressId, hold, JSON.stringify(refusal), now);++export type PressClaim = { kind: "claimed"; tries: number } | { kind: "starting" } | { kind: "done"; answer: PressAnswer };++++const answerOf = (r: PressRow | undefined): PressAnswer | null => {++ if (!r?.answer_json) return null;++ try {++ return JSON.parse(r.answer_json) as PressAnswer;++ } catch {++ // An answer that can't be read: started again, under the same try.++ return null;++ }++};++++/** A tool's press as a resend finds it before it is checked: answered, being started elsewhere, or neither (null). */++export function toolPressSeen(accountId: string, key: string, now = Date.now()): Exclude<PressClaim, { kind: "claimed" }> | null {++ const r = pressRow(accountId, key, now);++ const answer = answerOf(r);++ if (answer) return { kind: "done", answer };++ return r?.starting && now - r.at < PRESS_STARTING_MS ? { kind: "starting" } : null;+ }++ /**- * Note a press whose reserve was given up: a resend of it is refused at once (its hold, if the service made one, is- * being released by its request id), and a new press of Run starts afresh. False when a resend of the press got there- * first (it made its run, was refused or gave up too): then the press's hold, if any, is that resend's to keep or give- * back, and nothing may be released by its request id.++ * Claim a tool's press for this call, in one locked step, once its run is known to go to this install's GPUs: no two++ * calls (in any process) start the same press.+ */-export function notePressGaveUp(accountId: string, pressId: string, now = Date.now()): boolean {++export function claimPress(accountId: string, key: string, now = Date.now()): PressClaim {+ const d = db();- d.prepare("DELETE FROM run_requests WHERE account = ? AND request_id = ? AND at <= ?").run(accountId, pressId, now - PRESS_KEEP_MS);- return d.prepare("INSERT OR IGNORE INTO run_requests (account, request_id, ids_json, hold_id, gave_up, at) VALUES (?, ?, NULL, NULL, 1, ?)").run(accountId, pressId, now).changes > 0;++ const id = rowKey(accountId, key);++ return d++ .transaction((): PressClaim => {++ prune(now);++ const r = pressRow(accountId, key, now);++ if (!r) {++ d.prepare("INSERT INTO run_requests (account, request_id, tries, starting, at) VALUES (?, ?, 0, 1, ?)").run(accountId, id, now);++ return { kind: "claimed", tries: 0 };++ }++ const answer = answerOf(r);++ if (answer) return { kind: "done", answer };++ if (r.starting && now - r.at < PRESS_STARTING_MS) return { kind: "starting" };++ d.prepare("UPDATE run_requests SET answer_json = NULL, starting = 1, at = ? WHERE account = ? AND request_id = ?").run(now, accountId, id);++ return { kind: "claimed", tries: r.tries };++ })++ .immediate();++}++++/** A tool's press answered: every resend of it gets this answer from now on. */++export function answerPress(accountId: string, key: string, answer: PressAnswer, now = Date.now()): void {++ db().prepare("UPDATE run_requests SET answer_json = ?, starting = 0, at = ? WHERE account = ? AND request_id = ?").run(JSON.stringify(answer), now, accountId, rowKey(accountId, key));++}++++/**++ * A tool's press was refused: a resend checks it again. `held`: its hold had been made (and goes back), so the try ends++ * and the next send is a new try under its own request id.++ */++export function releasePress(accountId: string, key: string, tries: number, held: boolean, now = Date.now()): void {++ db()++ .prepare("UPDATE run_requests SET answer_json = NULL, starting = 0, tries = CASE WHEN ? AND tries = ? THEN tries + 1 ELSE tries END, at = ? WHERE account = ? AND request_id = ?")++ .run(held ? 1 : 0, tries, now, accountId, rowKey(accountId, key));++}++++/** A deleted account's presses go with it. */++export function forgetAccountPresses(accountId: string): void {++ db().prepare("DELETE FROM run_requests WHERE account = ?").run(accountId);+ }diff --cc tests/computer-security.test.tsindex 5ea7bb44,d8226986..8eb9ac59--- a/tests/computer-security.test.ts+++ b/tests/computer-security.test.ts@@@ -375,17 -375,17 +375,30 @@@ describe("reports", () =>expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(409);});+ it("a tab's progress report stays a few KB: a picture with it is refused and nothing is kept", async () => {+ waitingTask(`acct:${a}`);+ const c = await claimed("a");+ const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { ...body } });+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);+ const jpeg = Buffer.alloc(30 * 1024, 7);+ jpeg.set([0xff, 0xd8, 0xff]);+ expect((await report({ event: "running", value: 1, max: 4, preview: jpeg.toString("base64") })).status).toBe(413);- expect(tasks.taskPreview(c.id)).toBeNull();++ expect(tasks.taskById(c.id)?.preview_at).toBeNull();+ expect((await report({ event: "running", value: 2, max: 4 })).status).toBe(200);- expect(tasks.taskProgress(c.id)).toMatchObject({ value: 2, max: 4 });++ expect(tasks.taskProgress(tasks.taskById(c.id)!)).toMatchObject({ value: 2, max: 4 });++ });+++ it("from a person's own computer, a report over 64 KB counts against the lower limit a minute, as before", async () => {+ waitingTask(`acct:${a}`);+ const c = await claimed("a");+ const report = (body: Record<string, unknown>) => call("a", "POST", `/api/gpu/computer/tasks/${c.id}/report`, { headers: { "x-fuobe-lease": c.lease }, body: { ...body } });+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);+ // About 70 KB: under the bound a worker's report with its preview picture has, over a person's own computer's.+ const big = { event: "running", value: 1, max: 4, padding: "x".repeat(70 * 1024) };+ const statuses: number[] = [];+ for (let i = 0; i < 31; i++) statuses.push((await report(big)).status);+ expect(statuses.slice(0, 30).every((s) => s !== 429), JSON.stringify(statuses)).toBe(true);+ expect(statuses[30]).toBe(429);});it("a finished entry over 8 MB is refused", async () => {diff --cc tests/cpu-slot.test.tsindex 4b0b7d37,00000000..d13a0d34mode 100644,000000..100644--- a/tests/cpu-slot.test.ts+++ b/tests/cpu-slot.test.ts@@@ -1,862 -1,0 +1,874 @@@+/**+ * The CPU slot on the workers' line (src/server/computer/pool.ts) and the finishing jobs (src/server/computer/finish.ts,+ * src/lib/finish-ticket.ts): a worker may hold one GPU job and one CPU task at once, each claimed for its own slot; light+ * CPU work goes to a CPU slot when the worker has one, and to its GPU's slot as before when it hasn't; a finishing job+ * goes only to a CPU slot that runs its kind; the line counts each slot apart; another program on the GPU stops only+ * the GPU's job. Then the live previews a worker sends with its progress: a JPEG of at most 64 KB is kept, anything+ * else is dropped. Never a real ComfyUI, never a GPU.+ */+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";- import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { beforeAll, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-cpu-slot-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+globalThis.__fuobeTestDiskFree = 1e13;++const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const finish = await import("@/server/computer/finish");+const { onComputer } = await import("@/server/providers/comfyui");+const { allLanes } = await import("@/lib/lanes");+const { loadIndex } = await import("@/server/gpu/index-file");+const { finishProblem } = await import("@/lib/finish-ticket");+const { previewOf, PREVIEW_LIMITS } = await import("@/lib/relay");+const { previewForReport } = await import("@/lib/computer-runner");+const { exifOrientation, orientedImageSize } = await import("@/lib/image-size");+const { catalogVersion } = await import("@/server/computer/catalog-version");++const ROOT = path.resolve(__dirname, "..");+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+/** A workflow the requirements index marks as light CPU work, and one that uses the GPU. */+const CPU_WORKFLOW = "video-trim";+const GPU_WORKFLOW = "bg-remove-rmbg";++let routes: ComputerRoutes;+let accountId = "";+beforeAll(async () => {+ routes = await loadRoutes();+ setSetting("comfyWhere", "workers");+ auth.setPassword("install password");+ accountId = auth.createAccount("[email protected]", "long enough").id;+});+beforeEach(() => {+ resetRates();+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+});++type W = { id: string; token: string };+type TaskRow = import("@/server/computer/tasks").TaskRow;+const row = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as import("@/server/computer/workers").WorkerRow;++/** A worker the owner added and resumed, all day, allowed every lane, able to run every workflow. */+function addWorker(): W {+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);+ const lanes = allLanes(loadIndex(), sha);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });+ const workflows = (JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string }[] }).workflows.map((x) => x.id);+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);+ return w;+}++/** A worker's beat as the program sends it (built for this studio's catalog), with its CPU slot (null: none) and what each slot runs. */+const beat = (w: W, o: { cpuSlot?: { finishes: string[] } | null; local?: { paused: boolean; why: string | null }; running?: string[]; cpuRunning?: string[]; catalogVersion?: string | null; protocol?: number } = {}) =>+ pool.workerBeat(+ workerRow(w),+ pool.cleanBeat({+ device: `wkr-${w.id}`,+ protocol: o.protocol ?? 3,+ version: "1",+ catalogVersion: o.catalogVersion === undefined ? catalogVersion() : o.catalogVersion,+ local: { ...(o.local ?? { paused: false, why: null }), until: null },+ gpu: {},+ inventoryHash: null,+ running: (o.running ?? []).map((task) => ({ task })),+ stopped: [],+ ...(o.cpuSlot !== undefined && { cpuSlot: o.cpuSlot }),+ cpuRunning: (o.cpuRunning ?? []).map((task) => ({ task })),+ }),+ );+/** A slot's claim; `running`: the tasks the worker says it works on (any other it holds comes back to it). */+const claim = (w: W, slot: "gpu" | "cpu" = "gpu", running: string[] = []) => pool.workerClaim(workerRow(w), running, Date.now(), slot);++let gens = 0;+function generation(account: string | null, op = "edit") {+ const gid = `cpu-slot-gen-${++gens}`;+ const now = Date.now();+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-selftest-image', 'open', 'comfyui', ?, 'image', 'running', ?, '[]', ?, ?)")+ .run(gid, op, JSON.stringify(account ? { account, place: "pool" } : {}), now, now);+ return gid;+}++/** The owner's own job of this workflow on the workers (a whole graph, in the owner's class), each a second after the last in line. */+let ranks = 0;+function ownerTask(workflowId: string, o: { preview?: boolean; checkOutputs?: boolean } = {}) {+ const gid = generation(null);+ const graph = { "1": { class_type: "LoadImage", inputs: { image: "x.png" } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/cpu-slot" } } };+ const id = tasks.createTask({ principal: "owner", generationId: gid, graph, workflowId, ...(o.preview && { preview: true }), ...(o.checkOutputs && { extra: { checkOutputs: true } }), pool: pool.poolFields(workflowId, { class: "owner" }) }).id;+ db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(Date.now() - 3_600_000 + ++ranks * 1000, id);+ return id;+}++/** An account's run of this workflow on the workers. */+function accountTask(workflowId: string) {+ const gid = generation(accountId);+ const graph = { "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/cpu-slot" } } };+ return tasks.createTask({ principal: `acct:${accountId}`, generationId: gid, graph, workflowId, pool: pool.poolFields(workflowId, { account: accountId }) }).id;+}++/** An account's 3D finish, queued as the studio queues it after the run's GPU job. */+function modelFinish(glb = Buffer.from("glTF fake model bytes")) {+ const gid = generation(accountId, "image-to-3d");+ return finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: glb, contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });+}++describe("the CPU slot on the line", () => {+ it("light CPU work is marked for a CPU slot; a job that uses the GPU is not", () => {+ expect(pool.cpuWorkflow(CPU_WORKFLOW)).toBe(true);+ expect(pool.cpuWorkflow(GPU_WORKFLOW)).toBe(false);+ expect(row(ownerTask(CPU_WORKFLOW)).slot).toBe("cpu");+ expect(row(ownerTask(GPU_WORKFLOW)).slot).toBeNull();+ });++ it("a worker with a CPU slot holds one GPU job and one CPU task at once, each claimed for its own slot", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ const cpu = ownerTask(CPU_WORKFLOW);+ const gpu = ownerTask(GPU_WORKFLOW);+ // The GPU's slot leaves the CPU task (older in line) to the CPU slot.+ expect(claim(w)?.id).toBe(gpu);+ const c = claim(w, "cpu");+ expect(c?.id).toBe(cpu);+ expect(c?.slot).toBe("cpu");+ // Light CPU work has its lane's run limit in either slot, as on the GPU's.+ expect(c?.runLimitMs).toBe(pool.runLimitMs(null, row(cpu).lane));+ // One at a time in each slot.+ expect(claim(w, "gpu", [gpu])).toBeNull();+ expect(claim(w, "cpu", [cpu])).toBeNull();+ expect(row(gpu).device).toBe(`wkr-${w.id}`);+ expect(row(cpu).device).toBe(`wkr-${w.id}-cpu`);+ // Both stay alive by the worker's beats.+ beat(w, { cpuSlot: { finishes: [] }, running: [gpu], cpuRunning: [cpu] });+ expect(row(cpu).device_seen_at).toBeGreaterThan(0);+ });++ it("a worker with no CPU slot takes light CPU work in its GPU's slot, as before, and claims nothing for a CPU slot", () => {+ const w = addWorker();+ beat(w);+ const cpu = ownerTask(CPU_WORKFLOW);+ ownerTask(GPU_WORKFLOW);+ expect(claim(w, "cpu")).toBeNull();+ expect(claim(w)?.id).toBe(cpu);+ });++ it("a finishing job goes only to a CPU slot that runs its kind, and carries its ticket in place of a graph", () => {+ const plain = addWorker();+ beat(plain, { cpuSlot: { finishes: [] } });+ expect(finish.workersFinish("model3d")).toBe(false);+ const id = modelFinish();+ expect(claim(plain)).toBeNull();+ expect(claim(plain, "cpu")).toBeNull();+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d", "path", "something-else"] } });+ expect(JSON.parse(workerRow(w).cpu_slot_json!)).toEqual({ finishes: ["model3d", "path"] });+ expect(finish.workersFinish("model3d")).toBe(true);+ expect(claim(w)).toBeNull();+ const c = claim(w, "cpu")!;+ expect(c.id).toBe(id);+ expect(c.graph).toBeUndefined();+ expect(c.ticket).toBeUndefined();+ expect(c.finish).toMatchObject({ kind: "model3d", settings: { material: "auto", turntable: true }, inputs: [{ slot: "model" }] });+ expect(finishProblem(c.finish, { inputs: c.inputs })).toBeNull();+ });++ it("the line counts each slot apart: CPU tasks never stand ahead of a GPU job on a worker with a CPU slot", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ ownerTask(CPU_WORKFLOW);+ const cpu2 = ownerTask(CPU_WORKFLOW);+ const gpu = ownerTask(GPU_WORKFLOW);+ expect(pool.placeInLine(row(gpu)).place).toBe(1);+ expect(pool.placeInLine(row(cpu2)).place).toBe(2);+ // With no CPU slot, the same worker serves them all in one line, as before.+ beat(w, { cpuSlot: null });+ expect(pool.placeInLine(row(gpu)).place).toBe(3);+ });++ it("another program on the GPU stops only the GPU's job; the CPU slot's task goes on", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ const cpu = ownerTask(CPU_WORKFLOW);+ const gpu = ownerTask(GPU_WORKFLOW);+ claim(w);+ claim(w, "cpu");+ beat(w, { cpuSlot: { finishes: [] }, local: { paused: true, why: "gpu-busy:game.exe" }, running: [gpu], cpuRunning: [cpu] });+ expect(row(gpu).state).toBe("waiting");+ expect(row(cpu).state).toBe("sending");+ // A stop-now by hand stops both.+ beat(w, { cpuSlot: { finishes: [] }, local: { paused: true, why: "here-now" }, cpuRunning: [cpu] });+ expect(row(cpu).state).toBe("waiting");+ });++ it("people's tasks a worker may claim now count only its GPU's work", () => {+ const w = addWorker();+ accountTask(CPU_WORKFLOW);+ beat(w);+ expect(pool.claimableNow(workerRow(w))).toBe(1);+ beat(w, { cpuSlot: { finishes: [] } });+ expect(pool.claimableNow(workerRow(w))).toBe(0);+ });+});++describe("finishing jobs", () => {+ it("a finish ticket is checked the same way on both sides", () => {+ const name = "fuobe_abcdefgh1234.png";+ const good = { v: 1, kind: "path", settings: { keys: [{ t: 0, azimuth: 0, elevation: 0, distance: 1 }, { t: 1, azimuth: 30, elevation: 5, distance: 0.8, truck: 0.1 }], frames: 81, fps: 16 }, inputs: [{ slot: "photo", name, sha256: "a".repeat(64) }, { slot: "depth", name: "fuobe_abcdefgh5678.png", sha256: "b".repeat(64) }] };+ expect(finishProblem(good)).toBeNull();+ expect(finishProblem({ ...good, inputs: [...good.inputs].reverse() })).not.toBeNull();+ expect(finishProblem({ ...good, settings: { ...good.settings, frames: 100_000 } })).not.toBeNull();+ expect(finishProblem({ ...good, settings: { ...good.settings, keys: [{ t: 0, azimuth: 0, elevation: 0, distance: 1, path: "../x" }] } })).not.toBeNull();+ expect(finishProblem({ ...good, inputs: [{ ...good.inputs[0], name: "../../secret.png" }, good.inputs[1]] })).not.toBeNull();+ expect(finishProblem({ ...good, extra: 1 })).not.toBeNull();+ // Its inputs must be the files the job sends.+ expect(finishProblem(good, { inputs: [{ name, sha256: "a".repeat(64) }] })).not.toBeNull();+ expect(finishProblem({ v: 1, kind: "model3d", settings: { material: "chrome", turntable: true }, inputs: [{ slot: "model", name, sha256: "a".repeat(64) }] })).not.toBeNull();+ });++ it("a path's keys go in the ticket as the path render reads them, each inside its range", () => {+ const keys = finish.pathKeys([+ { t: 1, azimuth: 99_999, elevation: 200, distance: 50, truck: 500 },+ { t: 0.5, azimuth: 30, elevation: 5, distance: 0.01 },+ ]);+ expect(keys[0]).toEqual({ t: 0, azimuth: 0, elevation: 0, distance: 1 });+ expect(keys.map((k) => k.t)).toEqual([0, 0.5, 1]);+ expect(keys[2]).toEqual({ t: 1, azimuth: 3600, elevation: 90, distance: 4, truck: 20 });+ const name = "fuobe_abcdefgh1234.png";+ const ticket = { v: 1, kind: "path", settings: { keys, frames: 81, fps: 16 }, inputs: [{ slot: "photo", name, sha256: "a".repeat(64) }, { slot: "depth", name, sha256: "b".repeat(64) }] };+ expect(finishProblem(ticket)).toBeNull();+ });++ it("only the files its kind makes are asked for, each within its limit", () => {+ const id = modelFinish();+ const t = row(id);+ const entry = {+ status: { status_str: "success" },+ outputs: {+ finish: {+ results: [+ { filename: "web.glb", subfolder: "", type: "output", role: "web" },+ { filename: "turntable.mp4", subfolder: "", type: "output", role: "turntable" },+ { filename: "secret.txt", subfolder: "", type: "output", role: "notes" },+ { filename: "../x.glb", subfolder: "", type: "output", role: "poster" },+ { filename: "again.glb", subfolder: "", type: "output", role: "web" },+ ],+ stats: [{ material: "matte", triangles: 1200, bytesIn: 900, bytesOut: 300 }],+ },+ },+ };+ const plan = onComputer(t.principal, () => finish.planFinish(t, [entry]));+ expect("wanted" in plan && plan.wanted.map((w) => [w.filename, w.kind])).toEqual([+ ["web.glb", "model3d"],+ ["turntable.mp4", "video"],+ ]);+ expect("outputs" in plan && plan.outputs[0]).toMatchObject({ files: [{ role: "web", n: 0 }, { role: "turntable", n: 1 }], stats: { material: "matte", triangles: 1200 } });+ expect(onComputer(t.principal, () => finish.planFinish(t, [{ status: { status_str: "success" }, outputs: {} }]))).toHaveProperty("error");+ });+});++describe("live previews from a worker", () => {+ const jpeg = (bytes: number) => {+ const b = Buffer.alloc(bytes, 7);+ b[0] = 0xff;+ b[1] = 0xd8;+ b[2] = 0xff;+ return b;+ };++ it("a worker sends a JPEG of at most 64 KB, at most one every 2 s", async () => {+ const small = new Blob([jpeg(20_000)], { type: "image/jpeg" });+ expect(await previewForReport(small, -Infinity, 10_000)).toBe(jpeg(20_000).toString("base64"));+ expect(await previewForReport(small, 9_000, 10_000)).toBeUndefined();+ expect(await previewForReport(new Blob([jpeg(PREVIEW_LIMITS.maxBytes + 1)], { type: "image/jpeg" }), -Infinity, 10_000)).toBeUndefined();+ expect(await previewForReport(new Blob([Buffer.from("89504e470d0a1a0a", "hex")], { type: "image/png" }), -Infinity, 10_000)).toBeUndefined();+ });++ it("the studio keeps a preview up to 64 KB and drops a larger one, keeping the progress", async () => {++ // A preview picture shows only with hosted runs on (without them, a run shows what it showed before).++ process.env.FUOBE_HOSTED_RUNS = "1";++ onTestFinished(() => {++ delete process.env.FUOBE_HOSTED_RUNS;++ });+ expect(previewOf(jpeg(PREVIEW_LIMITS.maxBytes).toString("base64"))).toBeDefined();+ expect(previewOf(jpeg(PREVIEW_LIMITS.maxBytes + 1).toString("base64"))).toBeUndefined();+ expect(previewOf(Buffer.from("89504e470d0a1a0a", "hex").toString("base64"))).toBeUndefined();+ expect(previewOf("not base64!")).toBeUndefined();+ // Through the report route, as a worker sends it.+ const w = addWorker();+ beat(w);+ const id = ownerTask(GPU_WORKFLOW, { preview: true });+ const c = claim(w)!;+ expect(c.reportPreview).toBe(true);+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });+ const report = (body: Record<string, unknown>) => api(`/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { "Content-Type": "application/json", "X-Fuobe-Lease": c.lease }, body: JSON.stringify(body) });+ expect((await report({ event: "sent", promptId: c.promptId })).status).toBe(200);+ // Just over 64 KB: the report is kept, its preview dropped.+ const big = jpeg(PREVIEW_LIMITS.maxBytes + 1024).toString("base64");+ expect((await report({ event: "running", value: 2, max: 8, preview: big })).status).toBe(200);- expect(tasks.taskProgress(id)).toMatchObject({ value: 2, max: 8 });- expect(tasks.taskPreview(id)).toBeNull();++ expect(tasks.taskProgress(tasks.taskById(id)!)).toMatchObject({ value: 2, max: 8 });++ expect(keptPreview(id)).toBeNull();+ const ok = jpeg(30 * 1024);+ expect((await report({ event: "running", value: 3, max: 8, preview: ok.toString("base64") })).status).toBe(200);- expect(tasks.taskPreview(id)?.jpeg.equals(ok)).toBe(true);- expect(tasks.taskProgress(id)).toMatchObject({ value: 3, max: 8 });++ expect(keptPreview(id)?.equals(ok)).toBe(true);++ expect(tasks.taskProgress(tasks.taskById(id)!)).toMatchObject({ value: 3, max: 8 });+ // A beat never brings a preview.+ beat(w, { running: [id] });- expect(tasks.taskPreview(id)?.jpeg.equals(ok)).toBe(true);++ expect(keptPreview(id)?.equals(ok)).toBe(true);+ // A progress report with no preview stays a few KB; one with a preview, under about 91 KB in all (a 64 KB JPEG as+ // base64 and a few KB more).+ expect((await report({ event: "running", value: 4, max: 8, node: "x".repeat(20 * 1024) })).status).toBe(413);+ expect((await report({ event: "running", value: 5, max: 8, preview: jpeg(70 * 1024).toString("base64") })).status).toBe(413);+ expect((await report({ event: "running", value: 5, max: 8, preview: ok.toString("base64"), node: "x".repeat(8 * 1024) })).status).toBe(200);+ expect((await report({ event: "running", value: 6, max: 8, preview: jpeg(PREVIEW_LIMITS.maxBytes).toString("base64"), node: "x".repeat(8 * 1024) })).status).toBe(413);+ });+});+++/** A run's preview picture as the studio keeps it (a file in its task's folder), or null. */++function keptPreview(id: string): Buffer | null {++ const t = tasks.taskById(id);++ const p = t?.preview_at ? tasks.runPreview(t.generation_id) : null;++ return p ? fs.readFileSync(p.path) : null;++}+++describe("which runs show live previews", () => {+ it("a run whose results are checked first, a finishing job and a run with no previews never ask the worker for one", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ const checked = ownerTask(GPU_WORKFLOW, { preview: true, checkOutputs: true });+ const first = claim(w)!;+ expect(first.id).toBe(checked);+ expect(first.reportPreview).toBeUndefined();+ expect(tasks.showsPreview(row(checked))).toBe(false);+ tasks.endTask(checked, "canceled");+ const plain = ownerTask(GPU_WORKFLOW);+ expect(claim(w)?.reportPreview).toBeUndefined();+ tasks.endTask(plain, "canceled");+ const fin = modelFinish();+ const c = claim(w, "cpu")!;+ expect(c.id).toBe(fin);+ expect(c.reportPreview).toBeUndefined();+ });+});++describe("pictures as they show", () => {+ it("a JPEG stored on its side is sized upright, as the worker makes it again", async () => {+ const sharp = (await import("sharp")).default;+ const sideways = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#3c3" } })+ .jpeg()+ .withMetadata({ orientation: 6 })+ .withExif({ IFD0: { Artist: "someone" } })+ .toBuffer();+ expect(exifOrientation(sideways)).toBe(6);+ expect(orientedImageSize(sideways)).toEqual({ width: 20, height: 40 });+ const plain = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#3c3" } }).jpeg().toBuffer();+ expect(exifOrientation(plain)).toBeNull();+ expect(orientedImageSize(plain)).toEqual({ width: 40, height: 20 });+ });+});++// ---------------------------------------------------------------------------+// Each slot's own line, its limits and its claims++/** A finishing job made straight in the line (no files), ahead of everything made after it. */+function bareFinish(rankAt: number) {+ const gid = generation(accountId, "image-to-3d");+ return tasks.createTask({+ principal: `acct:${accountId}`,+ generationId: gid,+ graph: {},+ finish: { v: 1, kind: "model3d", settings: { material: "auto", turntable: false }, inputs: [] },+ workflowId: "finish-model3d",+ pool: { pools: ["pool"], account: accountId, class: "free", rankAt, lane: "small", needs: { workflowId: "finish-model3d", files: [], packs: [], minVramBytes: 0 }, slot: "cpu" },+ }).id;+}++describe("each slot's own line", () => {+ it("a long line of CPU work ahead never hides a GPU job from a worker's GPU slot, nor from the count of people's jobs it may take", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ // More light CPU tasks than a slot looks at, every one ahead of the GPU job in line.+ for (let i = 0; i < 205; i++) accountTask(CPU_WORKFLOW);+ const gpu = accountTask(GPU_WORKFLOW);+ expect(pool.claimableNow(workerRow(w))).toBe(1);+ expect(claim(w)?.id).toBe(gpu);+ for (const t of db().prepare("SELECT id FROM relay_tasks WHERE state = 'waiting'").all() as { id: string }[]) tasks.endTask(t.id, "canceled");+ // A worker with no CPU slot: as many finishing jobs ahead, which only a CPU slot takes.+ const plain = addWorker();+ beat(plain);+ for (let i = 0; i < 205; i++) bareFinish(Date.now() - 3_600_000 + i);+ const next = accountTask(GPU_WORKFLOW);+ expect(pool.claimableNow(workerRow(plain))).toBe(1);+ expect(claim(plain)?.id).toBe(next);+ });++ it("light CPU work has its lane's run limits in a CPU slot too, and a finishing job its lane's run ceiling, which the owner sets", async () => {+ const { saveQueueSettings, QUEUE_DEFAULTS } = await import("@/server/queue-settings");+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ const fin = modelFinish();+ expect(claim(w, "cpu")).toMatchObject({ id: fin, runLimitMs: 2700 * 1000 });+ tasks.endTask(fin, "canceled");+ saveQueueSettings({ ...QUEUE_DEFAULTS, runCeilingS: { default: 2700, lanes: { small: 3600 } } });+ try {+ const later = modelFinish();+ expect(claim(w, "cpu")).toMatchObject({ id: later, runLimitMs: 3600 * 1000 });+ tasks.endTask(later, "canceled");+ // Light CPU work given back once for running past its limit gets its lane's whole ceiling next, as on the GPU's slot.+ const cpu = ownerTask(CPU_WORKFLOW);+ expect(claim(w, "cpu")?.id).toBe(cpu);+ tasks.report(row(cpu), { event: "give-back", why: "run-limit" }, () => ({ error: "unused" }));+ expect(claim(w, "cpu")).toMatchObject({ id: cpu, runLimitMs: pool.runLimitMs(null, row(cpu).lane) });+ } finally {+ saveQueueSettings(QUEUE_DEFAULTS);+ }+ });++ it("each slot of a worker claims on its own count: two idle slots asking once a second are never turned away", async () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: [] } });+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });+ const ask = (slot?: "cpu") => api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "worker", running: [], ...(slot && { slot }) }) });+ for (let i = 0; i < 60; i++) {+ expect((await ask()).status).toBe(204);+ expect((await ask("cpu")).status).toBe(204);+ }+ // Each slot's own limit still holds.+ expect((await ask()).status).toBe(429);+ expect((await ask("cpu")).status).toBe(429);+ });++ it("after a claim that found nothing, a worker's slot asks again only a few seconds on, sooner while a person's job waits for it", async () => {+ const { claimDue, CLAIM_GAP_MS, IDLE_CLAIM_MS } = await import("../bin/lib/worker/run.mjs");+ expect(IDLE_CLAIM_MS).toBeGreaterThanOrEqual(2000);+ // Before any claim, and after a job: at once.+ expect(claimDue(1000, -Infinity)).toBe(true);+ const missed = 1000;+ expect(claimDue(missed + IDLE_CLAIM_MS - 1, missed)).toBe(false);+ expect(claimDue(missed + IDLE_CLAIM_MS, missed)).toBe(true);+ // A person's job waits: sooner, yet never once a second while the beat keeps saying so.+ expect(CLAIM_GAP_MS).toBeGreaterThan(1000);+ expect(claimDue(missed + 1000, missed, 1)).toBe(false);+ expect(claimDue(missed + CLAIM_GAP_MS, missed, 1)).toBe(true);+ // A loop that ticks every second, with two idle slots and a beat that always says a job waits: well under the+ // studio's 60 claims a minute for each slot.+ let gpu = -Infinity;+ let cpu = -Infinity;+ const claims = { gpu: 0, cpu: 0 };+ for (let t = 0; t < 60_000; t += 1000) {+ if (claimDue(t, gpu, 1)) {+ claims.gpu++;+ gpu = t;+ }+ if (claimDue(t, cpu)) {+ claims.cpu++;+ cpu = t;+ }+ }+ expect(claims.gpu).toBeLessThanOrEqual(40);+ expect(claims.cpu).toBeLessThanOrEqual(20);+ });+});++// ---------------------------------------------------------------------------+// Finishing jobs: once, with their run, and for no longer than its wait++/** A small PNG (1 by 1, whole and well formed). */+const smallPng = (): Buffer =>+ Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8ffffff7f0009fb03fd2a86e38a0000000049454e44ae426082", "hex");++/** An account's camera path step, queued as the studio queues it (its photo and depth staged as the account's). */+function pathFinish(photo = smallPng()) {+ const gid = generation(accountId, "image-to-video");+ const keys = finish.pathKeys([+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ]);+ const id = finish.queueFinish({+ kind: "path",+ generationId: gid,+ account: accountId,+ step: 0,+ inputs: [+ { slot: "photo", data: photo, contentType: photo[0] === 0xff ? "image/jpeg" : "image/png", name: "photo" },+ { slot: "depth", data: smallPng(), contentType: "image/png", name: "depth.png" },+ ],+ settings: { keys, frames: 9, fps: 16 },+ });+ return { id, gid };+}++describe("finishing jobs and their run", () => {+ it("are queued once for a run (and step), however often they are asked", () => {+ const gid = generation(accountId, "image-to-3d");+ const queue = () => finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: Buffer.from("glTF fake model bytes"), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });+ const a = queue();+ expect(queue()).toBe(a);+ expect(db().prepare("SELECT COUNT(*) FROM relay_tasks WHERE generation_id = ?").pluck().get(gid)).toBe(1);+ // One that was stopped makes room for another.+ tasks.endTask(a, "canceled");+ expect(queue()).not.toBe(a);+ });++ it("a canceled run's finish and a deleted run's camera path end at once, with their files, and no CPU slot gets them", async () => {+ const generations = await import("@/server/generations");+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d", "path"] } });+ // A 3D finish waiting in line; its run is canceled.+ const fin = modelFinish();+ const gid = row(fin).generation_id;+ db().prepare("UPDATE generations SET external_meta_json = ? WHERE id = ?").run(JSON.stringify({ finishing: true }), gid);+ expect(tasks.inputsOf(fin)).toHaveLength(1);+ await generations.cancelGeneration(gid);+ expect(row(fin).state).toBe("canceled");+ expect(tasks.inputsOf(fin)).toHaveLength(0);+ expect(claim(w, "cpu")).toBeNull();+ // A camera path a CPU slot already runs; its run is deleted. The CPU slot hears the stop in its next report.+ const path = pathFinish();+ const c = claim(w, "cpu")!;+ expect(c.id).toBe(path.id);+ tasks.report(row(path.id), { event: "sent", promptId: c.promptId }, () => ({ error: "unused" }));+ generations.deleteGeneration(path.gid);+ expect(row(path.id).state).toBe("canceled");+ expect(tasks.inputsOf(path.id)).toHaveLength(0);+ expect(tasks.report(row(path.id), { event: "running", value: 5, max: 100 }, () => ({ error: "unused" }))).toMatchObject({ stop: true });+ expect(claim(w, "cpu", [path.id])).toBeNull();+ });++ it("wait for a CPU slot as long as their run may wait in line; a 3D model whose finish never came keeps its raw GLB", async () => {+ const { saveFile } = await import("@/server/storage");+ // Its run's own wait, else this install's.+ const fin = modelFinish();+ expect(row(fin).not_after).toBeGreaterThan(Date.now() + pool.poolWaitMs() - 60_000);+ const gid = generation(accountId, "image-to-3d");+ db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify({ account: accountId, place: "pool", waitMs: 120_000 }), gid);+ const raw = saveFile({ data: Buffer.from("glTF raw model"), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ let finished: import("@/lib/catalog/types").OutputFile[] | null = null;+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });+ const t = finish.finishTask(gid, "model3d")!;+ expect(t.not_after).toBeGreaterThan(Date.now() + 60_000);+ expect(t.not_after).toBeLessThanOrEqual(Date.now() + 120_000);+ // While it waits, the run's place in line is the finish's.+ expect(pool.queueOfGeneration(gid)?.place).toBeGreaterThanOrEqual(1);+ // No CPU slot took it in time: it ends, and the run keeps its model as it is.+ db().prepare("UPDATE relay_tasks SET not_after = ? WHERE id = ?").run(Date.now() - 1, t.id);+ pool.sweepPool();+ expect(row(t.id).state).toBe("failed");+ const deadline = Date.now() + 10_000;+ while (!finished && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));+ const kept = finished as unknown as import("@/lib/catalog/types").OutputFile[];+ expect(kept[0]).toMatchObject({ assetId: raw.id, meta: { finish: { error: expect.stringContaining("kept as it is") } } });+ finish.stopWorkerFinish(gid);+ });++ it("count only a CPU slot heard from lately, on a worker built for this studio's catalog", () => {+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] }, catalogVersion: "e".repeat(64) });+ expect(finish.workersFinish("model3d")).toBe(false);+ beat(w, { cpuSlot: { finishes: ["model3d"] }, protocol: 2 });+ expect(finish.workersFinish("model3d")).toBe(false);+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ expect(finish.workersFinish("model3d")).toBe(true);+ expect(finish.workersFinish("path")).toBe(false);+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 11 * 60_000, w.id);+ expect(finish.workersFinish("model3d")).toBe(false);+ });+});++describe("CPU work is never metered as GPU time", () => {+ it("a 3D run's settle carries its GPU job's time only, never its finish's, and a lane's typical run leaves finishes out", async () => {+ const { queueReports } = await import("@/server/billing-outbox");+ const w = addWorker();+ beat(w, { cpuSlot: { finishes: ["model3d"] } });+ const gid = generation(accountId, "image-to-3d");+ const graph = { "9": { class_type: "SaveImage", inputs: { filename_prefix: "fuobe/cpu-slot" } } };+ const gpu = tasks.createTask({ principal: `acct:${accountId}`, generationId: gid, graph, workflowId: GPU_WORKFLOW, pool: pool.poolFields(GPU_WORKFLOW, { account: accountId }) }).id;+ const done = () => ({ wanted: [], outputs: [], budget: 0 });+ const g = claim(w)!;+ expect(g.id).toBe(gpu);+ tasks.report(row(gpu), { event: "sent", promptId: g.promptId }, done);+ tasks.report(row(gpu), { event: "finished", entry: { status: { status_str: "success" }, outputs: {} }, execMs: 1000, device: "Test GPU" }, done);+ const fin = finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: Buffer.from("glTF fake model bytes"), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: true } });+ const c = claim(w, "cpu")!;+ expect(c.id).toBe(fin);+ tasks.report(row(fin), { event: "sent", promptId: c.promptId }, done);+ tasks.report(row(fin), { event: "finished", entry: { status: { status_str: "success" }, outputs: {} }, execMs: 30_000, device: "cpu" }, done);+ expect(row(fin).state).toBe("done");+ expect(db().prepare("SELECT exec_ms, device FROM worker_jobs WHERE task_id = ? AND event = 'finished'").get(fin)).toEqual({ exec_ms: null, device: null });+ const now = Date.now();+ db().prepare("UPDATE generations SET status = 'succeeded', completed_at = ?, request_json = ? WHERE id = ?").run(now, JSON.stringify({ account: accountId, place: "pool", hold: `hold-${gid}` }), gid);+ queueReports(now);+ const report = JSON.parse(db().prepare("SELECT payload_json FROM billing_outbox WHERE key = ?").pluck().get(gid) as string) as { gpuMs: number; device: string };+ expect(report).toMatchObject({ gpuMs: 1000, device: "Test GPU" });+ expect(pool.typicalPoolMs("small")).not.toBe(30_000);+ });+});++// ---------------------------------------------------------------------------+// Pictures sent to the workers++describe("an account's pictures leave for a worker without what they carry besides their pixels", () => {+ /** A PNG with a text chunk (after its header). */+ async function pngWithText(text: string) {+ const zlib = await import("node:zlib");+ const sharp = (await import("sharp")).default;+ const png = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).png().toBuffer();+ const data = Buffer.from(`Comment\0${text}`, "latin1");+ const chunk = Buffer.alloc(12 + data.length);+ chunk.writeUInt32BE(data.length, 0);+ chunk.write("tEXt", 4, "latin1");+ data.copy(chunk, 8);+ chunk.writeUInt32BE(zlib.crc32(Buffer.concat([Buffer.from("tEXt", "latin1"), data])), 8 + data.length);+ return Buffer.concat([png.subarray(0, 33), chunk, png.subarray(33)]);+ }++ it("a JPEG keeps only its orientation, a PNG loses its text and a WebP its EXIF, each still the same picture", async () => {+ const { pictureWithoutMetadata } = await import("@/server/media-clean");+ const sharp = (await import("sharp")).default;+ const jpeg = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#c33" } })+ .jpeg()+ .withMetadata({ orientation: 6 })+ .withExif({ IFD0: { Artist: "someone private", Copyright: "a home address" } })+ .toBuffer();+ const clean = pictureWithoutMetadata(jpeg, "image/jpeg")!;+ expect(clean.length).toBe(jpeg.length);+ expect(clean.includes(Buffer.from("someone private"))).toBe(false);+ expect(clean.includes(Buffer.from("a home address"))).toBe(false);+ expect(exifOrientation(clean)).toBe(6);+ expect(orientedImageSize(clean)).toEqual({ width: 20, height: 40 });+ const meta = await sharp(clean).metadata();+ expect(meta.orientation).toBe(6);+ expect([meta.width, meta.height]).toEqual([40, 20]);+ // Upright already: nothing of its EXIF stays.+ const upright = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#c33" } }).jpeg().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();+ const plain = pictureWithoutMetadata(upright, "image/jpeg")!;+ expect(plain.includes(Buffer.from("someone private"))).toBe(false);+ expect((await sharp(plain).metadata()).exif).toBeUndefined();+ const png = await pngWithText("a private note");+ expect((await sharp(png).metadata()).width).toBe(8);+ const cleanPng = pictureWithoutMetadata(png, "image/png")!;+ expect(cleanPng.includes(Buffer.from("a private note"))).toBe(false);+ expect((await sharp(cleanPng).metadata()).width).toBe(8);+ const webp = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#123" } }).webp().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();+ const cleanWebp = pictureWithoutMetadata(webp, "image/webp")!;+ expect(cleanWebp.includes(Buffer.from("someone private"))).toBe(false);+ expect((await sharp(cleanWebp).metadata()).width).toBe(8);+ // Not a picture it can read where such things live: refused.+ expect(pictureWithoutMetadata(Buffer.from([0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0x00]), "image/jpeg")).toBeNull();+ });++ it("an account's run on the workers stages its picture that way, sized as it shows; its own GPU gets it as it came, sized by its pixels", async () => {+ const { comfyProvider, mediaInfoFor } = await import("@/server/providers/comfyui");+ const hosted = await import("@/server/hosted");+ const sharp = (await import("sharp")).default;+ const sideways = await sharp({ create: { width: 40, height: 20, channels: 3, background: "#3c3" } })+ .jpeg()+ .withMetadata({ orientation: 6 })+ .withExif({ IFD0: { Artist: "someone private" } })+ .toBuffer();+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const pooled = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(sideways, "image/jpeg", "me.jpg", route))!;+ return { name, info: mediaInfoFor(name) };+ });+ const staged = fs.readFileSync(path.join(dir, "relay", "in", pooled.name));+ expect(staged.length).toBe(sideways.length);+ expect(staged.includes(Buffer.from("someone private"))).toBe(false);+ expect(exifOrientation(staged)).toBe(6);+ expect(pooled.info).toMatchObject({ width: 20, height: 40 });+ // The account's own GPU gets the file as it came, sized by its pixels, as before.+ const own = await onComputer(`acct:${accountId}`, async () => {+ const name = (await comfyProvider.prepareFile!(sideways, "image/jpeg", "me.jpg", route))!;+ return { name, info: mediaInfoFor(name) };+ });+ expect(fs.readFileSync(path.join(dir, "relay", "in", own.name)).equals(sideways)).toBe(true);+ expect(own.info).toMatchObject({ width: 40, height: 20 });+ });++ it("a camera path's photo goes to the worker the same way", async () => {+ const sharp = (await import("sharp")).default;+ const photo = await sharp({ create: { width: 16, height: 12, channels: 3, background: "#36c" } }).jpeg().withExif({ IFD0: { Artist: "someone private" } }).toBuffer();+ const { id } = pathFinish(photo);+ const staged = tasks.inputsOf(id).map((i) => fs.readFileSync(path.join(dir, "relay", "in", i.name)));+ expect(staged).toHaveLength(2);+ expect(staged.some((b) => b.includes(Buffer.from("someone private")))).toBe(false);+ expect(staged[0].length).toBe(photo.length);+ });+});++// ---------------------------------------------------------------------------+// A finish's results are stored once, and a 3D model waits for its check++/** The smallest binary glTF with every part inside it. */+function tinyGlb(): Buffer {+ let j = Buffer.from(JSON.stringify({ asset: { version: "2.0" } }));+ j = Buffer.concat([j, Buffer.alloc((4 - (j.length % 4)) % 4, 0x20)]);+ const header = Buffer.alloc(20);+ header.writeUInt32LE(0x46546c67, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(20 + j.length, 8);+ header.writeUInt32LE(j.length, 12);+ header.writeUInt32LE(0x4e4f534a, 16);+ return Buffer.concat([header, j]);+}++/** A finishing job a worker finished: its one result file back, as `role`. */+function finishedOnWorker(id: string, role: string, data: Buffer, contentType: string) {+ const file = tasks.outputFile(id, 0);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, data);+ db()+ .prepare("UPDATE relay_tasks SET state = 'done', result_json = ?, received_json = ?, finished_at = ? WHERE id = ?")+ .run(JSON.stringify([{ files: [{ role, n: 0 }], stats: {} }]), JSON.stringify([{ n: 0, bytes: data.length, total: data.length, done: true, contentType }]), Date.now(), id);+}++/** Wait for `fn` to give something. */+async function until<T>(fn: () => T, ms = 15_000): Promise<NonNullable<T>> {+ const end = Date.now() + ms;+ for (;;) {+ const v = fn();+ if (v) return v as NonNullable<T>;+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);+ await new Promise((r) => setTimeout(r, 100));+ }+}++describe("a finish's results are kept once", () => {+ it("a 3D model's web GLB is stored once, however many app processes look at the finished job", async () => {+ const { saveFile } = await import("@/server/storage");+ expect(finish.glbSelfContained(tinyGlb())).toBe(true);+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: tinyGlb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ const id = finish.queueFinish({ kind: "model3d", generationId: gid, account: accountId, inputs: [{ slot: "model", data: tinyGlb(), contentType: "model/gltf-binary", name: "model.glb" }], settings: { material: "auto", turntable: false } });+ finishedOnWorker(id, "web", tinyGlb(), "model/gltf-binary");+ const got: import("@/lib/catalog/types").OutputFile[][] = [];+ // Each look as another app process makes it (a deploy's overlap): a watch of its own, the same finished job.+ for (let i = 0; i < 2; i++) finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void got.push(o) });+ expect(got).toHaveLength(2);+ expect(got[1]).toEqual(got[0]);+ expect((got[0][0].meta as { web?: string }).web).toBeTruthy();+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ? AND name = 'model-web.glb'").pluck().get(gid)).toBe(1);+ });++ it("a camera path's clip is stored once, however many app processes look at the finished job", async () => {+ const { runAsTenant } = await import("@/server/tenant");+ const { saveFile } = await import("@/server/storage");+ const photo = saveFile({ data: smallPng(), contentType: "image/png", name: "still.png", source: "upload", accountId });+ const depth = saveFile({ data: smallPng(), contentType: "image/png", name: "depth.png", source: "derived", accountId });+ const keys = [+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ];+ const gid = generation(accountId, "image-to-video");+ const step = () => runAsTenant({ kind: "account", id: accountId }, () => finish.pathOnWorker(gid, 0, { photo: photo.url, depth: depth.url, keys, frames: 9, fps: 16 }));+ expect(await step()).toEqual({ state: "waiting" });+ finishedOnWorker(finish.finishTask(gid, "path")!.id, "path", Buffer.from("....ftypisom path clip"), "video/mp4");+ const [a, b] = await Promise.all([step(), step()]);+ expect(a.state).toBe("done");+ expect(b).toEqual(a);+ expect(await step()).toEqual(a);+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ? AND name = 'path-render.mp4'").pluck().get(gid)).toBe(1);+ });+});++describe("pictures for a worker that this server can't blank in place", () => {+ /** A GIF with a comment in it. */+ async function gifWithComment(text: string) {+ const sharp = (await import("sharp")).default;+ const gif = await sharp({ create: { width: 8, height: 6, channels: 3, background: "#c63" } }).gif().toBuffer();+ const packed = gif[10];+ const at = 13 + (packed & 0x80 ? 3 * 2 ** ((packed & 7) + 1) : 0);+ const data = Buffer.from(text, "latin1");+ return Buffer.concat([gif.subarray(0, at), Buffer.from([0x21, 0xfe, data.length]), data, Buffer.from([0]), gif.subarray(at)]);+ }++ it("are made again from their pixels here, so nothing besides them leaves: a GIF's comment, a camera path's GIF photo", async () => {+ const { comfyProvider, mediaInfoFor } = await import("@/server/providers/comfyui");+ const { pictureWithoutMetadata } = await import("@/server/media-clean");+ const hosted = await import("@/server/hosted");+ const sharp = (await import("sharp")).default;+ const gif = await gifWithComment("a private note");+ expect((await sharp(gif).metadata()).width).toBe(8);+ expect(pictureWithoutMetadata(gif, "image/gif")).toBeNull();+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const pooled = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(gif, "image/gif", "me.gif", route))!;+ return { name, info: mediaInfoFor(name) };+ });+ const staged = fs.readFileSync(path.join(dir, "relay", "in", pooled.name));+ expect(staged.subarray(1, 4).toString()).toBe("PNG");+ expect(staged.includes(Buffer.from("a private note"))).toBe(false);+ expect(pooled.info).toMatchObject({ width: 8, height: 6 });+ // A camera path's photo the same way.+ const { runAsTenant } = await import("@/server/tenant");+ const { saveFile } = await import("@/server/storage");+ const photo = saveFile({ data: gif, contentType: "image/gif", name: "still.gif", source: "upload", accountId });+ const depth = saveFile({ data: smallPng(), contentType: "image/png", name: "depth.png", source: "derived", accountId });+ const gid = generation(accountId, "image-to-video");+ const keys = [+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ];+ expect(await runAsTenant({ kind: "account", id: accountId }, () => finish.pathOnWorker(gid, 0, { photo: photo.url, depth: depth.url, keys, frames: 9, fps: 16 }))).toEqual({ state: "waiting" });+ const files = tasks.inputsOf(finish.finishTask(gid, "path")!.id).map((i) => fs.readFileSync(path.join(dir, "relay", "in", i.name)));+ expect(files[0].subarray(1, 4).toString()).toBe("PNG");+ expect(files.some((b) => b.includes(Buffer.from("a private note")))).toBe(false);+ });+});++describe("a 3D model finished on a worker, for a run whose outputs are checked first", () => {+ it("waits for the check, as any run's outputs do, and never shows before it", async () => {+ const generations = await import("@/server/generations");+ const { saveFile } = await import("@/server/storage");+ process.env.FUOBE_MODERATION_URL = "http://127.0.0.1:9/check";+ const gid = `cpu-slot-checked-3d-${++gens}`;+ try {+ const now = Date.now();+ const raw = saveFile({ data: tinyGlb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d", contentType: "model/gltf-binary", assetId: raw.id }];+ // Its GPU job is done and its outputs are stored; the 3D finish comes next.+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, external_meta_json, created_at, updated_at) VALUES (?, 'image-to-3d', 'oss-pixal3d', 'open', 'comfyui', 'image-to-3d', 'model3d', 'running', ?, ?, 'job-1', ?, ?, ?)",+ )+ .run(gid, JSON.stringify({ account: accountId, place: "pool", checkOutputs: true }), JSON.stringify(outputs), JSON.stringify({ finishing: true }), now, now);+ generations.ensureRunner();+ await globalThis.__fuobeRunner?.tick();+ const t = await until(() => finish.finishTask(gid, "model3d"));+ // Its finish comes back (here: no CPU slot took it in time, so the model is kept as it is).+ db().prepare("UPDATE relay_tasks SET not_after = ? WHERE id = ?").run(Date.now() - 1, t.id);+ pool.sweepPool();+ const g = await until(() => {+ const r = db().prepare("SELECT status, stage FROM generations WHERE id = ?").get(gid) as { status: string; stage: string | null };+ return r.stage === "checking" && r;+ });+ expect(g).toMatchObject({ status: "running", stage: "checking" });+ expect(db().prepare("SELECT held FROM assets WHERE id = ?").pluck().get(raw.id)).toBe(1);+ } finally {+ delete process.env.FUOBE_MODERATION_URL;+ finish.stopWorkerFinish(gid);+ const r = globalThis.__fuobeRunner;+ if (r) {+ clearInterval(r.timer);+ if (r.fastTimer) clearInterval(r.fastTimer);+ globalThis.__fuobeRunner = undefined;+ }+ }+ });+});diff --cc tests/hosted-tool-runs.test.tsindex 1dee2b30,00000000..6993575cmode 100644,000000..100644--- a/tests/hosted-tool-runs.test.ts+++ b/tests/hosted-tool-runs.test.ts@@@ -1,472 -1,0 +1,498 @@@+import http from "node:http";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import { listenOnFreePort, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++/**+ * A tool's run (Storyboard here, and every tool that runs through account-tool-run.ts) for an account with no GPU of its+ * own: with hosted runs on it runs on this install's GPUs through the same gate as a studio run, held and counted once+ * however many steps it has; with them off, or for an account whose own GPU answers, nothing changes.+ */+const dir = tempDir("fuobe-hosted-tool-runs-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_BILLING_URL;+delete process.env.FUOBE_MODERATION_URL;+delete process.env.ANTHROPIC_API_KEY;+globalThis.__fuobeTestDiskFree = 1e13;++const probe = http.createServer();+const comfyPort = await listenOnFreePort(probe);+await new Promise<void>((r) => probe.close(() => r()));+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0, loras: [] }, comfyPort);+process.env.COMFYUI_URL = comfy.url;++const auth = await import("@/server/auth");+const boardsRoute = await import("@/app/api/storyboards/route");+const gpuRoute = await import("@/app/api/account/gpu/route");+const { proxy } = await import("@/proxy");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const billing = await import("@/server/billing");+const hostedRun = await import("@/server/hosted-run");+const toolRun = await import("@/server/account-tool-run");+const { createGenerations } = await import("@/server/generations");+const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");+const { drainOutbox, queueReports } = await import("@/server/billing-outbox");- const presses = await import("@/server/tool-presses");++const presses = await import("@/server/run-requests");+const pressRequestId = presses.reserveRequestId;++let fake: FakeBilling;+const ids: Record<string, string> = {};+const cookies: Record<string, string> = {};+beforeAll(async () => {+ fake = await startFakeBilling();+ auth.setPassword("install password");+ for (const who of ["none", "gpu"]) {+ ids[who] = auth.createAccount(`tools-${who}@example.com`, "long enough").id;+ cookies[who] = `${auth.SESSION_COOKIE}=${auth.createSession(ids[who]).value}`;+ }+ globalThis.__fuobeTestGpuPort = comfy.port;+ expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: comfy.url }, "gpu"))).status).toBe(200);+});+afterAll(async () => {+ globalThis.__fuobeTestDiskFree = undefined;+ globalThis.__fuobeTestGpuPort = undefined;+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ await fake.close();+ await comfy.close();+});+beforeEach(() => {+ resetRates();+ billing.resetBillingCache();+ delete process.env.FUOBE_HOSTED_RUNS;+ delete process.env.FUOBE_HOSTED_FREE;+ delete process.env.FUOBE_BILLING_URL;+ delete process.env.FUOBE_BILLING_TOKEN;+ fake.policy = { hosted: true, pool: {}, uploads: { image: true, video: false, audio: false }, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7 }, ttlS: 0 };+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+});++function json(url: string, method: string, body: unknown, who?: string): Request {+ const text = JSON.stringify(body);+ return new Request(`http://localhost:3000${url}`, {+ method,+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },+ body: text,+ });+}+const viaProxy = (url: string, who: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": "application/json" }, body: "{}" }));+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";++const SCENES = ["A model in an emerald gown on a palace stair at midnight", "She runs to a vintage car under the lamps", "The car on a coast road at dawn"];+const board = async (who: string, extra: Record<string, unknown> = {}) => {+ const r = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES, ...extra }, who));+ return { status: r.status, body: (await r.json()) as { items?: { id: string }[]; error?: string; code?: string } };+};+/** The stored requests of an account's runs (as the runner reads them). */+const stored = (who: string) =>+ (db().prepare("SELECT request_json FROM generations WHERE json_extract(request_json, '$.account') = ? AND status IN ('queued', 'running', 'succeeded') ORDER BY created_at").all(ids[who]) as { request_json: string }[]).map(+ (r) => JSON.parse(r.request_json) as { place?: string; hold?: string; light?: boolean },+ );+const reserves = () => fake.calls_of("/v1/reserve").length;+const useBilling = () => {+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+};++describe("hosted runs off (the default): tool runs are as before", () => {+ it("an account with no GPU or key is asked to connect one, at the proxy and at the route", async () => {+ const at = await viaProxy("/api/storyboards", "none");+ expect(at.status).toBe(403);+ expect(((await at.json()) as { code: string }).code).toBe("connect-gpu");+ const r = await board("none");+ expect(r.status).toBe(403);+ expect(r.body.code).toBe("connect-gpu");+ expect(stored("none")).toEqual([]);+ });++ it("a press is made once per server process, as before, and nothing of it is kept in the database", async () => {+ const account = auth.accountById(ids.none)!;+ let called = 0;+ const press = () =>+ toolRun.onceForAccount(+ account,+ "test-off",+ "press-off-00001",+ async () => ({ ok: true as const, value: ++called }),+ ({ value }) => Response.json({ value }, { status: 201 }),+ );+ expect(await (await press()).json()).toEqual({ value: 1 });+ expect(await (await press()).json()).toEqual({ value: 1 });- expect(db().prepare("SELECT COUNT(*) AS n FROM tool_presses WHERE account = ?").get(account.id)).toEqual({ n: 0 });++ expect(db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE account = ?").get(account.id)).toEqual({ n: 0 });+ });++ it("the seam answers its own GPU or key, whatever the steps", async () => {+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }]);+ expect(place).toEqual({ kind: "own" });+ });+});++describe("hosted runs on", () => {+ beforeEach(() => {+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_HOSTED_FREE = "1";+ });++ it("a tool's run reaches its route for an account with no GPU of its own; other tools still say so", async () => {+ expect(passed(await viaProxy("/api/storyboards", "none"))).toBe(true);+ const other = await viaProxy("/api/enhance", "none");+ expect(other.status).toBe(403);+ expect(((await other.json()) as { code: string }).code).toBe("own-gpu-tool");+ });++ it("a board runs on this install's GPUs: every step stamped for there", async () => {+ const r = await board("none");+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const rows = stored("none");+ expect(rows.length).toBe(SCENES.length);+ expect(rows.every((q) => q.place === "pool")).toBe(true);+ });++ it("with a billing service: one hold for the whole run, priced from every step, on every row", async () => {+ useBilling();+ const before = reserves();+ // The price the client showed before Run comes back with the run (a run priced higher is asked about again).+ const r = await board("none", { shown: { amount: fake.price.amount, priceVersion: fake.price.version } });+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(reserves() - before).toBe(1);+ const reserve = fake.calls_of("/v1/reserve").at(-1)!.body as { run: { steps?: { model: string; jobs: number }[] } };+ expect(reserve.run.steps?.reduce((n, s) => n + s.jobs, 0)).toBe(SCENES.length);+ const holds = new Set(stored("none").map((q) => q.hold));+ expect(holds.size).toBe(1);+ expect([...holds][0]).toBeTruthy();+ });++ it("a model the policy keeps off this install's GPUs refuses the run before anything is held or made", async () => {+ useBilling();+ fake.policy = { ...fake.policy, pool: { deny: ["oss-z-image-turbo"] } };+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);+ expect(place.kind).toBe("refuse");+ if (place.kind === "refuse") expect(place.refusal.body.code).toBe("not-offered");+ const before = reserves();+ const rows = stored("none").length;+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, { tool: "test", files: [], plan: () => steps, start: () => createGenerations(steps[0].request) });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(((await r.response.json()) as { code: string }).code).toBe("not-offered");+ expect(reserves()).toBe(before);+ expect(stored("none").length).toBe(rows);+ });++ it("a row the start makes that the policy doesn't allow stops the whole run, and its hold goes back", async () => {+ useBilling();+ fake.policy = { ...fake.policy, pool: { deny: ["oss-flux1-schnell"] } };+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const rows = stored("none").length;+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ shown: { amount: fake.price.amount, priceVersion: fake.price.version },+ plan: () => plan,+ // A start that makes more than it planned: a step the policy leaves out.+ start: () => [...createGenerations(plan[0].request), ...createGenerations({ feature: "image", modelId: "oss-flux1-schnell", prompt: "a fox in red" })],+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.response.status).toBe(403);+ expect(stored("none").length).toBe(rows);+ await drainOutbox();+ const hold = [...fake.holds.values()].at(-1);+ expect(hold?.released).toBe(true);+ });++ it("a start that makes more jobs than its plan was priced and held for is stopped, and its hold goes back", async () => {+ useBilling();+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const rows = stored("none").length;+ const before = reserves();+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ shown: { amount: fake.price.amount, priceVersion: fake.price.version },+ plan: () => plan,+ // Priced as one picture; the start makes two of the same model.+ start: () => [...createGenerations(plan[0].request), ...createGenerations({ ...plan[0].request, prompt: "a fox at dusk" })],+ });+ expect(r.ok).toBe(false);+ if (!r.ok) {+ expect(r.response.status).toBe(403);+ expect(((await r.response.json()) as { code: string }).code).toBe("not-offered");+ }+ expect(reserves() - before).toBe(1);+ expect((fake.calls_of("/v1/reserve").at(-1)!.body as { run: { steps: { jobs: number }[] } }).run.steps).toEqual([expect.objectContaining({ jobs: 1 })]);+ expect(stored("none").length).toBe(rows);+ await drainOutbox();+ expect([...fake.holds.values()].at(-1)?.released).toBe(true);+ });++ it("a start whose row asks for more outputs at once than a run here makes is stopped, its hold given back", async () => {+ useBilling();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), outputsPerRun: 1 } };+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const rows = stored("none").length;+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ shown: { amount: fake.price.amount, priceVersion: fake.price.version },+ plan: () => plan,+ start: () => createGenerations({ ...plan[0].request, params: { numOutputs: 2 } }),+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(((await r.response.json()) as { error: string }).error).toBe(hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, false));+ expect(stored("none").length).toBe(rows);+ await drainOutbox();+ expect([...fake.holds.values()].at(-1)?.released).toBe(true);+ });++ it("a run planned as light work (free, never counted) whose start makes GPU work is stopped before anything is sent", async () => {+ const light = [{ request: { feature: "video", modelId: "oss-ken-burns", op: "still-motion" as const, inputs: { images: ["/api/files/x.png"] }, params: { duration: 4 } } }];+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, light);+ expect(place.kind).toBe("pool");+ if (place.kind === "pool") expect(place.light).toBe(true);+ const rows = stored("none").length;+ const before = reserves();+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {+ tool: "test",+ files: [],+ plan: () => light,+ start: () => createGenerations({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" }),+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.response.status).toBe(403);+ expect(reserves()).toBe(before);+ expect(stored("none").length).toBe(rows);+ });++ it("a tool's step that asks for more outputs than a run here makes is refused before Run, never priced smaller", async () => {+ useBilling();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), outputsPerRun: 1 } };+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", params: { numOutputs: 4 } } }];+ const words = hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, false);+ const quotes = fake.calls_of("/v1/quote").length;+ const check = await toolRun.toolPriceCheck(json("/api/x?preview=1", "POST", {}, "none"), () => steps);+ expect(check?.quote).toMatchObject({ allowed: false, code: "not-offered", text: words });+ expect(fake.calls_of("/v1/quote").length).toBe(quotes);+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);+ expect(place.kind).toBe("refuse");+ if (place.kind === "refuse") expect(place.refusal.body).toMatchObject({ error: words, code: "not-offered" });+ // A guest's words name nothing it can't do yet; an account whose own GPU answers runs it there.+ expect(hostedRun.gateText({ ok: false, reason: "outputs", cap: 1 }, true)).not.toMatch(/Settings/);+ expect(await toolRun.placeOf(auth.accountById(ids.gpu)!, steps)).toEqual({ kind: "own" });+ });++ it("a press refused after its hold was made asks for a new hold on its next try; the first goes back", async () => {+ useBilling();+ const account = auth.accountById(ids.none)!;+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };+ const press = (start: () => unknown) =>+ toolRun.onceForAccount(+ account,+ "test-press",+ "press-tries-0001",+ () => toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start }),+ () => Response.json({ ok: true }, { status: 201 }),+ );+ const before = reserves();+ // Its start makes more than was priced: refused after the hold was made.+ const bad = await press(() => [...createGenerations(plan[0].request), ...createGenerations({ ...plan[0].request, prompt: "a fox at dusk" })]);+ expect(bad.status).toBe(403);+ const good = await press(() => createGenerations(plan[0].request));+ expect(good.status, await good.clone().text()).toBe(201);+ const sent = fake.calls_of("/v1/reserve").slice(before).map((c) => (c.body as { requestId: string }).requestId);- expect(sent).toEqual([pressRequestId(account.id, "test-press\npress-tries-0001"), pressRequestId(account.id, "test-press\npress-tries-0001\n1")]);++ expect(sent).toEqual([pressRequestId(account.id, "test-press\npress-tries-0001"), pressRequestId(account.id, "test-press\npress-tries-0001", 1)]);+ await drainOutbox();+ const holds = [...fake.holds.values()].filter((h) => sent.includes(h.requestId));+ expect(holds.map((h) => h.released)).toEqual([true, false]);+ // The press answered: sent again, it is the same run, with no new hold.+ expect((await press(() => createGenerations(plan[0].request))).status).toBe(201);+ expect(reserves() - before).toBe(2);+ });+++ it("a press whose run goes to the account's own GPU keeps nothing in the database, as with hosted runs off", async () => {++ useBilling();++ const account = auth.accountById(ids.gpu)!;++ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];++ expect(await toolRun.placeOf(account, plan)).toEqual({ kind: "own" });++ let called = 0;++ const press = () =>++ toolRun.onceForAccount(++ account,++ "test-own",++ "press-own-00001",++ async () => {++ // Placed on its own GPU: never startOnPool, so the press is never claimed.++ expect(await toolRun.placeOf(account, plan)).toEqual({ kind: "own" });++ return { ok: true as const, value: ++called };++ },++ ({ value }) => Response.json({ value }, { status: 201 }),++ );++ const before = reserves();++ expect(await (await press()).json()).toEqual({ value: 1 });++ // Sent again in this server process: the first run, as before (shorts-schemas.ts once).++ expect(await (await press()).json()).toEqual({ value: 1 });++ expect(db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE account = ?").get(account.id)).toEqual({ n: 0 });++ expect(reserves()).toBe(before);++ });+++ it("a resend while another server process starts the press waits for that answer and makes nothing", async () => {+ const account = auth.accountById(ids.none)!;- expect(presses.claimPress(account.id, "test-wait", "press-wait-0001").kind).toBe("claimed");++ expect(presses.claimPress(account.id, presses.toolPressKey("test-wait", "press-wait-0001")).kind).toBe("claimed");+ let called = 0;+ const resend = toolRun.onceForAccount(+ account,+ "test-wait",+ "press-wait-0001",+ async () => {+ called++;+ return { ok: true as const, value: 1 };+ },+ () => Response.json({ here: true }, { status: 201 }),+ );- setTimeout(() => presses.answerPress(account.id, "test-wait", "press-wait-0001", { status: 201, headers: [["content-type", "application/json"]], text: JSON.stringify({ elsewhere: true }) }), 300);++ setTimeout(() => presses.answerPress(account.id, presses.toolPressKey("test-wait", "press-wait-0001"), { status: 201, headers: [["content-type", "application/json"]], text: JSON.stringify({ elsewhere: true }) }), 300);+ const r = await resend;+ expect(r.status).toBe(201);+ expect(await r.json()).toEqual({ elsewhere: true });+ expect(called).toBe(0);+ });++ it("runs sent together whose start awaits before it makes its rows meet the limits one at a time", async () => {+ useBilling();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), activeRuns: 1 } };+ const account = auth.accountById(ids.none)!;+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };+ const rows = stored("none").length;+ // A start that waits (a channel made first, say) before it makes its rows.+ const start = async () => {+ await new Promise((r) => setTimeout(r, 30));+ return createGenerations(plan[0].request);+ };+ const go = () => toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start });+ const [a, b] = await Promise.all([go(), go()]);+ expect([a.ok, b.ok].filter(Boolean)).toHaveLength(1);+ const no = (a.ok ? b : a) as Extract<typeof a, { ok: false }>;+ expect(no.response.status).toBe(429);+ expect(stored("none").length - rows).toBe(1);+ // Its rows made, the run counts for itself: nothing is left open, and the next press meets the same limit.+ expect(db().prepare("SELECT COUNT(*) AS n FROM open_admissions WHERE account = ?").get(account.id)).toEqual({ n: 0 });+ const third = await go();+ expect(third.ok).toBe(false);+ // The account's own limit of runs at once counts such a run too, while its rows are being made.+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), activeRuns: 0, waiting: 0 } };+ const many = await Promise.all(Array.from({ length: 6 }, go));+ expect(many.filter((r) => r.ok)).toHaveLength(4);+ });++ it("a start that makes no rows gives its hold back, answers as the tool does, and isn't one of the hour's runs", async () => {+ useBilling();+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), runsPerHour: 1 } };+ const account = auth.accountById(ids.none)!;+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };+ const hours = () => (db().prepare("SELECT COUNT(*) AS n FROM pool_admissions WHERE account = ?").get(account.id) as { n: number }).n;+ db().prepare("DELETE FROM pool_admissions WHERE account = ?").run(account.id);+ for (const start of [() => [], async () => []]) {+ const before = reserves();+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start });+ expect(r.ok).toBe(true);+ expect(reserves() - before).toBe(1);+ await drainOutbox();+ const hold = [...fake.holds.values()].at(-1)!;+ expect(hold.released).toBe(true);+ expect(hold.reports.size).toBe(0);+ expect(hours()).toBe(0);+ }+ // The hour still has room for a run that makes something.+ const real = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start: () => createGenerations(plan[0].request) });+ expect(real.ok).toBe(true);+ expect(hours()).toBe(1);+ });++ it("a start that made a row and then failed: the row's report closes the hold, which is never released as well", async () => {+ useBilling();+ const account = auth.accountById(ids.none)!;+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };+ const releases = fake.calls_of("/v1/release").length;+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, {+ tool: "test",+ files: [],+ shown,+ plan: () => plan,+ start: async () => {+ createGenerations(plan[0].request);+ await new Promise((r) => setTimeout(r, 5));+ throw new Error("The plan changed. Please try again.");+ },+ });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.response.status).toBe(422);+ const hold = [...fake.holds.entries()].at(-1)!;+ // The stopped row reports once it is canceled.+ await expect.poll(() => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.hold') = ? AND status = 'canceled'").get(hold[0]) as { n: number }).n).toBe(1);+ queueReports();+ await drainOutbox();+ expect(fake.calls_of("/v1/release").length).toBe(releases);+ expect(hold[1].released).toBe(false);+ expect([...hold[1].reports.values()]).toEqual(["canceled"]);+ expect(fake.calls_of("/v1/refund").filter((c) => (c.body as { holdId: string }).holdId === hold[0])).toHaveLength(1);+ });++ it("a 3D model stays on an account's own GPU: refused here in the tools' words", async () => {+ const steps = [{ request: { feature: "3d", modelId: "oss-pixal3d", op: "image-to-3d" as const, prompt: "", inputs: { images: ["/api/files/x.png"] } } }];+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);+ expect(place.kind).toBe("refuse");+ if (place.kind === "refuse") {+ expect(place.refusal.body.code).toBe("own-gpu-tool");+ expect(place.refusal.body.error).toBe(OWN_GPU_TOOL_MESSAGE);+ }+ });++ it("an account whose own GPU answers keeps it, and asking for its own GPU always keeps it", async () => {+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ expect(await toolRun.placeOf(auth.accountById(ids.gpu)!, steps)).toEqual({ kind: "own" });+ expect(await toolRun.placeOf(auth.accountById(ids.none)!, steps, "own")).toEqual({ kind: "own" });+ expect((await toolRun.placeOf(auth.accountById(ids.gpu)!, steps, "pool")).kind).toBe("pool");+ });++ it("the price check before Run answers for the whole run: place, quote and line", async () => {+ useBilling();+ const plan = () => [+ { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } },+ { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox at night" }, deps: 1 },+ ];+ const asNone = new Request("http://localhost:3000/api/x?preview=1", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.none } });+ const check = await toolRun.toolPriceCheck(asNone, plan);+ expect(check?.place).toBe("pool");+ expect(check?.quote.allowed).toBe(true);+ expect(check?.line.place).toBeGreaterThanOrEqual(1);+ const quote = fake.calls_of("/v1/quote").at(-1)!.body as { run: { steps?: { jobs: number }[] } };+ expect(quote.run.steps?.reduce((n, s) => n + s.jobs, 0)).toBe(2);+ // A guest's is priced too (as nobody's run); the owner's never comes here.+ const guest = await toolRun.toolPriceCheck(new Request("http://localhost:3000/api/x?preview=1", { method: "POST", headers: { host: "localhost:3000" } }), plan);+ expect(guest?.place).toBe("pool");+ // A run asked for on its own GPU isn't priced here.+ expect(await toolRun.toolPriceCheck(asNone, plan, "own")).toBeNull();+ });+});++describe("text steps inside a run on this install's GPUs", () => {+ const step = (modelId: string, provider: string, i: number) => ({ id: `s${i}`, modelId, op: "t2i", provider, kind: "image", presetId: null, waits: i > 0 });+ it("run on the install's AI helper: allowed, never priced, never counted", () => {+ const steps = [step("oss-text-llm", "llm", 0), step("oss-z-image-turbo", "comfyui", 1)];+ expect(hostedRun.stepsProblem(billing.OPEN_POLICY, steps)).toBeNull();+ expect(hostedRun.pricedSteps(steps).map((s) => s.model)).toEqual(["oss-z-image-turbo"]);+ expect(hostedRun.lightRun(steps)).toBe(false);+ // A cloud step still can't run there.+ expect(hostedRun.stepsProblem(billing.OPEN_POLICY, [...steps, step("fal-flux", "fal", 2)])).not.toBeNull();+ });+});++void TINY_PNG;diff --cc tests/pool-account-runs.test.tsindex f683898e,5dfac42e..282d293c--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@@ -120,8 -118,10 +120,10 @@@ function standInWorker(name = "stand-inconst lanes = allLanes(loadIndex(), sha);pool.patchWorker(w.id, { paused: !!o.paused, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });db()- .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")- .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);+ // Connected: its worker program beat a moment ago.- db().prepare("UPDATE relay_workers SET seen_at = ?, protocol = ?, paused_local = 0 WHERE id = ?").run(Date.now(), pool.MIN_PROTOCOL, w.id);++ db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);return w;}diff --cc tests/pool-limits.test.tsindex 0ed2017e,35979e83..3c3528c7--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@@ -104,8 -102,10 +104,10 @@@ function standInWorker()const lanes = allLanes(loadIndex(), sha);pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });db()- .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")- .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);+ // Connected: its worker program beat a moment ago.- db().prepare("UPDATE relay_workers SET seen_at = ?, protocol = ?, paused_local = 0 WHERE id = ?").run(Date.now(), pool.MIN_PROTOCOL, w.id);++ db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);return w;}@@@ -239,6 -269,6 +277,27 @@@ describe("runs at once on this install'expect(fifth.status).toBe(429);});++ it("a press of Run is kept only for a run on this install's GPUs: on the account's own GPU each send makes its run, as before", async () => {++ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });++ const a = account({ gpu: "online" });++ const kept = () => (db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE account = ?").get(a.id) as { n: number }).n;++ const own = { ...IMAGE, requestId: `own-${crypto.randomUUID()}` };++ const first = await post(own, a.cookie);++ const again = await post(own, a.cookie);++ expect(first.status, JSON.stringify(first.body)).toBe(201);++ expect(again.status, JSON.stringify(again.body)).toBe(201);++ expect(first.body.items![0].place).toBeUndefined();++ expect(again.body.items![0].id).not.toBe(first.body.items![0].id);++ expect(kept()).toBe(0);++ // The same account's press on this install's GPUs is made once, however often it is sent.++ const pool = { ...IMAGE, place: "pool", ...SHOWN, requestId: `pool-${crypto.randomUUID()}` };++ const one = await post(pool, a.cookie);++ const two = await post(pool, a.cookie);++ expect(one.status, JSON.stringify(one.body)).toBe(201);++ expect(two.body.items!.map((g) => g.id)).toEqual(one.body.items!.map((g) => g.id));++ expect(kept()).toBe(1);++ });++it("with a free install (no billing service) the policy's limits apply to runs there too", async () => {const a = account();const p = await billing.policy(a.id);@@@ -794,34 -824,32 +853,60 @@@ describe("the price check before Run an}});+ it("while every worker that could run it is built from the catalog before the studio's update, Run is off with plain words, never a run that waits for nothing", async () => {+ const a = account();+ const acct = auth.accountById(a.id)!;+ withBilling({ limits: NO_LIMITS });+ const req = { ...IMAGE, account: a.id } as never;+ const endpoint = getModel(IMAGE.modelId)!.routes!.find((r) => r.provider === "comfyui")!.endpoint;+ beatWith(worker, catalogVersion());+ expect((await hostedRun.decidePlace(acct, req, undefined)).kind).toBe("pool");+ expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(1);+ // The studio was updated; its only worker not yet.+ beatWith(worker, "e".repeat(64));+ const before = db().prepare("SELECT COUNT(*) FROM generations").pluck().get();+ const run = await hostedRun.decidePlace(acct, req, undefined);+ expect(run.kind).toBe("refuse");+ expect(run.kind === "refuse" && run.refusal).toMatchObject({ status: 503, body: { code: "busy", error: HOSTED_WORDS.busy } });+ expect((await hostedRun.poolQuote(acct, req, undefined))?.quote).toMatchObject({ allowed: false, code: "busy", text: HOSTED_WORDS.busy });+ expect((await hostedRun.poolQuote(null, IMAGE as never, undefined))?.quote).toMatchObject({ allowed: false, text: HOSTED_GUEST_WORDS.busy });+ // Its place in line and the workers there count only a worker that takes the run now.+ expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(0);+ expect(db().prepare("SELECT COUNT(*) FROM generations").pluck().get()).toBe(before);+ // The owner's own jobs still go to it: a worker built from another catalog takes those.+ expect(pool.workersCanRun(endpoint)).toBe(true);+ // Updated: Run is on again.+ beatWith(worker, catalogVersion());+ expect((await hostedRun.poolQuote(acct, req, undefined))?.quote.allowed).toBe(true);+ expect(hosted.queueFacts(a.id, endpoint).workersOnline).toBe(1);+ });++ it("a chain whose later step only away workers could run is told it starts soon, though a worker for its first step is on", async () => {+ const endpointOf = (id: string) => getModel(id)!.routes.find((r) => r.provider === "comfyui")!.endpoint;+ const first = endpointOf("oss-z-image-turbo");+ const later = endpointOf("oss-rtx-video-upscale");+ const laterLane = pool.poolLane(later);+ expect(pool.poolLane(first)).not.toBe(laterLane);+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);+ // The worker that is on may run every lane but the later step's; the only one that may run that lane is away.+ pool.patchWorker(worker.id, { allow: Object.fromEntries(lanes.filter((l) => l !== laterLane).map((l) => [l, { delayMs: 0 }])) });+ const away = standInWorker();+ pool.patchWorker(away.id, { allow: { [laterLane]: { delayMs: 0 } } });+ db().prepare("UPDATE relay_workers SET paused_local = 1, local_why = 'gpu-busy:game.exe' WHERE id = ?").run(away.id);+ const chain = [+ { id: "s0", modelId: "oss-z-image-turbo", op: "t2i", provider: "comfyui", kind: "image", presetId: null, waits: false },+ { id: "s1", modelId: "oss-rtx-video-upscale", op: "upscale-video", provider: "comfyui", kind: "video", presetId: null, waits: true },+ ];+ const planned = { route: { endpoint: first } };+ expect(hostedRun.runAway(planned as never, [chain[0]])).toBe(false);+ expect(hostedRun.runAway(planned as never, chain)).toBe(true);+ // A step that isn't on this install's GPUs (a cloud step) is not looked at.+ expect(hostedRun.runAway(planned as never, [chain[0], { ...chain[1], provider: "fal" }])).toBe(false);+ // The away worker is back: the chain may be made.+ db().prepare("UPDATE relay_workers SET paused_local = 0, local_why = NULL WHERE id = ?").run(away.id);+ expect(hostedRun.runAway(planned as never, chain)).toBe(false);+ });+it("a guest's price check plans every step of a chain too, and words its refusals for someone with no Settings yet", async () => {withBilling({ limits: NO_LIMITS });expect((await hostedRun.poolQuote(null, EFFECT as never, undefined))?.quote.allowed).toBe(true);diff --cc tests/pool-line-order.test.tsindex 89d77c6f,1733543e..6c151f3f--- a/tests/pool-line-order.test.ts+++ b/tests/pool-line-order.test.ts@@@ -99,10 -98,11 +99,12 @@@ function standInWorker(name = "stand-inconst w = pool.addWorker(name);const lanes = allLanes(loadIndex(), sha);pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { 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 = ? WHERE id = ?")- .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);+ // Connected: its worker program beat a moment ago.- db().prepare("UPDATE relay_workers SET seen_at = ?, protocol = ?, paused_local = 0 WHERE id = ?").run(Date.now(), pool.MIN_PROTOCOL, w.id);++ db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);return w;}type WorkerRow = import("@/server/computer/workers").WorkerRow;diff --cc tests/recovery-server.test.tsindex ea9c5306,efaf3b92..aad3f4de--- a/tests/recovery-server.test.ts+++ b/tests/recovery-server.test.ts@@@ -54,9 -58,8 +58,9 @@@ const { NextRequest } = await import("nconst { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");const { setSetting } = await import("@/server/settings");- const { getGeneration, ensureRunner } = await import("@/server/generations");+ const { cancelGeneration, getGeneration, ensureRunner, QUIET_MS, updateLive } = await import("@/server/generations");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");@@@ -150,10 -158,10 +159,11 @@@ function standInWorker(name = "stand-inconst 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 = ? WHERE id = ?")- .run(JSON.stringify({ lanes, workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);- if (o.connected !== false) db().prepare("UPDATE relay_workers SET seen_at = ?, protocol = ?, paused_local = 0 WHERE id = ?").run(Date.now(), DRIVER_PROTOCOL, w.id);+ .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;}@@@ -472,9 -495,352 +497,323 @@@ describe("a refresh, a second session a});});- describe("a press of Run sent twice (a network drop at submit)", () => {- it("makes a second run and a second hold today: the run route reads no request id from the page, so each press reserves under an id of its own", async () => {+ 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("the worker's own runner sends ComfyUI's preview pictures with its reports: the Working tile shows the latest, at most one every 2 s", async () => {++ 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;- const frame = (step: number) => Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from(`step ${step} `), Buffer.alloc(1500, step)]);- comfy.inner.opts.previewPicture = (step) => ({ type: "image/jpeg", data: frame(step) });- // No help from the driver: the pictures are ComfyUI's, on its socket.++ // 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);- const sent: number[] = [];++ let n = 0;++ d.previews(() => jpegBase64(++n));++ const kept: number[] = [];+ const shown: string[] = [];- d.onStep(async (step, _path, report) => {++ d.onStep(async (step) => {+ await tick();+ await watch.look();+ if (step !== "running") return;- if (typeof report?.preview === "string") sent.push(Date.now());++ 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, 9).toString("latin1"));++ if (g.preview) shown.push(Buffer.from(await (await previewGet(a1, g.preview)).arrayBuffer()).subarray(4, 12).toString("latin1"));+ });+ await workAll(d);- expect(sent.length, "pictures sent").toBeGreaterThanOrEqual(2);- for (let i = 1; i < sent.length; i++) expect(sent[i] - sent[i - 1]).toBeGreaterThanOrEqual(1500);++ 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("step ");++ for (const s of shown) expect(s).toBe("preview ");+ await expectOnce(id, watch, { prompts: 1, place: 1 });+ });+- it("ComfyUI's PNG previews go as JPEGs the worker program makes; with nothing to make them, none is sent and the run goes on", async () => {- const w = standInWorker();- comfy.inner.opts.steps = 6;- comfy.inner.opts.stepMs = 500;- const types: string[] = [];- const made = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from("made "), Buffer.alloc(500, 7)]);- const shownWith = async (d: WorkerDriver, id: string) => {- const shown: string[] = [];- d.onStep(async (step) => {- await tick();- if (step !== "running") return;- 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, 9).toString("latin1"));- });- await workAll(d);- expect((await ended(id))?.status).toBe("succeeded");- return shown;- };- const first = await pressRun();- const withMaker = workerDriver({ routes, token: w.token, comfy, jpeg: async (_data, type) => (types.push(type), new Uint8Array(made)) });- drivers.push(withMaker);- const shown = await shownWith(withMaker, first.id);- expect(types.length).toBeGreaterThan(0);- expect(new Set(types)).toEqual(new Set(["image/png"]));- expect(shown.length).toBeGreaterThan(0);- for (const s of shown) expect(s).toBe("made ");- withMaker.stop();- const second = await pressRun();- expect(await shownWith(driver(w), second.id)).toEqual([]);- });-+ 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((d.runner as unknown as { previewed: Map<string, unknown> }).previewed.size);++ 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()}` };@@@ -483,12 -849,200 +822,206 @@@const again = await run(press);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(made() - rows, "runs made").toBe(2);- expect(svc.holds.size - holds, "holds made").toBe(2);- const ids = svc.callsOf("/v1/reserve").slice(-2).map((c) => (c.body as { requestId?: string }).requestId);- expect(new Set(ids).size).toBe(2);+ 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 gets the same answer, never a run against that hold", async () => {++ 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 would let the press through now; its answer was lost, and the page sends it again.++ // 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).toBe(a.status);- expect(again.body).toEqual(a.body);- expect(svc.callsOf("/v1/reserve").length, "no second reserve").toBe(before);- expect(made() - rows, "runs made").toBe(1);- // A new press works.- expect((await run({ ...IMAGE, requestId: `press-${crypto.randomUUID()}` })).status).toBe(201);++ 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 refused at once", async () => {++ 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: refused at once, nothing made, no new reserve.++ // 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).toBe(503);- expect(again.body.error).toBe(billing.BILLING_WAIT.run);- expect(svc.callsOf("/v1/reserve").length).toBe(reserves);- expect(made()).toBe(rows);- // A new press works.- expect((await run({ ...IMAGE, requestId: `press-${crypto.randomUUID()}` })).status).toBe(201);++ 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);+ }});});diff --cc tests/recovery-worker.test.tsindex c54c6edd,e53b1926..3ac3b55a--- a/tests/recovery-worker.test.ts+++ b/tests/recovery-worker.test.ts@@@ -164,8 -154,9 +164,10 @@@ describe("the worker program's recoverconst w = studio.pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);const lanes = studio.lanes();studio.pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: 0 });- studio.db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes, workflows: studio.workflows() }), JSON.stringify({ vramBytes: 32 * 2 ** 30 }), w.id);+ // Connected once: it said its build (one that takes this studio's job tickets).+ studio.db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?").run(JSON.stringify({ lanes, workflows: studio.workflows() }), JSON.stringify({ vramBytes: 32 * 2 ** 30 }), program.catalogVersion, w.id);+ // Connected, as a worker that beat a moment ago (a run is refused while every worker that could run it is away).- studio.db().prepare("UPDATE relay_workers SET seen_at = ?, protocol = ?, paused_local = 0 WHERE id = ?").run(Date.now(), studio.pool.MIN_PROTOCOL, w.id);++ studio.db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);return w;}diff --cc tests/worker-cpu-slot.test.tsindex 484a9dcd,00000000..3a2ff3e1mode 100644,000000..100644--- a/tests/worker-cpu-slot.test.ts+++ b/tests/worker-cpu-slot.test.ts@@@ -1,636 -1,0 +1,651 @@@+/**+ * The CPU slot in the worker program (bin/lib/worker/run.mjs) against the studio's real routes, with the worker's own+ * stand-in ComfyUIs (processes of its own, behind the worker's guard). Never a real ComfyUI, never a GPU.+ *+ * - A CPU task runs on the CPU slot while a GPU job runs.+ * - A 3D model whose GLB names an outside file is refused on the worker, and its run keeps the model as it is.+ * - A 3D model's finish comes back with its web GLB, its turntable and its poster, stored on the run.+ * - An account's picture with EXIF reaches its ComfyUI made again from its pixels, with no EXIF.+ * - A live preview reaches the studio as a small JPEG; one over 64 KB is dropped.+ * - With a worker that finishes 3D models, an account's Image to 3D run on this install's GPUs is taken.+ */+import { spawnSync } from "node:child_process";+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 { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";+import { finishers } from "../bin/lib/worker/finish.mjs";+import { previewArgs, previewShrinker, PREVIEW_MAX_BYTES } from "../bin/lib/worker/preview.mjs";+import { workerFiles } from "../scripts/lib/worker-build.mjs";+import { runWorker } from "../bin/lib/worker/run.mjs";+import { inputRules, readCatalog } from "../scripts/lib/worker-catalog.mjs";+import { FAKE_MP4, FAKE_PNG } from "./helpers/fake-local-comfy";+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 120_000 });++const dir = tempDir("fuobe-worker-cpu-slot-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+globalThis.__fuobeTestDiskFree = 1e13;++const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const finish = await import("@/server/computer/finish");+const { catalogVersion } = await import("@/server/computer/catalog-version");+const { comfyProvider } = await import("@/server/providers/comfyui");+const hosted = await import("@/server/hosted");+const { saveFile, getAsset, absolutePath } = await import("@/server/storage");+const { runAsTenant } = await import("@/server/tenant");+const { asAccount, createGenerations } = await import("@/server/generations");+const { withRunStamp } = await import("@/server/run-stamp");+const { getModel } = await import("@/lib/catalog");+const { allLanes } = await import("@/lib/lanes");+const { loadIndex } = await import("@/server/gpu/index-file");+const { ComputerRunner } = await import("@/lib/computer-runner");+const composer = await import("@/lib/ticket-compose");++const ROOT = path.resolve(__dirname, "..");+const FAKE = path.join(ROOT, "tests/helpers/fake-local-comfy.ts");+const SITE = "http://127.0.0.1:9";+const RULES = inputRules(readCatalog(ROOT));+const ALLOWED = new Set(["LoadImage", "ImageInvert", "SaveImage", "KSampler"]);+const VERSION = catalogVersion()!;+const realFetch = globalThis.fetch;+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;+/** Workflows the requirements index marks as light CPU work (the self-test only inverts a picture), and one that uses the GPU. */+const CPU_WORKFLOW = "video-trim";+const GPU_WORKFLOW = "bg-remove-rmbg";++let routes: ComputerRoutes;+let accountId = "";+beforeAll(async () => {+ routes = await loadRoutes();+ setSetting("comfyWhere", "workers");+ auth.setPassword("install password");+ accountId = auth.createAccount("[email protected]", "long enough").id;+});+afterAll(() => {+ globalThis.__fuobeTestDiskFree = undefined;+});+beforeEach(() => {+ resetRates();+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+});++type W = { id: string; token: string };+type TaskRow = import("@/server/computer/tasks").TaskRow;+const row = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;+const LANE = pool.poolLane("selftest-image");++/** A worker the owner added and resumed, all day, allowed every lane, able to run every workflow. */+function addWorker(): W {+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);+ const lanes = allLanes(loadIndex(), sha);+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });+ const workflows = (JSON.parse(fs.readFileSync(path.join(ROOT, "workflows/comfyui/manifest.json"), "utf8")) as { workflows: { id: string }[] }).workflows.map((x) => x.id);+ db().prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?").run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows }), JSON.stringify({ vramBytes: 24 * 2 ** 30 }), w.id);+ return w;+}++let gens = 0;+function generation(account: string | null, op = "edit") {+ const gid = `cpu-slot-worker-gen-${++gens}`;+ const now = Date.now();+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-selftest-image', 'open', 'comfyui', ?, 'image', 'running', ?, '[]', ?, ?)")+ .run(gid, op, JSON.stringify(account ? { account, place: "pool" } : {}), now, now);+ return gid;+}++/** The owner's own job of this workflow on the workers: a whole graph that inverts a picture. */+function ownerTask(workflowId: string, o: { preview?: boolean } = {}) {+ const gid = generation(null);+ const picture = tasks.stageInput("owner", FAKE_PNG, "image/png", "in.png");+ const graph = { "1": { class_type: "LoadImage", inputs: { image: picture } }, "3": { class_type: "KSampler", inputs: { seed: 1, steps: 4 } }, "9": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "fuobe/cpu-slot" } } };+ const t = tasks.createTask({ principal: "owner", generationId: gid, graph, workflowId, ...(o.preview && { preview: true }), pool: pool.poolFields(workflowId, { class: "owner" }) });+ return { id: t.id, gid };+}++/** A one-triangle GLB; `image` adds a picture (and a texture that uses it) with that URI. */+function glb(image?: string): Buffer {+ const bin = Buffer.alloc(36);+ [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => bin.writeFloatLE(v, i * 4));+ const json: Record<string, unknown> = {+ asset: { version: "2.0" },+ buffers: [{ byteLength: 36 }],+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }],+ accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3", min: [0, 0, 0], max: [1, 1, 0] }],+ meshes: [{ primitives: [{ attributes: { POSITION: 0 }, ...(image && { material: 0 }) }] }],+ nodes: [{ mesh: 0 }],+ scenes: [{ nodes: [0] }],+ scene: 0,+ ...(image && { images: [{ uri: image, mimeType: "image/png" }], textures: [{ source: 0 }], materials: [{ emissiveTexture: { index: 0 }, emissiveFactor: [1, 1, 1] }] }),+ };+ let j = Buffer.from(JSON.stringify(json));+ j = Buffer.concat([j, Buffer.alloc((4 - (j.length % 4)) % 4, 0x20)]);+ const header = Buffer.alloc(12);+ header.writeUInt32LE(0x46546c67, 0);+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(12 + 8 + j.length + 8 + bin.length, 8);+ const jh = Buffer.alloc(8);+ jh.writeUInt32LE(j.length, 0);+ jh.writeUInt32LE(0x4e4f534a, 4);+ const bh = Buffer.alloc(8);+ bh.writeUInt32LE(bin.length, 0);+ bh.writeUInt32LE(0x004e4942, 4);+ return Buffer.concat([header, jh, j, bh, bin]);+}++/** A stand-in for the turntable render (no browser here): it writes a clip and a poster, and says its frames. */+function standInTurntable(): string {+ const file = path.join(tempDir("fuobe-cpu-slot-turntable-"), "turntable.mjs");+ fs.writeFileSync(+ file,+ `import fs from "node:fs";+const arg = (n) => process.argv[process.argv.indexOf("--" + n) + 1];+if (!fs.existsSync(arg("glb"))) process.exit(1);+for (let i = 1; i <= 4; i++) console.log("frame " + i + "/4");+fs.writeFileSync(arg("out"), Buffer.from(${JSON.stringify(FAKE_MP4.toString("hex"))}, "hex"));+fs.writeFileSync(arg("poster"), Buffer.from("RIFF0000WEBPVP8 poster"));+console.log(JSON.stringify({ frames: 4, fps: 24 }));+`,+ );+ return file;+}++// ---------------------------------------------------------------------------+// The worker program++interface Studio {+ reports: (Record<string, unknown> & { task: string })[];+ claims: { slot?: string }[];+}+const studio = (): Studio => ({ reports: [], claims: [] });++/** fetch for the worker: the studio's routes for SITE, its own ComfyUIs for the rest. */+function router(w: W, s: Studio) {+ const api = apiAs(routes, null);+ return async (url: string, init: RequestInit = {}) => {+ if (!String(url).startsWith(SITE)) return realFetch(url, init);+ const u = new URL(url);+ const p = u.pathname + u.search;+ if (p === "/api/gpu/computer/inventory") return Response.json({ ok: true, lanes: [LANE], workflows: ["selftest-image"], missing: [] });+ if (typeof init.body === "string" && init.body.startsWith("{")) {+ const body = JSON.parse(init.body) as Record<string, unknown>;+ const m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/report$/.exec(u.pathname);+ if (m) s.reports.push({ ...body, task: m[1] });+ if (u.pathname === "/api/gpu/computer/claim") s.claims.push(body as { slot?: string });+ }+ expect(new Headers(init.headers).get("authorization")).toBe(`Bearer ${w.token}`);+ return api(p, init);+ };+}++interface Pc {+ home: string;+ workDir: string;+ comfyDir: string;+ uploadDir: string;+ logs: string[];+}+function pc(): Pc {+ const base = tempDir("fuobe-cpu-slot-pc-");+ const p = { home: path.join(base, "home"), workDir: path.join(base, "work"), comfyDir: path.join(base, "comfy"), uploadDir: path.join(base, "uploads"), logs: [] as string[] };+ for (const d of [p.home, p.workDir, p.comfyDir]) fs.mkdirSync(d, { recursive: true });+ return p;+}++const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];+afterEach(async () => {+ for (const r of running.splice(0)) {+ r.ctrl.abort();+ await r.done.catch(() => {});+ }+});++const standIn = (o: { steps: number; stepMs: number; uploadDir?: string }) => [+ process.execPath,+ "--disable-warning=MODULE_TYPELESS_PACKAGE_JSON",+ FAKE,+ "--port",+ "{port}",+ "--cors",+ "off",+ "--steps",+ String(o.steps),+ "--step-ms",+ String(o.stepMs),+ "--worker-guard",+ "1",+ ...(o.uploadDir ? ["--upload-dir", o.uploadDir] : []),+];++/** Start `fuobe worker run` in this process with a CPU slot (`cpuSlot`), its ComfyUIs stand-in processes of their own. */+function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: number }; cpu?: { steps: number; stepMs: number }; cpuSlot?: boolean; finishers?: unknown; shrinkPreview?: (b: Blob) => Promise<Blob | null> } = {}) {+ const ctrl = new AbortController();+ const cfg = {+ site: SITE,+ token: w.token,+ comfyDir: p.comfyDir,+ workDir: p.workDir,+ modelDirs: [],+ comfyCommand: standIn({ ...(o.gpu ?? { steps: 3, stepMs: 30 }), uploadDir: p.uploadDir }),+ cpuComfyCommand: standIn({ ...(o.cpu ?? { steps: 2, stepMs: 20 }), uploadDir: p.uploadDir }),+ comfyGuard: true,+ stallMin: 10,+ ffmpeg: null,+ cpuSlot: o.cpuSlot !== false,+ };+ const done = runWorker(cfg, {+ fetch: router(w, s),+ home: p.home,+ signal: ctrl.signal,+ requirements: { folders: [], files: {}, packs: {}, workflows: {} },+ ComputerRunner,+ rules: RULES,+ pins: {},+ allowed: ALLOWED,+ readGpu: async () => null,+ readGpuGen: async () => "8.9",+ ffmpegVersion: async () => null,+ awake: { set: () => {} },+ sleep: (ms: number) => sleep(Math.min(ms, 50)),+ log: (line: string) => void p.logs.push(line),+ composer,+ catalogVersion: VERSION,+ allLanes,+ ...(o.finishers !== undefined && { finishers: o.finishers }),+ ...(o.shrinkPreview && { shrinkPreview: o.shrinkPreview }),+ });+ const r = { ctrl, done };+ running.push(r);+ return r;+}++async function until<T>(fn: () => T | Promise<T>, ms = 60_000, every = 100): Promise<Exclude<T, false | null | undefined | 0 | "">> {+ const end = Date.now() + ms;+ for (;;) {+ const v = await fn();+ if (v) return v as Exclude<T, false | null | undefined | 0 | "">;+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);+ await sleep(every);+ }+}+const ENDED = ["done", "failed", "canceled"];+const ended = (id: string) => until(() => ENDED.includes(row(id).state) && row(id), 90_000);++describe("the worker program's CPU slot", () => {+ it("runs a CPU task while its GPU's job runs, each claimed for its own slot", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gpu = ownerTask(GPU_WORKFLOW);+ const cpu = ownerTask(CPU_WORKFLOW);+ expect(row(cpu.id).slot).toBe("cpu");+ expect(row(gpu.id).slot).toBeNull();+ // A slow GPU job (about 4 s) and a quick CPU task.+ start(w, s, p, { gpu: { steps: 40, stepMs: 100 } });+ const cpuDone = await ended(cpu.id);+ expect(cpuDone.state, cpuDone.error ?? "").toBe("done");+ // The GPU's job was still going when the CPU task ended.+ expect(["sending", "queued", "running", "collecting"]).toContain(row(gpu.id).state);+ expect(cpuDone.device).toBe(`wkr-${w.id}-cpu`);+ const gpuDone = await ended(gpu.id);+ expect(gpuDone.state, gpuDone.error ?? "").toBe("done");+ expect(gpuDone.device).toBe(`wkr-${w.id}`);+ expect(fs.readFileSync(tasks.outputFile(cpu.id, 0)).length).toBeGreaterThan(0);+ expect(s.claims.some((c) => c.slot === "cpu")).toBe(true);+ // The studio heard its CPU slot in its beat.+ expect(JSON.parse(db().prepare("SELECT cpu_slot_json FROM relay_workers WHERE id = ?").pluck().get(w.id) as string)).toHaveProperty("finishes");+ });++ it("without a CPU slot, it takes light CPU work in its GPU's slot, as before", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const cpu = ownerTask(CPU_WORKFLOW);+ start(w, s, p, { cpuSlot: false });+ const t = await ended(cpu.id);+ expect(t.state, t.error ?? "").toBe("done");+ expect(t.device).toBe(`wkr-${w.id}`);+ expect(s.claims.some((c) => c.slot === "cpu")).toBe(false);+ });+});++describe("the 3D finish on the worker", () => {+ it("refuses a GLB that names an outside file, and never reads it; the run keeps its model as it is", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: glb("../secret-marker.png"), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ let finished: unknown[] | null = null;+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });+ const id = finish.finishTask(gid, "model3d")!.id;+ start(w, s, p);+ const t = await ended(id);+ expect(t.state).toBe("failed");+ expect(t.error).toBe("tab:unsafe-model");+ expect(s.reports).toContainEqual(expect.objectContaining({ task: id, event: "failed", reason: "unsafe-model" }));+ const kept = await until(() => finished, 30_000);+ expect(kept).toHaveLength(1);+ expect((kept[0] as { meta: { finish: { error: string }; web?: string } }).meta.finish.error).toMatch(/self-contained/);+ expect((kept[0] as { meta: { web?: string } }).meta.web).toBeUndefined();+ // Nothing of the job stays in the CPU slot's folder.+ expect(fs.existsSync(path.join(p.workDir, "cpu", "finish"))).toBe(false);+ });++ it("sends back the web GLB with its turntable and poster, and the run stores them", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: glb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ let finished: import("@/lib/catalog/types").OutputFile[] | null = null;+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });+ const id = finish.finishTask(gid, "model3d")!.id;+ const made = finishers({ workDir: path.join(p.workDir, "cpu"), ffmpeg: null, scripts: { turntable: standInTurntable() } });+ expect(made.kinds).toContain("model3d");+ start(w, s, p, { finishers: made });+ const t = await ended(id);+ expect(t.state, t.error ?? "").toBe("done");+ const got = await until(() => finished, 30_000);+ const mesh = got.find((o) => o.kind === "model3d")!;+ const meta = mesh.meta as { web: string; poster: string; finish: { turntable: string; webAsset: string; triangles: number } };+ expect(meta.finish.turntable).toBe("done");+ expect(meta.finish.triangles).toBe(1);+ expect(meta.web).toBeTruthy();+ expect(meta.poster).toBeTruthy();+ // The web GLB is a binary glTF the worker wrote; the turntable is the clip it rendered.+ const web = getAsset(meta.finish.webAsset)!;+ expect(fs.readFileSync(absolutePath(web.relPath)).subarray(0, 4).toString()).toBe("glTF");+ const clip = got.find((o) => o.kind === "video" && o.meta?.role === "turntable")!;+ expect(fs.readFileSync(absolutePath(getAsset(clip.assetId!)!.relPath)).equals(FAKE_MP4)).toBe(true);+ // Stored as the account's files.+ expect(db().prepare("SELECT account_id FROM assets WHERE id = ?").pluck().get(clip.assetId)).toBe(accountId);+ });++ it("a turntable that didn't come back leaves the account's words on the model, never the worker's", async () => {+ const { ACCOUNT_TURNTABLE } = await import("@/server/model3d-finish");+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: glb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ let finished: import("@/lib/catalog/types").OutputFile[] | null = null;+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: (o) => void (finished = o) });+ const id = finish.finishTask(gid, "model3d")!.id;+ // A turntable render that fails, naming things of its PC.+ const failing = path.join(tempDir("fuobe-cpu-slot-turntable-"), "turntable.mjs");+ fs.writeFileSync(failing, 'console.error("no browser at C:/Users/someone-private/browsers/chrome.exe"); process.exit(1);');+ start(w, s, p, { finishers: finishers({ workDir: path.join(p.workDir, "cpu"), ffmpeg: null, scripts: { turntable: failing } }) });+ const t = await ended(id);+ expect(t.state, t.error ?? "").toBe("done");+ const got = await until(() => finished, 30_000);+ const mesh = got.find((o) => o.kind === "model3d")!;+ const meta = mesh.meta as { web?: string; finish: { turntable: string } };+ expect(meta.web).toBeTruthy();+ expect(meta.finish.turntable).toBe(ACCOUNT_TURNTABLE);+ expect(JSON.stringify(got)).not.toMatch(/someone-private|chrome|browsers/);+ });++ it("a finish its run no longer wants stops on the worker while it runs: the run was deleted", async () => {+ const { deleteGeneration } = await import("@/server/generations");+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId, "image-to-3d");+ const raw = saveFile({ data: glb(), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: () => {} });+ const id = finish.finishTask(gid, "model3d")!.id;+ // A finish that goes on until it is told to stop, saying how far it got now and then.+ let started = false;+ let stopped = false;+ const slow = {+ kinds: ["model3d"],+ finish: async (_t: unknown, _inputs: unknown, o: { signal: AbortSignal; progress: (f: number) => void }) => {+ started = true;+ for (let i = 0; i < 600 && !o.signal.aborted; i++) {+ o.progress(i / 600);+ await sleep(100);+ }+ stopped = o.signal.aborted;+ return { refused: "finish-failed" };+ },+ };+ start(w, s, p, { finishers: slow });+ await until(() => started, 30_000);+ expect(row(id).state).toBe("running");+ deleteGeneration(gid);+ expect(row(id).state).toBe("canceled");+ // Its next progress report hears the stop, and the finish's processes are stopped at once.+ await until(() => stopped, 15_000);+ await sleep(500);+ expect(s.reports.filter((r) => r.task === id && ["finished", "failed"].includes(String(r.event)))).toEqual([]);+ });++ it("the studio keeps an account's 3D model from the workers only as a binary glTF with every part inside it", async () => {+ const { outputType } = await import("@/server/computer/http");+ const want = { n: 0, filename: "m.glb", subfolder: "", type: "output" as const, kind: "model3d" as const, maxBytes: 1e6 };+ expect(finish.glbSelfContained(glb())).toBe(true);+ expect(finish.glbSelfContained(glb(`data:image/png;base64,${FAKE_PNG.toString("base64")}`))).toBe(true);+ for (const uri of ["../secret.png", "file:///etc/passwd", "https://example.com/x.png", "C:\\x.png"]) expect(finish.glbSelfContained(glb(uri)), uri).toBe(false);+ const ply = Buffer.from("ply\nformat ascii 1.0\n");+ expect(finish.glbSelfContained(ply)).toBe(false);+ const file = path.join(tempDir("fuobe-cpu-slot-glb-"), "m.glb");+ fs.writeFileSync(file, glb("../secret.png"));+ expect(finish.glbFileSelfContained(file)).toBe(false);+ fs.writeFileSync(file, glb());+ expect(finish.glbFileSelfContained(file)).toBe(true);+ // An account's run: a glTF only when its 3D finish runs on a worker, and never a PLY.+ expect(() => outputType(glb(), want, false)).toThrow(/3D model/);+ expect(outputType(glb(), want, false, { glb: true })).toBe("model/gltf-binary");+ expect(() => outputType(ply, want, false, { glb: true })).toThrow(/3D model/);+ expect(outputType(ply, want, true)).toBe("model/ply");+ });++ it("with a worker that finishes 3D models, an account's Image to 3D run on this install's GPUs is taken", () => {+ const photo = saveFile({ data: FAKE_PNG, contentType: "image/png", source: "upload", accountId }).url;+ const request = { feature: "image-to-3d", modelId: "oss-pixal3d", op: "image-to-3d", prompt: "", inputs: { images: [photo] }, engine: "open" } as Parameters<typeof createGenerations>[0];+ const onPool = () => asAccount(accountId, () => withRunStamp({ place: "pool" }, () => createGenerations(request)));+ expect(onPool).toThrow();+ const w = addWorker();+ pool.workerBeat(+ db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: VERSION, cpuSlot: { finishes: ["model3d"] } }),+ );+ const made = onPool();+ expect(made[0].kind).toBe("model3d");+ expect(JSON.parse(db().prepare("SELECT request_json FROM generations WHERE id = ?").pluck().get(made[0].id) as string).place).toBe("pool");+ });+});++describe("camera paths on the worker", () => {+ /** The worker's built parts the path render reads (camera-path, path-splat and scene3d), in a folder of their own. */+ function builtParts(): string {+ const out = tempDir("fuobe-cpu-slot-dist-");+ const files = workerFiles().files as unknown as Record<string, string>;+ for (const f of ["camera-path.mjs", "path-splat.mjs", "scene3d.mjs"]) fs.writeFileSync(path.join(out, f), files[f]);+ return out;+ }++ it.runIf(hasFfmpeg)("draws a step's camera path on the worker's CPU slot, and the run keeps the clip once", async () => {+ const sharp = (await import("sharp")).default;+ const photo = saveFile({ data: await sharp({ create: { width: 64, height: 48, channels: 3, background: "#36c" } }).png().toBuffer(), contentType: "image/png", name: "still.png", source: "upload", accountId });+ const depth = saveFile({ data: await sharp({ create: { width: 64, height: 48, channels: 3, background: "#808080" } }).png().toBuffer(), contentType: "image/png", name: "depth.png", source: "derived", accountId });+ const gid = generation(accountId, "image-to-video");+ const keys = [+ { t: 0, azimuth: 0, elevation: 0, distance: 1 },+ { t: 1, azimuth: 20, elevation: 4, distance: 0.8 },+ ];+ const step = () => runAsTenant({ kind: "account", id: accountId }, () => finish.pathOnWorker(gid, 0, { photo: photo.url, depth: depth.url, keys, frames: 9, fps: 16 }));+ expect(await step()).toEqual({ state: "waiting" });+ // Asked again before it is done: the same job, still waiting.+ expect(await step()).toEqual({ state: "waiting" });+ const id = finish.finishTask(gid, "path")!.id;+ expect(db().prepare("SELECT COUNT(*) FROM relay_tasks WHERE generation_id = ?").pluck().get(gid)).toBe(1);+ const w = addWorker();+ const s = studio();+ const p = pc();+ const made = finishers({ workDir: path.join(p.workDir, "cpu"), ffmpeg: "ffmpeg", distDir: builtParts() });+ expect(made.kinds).toContain("path");+ start(w, s, p, { finishers: made });+ const t = await ended(id);+ expect(t.state, t.error ?? "").toBe("done");+ const got = await step();+ expect(got.state).toBe("done");+ const url = (got as { url: string }).url;+ const clip = (db().prepare("SELECT id FROM assets WHERE generation_id = ? AND name = 'path-render.mp4'").all(gid) as { id: string }[]).map((r) => getAsset(r.id)!);+ expect(clip).toHaveLength(1);+ expect(clip[0].url).toBe(url);+ expect(fs.readFileSync(absolutePath(clip[0].relPath)).subarray(4, 8).toString()).toBe("ftyp");+ // Kept once: asked again, the same clip.+ expect(await step()).toEqual({ state: "done", url });+ expect(db().prepare("SELECT COUNT(*) FROM assets WHERE generation_id = ? AND name = 'path-render.mp4'").pluck().get(gid)).toBe(1);+ });+});++describe("an account's pictures on the worker", () => {+ it("a picture with EXIF reaches its ComfyUI made again from its pixels, with no EXIF", async () => {+ const sharp = (await import("sharp")).default;+ const jpeg = await sharp({ create: { width: 64, height: 48, channels: 3, background: "#c33" } })+ .jpeg()+ .withExif({ IFD0: { Copyright: "private note", Artist: "someone" } })+ .toBuffer();+ expect((await sharp(jpeg).metadata()).exif).toBeDefined();+ const w = addWorker();+ const s = studio();+ const p = pc();+ const gid = generation(accountId);+ const route = { provider: "comfyui", endpoint: "selftest-image", op: "edit" } as never;+ const { picture, sent } = await hosted.runOnPool(accountId, async () => {+ const name = (await comfyProvider.prepareFile!(jpeg, "image/jpeg", "me.jpg", route))!;+ return { picture: name, sent: await comfyProvider.submit({ route, input: { images: [name], seed: 5 }, generationId: gid, model: getModel("oss-selftest-image") } as never) };+ });+ const id = String((sent.meta as { relay: string }).relay);+ // The studio keeps it undecoded, its EXIF blanked.+ const kept = fs.readFileSync(path.join(dir, "relay", "in", picture));+ expect(kept.length).toBe(jpeg.length);+ expect(kept.includes(Buffer.from("private note"))).toBe(false);+ start(w, s, p);+ const t = await ended(id);+ expect(t.state, t.error ?? "").toBe("done");+ const reached = fs.readFileSync(path.join(p.uploadDir, picture));+ const meta = await sharp(reached).metadata();+ expect(meta.format).toBe("png");+ expect(meta.exif).toBeUndefined();+ expect([meta.width, meta.height]).toEqual([64, 48]);+ expect(reached.includes(Buffer.from("private note"))).toBe(false);+ });+});++describe("live previews from the worker", () => {+ const jpeg = (bytes: number) => {+ const b = Buffer.alloc(bytes, 7);+ b[0] = 0xff;+ b[1] = 0xd8;+ b[2] = 0xff;+ return b;+ };+ const previews = (s: Studio, id: string) => s.reports.filter((r) => r.task === id && r.event === "running" && typeof r.preview === "string");++ /** A run's preview picture as the studio keeps it (a file in its task's folder), or null. */++ const keptPreview = (id: string): Buffer | null => {++ const t = tasks.taskById(id);++ const p = t?.preview_at ? tasks.runPreview(t.generation_id) : null;++ return p ? fs.readFileSync(p.path) : null;++ };++ it("sends its ComfyUI's preview as a small JPEG, at most one every 2 s, and the studio keeps it", async () => {++ // A preview picture shows only with hosted runs on (without them, a run shows what it showed before).++ process.env.FUOBE_HOSTED_RUNS = "1";++ onTestFinished(() => {++ delete process.env.FUOBE_HOSTED_RUNS;++ });+ const w = addWorker();+ const s = studio();+ const p = pc();+ const t = ownerTask(GPU_WORKFLOW, { preview: true });+ const small = jpeg(20_000);+ const asked: string[] = [];+ // Its ComfyUI's previews are PNGs: the worker makes each one again as a JPEG.+ start(w, s, p, { gpu: { steps: 12, stepMs: 400 }, shrinkPreview: async (b) => (asked.push(b.type), new Blob([small], { type: "image/jpeg" })) });- const got = await until(() => tasks.taskPreview(t.id), 30_000);- expect(got.jpeg.equals(small)).toBe(true);++ const got = await until(() => keptPreview(t.id), 30_000);++ expect(got.equals(small)).toBe(true);+ expect(asked[0]).toBe("image/png");+ expect((await ended(t.id)).state).toBe("done");+ const sent = previews(s, t.id);+ expect(sent.length).toBeGreaterThan(0);+ // At most one every 2 s: a 5 s job sends at most 3.+ expect(sent.length).toBeLessThanOrEqual(3);+ });++ it("drops a preview over 64 KB, keeping the progress", async () => {++ process.env.FUOBE_HOSTED_RUNS = "1";++ onTestFinished(() => {++ delete process.env.FUOBE_HOSTED_RUNS;++ });+ const w = addWorker();+ const s = studio();+ const p = pc();+ const t = ownerTask(GPU_WORKFLOW, { preview: true });+ start(w, s, p, { gpu: { steps: 8, stepMs: 400 }, shrinkPreview: async () => new Blob([jpeg(70 * 1024)], { type: "image/jpeg" }) });+ expect((await ended(t.id)).state).toBe("done");+ expect(previews(s, t.id)).toEqual([]);+ expect(s.reports.some((r) => r.task === t.id && r.event === "running")).toBe(true);- expect(tasks.taskPreview(t.id)).toBeNull();++ expect(keptPreview(t.id)).toBeNull();+ });++ it("sends none for a run that doesn't ask for previews", async () => {+ const w = addWorker();+ const s = studio();+ const p = pc();+ const t = ownerTask(GPU_WORKFLOW);+ let asked = 0;+ start(w, s, p, { gpu: { steps: 8, stepMs: 300 }, shrinkPreview: async () => (asked++, new Blob([jpeg(1000)], { type: "image/jpeg" })) });+ expect((await ended(t.id)).state).toBe("done");+ expect(previews(s, t.id)).toEqual([]);+ expect(asked).toBe(0);+ });++ it.runIf(hasFfmpeg)("ffmpeg makes a PNG preview again as a JPEG under 64 KB, and nothing of it stays", async () => {+ const sharp = (await import("sharp")).default;+ const png = await sharp({ create: { width: 1024, height: 768, channels: 3, background: "#a5c" } }).png().toBuffer();+ const dir2 = tempDir("fuobe-cpu-slot-preview-");+ const shrink = previewShrinker({ ffmpeg: "ffmpeg", dir: dir2 });+ const out = (await shrink(new Blob([png], { type: "image/png" })))!;+ expect(out.type).toBe("image/jpeg");+ expect(out.size).toBeLessThanOrEqual(PREVIEW_MAX_BYTES);+ const meta = await sharp(Buffer.from(await out.arrayBuffer())).metadata();+ expect(meta.format).toBe("jpeg");+ expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(512);+ expect(fs.readdirSync(dir2)).toEqual([]);+ // Not a picture: nothing.+ expect(await shrink(new Blob([Buffer.from("<html>")], { type: "image/png" }))).toBeNull();+ expect(await previewShrinker({ ffmpeg: null, dir: dir2 })(new Blob([png]))).toBeNull();+ });++ it("ffmpeg makes a preview again only from a local PNG or JPEG, at most 512 pixels, with no metadata", () => {+ const a = previewArgs("in.png", "out.jpg");+ expect(a.slice(a.indexOf("-protocol_whitelist"), a.indexOf("-protocol_whitelist") + 2)).toEqual(["-protocol_whitelist", "file"]);+ expect(a[a.indexOf("-vf") + 1]).toMatch(/min\(512,iw\).*min\(512,ih\)/);+ expect(a).toEqual(expect.arrayContaining(["-map_metadata", "-1", "-frames:v", "1"]));+ expect(a[a.length - 1]).toBe("out.jpg");+ });+});diff --cc tests/worker-parts.test.tsindex f558deef,bbd49c7c..9b16f623--- a/tests/worker-parts.test.ts+++ b/tests/worker-parts.test.ts@@@ -18,6 -18,10 +18,8 @@@ import { onSignals, STOP_SIGNALS } froimport { tempDir } from "./helpers/temp-dir";const hasFfmpeg = spawnSync("ffmpeg", ["-hide_banner", "-version"]).status === 0;-/** A check that starts the real ffmpeg (several times, for a preview): time for a busy machine running other tests too. */++/** A check that starts the real ffmpeg: time for a busy machine running other tests too. */+ const FFMPEG_MS = 60_000;-/** Each of a preview's tries, on a busy machine (ffmpeg runs at low priority): the check waits for every try. */-const PREVIEW_TRY_MS = 30_000;/** A clock that moves only when the policy sleeps. */function clock() {