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
Queue: owner controls for who the GPUs serve first
Adarsh87a3c1131b34
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex e07d190d..29638f37 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -43,7 +43,7 @@ import { LogRing } from "./log-ring.mjs";import { failure, Reach, retrying } from "./retry.mjs";import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";-import { SiteTurns, writeSite } from "./turns.mjs";+import { readLocalWork, SiteTurns, writeMode, writeSite } from "./turns.mjs";import { CodeWatch, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";const here = path.dirname(fileURLToPath(import.meta.url));@@ -353,6 +353,9 @@ async function work(saved, deps, owner) {let siteWritten = "";let siteAt = 0;let siteFailed = false;+ // The owner's mode as last written to the turns folder and said in the log.+ let modeFailed = false;+ let modeSaid = null;const writeTurn = (t, body) => {const key = JSON.stringify([body.siteWaiting, body.interruptAt]);siteWritten = key;@@ -673,6 +676,8 @@ async function work(saved, deps, owner) {...(cpuOn && { cpuSlot: { finishes: finish.kinds }, cpuRunning: cpuRunner ? runningOf(cpuRunner) : [] }),// Why the line's work waits on it now (the owner's queue view shows it); older studios ignore it....(holding && { holding }),+ // Local work on its PC, as the helper there wrote it to the turns folder (counts and codes only).+ ...(turns && { localWork: readLocalWork(cfg.yieldFolder, now()) }),};},onBeat: (a) => {@@ -690,6 +695,21 @@ async function work(saved, deps, owner) {if (typeof theirs === "string") studioCatalog = theirs;answer = a;takeToken(a?.worker?.token);+ // The owner's mode (who goes first), for the helper on the PC's side: mode.json in the turns folder.+ if (turns && a?.worker?.queue && turns.folderOk()) {+ try {+ writeMode(cfg.yieldFolder, a.worker.queue, now());+ modeFailed = false;+ } catch (e) {+ if (!modeFailed) log(`Couldn't write the owner's mode to the turns folder: ${e.message}`);+ modeFailed = true;+ }+ }+ const q = a?.worker?.queue;+ if (q && typeof q.mode === "string" && q.mode !== modeSaid) {+ if (modeSaid !== null || q.mode !== "people-first") log(`The owner set who goes first: ${q.mode}${typeof q.until === "number" ? ` until ${new Date(q.until).toISOString().slice(11, 16)} UTC` : ""}.`);+ modeSaid = q.mode;+ }// A token from the environment with a lifetime: said once for each end date, so it is replaced there in time.const ends = Number(a?.worker?.tokenExpiresAt);if (envToken && Number.isFinite(ends) && ends > 0 && ends !== endWarned) {diff --git a/bin/lib/worker/turns.mjs b/bin/lib/worker/turns.mjsindex e67ba849..3a9bb4d7 100644--- a/bin/lib/worker/turns.mjs+++ b/bin/lib/worker/turns.mjs@@ -52,6 +52,48 @@ export function writeSite(folder, body) {fs.renameSync(tmp, p);}+/**+ * mode.json, written whole on each beat answer that carries the owner's mode (the beat's `worker.queue`):+ * { mode, localWork, until, at }. localWork tells the helper what local work does now: "yield" (make room for the+ * studio's jobs, as site.json asks), "pause" (start nothing new: the owner chose people only) or "run" (keep the GPU: the+ * owner chose their own work first). A helper counts a file older than its own limit as gone, and then does as before.+ */+export function writeMode(folder, q, t) {+ const modes = ["people-first", "people-only", "ours-first", "balanced"];+ const rules = ["yield", "pause", "run"];+ if (!q || typeof q !== "object" || !modes.includes(q.mode) || !rules.includes(q.localWork)) return false;+ const p = path.join(folder, "mode.json");+ const tmp = `${p}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify({ mode: q.mode, localWork: q.localWork, until: finite(q.until) ? q.until : null, at: t })}\n`);+ fs.renameSync(tmp, p);+ return true;+}++/** local.json counts while it is at most this old. */+export const LOCAL_FRESH_MS = 2 * 60_000;++/**+ * local.json, which the helper on the PC's side may write: { state, why, waiting, running, at } about local work (its+ * own queue). Passed on in the beat (`localWork`) as plain counts and short codes only; null when there is none, it is+ * too big, not fresh, or not one.+ */+export function readLocalWork(folder, t) {+ try {+ const p = path.join(folder, "local.json");+ const st = fs.lstatSync(p);+ if (!st.isFile() || st.size > 4096) return null;+ const o = JSON.parse(fs.readFileSync(p, "utf8"));+ if (!o || typeof o !== "object" || !finite(o.at) || t - o.at > LOCAL_FRESH_MS || o.at > t + 60_000) return null;+ const states = ["running", "idle", "paused", "yielding", "stopped"];+ if (!states.includes(o.state)) return null;+ const why = typeof o.why === "string" && /^[a-z0-9][a-z0-9:-]{0,47}$/.test(o.why) ? o.why : null;+ const waiting = finite(o.waiting) && o.waiting >= 0 ? Math.min(Math.floor(o.waiting), 1_000_000) : null;+ return { state: o.state, why, waiting, running: o.running === true, at: Math.min(o.at, t) };+ } catch {+ return null;+ }+}+/** The local day (a cap counts per day on this PC's clock). */const dayOf = (t) => {const d = new Date(t);diff --git a/docs/admin-api.md b/docs/admin-api.mdindex a739886f..8f5c9ea6 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -46,8 +46,9 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs`, `GET /api/admin/workers/events` || `workers:write` | `PATCH /api/admin/workers/{id}`: pause, resume, drain, hours, lanes, revoke || `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those |-| `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings` |+| `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings`, `GET /api/admin/queue/overrides` || `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget (`pausedBudgetS`: how long a run that has started may spend back in line) |+| `queue:control` | `POST /api/admin/queue/mode`, `POST /api/admin/queue/overrides`, `DELETE /api/admin/queue/overrides/{id}`, `POST /api/admin/queue/cancel`: who the GPUs serve first, runs and people sent first or held, and cancelling a run ([gpu-workers.md](gpu-workers.md#who-goes-first)) || `site:read` | `GET /api/admin/site/uploads` || `site:write` | `PATCH /api/admin/site/uploads`: the upload switches || `audit:read` | `GET /api/admin/audit` |@@ -112,7 +113,12 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `POST /api/admin/outputs/remove` | the same, and `evidence?: true` to keep the files in a locked folder | `{ removed }` || `GET /api/admin/files/{path}` | `Range` works | the file; 404 for the owner's own files (held or not) and unknown paths || `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |-| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, now }` ([gpu-workers.md](gpu-workers.md#the-queue)) |+| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, controls, now }`. `queued` is in the order the workers serve it, each with `rank` (null while no worker takes it), `why`, `code` (`class`, `next`, `boost`, `held`, `pinned`, `paused`), `override` and `person` (a key, never an account id). `controls`: `{ pools, workers, overrides, ended, modes }` ([gpu-workers.md](gpu-workers.md#the-queue)) |+| `POST /api/admin/queue/mode` | `{ pool?, worker?, mode, forMin? }`: `mode` is `people-first`, `people-only`, `ours-first`, `balanced`, or `null` (back to normal); `forMin` is 1 to 10080, or `null` (until switched back) | `{ mode, before }`; 400 for a value out of bounds, 404 for no such worker |+| `GET /api/admin/queue/overrides` | | `{ live, ended }` (the last 20 that ended) |+| `POST /api/admin/queue/overrides` | `{ kind: "run", generationId, action: "next" | "hold", worker?, forMin? }` or `{ kind: "person", person | account, action: "boost" | "hold", forMin }` (`forMin` is needed for a boost) | 201 `{ override, replaced }`; 404 for no such run, worker or person with a run on the GPUs; 409 for a run that ended |+| `DELETE /api/admin/queue/overrides/{id}` | | `{ override }` (ended now); 404 when it isn't in effect |+| `POST /api/admin/queue/cancel` | `{ generationId }` | `{ generationId, status }`: the run ends as the person's own Cancel ends it; 404 for no such run, 409 for one that ended || `GET /api/admin/queue/settings` | | `{ settings: { runCeilingS: { default, lanes }, ownerWaitLimitS, fairShare, pickAllowanceMs, pausedBudgetS } }` ([gpu-workers.md](gpu-workers.md#the-queue)) || `PATCH /api/admin/queue/settings` | any of `runCeilingS: { default, lanes? }` (seconds, 60 to 86400; a given `runCeilingS` replaces the default and every lane's value), `ownerWaitLimitS` (seconds, 60 to 604800, or `null` for no limit), `fairShare` (boolean), `pickAllowanceMs` (0 to 3600000), `pausedBudgetS` (seconds, 0 to 604800) | `{ settings }`; 400 with the reason for a value out of bounds, an unknown setting or an unknown lane || `GET /api/admin/site/uploads` | | `{ switches: { soundConvert, soundTrim, videoTrim, photoConvert, photoCrop } }`: what a browser may do to a file that doesn't fit a tool before it is uploaded (convert a sound to MP3, offer a part of a sound or clip, convert or shrink a photo, offer a crop). All `true` by default. Every visitor reads the same values at `GET /api/site/uploads` |@@ -129,7 +135,8 @@ A log row is `{ id, at, actor: "owner" | "token" | "system", token: { id, name }`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`,`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,`worker.rotate`, `worker.revoke`, `worker.revoke_all` (Sign everyone out with every API token), `queue.settings` (with-the values before and after), `site.uploads` (the upload switches, with the values before and after), `token.create`, `token.revoke`,+the values before and after), `queue.mode`, `queue.override`, `queue.override.end`, `queue.cancel`, `queue.mode.end`+(actor `system` when a mode, a hold or a boost ended by itself), `site.uploads` (the upload switches, with the values before and after), `token.create`, `token.revoke`,`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, with the values before and after); a token's reads`accounts.list`, `accounts.csv`, `account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and actionevery 10 minutes); reads of accounts' content by a token or the owner: `runs.content` (one row per reader and accountdiff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 7a41e8a3..23d0ef63 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -482,6 +482,47 @@ in words: "Took a … run", "Sent back in line: went silent", "Delivered after 4`log` (its own log lines, from its beat). Log lines are kept 7 days, the rest 30 days. The owner reads it at`GET /api/admin/workers/events` ([admin-api.md](admin-api.md)).+### Who goes first++The owner can change who the workers serve first, through the admin API ([admin-api.md](admin-api.md), scope+`queue:control`). Every change is in the admin log with who made it. Every change has an end: a time, the end of the+run it is for, or "back to normal". Workers follow a change at their next claim and beat. A held run is never refused+or hidden: it keeps its place in line and starts after the hold ends.++**The mode.** A pool has a mode, and one worker can have its own mode that wins over its pool's mode until it ends:++| Mode | Order on the workers | Local work on the worker's PC |+| --- | --- | --- |+| `people-first` (the default) | paid runs, free runs, then the owner's own jobs | makes room for people's runs (studio jobs first) |+| `people-only` | people's runs only; the owner's own jobs wait | starts nothing new |+| `ours-first` | the owner's own jobs, then paid runs, then free runs | keeps the GPU while it runs; people's runs start when it is idle |+| `balanced` | paid runs, then free runs and the owner's own jobs together, by when they came | makes room for people's runs |++A mode lasts 1 minute to a week (`forMin`), or until the owner switches it back. A mode past its end is gone at the next+beat, and the admin log gets a `queue.mode.end` row (actor `system`). In `ours-first`, the beat's `claimableNow` counts+people's runs only when local work on the PC doesn't run (its last `localWork`), or when the owner sent the run next or+boosted the person. So the worker asks local work for no room for them.++**A run.** "Run next" sends one run to the front of every worker's line, or to the front of one worker's line+(`worker`: that worker only, no other takes it). It ends when the run ends, or after a day at most. "Hold" keeps the+run in its place, and no worker takes it until the hold ends. Every step that the same press of Run made gets the same+override.++**A person.** "Boost" sends an account's runs (or the guests' runs) to the front, after the runs sent next, for 1 minute+to a week. "Hold" keeps them in place until the hold ends. A run's own override wins over its person's override. The+queue view names a person by a key (`p-` and 12 hex digits), never by an account id.++The order in one look at the line: runs sent next, then boosted people's runs, then the mode's classes, each group in+its own order (fair share included). A person's place in line (`placeInLine`, the billing service's line facts) reads+the same order, with the pool's mode.++**The turns folder.** A worker with a turns folder writes the mode from each beat answer (`worker.queue`) to+`mode.json` there: `{ mode, localWork, until, at }`, where `localWork` is `yield`, `pause` or `run`. The helper on the+PC's side reads it. The helper can write `local.json`: `{ state, why, waiting, running, at }`, where `state` is+`running`, `idle`, `paused`, `yielding` or `stopped`, `why` is a short code and `waiting` is a count. The worker sends+it in its beat as `localWork` while it is at most 2 minutes old. The studio keeps known values only, and the Workers+and Queue views show it. No connection ever goes to the PC: the PC reads and writes files in its own folder.+### Job tickets and the PC's ceilingAn account's run reaches a worker as a job ticket, never as a graph. The ticket names a workflow of the catalog, thediff --git a/src/app/api/admin/queue/cancel/route.ts b/src/app/api/admin/queue/cancel/route.tsnew file mode 100644index 00000000..4026a6ba--- /dev/null+++ b/src/app/api/admin/queue/cancel/route.ts@@ -0,0 +1,34 @@+import { adminAccess, audit } from "@/server/admin-tokens";+import { runRows } from "@/server/computer/queue-controls";+import { cancelGeneration, getGeneration } from "@/server/generations";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * Cancel a run that waits or runs on the GPUs (owner only, or an admin token with queue:control): `{ generationId }`. It+ * ends as the person's own Cancel ends it (its hold is released by the same rules, and steps that only fed it are+ * dropped). 404 for no such run, 409 for one that ended already.+ */+export async function POST(request: Request) {+ const access = adminAccess(request, "queue:control", "Only the studio's owner changes the queue");+ if (access instanceof Response) return access;+ const body = (await request.json().catch(() => null)) as { generationId?: unknown } | null;+ const id = body && typeof body === "object" && typeof body.generationId === "string" && /^[\w-]{1,80}$/.test(body.generationId) ? body.generationId : null;+ if (!id) {+ audit(access.actor, "queue.cancel", null, null, 400);+ return Response.json({ error: "generationId is a run's id" }, { status: 400, headers: NO_STORE });+ }+ const run = runRows(id);+ if (!run) {+ audit(access.actor, "queue.cancel", id, null, 404);+ return Response.json({ error: "No such run" }, { status: 404, headers: NO_STORE });+ }+ if (run.status !== "queued" && run.status !== "running") {+ audit(access.actor, "queue.cancel", id, { status: run.status }, 409);+ return Response.json({ error: "That run has ended" }, { status: 409, headers: NO_STORE });+ }+ await cancelGeneration(id);+ const after = getGeneration(id, { includeDeleted: true });+ audit(access.actor, "queue.cancel", id, { account: run.account, status: after?.status ?? null }, 200);+ return Response.json({ generationId: id, status: after?.status ?? null }, { headers: NO_STORE });+}diff --git a/src/app/api/admin/queue/mode/route.ts b/src/app/api/admin/queue/mode/route.tsnew file mode 100644index 00000000..f4eba03f--- /dev/null+++ b/src/app/api/admin/queue/mode/route.ts@@ -0,0 +1,31 @@+import { adminAccess, audit } from "@/server/admin-tokens";+import { applyModeChange, checkModeChange } from "@/server/computer/queue-controls";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * Who the GPUs serve first (owner only, or an admin token with queue:control): `{ pool?: "pool", worker?: id, mode,+ * forMin? }`, mode one of people-first, people-only, ours-first, balanced, or null for back to normal (the pool to people+ * first, a worker to its pool's mode). forMin: 1 to 10080 minutes, or null for until it is switched back. Workers follow+ * it from their next claim and beat. Each change is in the admin log with the mode before and after.+ */+export async function POST(request: Request) {+ const access = adminAccess(request, "queue:control", "Only the studio's owner changes the queue");+ if (access instanceof Response) return access;+ const by = access.actor.kind === "token" ? access.actor.name : "owner";+ const body = (await request.json().catch(() => null)) as unknown;+ const now = Date.now();+ const c = checkModeChange(body, by, now);+ if ("error" in c) {+ audit(access.actor, "queue.mode", null, null, 400, now);+ return Response.json({ error: c.error }, { status: 400, headers: NO_STORE });+ }+ const target = c.scope === "pool" ? `pool:${c.pool}` : `worker:${c.worker}`;+ const r = applyModeChange(c, now);+ if (!r) {+ audit(access.actor, "queue.mode", target, null, 404, now);+ return Response.json({ error: "No such worker" }, { status: 404, headers: NO_STORE });+ }+ audit(access.actor, "queue.mode", target, { before: r.before.mode, after: r.after.mode, from: r.after.from, until: r.after.until }, 200, now);+ return Response.json({ mode: r.after, before: r.before }, { headers: NO_STORE });+}diff --git a/src/app/api/admin/queue/overrides/[id]/route.ts b/src/app/api/admin/queue/overrides/[id]/route.tsnew file mode 100644index 00000000..4cdb2d46--- /dev/null+++ b/src/app/api/admin/queue/overrides/[id]/route.ts@@ -0,0 +1,17 @@+import { adminAccess, audit } from "@/server/admin-tokens";+import { endOverride, overrideView } from "@/server/computer/queue-controls";++const NO_STORE = { "Cache-Control": "no-store" };++/** Back to normal for one run or person (owner only, or an admin token with queue:control): the override ends now. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/queue/overrides/[id]">) {+ const access = adminAccess(request, "queue:control", "Only the studio's owner changes the queue");+ if (access instanceof Response) return access;+ const by = access.actor.kind === "token" ? access.actor.name : "owner";+ const { id } = await ctx.params;+ if (!/^[0-9a-f]{12}$/.test(id)) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });+ const ended = endOverride(id, by, "released");+ audit(access.actor, "queue.override.end", ended?.target ?? id, ended ? { id, kind: ended.kind, action: ended.action, why: "released" } : null, ended ? 200 : 404);+ if (!ended) return Response.json({ error: "No such override in effect" }, { status: 404, headers: NO_STORE });+ return Response.json({ override: overrideView(ended) }, { headers: NO_STORE });+}diff --git a/src/app/api/admin/queue/overrides/route.ts b/src/app/api/admin/queue/overrides/route.tsnew file mode 100644index 00000000..3373ec54--- /dev/null+++ b/src/app/api/admin/queue/overrides/route.ts@@ -0,0 +1,40 @@+import { connection } from "next/server";+import { adminAccess, audit } from "@/server/admin-tokens";+import { addOverride, checkOverride, liveOverrides, overrideView, recentOverrides } from "@/server/computer/queue-controls";++const NO_STORE = { "Cache-Control": "no-store" };++/** The overrides in effect, and the last 20 that ended (owner only, or an admin token with queue:read). */+export async function GET(request: Request) {+ await connection();+ const access = adminAccess(request, "queue:read", "Only the studio's owner sees the queue");+ if (access instanceof Response) return access;+ return Response.json({ live: liveOverrides().map(overrideView), ended: recentOverrides().map(overrideView) }, { headers: NO_STORE });+}++/**+ * A run or a person first, or held (owner only, or an admin token with queue:control; src/server/computer/queue-controls.ts+ * checkOverride): `{ kind: "run", generationId, action: "next" | "hold", worker?, forMin? }` or `{ kind: "person",+ * person (their key on the Queue page) | account, action: "boost" | "hold", forMin }` (a boost needs forMin). A newer one for the same run or person ends the+ * older. 201 with the override; 404 for no such run or worker; 409 for a run that ended.+ */+export async function POST(request: Request) {+ const access = adminAccess(request, "queue:control", "Only the studio's owner changes the queue");+ if (access instanceof Response) return access;+ const by = access.actor.kind === "token" ? access.actor.name : "owner";+ const body = (await request.json().catch(() => null)) as unknown;+ const now = Date.now();+ const o = checkOverride(body, now);+ if ("error" in o) {+ audit(access.actor, "queue.override", null, null, 400, now);+ return Response.json({ error: o.error }, { status: 400, headers: NO_STORE });+ }+ const r = addOverride(o, by, now);+ const target = o.kind === "run" ? o.generationId : ("override" in r ? r.override.target : (o.account ?? o.person!));+ if ("error" in r) {+ audit(access.actor, "queue.override", target, { kind: o.kind, action: o.action }, r.status, now);+ return Response.json({ error: r.error }, { status: r.status, headers: NO_STORE });+ }+ audit(access.actor, "queue.override", target, { id: r.override.id, kind: o.kind, action: o.action, worker: r.override.workerId, until: r.override.until, replaced: r.replaced.map((x) => x.id) }, 201, now);+ return Response.json({ override: overrideView(r.override), replaced: r.replaced.map(overrideView) }, { status: 201, headers: NO_STORE });+}diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 0d1d4704..61eddc3e 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -242,6 +242,8 @@ export interface WorkerAnswer {catalogVersion?: string;/** The lanes it may take now: the owner's allowed lanes (`lanes`), narrowed to its PC's ceiling. */lanesInside?: string[];+ /** The owner's mode it follows now (absent: an older studio, which has people first). */+ queue?: WorkerQueueMode;}/** What a worker says in its beat, on top of a browser's. */@@ -293,6 +295,8 @@ export interface WorkerBeat {* studio (src/server/computer/worker-events.ts). At most WORKER_LOG_LIMITS.perBeat lines of lineChars characters.*/log?: WorkerLogLine[];+ /** Local work on its PC, as the helper there last wrote it (absent: none written, or an older worker program). */+ localWork?: LocalWork | null;}/** A worker's log line in its beat. */@@ -323,6 +327,31 @@ export const HOLDING_WHY: Record<string, string> = {};export const HOLDING_OTHER = "Not starting yet";+/**+ * The owner's mode as a beat answer gives it to a worker (`worker.queue`; docs/gpu-workers.md, "Who goes first"): the+ * mode's name, what local work on its PC does in it (`localWork`: "yield" makes room for people's runs, "pause" starts+ * nothing new, "run" keeps the GPU), and until when (null: until the owner switches it back). A worker with a turns+ * folder writes it there as mode.json, for the helper on the PC's side.+ */+export interface WorkerQueueMode {+ mode: "people-first" | "people-only" | "ours-first" | "balanced";+ localWork: "yield" | "pause" | "run";+ until: number | null;+}++/**+ * Local work on a worker's PC, as the helper on the PC's side writes it to the turns folder (local.json) and the+ * worker passes it on in its beat (`localWork`): its state, why in a short code, how many of its jobs wait, whether one+ * runs, and when the helper wrote it. Counts and codes only: never a job's name, prompt or file.+ */+export interface LocalWork {+ state: "running" | "idle" | "paused" | "yielding" | "stopped";+ why: string | null;+ waiting: number | null;+ running: boolean;+ at: number;+}+/** A worker's CPU slot: it takes light CPU work (catalog workflows marked cpu) and these finishing jobs. */export interface CpuSlot {finishes: string[];diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.tsindex d4e9f0d8..da49f822 100644--- a/src/server/admin-tokens.ts+++ b/src/server/admin-tokens.ts@@ -33,6 +33,7 @@ export const SCOPES = ["workers:tokens","queue:read","queue:write",+ "queue:control","site:read","site:write","audit:read",@@ -56,6 +57,7 @@ export const SCOPE_LABELS: Record<Scope, string> = {"workers:tokens": "Add workers and give them new tokens (a worker runs accounts' queued jobs, with their files)","queue:read": "See the queue and its settings","queue:write": "Change the queue's settings: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget",+ "queue:control": "Choose who the GPUs serve first: the mode (people first, people only, our work first, balanced), a run next, pinned or held, a person's runs first or held, and cancel a waiting run","site:read": "See the site's switches: the upload fitting steps","site:write": "Switch the upload fitting steps off and on: convert, offer a part, offer a crop","audit:read": "See the admin log",diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 35451cc0..50c19fb4 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -16,6 +16,8 @@ import { cleanFacts, dropProgress, endTask, json, logWorkerJob, noteCold, notePrimport { queueSettings, runCeilingMs } from "../queue-settings";import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";import { modelLabel } from "./queue-live";+import { effectiveMode, workerModeOf, LOCAL_WORK, lineControls, liveOverrides, modeClass, modeClassSql, overrideTargets, plainLine, poolMode, sweepControls, taskControl, DEFAULT_MODE, type EffectiveMode, type LineControls, type QueueMode, type TaskControl } from "./queue-controls";+import type { LocalWork } from "@/lib/relay";import { cleanLogLines, lastEventOf, lastOfKind, logWorkerEvent, logWorkerEvents, setEventNames, type NewWorkerEvent, type WorkerEventKind } from "./worker-events";/**@@ -76,7 +78,7 @@ export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.c*/const LINE_ORDER = `${CLASS_RANK}, rank_at, created_at, id`;/** The columns the line's counts read (never a task's graph or files). */-const LINE_COLS = "id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json, slot, finish_json";+const LINE_COLS = "id, generation_id, principal, pools, only_worker, stop, lane, needs_json, created_at, rank_at, est_ms, tried_json, worker_id, claimed_at, account, class, extra_json, slot, finish_json";/*** A task a worker took that is still sending its files to its ComfyUI this long after the claim (or after its ComfyUI lost* it and it began sending them again on the same claim) goes back in line.@@ -264,9 +266,33 @@ export function cleanBeat(b: unknown): WorkerBeat {...(cleanHolding(o.holding) && { holding: cleanHolding(o.holding) }),// Its own log lines, masked again here (worker-events.ts); an older worker sends none....(Array.isArray(o.log) && o.log.length > 0 && { log: cleanLogLines(o.log) }),+ // Local work on its PC (counts and codes only); an older worker sends none.+ ...(o.localWork !== undefined && { localWork: cleanLocalWork(o.localWork) }),};}+/** A beat's `localWork` as it may be kept: a known state, a short code, a count, whether one runs, when; else null. */+export function cleanLocalWork(v: unknown): LocalWork | null {+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;+ const o = v as Record<string, unknown>;+ const states = ["running", "idle", "paused", "yielding", "stopped"] as const;+ const state = states.find((s) => s === o.state);+ const at = num(o.at);+ if (!state || at === null || at <= 0) return null;+ const why = typeof o.why === "string" && /^[a-z0-9][a-z0-9:-]{0,47}$/.test(o.why) ? o.why : null;+ const waiting = num(o.waiting);+ return { state, why, waiting: waiting !== null && waiting >= 0 ? Math.min(Math.floor(waiting), 1_000_000) : null, running: o.running === true, at };+}++/** Local work on a worker's PC counts as there while its last word is this fresh. */+export const LOCAL_WORK_FRESH_MS = 2 * 60_000;++/** Local work on a worker's PC as its last beat said, while fresh (null: none, or too old). */+export function localWorkOf(w: Pick<WorkerRow, "local_work_json" | "seen_at">, now = Date.now()): LocalWork | null {+ const l = w.local_work_json ? cleanLocalWork(json<unknown>(w.local_work_json, null)) : null;+ return l && now - l.at <= LOCAL_WORK_FRESH_MS ? l : null;+}+/** A beat's `holding` as it may be kept: a short reason in lower-case words, since when, and a task id; else null. */export function cleanHolding(v: unknown): WorkerHolding | null {if (!v || typeof v !== "object") return null;@@ -290,12 +316,14 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAreturn d.transaction(() => {// A worker back after going silent finds its task back in line first (its lease no longer works).sweepPool(now);+ // The owner's controls that ran their course end first (a mode or a hold past its time).+ sweepControls(now);// Its saved state and version before this beat: a timeline row only when either changes.const before = d.prepare("SELECT state, version FROM relay_workers WHERE id = ?").get(w.id) as Pick<WorkerRow, "state" | "version"> | undefined;const facts = b.facts ? { ...b.facts, loras: undefined } : undefined;d.prepare(`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,- warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ?, holding_json = ? WHERE id = ?`,+ warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ?, holding_json = ?, local_work_json = ? WHERE id = ?`,).run(now,device,@@ -311,6 +339,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAb.cpuSlot ? JSON.stringify(b.cpuSlot) : null,// Its own "since" is never later than now (a PC clock ahead of the studio's).b.holding ? JSON.stringify({ ...b.holding, since: Math.min(b.holding.since, now) }) : null,+ // Local work on its PC: its time never later than now either.+ b.localWork ? JSON.stringify({ ...b.localWork, at: Math.min(b.localWork.at, now) }) : null,w.id,);// Its PC slept: a job taken back from it for going quiet meanwhile counts against no one.@@ -367,6 +397,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA// Pool names are validated at creation (/^[a-z0-9-]{1,32}$/), so they never contain commas. INSTR on the// CSV avoids the LIKE-wildcard class of risk (%, _) entirely.const waiting = (d.prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND INSTR(',' || pools || ',', ?) > 0").get(`,${fresh.pool},`) as { n: number }).n;+ const mode = effectiveMode(fresh, now);return {runner: eligible(fresh, now),heldElsewhere: false,@@ -389,6 +420,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAsendInventory: b.local.why !== MODELS_NOT_READY && (!fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash),...(nextToken && { token: nextToken }),...(fresh.expires_at && { tokenExpiresAt: fresh.expires_at }),+ // The owner's mode it follows now: who goes first, and what local work on its PC does.+ queue: { mode: mode.mode, localWork: LOCAL_WORK[mode.mode], until: mode.until },},};}).immediate();@@ -414,12 +447,66 @@ export function ownerWaitingNow(w: WorkerRow, now = Date.now()): number {function gpuClaimable(w: WorkerRow, now: number, whose: "people" | "owner"): number {if (w.kind !== "pool" || w.revoked_at || w.paused_server || w.drain || (w.protocol ?? 0) < MIN_PROTOCOL || !hoursAt(hoursOf(w), now).inside) return 0;+ const c = controlsOf(w, now);// Only its GPU's: work its CPU slot takes never asks local ComfyUI work to make room (left out in the query, so a long// line of CPU work never hides the GPU's).- const rows = db()- .prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS ${whose === "people" ? "NOT NULL" : "NULL"} AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}ORDER BY ${LINE_ORDER} LIMIT ?`)- .all(`,${w.pool},`, LOOK_AT) as TaskRow[];- return rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now)).length;+ const rows = lineRows(LINE_COLS, `pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND account IS ${whose === "people" ? "NOT NULL" : "NULL"} AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, "gpu")}`, [`,${w.pool},`], c, LOOK_AT);+ const fit = rows.filter((t) => fitsSlot(t, w, now, "gpu") && retryOk(t, w, now) && beforeWindowEnds(t, w, now));+ if (plainLine(c)) return fit.length;+ // Held runs and people, runs pinned to another worker, and the owner's own jobs in People only don't count. In Our work+ // first, while local work on its PC runs, people's runs ask it for no room unless the owner sent them next or boosted+ // them: the owner's work keeps the GPU, and people's runs start once it is free.+ const keepGpu = whose === "people" && c.mode === "ours-first" && localWorkOf(w, now)?.state === "running";+ return fit.filter((t) => {+ const tc = taskControl(t, classRank(t), c, w.id);+ return !tc.out && (!keepGpu || tc.tier < 2);+ }).length;+}++/** The controls one look at the line reads: the mode of this worker (or of a pool: `w` its name) and the live overrides. */+function controlsOf(w: Pick<WorkerRow, "pool" | "mode_json"> | string, now: number): LineControls {+ return lineControls((typeof w === "string" ? poolMode(w, now) : effectiveMode(w, now)).mode, liveOverrides(now));+}++/** The line's order in SQL under a mode: the mode's class, then rank, when it came and id (LINE_ORDER for people first). */+const lineOrderSql = (mode: QueueMode) => (mode === DEFAULT_MODE ? LINE_ORDER : `${modeClassSql(CLASS_RANK, mode)}, rank_at, created_at, id`);++/**+ * The waiting rows one look at the line reads: the first `limit` in the mode's order and, wherever they stand, the rows+ * of the runs sent next and of the people boosted (a run sent next is never missed past the window).+ */+function lineRows(cols: string, where: string, args: unknown[], c: LineControls, limit: number): TaskRow[] {+ const d = db();+ const rows = d.prepare(`SELECT ${cols} FROM relay_tasks WHERE ${where} ORDER BY ${lineOrderSql(c.mode)} LIMIT ?`).all(...args, limit) as TaskRow[];+ const { generations, accounts } = overrideTargets(c);+ if (!generations.length && !accounts.length) return rows;+ const seen = new Set(rows.map((r) => r.id));+ const extra = d+ .prepare(`SELECT ${cols} FROM relay_tasks WHERE ${where} AND (generation_id IN (SELECT value FROM json_each(?)) OR account IN (SELECT value FROM json_each(?))) ORDER BY ${lineOrderSql(c.mode)} LIMIT ?`)+ .all(...args, JSON.stringify(generations), JSON.stringify(accounts), limit) as TaskRow[];+ return [...rows, ...extra.filter((r) => !seen.has(r.id))];+}++/**+ * Waiting tasks in the order a worker (`workerId`; null: the line as a whole) serves them under the owner's controls:+ * the mode's order (lineOrder), then runs sent next first, then boosted people's runs, each group keeping its order.+ * The ones it doesn't take now (held, pinned to another worker, the owner's own in People only) are left out, except+ * `keep` (the task whose own place is asked).+ */+function controlledOrder(rows: TaskRow[], fairShare: boolean, c: LineControls, workerId: string | null, keep?: string): TaskRow[] {+ const ordered = lineOrder(rows, fairShare, c.mode);+ if (plainLine(c)) return ordered;+ const tiers = new Map<string, number>();+ const kept = ordered.filter((t) => {+ const tc = taskControl(t, classRank(t), c, workerId);+ if (tc.out && t.id !== keep) return false;+ tiers.set(t.id, tc.out ? 2 : tc.tier);+ return true;+ });+ return kept+ .map((t, i) => ({ t, i }))+ .sort((a, b) => tiers.get(a.t.id)! - tiers.get(b.t.id)! || a.i - b.i)+ .map((x) => x.t);}// ---------------------------------------------------------------------------@@ -666,17 +753,19 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {*/function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): { task: TaskRow | null; looked: number } {const settings = queueSettings(now);+ // The owner's controls: this worker's mode, and the runs and people sent first or held.+ const c = controlsOf(w, now);// Each slot looks only at its own tasks.- const rows = db()- .prepare(`SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, slot)}ORDER BY ${LINE_ORDER} LIMIT ?`)- .all(`,${w.pool},`, LOOK_AT) as TaskRow[];+ const rows = lineRows("*", `pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0 ${slotWhere(w, slot)}`, [`,${w.pool},`], c, LOOK_AT);const looked = rows.length;- const ok = lineOrder(rows, settings.fairShare).filter((t) => fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));+ const ok = controlledOrder(rows, settings.fairShare, c, w.id).filter((t) => fitsSlot(t, w, now, slot) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));if (!ok.length) return { task: null, looked };const best = ok[0];const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);- if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane || classRank(best) !== OWNER_CLASS) return { task: best, looked };- const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === OWNER_CLASS);+ // A run the owner sent next, or a boosted person's, never waits for a warm lane either.+ const plain = (t: TaskRow) => plainLine(c) || taskControl(t, classRank(t), c, w.id).tier === 2;+ if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane || classRank(best) !== OWNER_CLASS || !plain(best)) return { task: best, looked };+ const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === OWNER_CLASS && plain(t));return { task: warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best, looked };}@@ -704,9 +793,11 @@ function servedTurns(waiting: TaskRow[]): Map<string, number> {/** Whose turn a task takes with fair share: its account's, or the owner's. */const turnKey = (t: Pick<TaskRow, "account" | "principal" | "class">) => `${classRank(t as Pick<TaskRow, "class" | "account">)}:${t.account ?? t.principal}`;-/** The strict order (LINE_ORDER) of two tasks, in code. */-const strictOrder = (a: TaskRow, b: TaskRow) =>- classRank(a) - classRank(b) || (a.rank_at ?? a.created_at) - (b.rank_at ?? b.created_at) || a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);+/**+ * Two tasks of one class in the line's order (LINE_ORDER after the class, in code): by rank, then when each came, then+ * id. The class comes first, in the order of the mode (lineOrder).+ */+const sameClassOrder = (a: TaskRow, b: TaskRow) => (a.rank_at ?? a.created_at) - (b.rank_at ?? b.created_at) || a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);/*** Waiting tasks (given in strict order) in the order workers serve them. Fair share off: as given. On: within a class,@@ -714,18 +805,22 @@ const strictOrder = (a: TaskRow, b: TaskRow) =>* account's turns count the runs a worker holds for it now and those a worker finished for it since the oldest run* still waiting in its class came, so one account with many runs never holds the line.*/-export function lineOrder(rows: TaskRow[], fairShare: boolean): TaskRow[] {- if (!fairShare || rows.length < 2) return rows;+export function lineOrder(rows: TaskRow[], fairShare: boolean, mode: QueueMode = DEFAULT_MODE): TaskRow[] {+ // The class in the mode's order (people first: paid, free, the owner's own).+ const cls = (t: TaskRow) => modeClass(classRank(t), mode);+ const strict = (a: TaskRow, b: TaskRow) => cls(a) - cls(b) || sameClassOrder(a, b);+ if (rows.length < 2) return rows;+ if (!fairShare) return [...rows].sort(strict);const held = servedTurns(rows);const seen = new Map<string, number>();const turns = new Map<string, number>();- for (const r of [...rows].sort(strictOrder)) {+ for (const r of [...rows].sort(strict)) {const k = turnKey(r);const n = seen.get(k) ?? 0;seen.set(k, n + 1);turns.set(r.id, (held.get(k) ?? 0) + n);}- return [...rows].sort((a, b) => classRank(a) - classRank(b) || turns.get(a.id)! - turns.get(b.id)! || strictOrder(a, b));+ return [...rows].sort((a, b) => cls(a) - cls(b) || turns.get(a.id)! - turns.get(b.id)! || strict(a, b));}// ---------------------------------------------------------------------------@@ -1042,6 +1137,14 @@ function lineBefore(t: TaskRow, now: number): TaskRow[] {const d = db();const rank = t.rank_at ?? t.created_at;const cls = classRank(t);+ // The owner's controls (the pool's mode, runs or people sent first or held): the line as the pool's workers serve it,+ // with those that wait held left out (they take no turn before it).+ const c = controlsOf((t.pools ?? "pool").split(",")[0] || "pool", now);+ if (!plainLine(c)) {+ const rows = lineRows(LINE_COLS, "pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ?", [t.id], c, LOOK_AHEAD);+ const line = controlledOrder([...rows, t], queueSettings(now).fairShare, c, null, t.id);+ return line.slice(0, line.findIndex((x) => x.id === t.id));+ }if (!queueSettings(now).fairShare) {return d.prepare(@@ -1409,6 +1512,11 @@ export interface WorkerView {jobs: ActiveJob[];/** Its timeline's newest row other than a log line (null: none). */lastEvent: { at: number; kind: WorkerEventKind; event: string; words: string | null } | null;+ /** The owner's mode it follows now (its own, its pool's, or people first), and its own mode as set (null: none). */+ mode: EffectiveMode;+ ownMode: { mode: QueueMode; until: number | null; by: string; at: number } | null;+ /** Local work on its PC, as its last beat said while fresh (null: none). */+ localWork: LocalWork | null;}/** A task a worker holds now: where it is, and how long it should take. No prompt, no account's details. */@@ -1532,6 +1640,9 @@ export function workerView(w: WorkerRow, now = Date.now(), typical: (lane: strinasked: w.asked_at && w.asked_words ? { at: w.asked_at, words: w.asked_words } : null,jobs: activeJobs(w, held, now, typical),lastEvent: lastEventOf(w.id),+ mode: effectiveMode(w, now),+ ownMode: workerModeOf(w),+ localWork: localWorkOf(w, now),};}@@ -1684,3 +1795,21 @@ export function queueView(now = Date.now()) {/** Every lane in this studio's catalog, for the owner to allow per worker. */export const lanesCatalog = () => catalogLanes().lanes.map((l) => ({ lane: l.lane, label: l.label, workflows: l.workflows.length }));++/**+ * The waiting line of a pool as the owner's Queue page shows it (GET /api/admin/queue): in the order its workers serve+ * it under the owner's controls (the pool's mode, runs and people sent first), each with its place (`rank`, 1 first)+ * and what the controls say of it. The tasks no worker takes now (held, the owner's own in People only) follow, with no+ * place. At most `limit` tasks are looked at.+ */+export function controlledLine(pool = "pool", now = Date.now(), limit = LOOK_AHEAD): { mode: QueueMode; items: { task: TaskRow; rank: number | null; base: number; control: TaskControl }[] } {+ const c = controlsOf(pool, now);+ const rows = lineRows("*", "pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND INSTR(',' || pools || ',', ?) > 0", [`,${pool},`], c, limit);+ const all = lineOrder(rows, queueSettings(now).fairShare, c.mode).map((task, i) => ({ task, i, base: classRank(task), control: taskControl(task, classRank(task), c, null) }));+ const served = all.filter((x) => !x.control.out).sort((a, b) => a.control.tier - b.control.tier || a.i - b.i);+ const out = all.filter((x) => x.control.out);+ return {+ mode: c.mode,+ items: [...served.map((x, k) => ({ task: x.task, rank: k + 1, base: x.base, control: x.control })), ...out.map((x) => ({ task: x.task, rank: null, base: x.base, control: x.control }))],+ };+}diff --git a/src/server/computer/queue-controls.ts b/src/server/computer/queue-controls.tsnew file mode 100644index 00000000..b84318d4--- /dev/null+++ b/src/server/computer/queue-controls.ts@@ -0,0 +1,539 @@+import "server-only";+import crypto from "node:crypto";+import { db } from "../db";+import type { TaskRow } from "./tasks";+import type { WorkerRow } from "./workers";++/**+ * The owner's controls over who the GPUs serve first (docs/gpu-workers.md, "Who goes first"; the admin API's+ * /api/admin/queue/mode, /overrides and /cancel). Owner-only, every change in the admin log, and each one has an end:+ * a time, or the run it is for ending, or the owner's "Back to normal". Nothing here hides or refuses a person's run:+ * a held run keeps its place in line and starts once the hold ends.+ *+ * - A mode for the pool, and one for a single worker that wins over its pool's while it lasts:+ * - "people-first" (the default): people's runs before the owner's own jobs; local work on a worker's PC makes room+ * for people's runs.+ * - "people-only": workers take only people's runs; the owner's own jobs wait, and local work on the PC pauses.+ * - "ours-first": the owner's own jobs before people's runs, and local work on the PC keeps the GPU (people's runs+ * wait in line, in their order, and start when a GPU is free).+ * - "balanced": people's free runs and the owner's own jobs in one line by when they came (paid runs first); local+ * work makes room for people's runs as in people-first.+ * - A run: "next" (to the front of every worker's line, or of one worker's: `worker`), or "hold" (it keeps its place+ * and no worker takes it until the hold ends).+ * - A person (an account, or the guests' key): "boost" (their runs go first, for a while), or "hold".+ */++export const QUEUE_MODES = ["people-first", "people-only", "ours-first", "balanced"] as const;+export type QueueMode = (typeof QUEUE_MODES)[number];+export const DEFAULT_MODE: QueueMode = "people-first";++/** What local work on a worker's PC does in each mode: makes room for people's runs, pauses, or keeps the GPU. */+export type LocalWorkRule = "yield" | "pause" | "run";+export const LOCAL_WORK: Record<QueueMode, LocalWorkRule> = { "people-first": "yield", balanced: "yield", "people-only": "pause", "ours-first": "run" };++/** The owner's words for each mode. */+export const MODE_WORDS: Record<QueueMode, string> = {+ "people-first": "People first",+ "people-only": "People only",+ "ours-first": "Our work first",+ balanced: "Balanced",+};++/** A mode the owner set: until when (null: until it is switched back), who set it and when. */+export interface ModeSetting {+ mode: QueueMode;+ until: number | null;+ by: string;+ at: number;+}++/** The mode a worker follows now, and where it comes from. */+export interface EffectiveMode {+ mode: QueueMode;+ from: "worker" | "pool" | "default";+ until: number | null;+ by: string | null;+ at: number | null;+}++/** The longest a mode, a hold or a boost may be set for, in minutes (a week). */+export const MAX_FOR_MIN = 7 * 24 * 60;+/** The longest a run stays "next" without being taken (a day). */+export const NEXT_MAX_MS = 24 * 60 * 60_000;++const MODES_KEY = "queue.modes";+const POOL = /^[a-z0-9-]{1,32}$/;+const GEN = /^[\w-]{1,80}$/;+const ACCOUNT = /^[\w:.@-]{1,80}$/;+const WORKER = /^[\w-]{1,64}$/;++declare global {+ var __fuobeQueueModes: { at: number; raw: string | null; value: Record<string, ModeSetting> } | undefined;+}++const isMode = (v: unknown): v is QueueMode => typeof v === "string" && (QUEUE_MODES as readonly string[]).includes(v);++/** A stored mode read leniently: anything not valid is none. */+export function cleanMode(v: unknown): ModeSetting | null {+ if (!v || typeof v !== "object") return null;+ const o = v as Record<string, unknown>;+ if (!isMode(o.mode)) return null;+ const until = typeof o.until === "number" && Number.isFinite(o.until) ? o.until : null;+ return { mode: o.mode, until, by: typeof o.by === "string" ? o.by.slice(0, 80) : "owner", at: typeof o.at === "number" ? o.at : 0 };+}++const live = (s: ModeSetting | null, now: number): s is ModeSetting => !!s && (s.until === null || s.until > now);++/** Every pool's mode as stored (read again at most every 2 s; a change clears it at once in this process). */+export function poolModes(now = Date.now()): Record<string, ModeSetting> {+ const c = globalThis.__fuobeQueueModes;+ if (c && now - c.at < 2000) return { ...c.value };+ const raw = (db().prepare("SELECT value FROM settings WHERE key = ?").get(MODES_KEY) as { value: string } | undefined)?.value ?? null;+ let value: Record<string, ModeSetting> = {};+ if (c && c.raw === raw) value = c.value;+ else if (raw) {+ try {+ const pools = (JSON.parse(raw) as { pools?: Record<string, unknown> }).pools ?? {};+ for (const [pool, s] of Object.entries(pools)) {+ const m = POOL.test(pool) ? cleanMode(s) : null;+ if (m) value[pool] = m;+ }+ } catch {+ value = {};+ }+ }+ globalThis.__fuobeQueueModes = { at: now, raw, value };+ return { ...value };+}++function savePoolModes(pools: Record<string, ModeSetting>): void {+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(MODES_KEY, JSON.stringify({ pools }));+ globalThis.__fuobeQueueModes = undefined;+}++/** A worker's own mode as stored (null: none; it follows its pool). */+export const workerModeOf = (w: Pick<WorkerRow, "mode_json">): ModeSetting | null => {+ if (!w.mode_json) return null;+ try {+ return cleanMode(JSON.parse(w.mode_json));+ } catch {+ return null;+ }+};++/** The mode a worker follows now: its own while it lasts, else its pool's while it lasts, else people first. */+export function effectiveMode(w: Pick<WorkerRow, "pool" | "mode_json"> | { pool: string; mode_json?: string | null }, now = Date.now()): EffectiveMode {+ const own = workerModeOf({ mode_json: w.mode_json ?? null });+ if (live(own, now)) return { mode: own.mode, from: "worker", until: own.until, by: own.by, at: own.at };+ const pool = poolModes(now)[w.pool] ?? null;+ if (live(pool, now)) return { mode: pool.mode, from: "pool", until: pool.until, by: pool.by, at: pool.at };+ return { mode: DEFAULT_MODE, from: "default", until: null, by: null, at: null };+}++/** The pool's own mode now (people first when none is set or it ended). */+export const poolMode = (pool: string, now = Date.now()): EffectiveMode => effectiveMode({ pool, mode_json: null }, now);++/**+ * A task's class in the order a mode serves them (lower first): its base class (pool.ts classRank: paid 0, free 1, the+ * owner's own 2) mapped by the mode. "people-only" puts the owner's own jobs last (they aren't taken: modeServes).+ */+export function modeClass(base: number, mode: QueueMode): number {+ if (mode === "ours-first") return base === 2 ? 0 : base + 1;+ if (mode === "balanced") return Math.min(base, 1);+ if (mode === "people-only") return base === 2 ? 3 : base;+ return base;+}++/** modeClass as SQL over the base class's SQL. */+export function modeClassSql(baseSql: string, mode: QueueMode): string {+ if (mode === "ours-first") return `(CASE ${baseSql} WHEN 2 THEN 0 WHEN 0 THEN 1 ELSE 2 END)`;+ if (mode === "balanced") return `(CASE ${baseSql} WHEN 0 THEN 0 ELSE 1 END)`;+ if (mode === "people-only") return `(CASE ${baseSql} WHEN 2 THEN 3 ELSE ${baseSql} END)`;+ return baseSql;+}++// ---------------------------------------------------------------------------+// Runs and people++export type OverrideAction = "next" | "hold" | "boost";++export interface QueueOverride {+ id: string;+ kind: "run" | "person";+ /** A run's generation id, or a person's account key (as their runs carry it: an account id, or the guests' key). */+ target: string;+ action: OverrideAction;+ /** "next" for one worker only (pinned): that worker takes it first, and no other worker takes it. */+ workerId: string | null;+ /** A run's rows: every step the same press of Run made (its later steps keep the override). */+ generations: string[];+ until: number | null;+ by: string;+ at: number;+ endedAt: number | null;+ endedBy: string | null;+ endWhy: string | null;+}++interface OverrideRow {+ id: string;+ kind: string;+ target: string;+ action: string;+ worker_id: string | null;+ gens_json: string | null;+ until: number | null;+ set_by: string;+ set_at: number;+ ended_at: number | null;+ ended_by: string | null;+ end_why: string | null;+}++const fromRow = (r: OverrideRow): QueueOverride => {+ let generations: string[] = [];+ try {+ const g = JSON.parse(r.gens_json ?? "[]") as unknown;+ if (Array.isArray(g)) generations = g.filter((x): x is string => typeof x === "string");+ } catch {}+ return {+ id: r.id,+ kind: r.kind === "person" ? "person" : "run",+ target: r.target,+ action: r.action === "hold" ? "hold" : r.action === "boost" ? "boost" : "next",+ workerId: r.worker_id,+ generations: generations.length ? generations : r.kind === "run" ? [r.target] : [],+ until: r.until,+ by: r.set_by,+ at: r.set_at,+ endedAt: r.ended_at,+ endedBy: r.ended_by,+ endWhy: r.end_why,+ };+};++/** The overrides in effect now (not ended, not past their time), the oldest first. */+export function liveOverrides(now = Date.now()): QueueOverride[] {+ return (db().prepare("SELECT * FROM queue_overrides WHERE ended_at IS NULL AND (until IS NULL OR until > ?) ORDER BY set_at, id").all(now) as OverrideRow[]).map(fromRow);+}++/** The overrides that ended most recently (for the owner's view: what ended, when, and why). */+export function recentOverrides(limit = 20): QueueOverride[] {+ return (db().prepare("SELECT * FROM queue_overrides WHERE ended_at IS NOT NULL ORDER BY ended_at DESC LIMIT ?").all(limit) as OverrideRow[]).map(fromRow);+}++/** An override's end, written once (an override already ended stays as it ended). Returns whether it changed. */+export function endOverride(id: string, by: string, why: "released" | "expired" | "run-ended" | "replaced", now = Date.now()): QueueOverride | null {+ const d = db();+ const changed = d.prepare("UPDATE queue_overrides SET ended_at = ?, ended_by = ?, end_why = ? WHERE id = ? AND ended_at IS NULL").run(now, by, why, id).changes > 0;+ if (!changed) return null;+ const r = d.prepare("SELECT * FROM queue_overrides WHERE id = ?").get(id) as OverrideRow | undefined;+ return r ? fromRow(r) : null;+}++/**+ * Ends what has run its course, and says so in the admin log (actor "system"): an override past its time, a run's+ * override once the run ended (it no longer waits or runs), a mode past its time (pool or worker). Cheap: a look at the+ * few live rows. Best-effort: it never fails a claim or a beat.+ */+export function sweepControls(now = Date.now()): void {+ try {+ const d = db();+ const ended: { action: string; target: string; detail: Record<string, unknown> }[] = [];+ const rows = d.prepare("SELECT * FROM queue_overrides WHERE ended_at IS NULL").all() as OverrideRow[];+ if (rows.length) {+ const going = d.prepare("SELECT 1 FROM generations WHERE id = ? AND status IN ('queued','running')");+ for (const r of rows.map(fromRow)) {+ if (r.until !== null && r.until <= now) {+ if (endOverride(r.id, "system", "expired", r.until)) ended.push({ action: "queue.override.end", target: r.target, detail: { id: r.id, kind: r.kind, action: r.action, why: "expired" } });+ } else if (r.kind === "run" && !r.generations.some((g) => going.get(g))) {+ if (endOverride(r.id, "system", "run-ended", now)) ended.push({ action: "queue.override.end", target: r.target, detail: { id: r.id, kind: r.kind, action: r.action, why: "run-ended" } });+ }+ }+ }+ const pools = poolModes(now);+ const over = Object.entries(pools).filter(([, s]) => s.until !== null && s.until <= now);+ if (over.length) {+ const kept = Object.fromEntries(Object.entries(pools).filter(([, s]) => !(s.until !== null && s.until <= now)));+ savePoolModes(kept);+ for (const [pool, s] of over) ended.push({ action: "queue.mode.end", target: `pool:${pool}`, detail: { was: s.mode, why: "expired", until: s.until } });+ }+ const workers = d.prepare("SELECT id, name, mode_json FROM relay_workers WHERE mode_json IS NOT NULL").all() as Pick<WorkerRow, "id" | "name" | "mode_json">[];+ for (const w of workers) {+ const s = workerModeOf(w);+ if (s && (s.until === null || s.until > now)) continue;+ if (d.prepare("UPDATE relay_workers SET mode_json = NULL WHERE id = ? AND mode_json = ?").run(w.id, w.mode_json).changes > 0 && s)+ ended.push({ action: "queue.mode.end", target: `worker:${w.id}`, detail: { worker: w.name, was: s.mode, why: "expired", until: s.until } });+ }+ const log = d.prepare("INSERT INTO admin_audit (at, actor, token_id, token_name, action, target, detail_json, status) VALUES (?, 'system', NULL, NULL, ?, ?, ?, 200)");+ for (const e of ended) log.run(now, e.action, e.target, JSON.stringify(e.detail));+ } catch (e) {+ console.warn(`[fuobe] Couldn't sweep the queue's controls: ${(e as Error).message}`);+ }+}++// ---------------------------------------------------------------------------+// Checking the owner's changes++export type ModeChange = { scope: "pool"; pool: string; setting: ModeSetting | null } | { scope: "worker"; worker: string; setting: ModeSetting | null };++/** A length in minutes: 1 to MAX_FOR_MIN, or null for "until I switch back". */+function forMinOf(v: unknown, now: number, required: boolean): { until: number | null } | { error: string } {+ if (v === undefined || v === null) return required ? { error: `forMin is 1 to ${MAX_FOR_MIN} minutes` } : { until: null };+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > MAX_FOR_MIN) return { error: `forMin is 1 to ${MAX_FOR_MIN} minutes${required ? "" : ", or null for until you switch it back"}` };+ return { until: now + v * 60_000 };+}++/**+ * POST /api/admin/queue/mode's body: `{ pool?: "pool", worker?: id, mode: QueueMode | null, forMin?: minutes | null }`.+ * `mode: null` is "Back to normal": the pool goes back to people first, a worker back to its pool's mode.+ */+export function checkModeChange(body: unknown, by: string, now = Date.now()): ModeChange | { error: string } {+ if (!body || typeof body !== "object" || Array.isArray(body)) return { error: "Send the mode as an object" };+ const b = body as Record<string, unknown>;+ const unknown = Object.keys(b).filter((k) => !["pool", "worker", "mode", "forMin"].includes(k));+ if (unknown.length) return { error: `Unknown field: ${unknown[0].slice(0, 40)}` };+ if (b.pool !== undefined && b.worker !== undefined) return { error: "Name a pool or a worker, not both" };+ if (b.mode !== null && !isMode(b.mode)) return { error: `mode is one of ${QUEUE_MODES.join(", ")}, or null for back to normal` };+ let setting: ModeSetting | null = null;+ if (b.mode !== null) {+ const f = forMinOf(b.forMin, now, false);+ if ("error" in f) return f;+ setting = { mode: b.mode as QueueMode, until: f.until, by, at: now };+ // People first on a pool, with no end, is the default: stored as none.+ if (b.worker === undefined && setting.mode === DEFAULT_MODE && setting.until === null) setting = null;+ } else if (b.forMin !== undefined && b.forMin !== null) return { error: "Back to normal takes no forMin" };+ if (b.worker !== undefined) {+ if (typeof b.worker !== "string" || !WORKER.test(b.worker)) return { error: "worker is a worker's id" };+ return { scope: "worker", worker: b.worker, setting };+ }+ const pool = b.pool === undefined ? "pool" : b.pool;+ if (typeof pool !== "string" || !POOL.test(pool)) return { error: "pool is a pool's name" };+ return { scope: "pool", pool, setting };+}++/** Save a checked mode change. The worker's must exist (null: no such worker). Returns the mode before and after. */+export function applyModeChange(c: ModeChange, now = Date.now()): { before: EffectiveMode; after: EffectiveMode } | null {+ if (c.scope === "pool") {+ const before = poolMode(c.pool, now);+ const pools = poolModes(now);+ if (c.setting) pools[c.pool] = c.setting;+ else delete pools[c.pool];+ savePoolModes(pools);+ return { before, after: poolMode(c.pool, now) };+ }+ const d = db();+ const w = d.prepare("SELECT * FROM relay_workers WHERE id = ? AND kind = 'pool' AND revoked_at IS NULL").get(c.worker) as WorkerRow | undefined;+ if (!w) return null;+ const before = effectiveMode(w, now);+ d.prepare("UPDATE relay_workers SET mode_json = ? WHERE id = ?").run(c.setting ? JSON.stringify(c.setting) : null, w.id);+ return { before, after: effectiveMode({ ...w, mode_json: c.setting ? JSON.stringify(c.setting) : null }, now) };+}++export type OverrideInput =+ | { kind: "run"; generationId: string; action: "next" | "hold"; worker: string | null; until: number | null }+ | { kind: "person"; account?: string; person?: string; action: "boost" | "hold"; until: number | null };++/**+ * A person's key on the owner's Queue page: the same for all of one account's runs (or the guests'), and never their+ * account id (the queue view names no account).+ */+export const personKey = (account: string): string => `p-${crypto.createHash("sha256").update(`fuobe-person:${account}`).digest("hex").slice(0, 12)}`;+const PERSON = /^p-[0-9a-f]{12}$/;++/** The account a person's key stands for, among the accounts with a run on the GPUs now (null: none). */+export function accountOfPerson(key: string): string | null {+ const rows = db().prepare("SELECT DISTINCT account FROM relay_tasks WHERE account IS NOT NULL AND pools IS NOT NULL AND state IN ('waiting','sending','queued','running','collecting')").all() as { account: string }[];+ return rows.find((r) => personKey(r.account) === key)?.account ?? null;+}++/** An override as the admin API shows it: a person by their key (never an account id), a run by its id. */+export function overrideView(o: QueueOverride) {+ return {+ id: o.id,+ kind: o.kind,+ action: o.action,+ generationId: o.kind === "run" ? o.target : null,+ person: o.kind === "person" ? personKey(o.target) : null,+ guest: o.kind === "person" && o.target.startsWith("guest"),+ workerId: o.workerId,+ until: o.until,+ by: o.by,+ at: o.at,+ endedAt: o.endedAt,+ endedBy: o.endedBy,+ endWhy: o.endWhy,+ };+}+export type OverrideView = ReturnType<typeof overrideView>;++/**+ * POST /api/admin/queue/overrides's body:+ * - `{ kind: "run", generationId, action: "next", worker?, forMin? }`: the run goes first (on that worker only, when+ * one is named), until a worker takes it (at most a day, or forMin);+ * - `{ kind: "run", generationId, action: "hold", forMin? }`: no worker takes it until the hold ends (forMin, or Release);+ * - `{ kind: "person", account, action: "boost", forMin }`: their runs go first for forMin minutes;+ * - `{ kind: "person", account, action: "hold", forMin? }`: no worker takes their runs until the hold ends.+ */+export function checkOverride(body: unknown, now = Date.now()): OverrideInput | { error: string } {+ if (!body || typeof body !== "object" || Array.isArray(body)) return { error: "Send the change as an object" };+ const b = body as Record<string, unknown>;+ const unknown = Object.keys(b).filter((k) => !["kind", "generationId", "account", "person", "action", "worker", "forMin"].includes(k));+ if (unknown.length) return { error: `Unknown field: ${unknown[0].slice(0, 40)}` };+ if (b.kind === "run") {+ if (typeof b.generationId !== "string" || !GEN.test(b.generationId)) return { error: "generationId is a run's id" };+ if (b.action !== "next" && b.action !== "hold") return { error: "A run's action is next or hold" };+ if (b.account !== undefined || b.person !== undefined) return { error: "A run takes no account or person" };+ let worker: string | null = null;+ if (b.worker !== undefined && b.worker !== null) {+ if (b.action !== "next") return { error: "Only Run next is pinned to a worker" };+ if (typeof b.worker !== "string" || !WORKER.test(b.worker)) return { error: "worker is a worker's id" };+ worker = b.worker;+ }+ const f = forMinOf(b.forMin, now, false);+ if ("error" in f) return f;+ const until = b.action === "next" ? Math.min(f.until ?? now + NEXT_MAX_MS, now + NEXT_MAX_MS) : f.until;+ return { kind: "run", generationId: b.generationId, action: b.action, worker, until };+ }+ if (b.kind === "person") {+ const byKey = b.person !== undefined;+ if (byKey === (b.account !== undefined)) return { error: "Name the person by person (their key on the Queue page) or account, one of them" };+ if (byKey ? typeof b.person !== "string" || !PERSON.test(b.person) : typeof b.account !== "string" || !ACCOUNT.test(b.account)) return { error: byKey ? "person is a person's key from the Queue page" : "account is an account's id, or the guests' key" };+ if (b.action !== "boost" && b.action !== "hold") return { error: "A person's action is boost or hold" };+ if (b.generationId !== undefined || (b.worker !== undefined && b.worker !== null)) return { error: "A person takes no generationId or worker" };+ const f = forMinOf(b.forMin, now, b.action === "boost");+ if ("error" in f) return f;+ return { kind: "person", ...(byKey ? { person: b.person as string } : { account: b.account as string }), action: b.action, until: f.until };+ }+ return { error: "kind is run or person" };+}++/** SQL: row `g` was made by the same press of Run as the row asked about (pool.ts SAME_PRESS). */+const SAME_PRESS = "(CASE WHEN @hold IS NOT NULL THEN json_extract(g.request_json, '$.hold') IS @hold ELSE @batch IS NOT NULL AND g.batch_id IS @batch END)";++/** A run's rows: it and every other step the same press made (null: no such run). */+export function runRows(generationId: string): { generations: string[]; account: string | null; status: string } | null {+ const d = db();+ const g = d.prepare("SELECT id, status, batch_id, json_extract(request_json, '$.hold') AS hold, json_extract(request_json, '$.account') AS account FROM generations WHERE id = ?").get(generationId) as+ | { id: string; status: string; batch_id: string | null; hold: unknown; account: unknown }+ | undefined;+ if (!g) return null;+ const press = { hold: typeof g.hold === "string" && g.hold ? g.hold : null, batch: g.batch_id };+ const same = press.hold || press.batch ? (d.prepare(`SELECT g.id FROM generations g WHERE ${SAME_PRESS} AND g.status IN ('queued','running') LIMIT 64`).all(press) as { id: string }[]).map((r) => r.id) : [];+ return { generations: [...new Set([g.id, ...same])], account: typeof g.account === "string" ? g.account : null, status: g.status };+}++/**+ * Save a checked override. A run's must be one that still waits or runs; the worker it is pinned to must exist. A new+ * override of a run or a person ends the one it had (the newest wins). Returns the override and the ones it ended, or+ * the error to answer (404).+ */+export function addOverride(o: OverrideInput, by: string, now = Date.now()): { override: QueueOverride; replaced: QueueOverride[] } | { error: string; status: number } {+ const d = db();+ return d.transaction(() => {+ let generations: string[] = [];+ if (o.kind === "run") {+ const run = runRows(o.generationId);+ if (!run) return { error: "No such run", status: 404 };+ if (run.status !== "queued" && run.status !== "running") return { error: "That run has ended", status: 409 };+ generations = run.generations;+ if (o.worker && !d.prepare("SELECT 1 FROM relay_workers WHERE id = ? AND kind = 'pool' AND revoked_at IS NULL").get(o.worker)) return { error: "No such worker", status: 404 };+ }+ const target = o.kind === "run" ? o.generationId : (o.account ?? accountOfPerson(o.person!));+ if (!target) return { error: "That person has no run on the GPUs now", status: 404 };+ const replaced = (d.prepare("SELECT * FROM queue_overrides WHERE ended_at IS NULL AND kind = ? AND target = ?").all(o.kind, target) as OverrideRow[])+ .map((r) => endOverride(r.id, by, "replaced", now))+ .filter((r): r is QueueOverride => !!r);+ const row: OverrideRow = {+ id: crypto.randomBytes(6).toString("hex"),+ kind: o.kind,+ target,+ action: o.action,+ worker_id: o.kind === "run" ? o.worker : null,+ gens_json: o.kind === "run" ? JSON.stringify(generations) : null,+ until: o.until,+ set_by: by,+ set_at: now,+ ended_at: null,+ ended_by: null,+ end_why: null,+ };+ d.prepare(+ "INSERT INTO queue_overrides (id, kind, target, action, worker_id, gens_json, until, set_by, set_at) VALUES (@id, @kind, @target, @action, @worker_id, @gens_json, @until, @set_by, @set_at)",+ ).run(row);+ return { override: fromRow(row), replaced };+ })();+}++// ---------------------------------------------------------------------------+// The line with the controls++/** What the controls say about one task for one worker (or for the line as a whole: `workerId` null). */+export interface TaskControl {+ /** 0: a run sent next; 1: a boosted person's; 2: any other. Lower goes first, before the mode's classes. */+ tier: number;+ /** Not taken now: held (the run or the person), pinned to another worker, or the owner's own in People only. */+ out: null | "held" | "pinned" | "paused";+ /** The override that decides it, if one does. */+ by: QueueOverride | null;+}++/** The controls in effect for one look at the line: the mode, and the live overrides by run row and by person. */+export interface LineControls {+ mode: QueueMode;+ overrides: QueueOverride[];+ runs: Map<string, QueueOverride>;+ people: Map<string, QueueOverride>;+}++export function lineControls(mode: QueueMode, overrides: QueueOverride[]): LineControls {+ const runs = new Map<string, QueueOverride>();+ const people = new Map<string, QueueOverride>();+ for (const o of overrides) {+ if (o.kind === "run") for (const g of o.generations) runs.set(g, o);+ else people.set(o.target, o);+ }+ return { mode, overrides, runs, people };+}++/** Is this the default line (people first, no override): the claim and the place in line then read the line as before. */+export const plainLine = (c: LineControls) => c.mode === DEFAULT_MODE && c.overrides.length === 0;++/**+ * One task under the controls. A run's own override wins over its person's: a run sent next goes even while its person+ * is held, and a held run stays held while its person is boosted. The owner's own jobs in People only are paused,+ * unless the owner sent that run next.+ */+export function taskControl(t: Pick<TaskRow, "generation_id" | "account">, base: number, c: LineControls, workerId: string | null): TaskControl {+ const run = c.runs.get(t.generation_id) ?? null;+ if (run?.action === "hold") return { tier: 2, out: "held", by: run };+ if (run?.action === "next") {+ if (run.workerId && workerId && run.workerId !== workerId) return { tier: 2, out: "pinned", by: run };+ return { tier: 0, out: null, by: run };+ }+ const person = t.account ? (c.people.get(t.account) ?? null) : null;+ if (person?.action === "hold") return { tier: 2, out: "held", by: person };+ if (c.mode === "people-only" && base === 2) return { tier: 2, out: "paused", by: null };+ if (person?.action === "boost") return { tier: 1, out: null, by: person };+ return { tier: 2, out: null, by: null };+}++/** The generation ids and accounts the live overrides name: fetched beside the line's first rows, so none is missed. */+export function overrideTargets(c: LineControls): { generations: string[]; accounts: string[] } {+ const gens = c.overrides.filter((o) => o.kind === "run" && o.action === "next").flatMap((o) => o.generations);+ const accounts = c.overrides.filter((o) => o.kind === "person" && o.action === "boost").map((o) => o.target);+ return { generations: [...new Set(gens)].slice(0, 500), accounts: [...new Set(accounts)].slice(0, 100) };+}++/** Why a task stands where it does, in the owner's words ("Run next", "Boosted"); the override's `until` says until when. */+export function controlWords(tc: TaskControl, base: number, mode: QueueMode, workerName: (id: string) => string | null): string {+ const o = tc.by;+ if (tc.out === "held") return o?.kind === "person" ? "Held: this person's runs wait" : "Held by the owner";+ if (tc.out === "pinned") return `Pinned to ${workerName(o!.workerId!) ?? "another worker"}`;+ if (tc.out === "paused") return "Waits: People only";+ if (tc.tier === 0) return o?.workerId ? `Run next on ${workerName(o.workerId) ?? "its worker"}` : "Run next";+ if (tc.tier === 1) return "Boosted: this person's runs first";+ if (mode === "ours-first") return base === 2 ? "Our work first" : "After our work (Our work first)";+ if (mode === "balanced") return base === 0 ? "Paid run" : "Balanced: by when it came";+ return base === 0 ? "Paid run" : base === 1 ? "People first" : "Our work: after people's runs";+}diff --git a/src/server/computer/queue-live.ts b/src/server/computer/queue-live.tsindex cf2fd9ed..2a5dd194 100644--- a/src/server/computer/queue-live.ts+++ b/src/server/computer/queue-live.ts@@ -6,7 +6,9 @@ import { laneLabel } from "@/lib/lanes";import { HOLDING_OTHER, HOLDING_WHY, SENT_STATES, type WorkerHolding } from "@/lib/relay";import { db } from "../db";import { loadIndex } from "../gpu/index-file";-import { claimableNow, ownerWaitingNow, workerState } from "./pool";+import { claimableNow, controlledLine, localWorkOf, ownerWaitingNow, workerState } from "./pool";+import { controlWords, effectiveMode, liveOverrides, MODE_WORDS, overrideView, personKey, poolMode, poolModes, recentOverrides, sweepControls, workerModeOf, type EffectiveMode, type OverrideView, type QueueMode } from "./queue-controls";+import type { LocalWork } from "@/lib/relay";import { json, taskCold, taskProgress, type TaskRow } from "./tasks";import type { WorkerRow } from "./workers";@@ -41,7 +43,7 @@ export interface RunningJob {principal: PrincipalKind;}-/** A job waiting in line for a worker (the oldest first). */+/** A job waiting in line for a worker, in the order the workers serve them (the ones no worker takes now last). */export interface QueuedJob {task: string;generationId: string;@@ -53,6 +55,37 @@ export interface QueuedJob {/** When its run was made, and its place in line (a run back in line keeps its place). */createdAt: number | null;inLineAt: number;+ /** Its place in the line its pool's workers serve (1: next); null while no worker takes it (held, People only). */+ rank: number | null;+ /** Why it stands there, in words ("People first", "Run next", "Held by the owner"). */+ why: string;+ /** What decides it: the class's order ("class"), a run sent next ("next"), a boosted person ("boost"), or why no worker takes it now. */+ code: "class" | "next" | "boost" | "held" | "pinned" | "paused";+ /** The owner's override that decides it (null: none), with until when. */+ override: { id: string; until: number | null; by: string; at: number; workerId: string | null } | null;+ /** The person whose run it is, as a key (never an account id; null: the owner's own), and whether a guest's. */+ person: string | null;+ guest: boolean;+}++/** A worker's mode and the local work on its PC, for the owner's Queue page. */+export interface WorkerControl {+ id: string;+ name: string;+ pool: string;+ mode: EffectiveMode;+ /** Its own mode as set (null: it follows its pool). */+ own: { mode: QueueMode; until: number | null; by: string; at: number } | null;+ localWork: LocalWork | null;+}++/** The owner's controls in effect: each pool's mode, each worker's, the overrides, and the ones that ended lately. */+export interface QueueControls {+ pools: Record<string, EffectiveMode>;+ workers: WorkerControl[];+ overrides: OverrideView[];+ ended: OverrideView[];+ modes: { id: QueueMode; label: string }[];}/**@@ -115,8 +148,10 @@ const mins = (ms: number) => Math.max(1, Math.round(ms / 60_000));type GenFacts = { id: string; model_id: string; op: string; kind: string; status: string; message: string | null; created_at: number; completed_at: number | null };-export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: HeldJob[]; queued: QueuedJob[]; next: NextStep[]; nextTotal: number; text: TextLine } {+export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: HeldJob[]; queued: QueuedJob[]; next: NextStep[]; nextTotal: number; text: TextLine; controls: QueueControls } {const d = db();+ // The owner's controls that ran their course end before the view is read.+ sweepControls(now);const index = loadIndex();const workers = d.prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as WorkerRow[];const byId = new Map(workers.map((w) => [w.id, w]));@@ -163,11 +198,17 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: H});}- // The jobs waiting in line, the oldest place first.- const queued: QueuedJob[] = (- d.prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' ORDER BY COALESCE(rank_at, created_at), id LIMIT ?").all(QUEUED_LIMIT) as TaskRow[]- ).map((t) => {+ // The jobs waiting in line, in the order each pool's workers serve them under the owner's controls; then the ones no+ // worker takes now (held, the owner's own in People only).+ const pools = [...new Set(["pool", ...workers.map((w) => w.pool)])];+ const lines = pools.map((pool) => controlledLine(pool, now));+ const seen = new Set<string>();+ const items = lines.flatMap((l) => l.items.map((x) => ({ ...x, mode: l.mode }))).filter((x) => !seen.has(x.task.id) && !!seen.add(x.task.id));+ const ordered = [...items.filter((x) => x.rank !== null), ...items.filter((x) => x.rank === null)];+ const nameOf = (id: string) => byId.get(id)?.name ?? null;+ const queued: QueuedJob[] = ordered.slice(0, QUEUED_LIMIT).map(({ task: t, rank, base, control, mode }) => {const g = genOf(t.generation_id);+ const o = control.by;return {task: t.id,generationId: t.generation_id,@@ -178,6 +219,12 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: Hprincipal: principalKind(t),createdAt: g?.created_at ?? null,inLineAt: t.rank_at ?? t.created_at,+ rank,+ why: controlWords(control, base, mode, nameOf),+ code: control.out ?? (control.tier === 0 ? "next" : control.tier === 1 ? "boost" : "class"),+ override: o ? { id: o.id, until: o.until, by: o.by, at: o.at, workerId: o.workerId } : null,+ person: t.account ? personKey(t.account) : null,+ guest: !!t.account?.startsWith("guest"),};});@@ -224,5 +271,12 @@ export function liveQueue(now = Date.now()): { running: RunningJob[]; holding: Hrunning: number | null;oldest: number | null;};- return { running, holding, queued, next, nextTotal, text: { waiting: tx.waiting ?? 0, running: tx.running ?? 0, oldestAt: tx.oldest ?? null } };+ const controls: QueueControls = {+ pools: Object.fromEntries([...new Set(["pool", ...workers.map((w) => w.pool), ...Object.keys(poolModes(now))])].map((pool) => [pool, poolMode(pool, now)])),+ workers: workers.map((w) => ({ id: w.id, name: w.name, pool: w.pool, mode: effectiveMode(w, now), own: workerModeOf(w), localWork: localWorkOf(w, now) })),+ overrides: liveOverrides(now).map(overrideView),+ ended: recentOverrides(10).map(overrideView),+ modes: (Object.keys(MODE_WORDS) as QueueMode[]).map((id) => ({ id, label: MODE_WORDS[id] })),+ };+ return { running, holding, queued, next, nextTotal, text: { waiting: tx.waiting ?? 0, running: tx.running ?? 0, oldestAt: tx.oldest ?? null }, controls };}diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.tsindex 06a4a404..52d40e6f 100644--- a/src/server/computer/workers.ts+++ b/src/server/computer/workers.ts@@ -81,6 +81,10 @@ export interface WorkerRow {/** Its last claim for its GPU's slot, and the answer in words (pool.ts workerClaim). */asked_at?: number | null;asked_words?: string | null;+ /** The owner's mode for this worker (queue-controls.ts ModeSetting), winning over its pool's while it lasts. NULL: none. */+ mode_json?: string | null;+ /** Local work on its PC (a queue of the owner's own), as its last beat said (src/lib/relay.ts LocalWork). NULL: none. */+ local_work_json?: string | null;}const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");diff --git a/src/server/db.ts b/src/server/db.tsindex 4b50c822..b4aefcbb 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -812,6 +812,21 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (seen_at INTEGER);CREATE INDEX IF NOT EXISTS relay_workers_principal ON relay_workers(principal);+ CREATE TABLE IF NOT EXISTS queue_overrides (+ id TEXT PRIMARY KEY,+ kind TEXT NOT NULL,+ target TEXT NOT NULL,+ action TEXT NOT NULL,+ worker_id TEXT,+ gens_json TEXT,+ until INTEGER,+ set_by TEXT NOT NULL,+ set_at INTEGER NOT NULL,+ ended_at INTEGER,+ ended_by TEXT,+ end_why TEXT+ );+ CREATE INDEX IF NOT EXISTS queue_overrides_live ON queue_overrides(ended_at, kind, target);CREATE TABLE IF NOT EXISTS relay_pairings (id TEXT PRIMARY KEY,code TEXT NOT NULL UNIQUE,@@ -1113,6 +1128,9 @@ const RELAY_COLUMNS: [string, string, string][] = [// A worker's last claim for its GPU's slot, and the answer in words (pool.ts workerClaim).["relay_workers", "asked_at", "INTEGER"],["relay_workers", "asked_words", "TEXT"],+ // The owner's mode for one worker (computer/queue-controls.ts), and local work on its PC as its last beat said.+ ["relay_workers", "mode_json", "TEXT"],+ ["relay_workers", "local_work_json", "TEXT"],];declare global {diff --git a/tests/admin-queue-live.test.ts b/tests/admin-queue-live.test.tsindex f287957e..36302a5f 100644--- a/tests/admin-queue-live.test.ts+++ b/tests/admin-queue-live.test.ts@@ -201,13 +201,14 @@ describe("what the workers do now", () => {expect(liveQueue(clock).nextTotal).toBe(NEXT_LIMIT + 3);});- it("the jobs waiting in line, by their place, with when their run was made", () => {+ it("the jobs waiting in line, in the order the workers serve them, with their place, why, and when their run was made", () => {const a = task({ account: "acct-5" });const b = task();db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(clock - 9 * MIN, b.id);+ // People first: the account's run ahead of the owner's own, although the owner's came first.expect(liveQueue(clock).queued).toEqual([- { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN },- { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock },+ { task: a.id, generationId: a.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "user", createdAt: clock, inLineAt: clock, rank: 1, why: "People first", code: "class", override: null, person: expect.stringMatching(/^p-[0-9a-f]{12}$/), guest: false },+ { task: b.id, generationId: b.gid, model: "m-test", op: "t2i", lane: LANE, laneLabel: expect.any(String), principal: "owner", createdAt: clock, inLineAt: clock - 9 * MIN, rank: 2, why: "Our work: after people's runs", code: "class", override: null, person: null, guest: false },]);// A worker takes the account's run first (people's runs go before the owner's own): the owner's stays in line.const w = worker("takes");@@ -237,7 +238,7 @@ describe("GET /api/admin/queue", () => {const res = await queueRoute.GET(new NextRequest("http://localhost:3000/api/admin/queue", { headers: { authorization: `Bearer ${token}` } }));expect(res.status).toBe(200);const body = (await res.json()) as Record<string, unknown>;- expect(Object.keys(body).sort()).toEqual(["held", "holding", "lanes", "next", "nextTotal", "now", "queued", "running", "text"]);+ expect(Object.keys(body).sort()).toEqual(["controls", "held", "holding", "lanes", "next", "nextTotal", "now", "queued", "running", "text"]);expect(body.held).toMatchObject({ mine: 0, oldestAt: null });expect(body.holding).toEqual([expect.objectContaining({ task: id, principal: "user" })]);expect(JSON.stringify(body)).not.toContain("acct-secret");diff --git a/tests/queue-controls.test.ts b/tests/queue-controls.test.tsnew file mode 100644index 00000000..8785fa71--- /dev/null+++ b/tests/queue-controls.test.ts@@ -0,0 +1,396 @@+import crypto from "node:crypto";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++/**+ * The owner's controls over who the GPUs serve first (src/server/computer/queue-controls.ts): the pool's mode and a+ * worker's own (people first, people only, our work first, balanced), with their ends; a run sent next, pinned to a+ * worker or held; a person boosted or held; what the beat answer and the queue view say; the admin routes, their+ * scope and the admin log.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++const dir = tempDir("fuobe-queue-controls-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_BILLING_URL;+globalThis.__fuobeTestDiskFree = 1e13;++const auth = await import("@/server/auth");+const admin = await import("@/server/admin-tokens");+const modeRoute = await import("@/app/api/admin/queue/mode/route");+const overridesRoute = await import("@/app/api/admin/queue/overrides/route");+const overrideRoute = await import("@/app/api/admin/queue/overrides/[id]/route");+const cancelRoute = await import("@/app/api/admin/queue/cancel/route");+const queueRoute = await import("@/app/api/admin/queue/route");+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 qc = await import("@/server/computer/queue-controls");+const { liveQueue } = await import("@/server/computer/queue-live");+const { catalogVersion } = await import("@/server/computer/catalog-version");+const qs = await import("@/server/queue-settings");+const { loadManifest } = await import("@/server/providers/comfyui");+const { loadIndex } = await import("@/server/gpu/index-file");+const { allLanes } = await import("@/lib/lanes");++const MIN = 60_000;+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");+type WorkerRow = import("@/server/computer/workers").WorkerRow;+type TaskRow = import("@/server/computer/tasks").TaskRow;++let alice = "";+let bob = "";++beforeAll(() => {+ auth.setPassword("install password");+ alice = auth.createAccount("[email protected]", "long enough").id;+ bob = auth.createAccount("[email protected]", "long enough").id;+});+beforeEach(() => {+ resetRates();+ qs.saveQueueSettings(qs.QUEUE_DEFAULTS);+ setSetting("comfyWhere", "workers");+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("DELETE FROM queue_overrides").run();+ db().prepare("DELETE FROM settings WHERE key = 'queue.modes'").run();+ globalThis.__fuobeQueueModes = undefined;+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state != 'canceled'").run();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+});++function worker(name: string) {+ const 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 });+ db()+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3, seen_at = ?, paused_local = 0 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(), Date.now(), w.id);+ return w;+}+const row = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;+const beat = (w: { id: string }, extra: Record<string, unknown> = {}, now = Date.now()) =>+ pool.workerBeat(row(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [], catalogVersion: catalogVersion(), ...extra }), now);+const claim = (w: { id: string }, now = Date.now()) => pool.workerClaim(row(w), [], now);+const taskRow = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow;+const done = (id: string) => db().prepare("UPDATE relay_tasks SET state = 'done', finished_at = ? WHERE id = ?").run(Date.now(), id);++let gens = 0;+/** A task in line: a person's (`account`) or the owner's, made `agoMs` ago; returns its task and run ids. */+function job(o: { account?: string; class?: "paid" | "free" | "owner"; agoMs?: number } = {}) {+ const gid = `ctl-gen-${++gens}`;+ const at = Date.now() - (o.agoMs ?? 0);+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")+ .run(gid, JSON.stringify(o.account ? { account: o.account, place: "pool" } : {}), at, at);+ const t = tasks.createTask({+ principal: o.account ? `acct:${o.account}` : "owner",+ generationId: gid,+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },+ pool: { pools: ["pool"], account: o.account, class: o.class, rankAt: at, lane: allLanes(loadIndex(), sha)[0].lane, needs: { workflowId: loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 } },+ });+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(at, t.id);+ return { id: t.id, gid };+}++/** Every waiting task this worker takes, one by one, each finished at once. */+function served(w: { id: string }): string[] {+ const out: string[] = [];+ for (;;) {+ beat(w);+ const t = claim(w);+ if (!t) return out;+ out.push(t.id);+ done(t.id);+ }+}++const setMode = (body: Record<string, unknown>, now = Date.now()) => {+ const c = qc.checkModeChange(body, "owner", now);+ if ("error" in c) throw new Error(c.error);+ return qc.applyModeChange(c, now);+};+const override = (body: Record<string, unknown>, now = Date.now()) => {+ const o = qc.checkOverride(body, now);+ if ("error" in o) throw new Error(o.error);+ const r = qc.addOverride(o, "owner", now);+ if ("error" in r) throw new Error(r.error);+ return r.override;+};++describe("modes", () => {+ it("people first (the default): people's runs before the owner's own; the beat says so, with local work making room", () => {+ const w = worker("w1");+ const owner = job({ agoMs: 60 * MIN });+ const a = job({ account: alice, agoMs: 10 * MIN });+ const answer = beat(w);+ expect(answer.worker.queue).toEqual({ mode: "people-first", localWork: "yield", until: null });+ expect(served(w)).toEqual([a.id, owner.id]);+ });++ it("our work first: the owner's own jobs first, with a person's place counting them; local work keeps the GPU while it runs", () => {+ const w = worker("w1");+ const a = job({ account: alice, agoMs: 30 * MIN });+ const owner = job({ agoMs: 1 * MIN });+ setMode({ mode: "ours-first", forMin: 30 });+ expect(pool.placeInLine(taskRow(a.id)).place).toBe(2);+ // Local work on its PC runs: people's runs ask it for no room; once it is idle they do.+ expect(beat(w, { localWork: { state: "running", why: null, waiting: 12, running: true, at: Date.now() } }).claimableNow).toBe(0);+ expect(beat(w, { localWork: { state: "idle", why: "no-work", waiting: 0, running: false, at: Date.now() } }).claimableNow).toBe(1);+ const answer = beat(w);+ expect(answer.worker.queue).toMatchObject({ mode: "ours-first", localWork: "run" });+ expect(answer.worker.queue!.until).toBeGreaterThan(Date.now() + 29 * MIN);+ expect(served(w)).toEqual([owner.id, a.id]);+ });++ it("people only: the owner's own jobs are never taken and their count is 0; local work pauses; they are listed with no place", () => {+ const w = worker("w1");+ const owner = job({ agoMs: 60 * MIN });+ const a = job({ account: alice, agoMs: 1 * MIN });+ setMode({ mode: "people-only", forMin: null });+ const answer = beat(w);+ expect(answer.worker.queue).toEqual({ mode: "people-only", localWork: "pause", until: null });+ expect(answer.ownerWaitingNow).toBe(0);+ expect(answer.claimableNow).toBe(1);+ expect(served(w)).toEqual([a.id]);+ const q = liveQueue().queued;+ expect(q).toEqual([expect.objectContaining({ task: owner.id, rank: null, code: "paused", why: "Waits: People only", person: null })]);+ // Back to normal: the owner's job goes.+ setMode({ mode: null });+ expect(served(w)).toEqual([owner.id]);+ });++ it("balanced: free runs and the owner's own jobs in one line by when they came; paid runs first", () => {+ const w = worker("w1");+ const owner = job({ agoMs: 30 * MIN });+ const a = job({ account: alice, agoMs: 20 * MIN });+ const paid = job({ account: bob, class: "paid", agoMs: 1 * MIN });+ setMode({ mode: "balanced", forMin: 60 });+ expect(served(w)).toEqual([paid.id, owner.id, a.id]);+ });++ it("a worker's own mode wins over its pool's; back to normal follows the pool again", () => {+ const w1 = worker("w1");+ const w2 = worker("w2");+ setMode({ mode: "people-only", forMin: 60 });+ setMode({ worker: w2.id, mode: "ours-first", forMin: 30 });+ expect(beat(w1).worker.queue!.mode).toBe("people-only");+ expect(beat(w2).worker.queue!.mode).toBe("ours-first");+ expect(pool.workerView(row(w2)).mode).toMatchObject({ mode: "ours-first", from: "worker", by: "owner" });+ setMode({ worker: w2.id, mode: null });+ expect(pool.workerView(row(w2)).mode).toMatchObject({ mode: "people-only", from: "pool" });+ });++ it("a mode ends at its time: people first again, and the admin log says so (system)", () => {+ const w = worker("w1");+ const now = Date.now();+ setMode({ mode: "ours-first", forMin: 1 }, now);+ setMode({ worker: w.id, mode: "people-only", forMin: 1 }, now);+ expect(qc.poolMode("pool", now + 30_000).mode).toBe("ours-first");+ const later = now + 2 * MIN;+ expect(qc.poolMode("pool", later).mode).toBe("people-first");+ beat(w, {}, later);+ expect(qc.poolModes(later + 5000)).toEqual({});+ expect(row(w).mode_json).toBeNull();+ const ends = db().prepare("SELECT actor, target, detail_json FROM admin_audit WHERE action = 'queue.mode.end' ORDER BY id").all() as { actor: string; target: string; detail_json: string }[];+ expect(ends.map((e) => [e.actor, e.target])).toEqual([+ ["system", "pool:pool"],+ ["system", `worker:${w.id}`],+ ]);+ });++ it("checks a change: known modes, 1 minute to a week, a pool or a worker", () => {+ expect(qc.checkModeChange({ mode: "everything" }, "owner")).toEqual({ error: expect.stringMatching(/^mode is one of/) });+ expect(qc.checkModeChange({ mode: "ours-first", forMin: 0 }, "owner")).toEqual({ error: expect.stringMatching(/^forMin is 1 to 10080/) });+ expect(qc.checkModeChange({ mode: "ours-first", forMin: 10081 }, "owner")).toHaveProperty("error");+ expect(qc.checkModeChange({ mode: "ours-first", pool: "pool", worker: "x" }, "owner")).toHaveProperty("error");+ expect(qc.checkModeChange({ mode: null, forMin: 5 }, "owner")).toHaveProperty("error");+ expect(qc.checkModeChange({ mode: "ours-first", extra: 1 }, "owner")).toEqual({ error: "Unknown field: extra" });+ // People first with no end on a pool is the default: stored as none.+ expect(qc.checkModeChange({ mode: "people-first" }, "owner")).toEqual({ scope: "pool", pool: "pool", setting: null });+ });+});++describe("runs and people", () => {+ it("run next goes ahead of every class, paid runs too; it ends once its run ends", () => {+ const w = worker("w1");+ const paid = job({ account: bob, class: "paid", agoMs: 30 * MIN });+ const owner = job({ agoMs: 1 * MIN });+ const o = override({ kind: "run", generationId: owner.gid, action: "next" });+ expect(pool.placeInLine(taskRow(paid.id)).place).toBe(2);+ expect(liveQueue().queued.map((q) => [q.task, q.rank, q.code])).toEqual([+ [owner.id, 1, "next"],+ [paid.id, 2, "class"],+ ]);+ expect(served(w)).toEqual([owner.id, paid.id]);+ db().prepare("UPDATE generations SET status = 'succeeded' WHERE id = ?").run(owner.gid);+ qc.sweepControls();+ expect(qc.liveOverrides().map((x) => x.id)).not.toContain(o.id);+ expect(qc.recentOverrides(1)[0]).toMatchObject({ id: o.id, endWhy: "run-ended", endedBy: "system" });+ });++ it("pinned to a worker: only that worker takes it, first", () => {+ const w1 = worker("w1");+ const w2 = worker("w2");+ const a = job({ account: alice, agoMs: 30 * MIN });+ const owner = job({ agoMs: 1 * MIN });+ override({ kind: "run", generationId: owner.gid, action: "next", worker: w2.id });+ expect(served(w1)).toEqual([a.id]);+ expect(served(w2)).toEqual([owner.id]);+ });++ it("a held run keeps its place, isn't taken or counted, shows as held, and goes once released", () => {+ const w = worker("w1");+ const a = job({ account: alice, agoMs: 30 * MIN });+ const b = job({ account: bob, agoMs: 1 * MIN });+ const o = override({ kind: "run", generationId: a.gid, action: "hold", forMin: 60 });+ expect(beat(w).claimableNow).toBe(1);+ expect(pool.placeInLine(taskRow(b.id)).place).toBe(1);+ expect(liveQueue().queued.find((q) => q.task === a.id)).toMatchObject({ rank: null, code: "held", why: "Held by the owner", override: { id: o.id, by: "owner" } });+ expect(served(w)).toEqual([b.id]);+ expect(qc.endOverride(o.id, "owner", "released")).toMatchObject({ endWhy: "released" });+ expect(served(w)).toEqual([a.id]);+ });++ it("a boosted person's runs go first until the boost ends; a held person's wait", () => {+ const w = worker("w1");+ const a1 = job({ account: alice, agoMs: 30 * MIN });+ const b1 = job({ account: bob, agoMs: 20 * MIN });+ const b2 = job({ account: bob, agoMs: 10 * MIN });+ const now = Date.now();+ override({ kind: "person", person: qc.personKey(bob), action: "boost", forMin: 30 }, now);+ expect(liveQueue().queued.slice(0, 2).map((q) => [q.task, q.code, q.why])).toEqual([+ [b1.id, "boost", "Boosted: this person's runs first"],+ [b2.id, "boost", "Boosted: this person's runs first"],+ ]);+ expect(served(w)).toEqual([b1.id, b2.id, a1.id]);+ const a2 = job({ account: alice });+ const c = job({ account: bob });+ override({ kind: "person", account: alice, action: "hold" });+ expect(served(w)).toEqual([c.id]);+ expect(taskRow(a2.id).state).toBe("waiting");+ });++ it("our work first: a boosted person's run still asks local work for room", () => {+ const w = worker("w1");+ job({ account: alice });+ job({ account: bob });+ setMode({ mode: "ours-first", forMin: 30 });+ override({ kind: "person", account: bob, action: "boost", forMin: 30 });+ expect(beat(w, { localWork: { state: "running", why: null, waiting: 3, running: true, at: Date.now() } }).claimableNow).toBe(1);+ });++ it("a boost ends at its time", () => {+ const w = worker("w1");+ const a = job({ account: alice, agoMs: 30 * MIN });+ const b = job({ account: bob, agoMs: 1 * MIN });+ const now = Date.now();+ const o = override({ kind: "person", account: bob, action: "boost", forMin: 1 }, now - 2 * MIN);+ qc.sweepControls(now);+ expect(qc.recentOverrides(1)[0]).toMatchObject({ id: o.id, endWhy: "expired" });+ expect(served(w)).toEqual([a.id, b.id]);+ });++ it("checks a change", () => {+ expect(qc.checkOverride({ kind: "person", account: alice, action: "boost" })).toEqual({ error: expect.stringMatching(/^forMin/) });+ expect(qc.checkOverride({ kind: "run", generationId: "x", action: "boost" })).toHaveProperty("error");+ expect(qc.checkOverride({ kind: "run", generationId: "x", action: "hold", worker: "w" })).toEqual({ error: "Only Run next is pinned to a worker" });+ expect(qc.checkOverride({ kind: "person", account: alice, person: "p-000000000000", action: "hold" })).toHaveProperty("error");+ expect(qc.checkOverride({ kind: "thing" })).toEqual({ error: "kind is run or person" });+ // Run next lasts at most a day.+ const now = Date.now();+ expect(qc.checkOverride({ kind: "run", generationId: "x", action: "next", forMin: 5000 }, now)).toMatchObject({ until: now + 24 * 60 * MIN });+ });+});++describe("local work on the PC", () => {+ it("the beat keeps it (codes and counts only) while fresh; the worker's view shows it", () => {+ const w = worker("w1");+ const now = Date.now();+ beat(w, { localWork: { state: "paused", why: "people-only", waiting: 77, running: false, at: now + 5 * MIN, name: "secret job" } }, now);+ expect(JSON.parse(row(w).local_work_json!)).toEqual({ state: "paused", why: "people-only", waiting: 77, running: false, at: now });+ expect(pool.workerView(row(w), now).localWork).toMatchObject({ state: "paused", waiting: 77 });+ expect(pool.workerView(row(w), now + 3 * MIN).localWork).toBeNull();+ expect(pool.cleanLocalWork({ state: "exploding", at: now })).toBeNull();+ expect(pool.cleanLocalWork({ state: "idle", why: "Not A Code!", at: now })).toMatchObject({ why: null });+ });+});++describe("the admin routes", () => {+ const post = (route: { POST: (r: Request) => Promise<Response> }, path: string, body: unknown, token?: string) =>+ route.POST(new NextRequest(`http://localhost:3000${path}`, { method: "POST", body: JSON.stringify(body), headers: { "content-type": "application/json", ...(token && { authorization: `Bearer ${token}` }) } }));++ it("need queue:control; a reader can't change anything; every change is in the admin log", async () => {+ const reader = admin.createAdminToken({ name: "reader", scopes: ["queue:read"], expiresInDays: null }).token;+ const controller = admin.createAdminToken({ name: "controller", scopes: ["queue:read", "queue:control"], expiresInDays: null }).token;+ expect((await post(modeRoute, "/api/admin/queue/mode", { mode: "people-only" }, reader)).status).toBe(403);+ const bad = await post(modeRoute, "/api/admin/queue/mode", { mode: "nobody" }, controller);+ expect(bad.status).toBe(400);+ const ok = await post(modeRoute, "/api/admin/queue/mode", { mode: "ours-first", forMin: 30 }, controller);+ expect(ok.status).toBe(200);+ expect(await ok.json()).toMatchObject({ mode: { mode: "ours-first", from: "pool", by: "controller" }, before: { mode: "people-first" } });+ const missing = await post(modeRoute, "/api/admin/queue/mode", { worker: "nope", mode: "people-only" }, controller);+ expect(missing.status).toBe(404);+ const log = db().prepare("SELECT token_name, target, status FROM admin_audit WHERE action = 'queue.mode' ORDER BY id").all();+ expect(log).toEqual([+ { token_name: "controller", target: null, status: 400 },+ { token_name: "controller", target: "pool:pool", status: 200 },+ { token_name: "controller", target: "worker:nope", status: 404 },+ ]);+ });++ it("overrides: add by a person's key, list, release; the answers name no account", async () => {+ const controller = admin.createAdminToken({ name: "controller2", scopes: ["queue:read", "queue:control"], expiresInDays: null }).token;+ job({ account: alice });+ const none = await post(overridesRoute, "/api/admin/queue/overrides", { kind: "person", person: "p-000000000000", action: "hold" }, controller);+ expect(none.status).toBe(404);+ const made = await post(overridesRoute, "/api/admin/queue/overrides", { kind: "person", person: qc.personKey(alice), action: "boost", forMin: 15 }, controller);+ expect(made.status).toBe(201);+ const body = (await made.json()) as { override: { id: string; person: string; by: string } };+ expect(body.override).toMatchObject({ person: qc.personKey(alice), by: "controller2", action: "boost" });+ expect(JSON.stringify(body)).not.toContain(alice);+ const list = await overridesRoute.GET(new NextRequest("http://localhost:3000/api/admin/queue/overrides", { headers: { authorization: `Bearer ${controller}` } }));+ expect(((await list.json()) as { live: { id: string }[] }).live.map((o) => o.id)).toEqual([body.override.id]);+ const del = (id: string) =>+ overrideRoute.DELETE(new NextRequest(`http://localhost:3000/api/admin/queue/overrides/${id}`, { method: "DELETE", headers: { authorization: `Bearer ${controller}` } }), { params: Promise.resolve({ id }) } as never);+ expect((await del(body.override.id)).status).toBe(200);+ expect((await del(body.override.id)).status).toBe(404);+ expect(db().prepare("SELECT action, status FROM admin_audit WHERE action LIKE 'queue.override%' AND actor != 'system' ORDER BY id").all()).toEqual([+ { action: "queue.override", status: 404 },+ { action: "queue.override", status: 201 },+ { action: "queue.override.end", status: 200 },+ { action: "queue.override.end", status: 404 },+ ]);+ });++ it("cancel: a waiting run ends canceled; one that ended is 409; none is 404", async () => {+ const controller = admin.createAdminToken({ name: "controller3", scopes: ["queue:control"], expiresInDays: null }).token;+ const a = job({ account: alice });+ expect((await post(cancelRoute, "/api/admin/queue/cancel", { generationId: "nope" }, controller)).status).toBe(404);+ const r = await post(cancelRoute, "/api/admin/queue/cancel", { generationId: a.gid }, controller);+ expect(r.status).toBe(200);+ expect(await r.json()).toEqual({ generationId: a.gid, status: "canceled" });+ expect((await post(cancelRoute, "/api/admin/queue/cancel", { generationId: a.gid }, controller)).status).toBe(409);+ });++ it("GET /api/admin/queue shows the controls: each pool's mode, each worker's, the overrides, and why each run stands where it does", async () => {+ const w = worker("w1");+ job({ account: alice });+ setMode({ worker: w.id, mode: "people-only", forMin: 20 });+ const reader = admin.createAdminToken({ name: "reader2", scopes: ["queue:read"], expiresInDays: null }).token;+ const res = await queueRoute.GET(new NextRequest("http://localhost:3000/api/admin/queue", { headers: { authorization: `Bearer ${reader}` } }));+ const body = (await res.json()) as { controls: { pools: Record<string, { mode: string }>; workers: { name: string; mode: { mode: string; from: string } }[]; modes: unknown[] }; queued: { why: string; person: string }[] };+ expect(body.controls.pools.pool.mode).toBe("people-first");+ expect(body.controls.workers).toEqual([expect.objectContaining({ name: "w1", mode: expect.objectContaining({ mode: "people-only", from: "worker" }) })]);+ expect(body.controls.modes).toHaveLength(4);+ expect(body.queued[0]).toMatchObject({ why: "People first", person: qc.personKey(alice) });+ expect(JSON.stringify(body)).not.toContain(alice);+ });+});diff --git a/tests/worker-turns-run.test.ts b/tests/worker-turns-run.test.tsindex ace3d71e..5b03fff7 100644--- a/tests/worker-turns-run.test.ts+++ b/tests/worker-turns-run.test.ts@@ -433,6 +433,35 @@ describe("studio jobs first", () => {await until(() => workerRow(w).local_why?.startsWith("gpu-busy"));await until(() => site(p)?.siteWaiting === 0);});++ it("the owner's mode reaches the turns folder (mode.json), and local work's own word (local.json) reaches the studio", async () => {+ const qc = await import("@/server/computer/queue-controls");+ const w = addWorker();+ const p = pc();+ const c = qc.checkModeChange({ worker: w.id, mode: "people-only", forMin: 30 }, "owner");+ if ("error" in c) throw new Error(c.error);+ qc.applyModeChange(c);+ start(w, p, fakeGpu(p, { workMb: 0 }));+ const mode = await until(() => {+ try {+ return JSON.parse(fs.readFileSync(path.join(p.turns, "mode.json"), "utf8")) as { mode: string; localWork: string; until: number | null; at: number };+ } catch {+ return null;+ }+ });+ expect(mode).toMatchObject({ mode: "people-only", localWork: "pause" });+ expect(mode.until).toBeGreaterThan(Date.now() + 25 * 60_000);+ await until(() => p.logs.some((l) => /The owner set who goes first: people-only/.test(l)));+ // Back to normal: the next beat answer says people first.+ const back = qc.checkModeChange({ worker: w.id, mode: null }, "owner");+ if ("error" in back) throw new Error(back.error);+ qc.applyModeChange(back);+ await until(() => JSON.parse(fs.readFileSync(path.join(p.turns, "mode.json"), "utf8")).localWork === "yield");+ // The helper on the PC's side writes its state: the beat carries it, codes and counts only.+ fs.writeFileSync(path.join(p.turns, "local.json"), JSON.stringify({ state: "paused", why: "people-only", waiting: 42, running: false, at: Date.now(), job: "a secret name" }));+ const kept = await until(() => (db().prepare("SELECT local_work_json FROM relay_workers WHERE id = ?").get(w.id) as { local_work_json: string | null }).local_work_json);+ expect(JSON.parse(kept)).toEqual({ state: "paused", why: "people-only", waiting: 42, running: false, at: expect.any(Number) });+ });});describe("its own job and the busy pause", () => {