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
Text helper: keep answering while the worker waits to restart, and say when it is coming back
Adarsh50b3f5ab3c13
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex eca87e5a..1e6c7694 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -41,7 +41,7 @@ import { previewShrinker } from "./preview.mjs";import { withPlainResults } from "./results.mjs";import { failure, Reach, retrying } from "./retry.mjs";import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";-import { TextSlot, textSlotOf } from "./text.mjs";+import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";import { SiteTurns, writeSite } from "./turns.mjs";import { CodeWatch } from "./update.mjs";@@ -319,6 +319,8 @@ async function work(saved, deps, owner) {// New code on disk (update.mjs): it takes no new job, finishes the one it has, and ends to start again on the new code.const codeWatch = deps.codeWatch ?? new CodeWatch({ root: ROOT, dist: path.join(here, "dist"), home: deps.home });let updating = false;+ // When its last GPU or CPU job ended while it waits to restart on new code (a text job in hand may still end).+ let textDrainAt = null;// Its ComfyUI's start, while it goes on (beats go on meanwhile), and the signal that ends a start when the worker stops.let starting = null;const stopStarts = new AbortController();@@ -866,12 +868,16 @@ async function work(saved, deps, owner) {try {while (!deps.signal?.aborted) {const t = now();- // New code installed: once no job is in hand (the GPU's and the CPU slot's), it ends, and starts again on it.+ // New code installed: once no job is in hand (the GPU's and the CPU slot's), it ends, and starts again on it. The+ // text slot takes jobs until then; a text job in hand then gets up to TEXT_DRAIN_MS to end.if (!updating && codeWatch.check(t)) {updating = true;log("New worker code is installed: restarting after this job.");}- if (updating && !busyJob && !busyCpu && !text?.busy) break;+ if (updating && !busyJob && !busyCpu) {+ textDrainAt ??= t;+ if (!text?.running || t - textDrainAt >= TEXT_DRAIN_MS) break;+ }// Its own switch, and --for running out.let control = readControl(deps.home);if (control.paused && control.until && t >= control.until) {@@ -1082,10 +1088,12 @@ async function work(saved, deps, owner) {await cpuComfy.stop();}}- // The text slot: never while paused by hand, on the website, outside its hours or ending for new code.+ // The text slot: never while paused by hand, on the website or outside its hours. While the worker waits for its+ // GPU's job to end before it restarts on new code, the text slot goes on: text jobs take seconds.if (text) {const byHand = pause.paused && /^here/.test(pause.why ?? "");- text.tick(t, { may: !updating && !byHand && !!answer?.worker && !answer.worker.paused && !!answer.worker.insideHours && !answer.worker.drain, room: textRoom() });+ const turn = textTurn({ updating, gpuBusy: busyJob || busyCpu, byHand, worker: answer?.worker ?? null });+ text.tick(t, { ...turn, room: textRoom() });}// Kept results the studio never took are deleted after a day.if (t - holdCheckedAt >= 60_000) {@@ -1136,7 +1144,7 @@ async function work(saved, deps, owner) {runner.stop();cpuRunner?.stop();await Promise.race([Promise.all([job, cpuJob]), new Promise((r) => setTimeout(r, 10_000).unref?.())]);- await text?.end();+ await text?.end(updating && !deps.signal?.aborted ? "updating" : "stopped");awake.set(false);// No turn any more: local ComfyUI work may go on at once.if (turns?.folderOk()) writeTurn(now(), { siteWaiting: 0, oldestWaitS: 0, interrupt: false, interruptAt: null });diff --git a/bin/lib/worker/text.mjs b/bin/lib/worker/text.mjsindex 9b21897e..6e69ad11 100644--- a/bin/lib/worker/text.mjs+++ b/bin/lib/worker/text.mjs@@ -259,6 +259,22 @@ export class TextSlot {this.missedAt = -Infinity;// Ends a claim that waits for a job when the worker stops.this.ending = new AbortController();+ // The claim that waits now (ended when the slot stops taking jobs), and whether a job is in hand.+ this.claiming = null;+ this.running = false;+ // What the studio last heard of why the slot is away ("updating", "paused", "stopped"), and that call.+ this.away = null;+ this.awayCall = Promise.resolve();+ }++ /** Tell the studio why the slot takes no jobs for now, once for each reason (its next claim says it is back). */+ sayAway(state) {+ if (!this.ok || this.away === state) return;+ this.away = state;+ this.awayCall = this.d+ .call("/api/gpu/computer/text/away", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ state }), signal: AbortSignal.timeout(5000) })+ .then((r) => r.body?.cancel().catch(() => {}))+ .catch(() => {});}/** The model (and the server, when worker.json gives its SHA-256) checked once, in the background. */@@ -290,13 +306,20 @@ export class TextSlot {/*** Once a second from the worker's loop. `may`: the worker may take text jobs (not paused by hand or on the website,- * inside its hours). `room`: "gpu", "cpu" or null, where a new start may run now.+ * inside its hours, not ending for new code). `away`: why not, for the studio ("updating" or "paused"), or null.+ * `room`: "gpu", "cpu" or null, where a new start may run now.+ * @param {number} t+ * @param {{ may: boolean; room: "gpu" | "cpu" | null; away?: string | null }} o*/- tick(t, { may, room }) {+ tick(t, { may, room, away = null }) {if (!may) {+ // A claim that waits ends now; a job in hand goes on to its answer.+ this.claiming?.abort();+ if (away) this.sayAway(away);if (this.server && !this.busy) void this.stop("paused");return;}+ this.away = null;this.check();if (!this.ok || this.busy) return;if (this.server && t - this.lastJobAt >= this.slot.idleMin * 60_000) {@@ -323,13 +346,38 @@ export class TextSlot {}async claimAndRun(device) {- const res = await this.d.call("/api/gpu/computer/text/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: modelName(this.slot), device, vision: !!this.slot.mmproj, chat: true, wait: this.slot.claimWaitMs }), signal: this.ending.signal });- if (res.status === 204 || !res.ok) {- await res.body?.cancel().catch(() => {});- return false;+ const claiming = new AbortController();+ this.claiming = claiming;+ let job;+ try {+ const res = await this.d.call("/api/gpu/computer/text/claim", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model: modelName(this.slot), device, vision: !!this.slot.mmproj, chat: true, wait: this.slot.claimWaitMs }),+ signal: AbortSignal.any([this.ending.signal, claiming.signal]),+ });+ if (res.status === 204 || !res.ok) {+ await res.body?.cancel().catch(() => {});+ return false;+ }+ job = jobOf(await res.json().catch(() => null));+ } catch (e) {+ // The slot stopped taking jobs while it waited for one: no job, nothing went wrong.+ if (claiming.signal.aborted && !this.ending.signal.aborted) return false;+ throw e;+ } finally {+ if (this.claiming === claiming) this.claiming = null;}- const job = jobOf(await res.json().catch(() => null));if (!job) return false;+ this.running = true;+ try {+ return await this.runJob(job, device);+ } finally {+ this.running = false;+ }+ }++ async runJob(job, device) {let answer;try {if (job.images.length && !this.slot.mmproj) throw new Error("this slot's model doesn't take pictures");@@ -486,7 +534,7 @@ export class TextSlot {this.log(`llama-server didn't start: ${e.message}`);});this.server = s;- this.log(`Starting llama-server on the ${device === "gpu" ? "GPU" : "CPU"} for text jobs.`);+ this.log(`Starting llama-server on the ${device === "gpu" ? "GPU" : "CPU"} for text jobs (context ${contextOf(this.slot)}).`);const f = this.d.fetch ?? fetch;const sleep = this.d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));const end = this.now() + this.slot.startMs;@@ -514,10 +562,30 @@ export class TextSlot {if (s.alive && s.pid) await (this.d.kill ?? killTree)(s.pid);}- /** The worker ends: its job ends first (at most 10 s), then its server. */- async end() {+ /**+ * The worker ends: its job ends first (at most 10 s), the studio hears why the slot is away ("updating": it is back in+ * moments, on new code), then its server stops.+ */+ async end(why = "stopped") {this.ending.abort();await Promise.race([this.job, new Promise((r) => setTimeout(r, 10_000).unref?.())]);+ this.sayAway(why);+ await this.awayCall;await this.stop("end");}}++/** How long a worker that ends for new code waits for a text job in hand, once its other jobs are done. */+export const TEXT_DRAIN_MS = 60_000;++/**+ * May the text slot take jobs now, and if not, why (for the studio). It goes on while the worker waits for its GPU's+ * (or CPU slot's) job to end before it restarts on new code: text jobs take seconds. It stops when those jobs are done+ * and the worker is about to restart ("updating"), and while paused by hand, on the website, outside its hours or+ * drained ("paused"). Before the studio's first answer it waits, saying nothing.+ */+export function textTurn({ updating, gpuBusy, byHand, worker }) {+ const restarting = updating && !gpuBusy;+ const stopped = byHand || (!!worker && (!!worker.paused || !worker.insideHours || !!worker.drain));+ return { may: !restarting && !stopped && !!worker, away: restarting ? "updating" : stopped ? "paused" : null };+}diff --git a/src/app/api/gpu/computer/text/away/route.ts b/src/app/api/gpu/computer/text/away/route.tsnew file mode 100644index 00000000..0e369c26--- /dev/null+++ b/src/app/api/gpu/computer/text/away/route.ts@@ -0,0 +1,21 @@+import { connection } from "next/server";+import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";+import { noteHelperAway } from "@/server/text-helper";++const answer = (status: number, body: Record<string, unknown>) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });++/**+ * A worker's text slot says why it takes no text jobs for now (`{ state }`): "updating" (its worker restarts on new code+ * and is back in moments: a chat waits for it), "paused" or "stopped". Its next claim says it is back.+ */+export async function POST(request: Request) {+ await connection();+ const principal = principalOf(request);+ if (principal instanceof Response) return principal;+ const worker = requestWorker(request);+ if (worker?.kind !== "pool") return answer(403, { error: "Only a shared worker takes text jobs." });+ const limited = rateOf(callerKey(request, principal), "text-away", 30);+ if (limited) return limited;+ const body = ((await request.json().catch(() => null)) ?? {}) as { state?: unknown };+ return noteHelperAway(worker, body.state) ? answer(200, { ok: true }) : answer(400, { error: 'Send { state: "updating" | "paused" | "stopped" } from a slot that has claimed.' });+}diff --git a/src/server/db.ts b/src/server/db.tsindex 2c10d3bd..c310a0ef 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1201,6 +1201,9 @@ function open(): Database.Database {["helper_jobs", "partial", "TEXT"],["helper_jobs", "partial_at", "INTEGER"],["helper_slots", "chat", "INTEGER NOT NULL DEFAULT 0"],+ // Why a slot takes no jobs for now ("updating": its worker restarts on new code), and since when.+ ["helper_slots", "away", "TEXT"],+ ["helper_slots", "away_at", "INTEGER"],]) {if (!(db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column)) addColumn(db, `ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}@@ -1414,7 +1417,9 @@ const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (model TEXT,device TEXT,vision INTEGER NOT NULL DEFAULT 0,- chat INTEGER NOT NULL DEFAULT 0+ chat INTEGER NOT NULL DEFAULT 0,+ away TEXT,+ away_at INTEGER);`;export function db(): Database.Database {diff --git a/src/server/text-helper.ts b/src/server/text-helper.tsindex 66d4fbff..a82e59b9 100644--- a/src/server/text-helper.ts+++ b/src/server/text-helper.ts@@ -48,6 +48,10 @@ export const HELPER_TIMES = {keepMs: 10 * 60_000,pollMs: 200,freshBeatMs: 30_000,+ /** A slot seen this recently that asks for no jobs now (its worker restarts) is coming back: a chat waits for it. */+ startingMs: 180_000,+ /** How long a chat may wait in line or for a slot that is coming back (another task waits 45 s). */+ chatWaitMs: 120_000,};export const HELPER_LIMITS = {@@ -185,11 +189,57 @@ export function textEligible(w: WorkerRow, now = Date.now()): boolean {*/export function helperLive(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): boolean {const rows = db()- .prepare(`SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}`)+ .prepare(`SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ? AND s.away IS NULL${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}`).all(now - HELPER_TIMES.liveMs) as WorkerRow[];return rows.some((w) => textEligible(w, now));}+/**+ * How the helper's slots stand for a job like this one. "ready": one asks for jobs and has none in hand. "busy": every+ * one that asks has a job in hand (the line moves). "starting": none asks now, but one was here moments ago and is+ * coming back (its worker restarts on new code, or it just went quiet). "absent": none is coming.+ */+export type HelperState = "ready" | "busy" | "starting" | "absent";++export function helperState(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): HelperState {+ const d = db();+ const rows = d+ .prepare(`SELECT w.*, s.seen_at AS slot_seen_at, s.away AS slot_away FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}`)+ .all(now - HELPER_TIMES.startingMs) as (WorkerRow & { slot_seen_at: number; slot_away: string | null })[];+ const live = rows.filter((r) => r.slot_away === null && now - r.slot_seen_at <= HELPER_TIMES.liveMs && textEligible(r, now));+ if (live.length) {+ const working = d.prepare("SELECT 1 FROM helper_jobs WHERE state = 'running' AND worker_id = ? LIMIT 1");+ return live.every((r) => working.get(r.id)) ? "busy" : "ready";+ }+ // Coming back: a worker the website lets work, restarting on new code or quiet for a moment (not paused, not gone).+ const coming = rows.some(+ (r) =>+ (r.slot_away === null || r.slot_away === "updating") &&+ r.kind === "pool" &&+ !r.revoked_at &&+ !(r.expires_at && r.expires_at <= now) &&+ !r.paused_server &&+ !r.drain &&+ hoursAt(parseHours(json<unknown>(r.hours_json, null)), now).inside,+ );+ return coming ? "starting" : "absent";+}++/** A worker's text slot says why it takes no jobs for now ("updating": back in moments; "paused" or "stopped"). */+export function noteHelperAway(w: WorkerRow, state: unknown, now = Date.now()): boolean {+ if (state !== "updating" && state !== "paused" && state !== "stopped") return false;+ return db().prepare("UPDATE helper_slots SET away = ?, away_at = ? WHERE worker_id = ?").run(state, now, w.id).changes === 1;+}++/**+ * How the free helper stands for this call: helperState, and "absent" for a call that may not use it (a guest's, or an+ * account's while hosted runs are off). A chat may be asked unless "absent": it waits for a slot that is coming back.+ */+export function freeHelperState(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): HelperState {+ const t = tenant();+ return !t || (t.kind === "account" && hostedRunsOn()) ? helperState(now, o) : "absent";+}+/** May this call use the free helper now: it is live, and an account's call only while hosted runs are on (a guest's never: sign up first). */export function freeHelperOn(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): boolean {const t = tenant();@@ -256,7 +306,7 @@ export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: uconst chat = slot.chat === true ? 1 : 0;if (note) {d.prepare(- "INSERT INTO helper_slots (worker_id, seen_at, model, device, vision, chat) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device, vision = excluded.vision, chat = excluded.chat",+ "INSERT INTO helper_slots (worker_id, seen_at, model, device, vision, chat, away, away_at) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device, vision = excluded.vision, chat = excluded.chat, away = NULL, away_at = NULL",).run(w.id, now, model, device, vision, chat);}const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow | undefined;@@ -360,6 +410,11 @@ export interface AskHelper {onText?: (soFar: string) => void;/** Where the job stands in the line while it waits (1 is next), each time that changes. */onQueue?: (position: number) => void;+ /**+ * What the job waits for, each time that changes: "starting" (no slot asks for jobs now, but one is coming back: its+ * worker restarts), "in-line" (a slot asks; onQueue says the place), "running" (a slot is writing the answer).+ */+ onState?: (state: "starting" | "in-line" | "running") => void;now?: () => number;sleep?: (ms: number) => Promise<void>;}@@ -381,7 +436,8 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {const d = db();sweepHelper(now());const vision = !!o.images?.length;- if (!helperLive(now(), { vision, chat })) return { error: "busy" };+ // A chat waits for a slot that is coming back (its worker restarts on new code); another task needs one asking now.+ if (chat ? helperState(now(), { vision, chat }) === "absent" : !helperLive(now(), { vision, chat })) return { error: "busy" };const pictures = vision ? await helperPictures(o.images!) : null;if (vision && !pictures) return { error: "failed" };if (who !== "owner" && o.counted !== false) {@@ -431,7 +487,7 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {sampling ? JSON.stringify(sampling) : null,stream ? 1 : 0,);- const waitMs = o.waitMs ?? 45_000;+ const waitMs = o.waitMs ?? (chat ? HELPER_TIMES.chatWaitMs : 45_000);// A caller's hook never stops the wait.const tell = <T,>(f: ((v: T) => void) | undefined, v: T) => {try {@@ -440,6 +496,8 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {};let shown = "";let place = 0;+ let said = "";+ const say = (state: "starting" | "in-line" | "running") => state !== said && tell(o.onState, (said = state));try {for (;;) {if (o.signal?.aborted) return { error: "failed" };@@ -460,12 +518,22 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {if (d.prepare("UPDATE helper_jobs SET state = 'failed', error = 'busy' WHERE id = ? AND state = 'waiting'").run(id).changes === 1) return { error: "busy" };continue;}+ if (chat || o.onState) {+ const state = helperState(t, { vision, chat });+ // No slot is coming any more (none asked for minutes, or its worker was paused): it ends now.+ if (chat && state === "absent") {+ if (d.prepare("UPDATE helper_jobs SET state = 'failed', error = 'busy' WHERE id = ? AND state = 'waiting'").run(id).changes === 1) return { error: "busy" };+ continue;+ }+ say(state === "starting" ? "starting" : "in-line");+ }if (o.onQueue) {const p = helperPosition(id);if (p && p !== place) tell(o.onQueue, (place = p));}}if (row.state === "running") {+ say("running");if (row.partial && row.partial !== shown) tell(o.onText, (shown = row.partial));// A slot that sends its words has the time again with each; an older one has it from its claim.const claimed = row.claimed_at ?? t;diff --git a/tests/helpers/computer-tab.ts b/tests/helpers/computer-tab.tsindex cac4ddd5..b59f4005 100644--- a/tests/helpers/computer-tab.ts+++ b/tests/helpers/computer-tab.ts@@ -21,6 +21,9 @@ export interface ComputerRoutes {/** The text slot's claim and answer (the free text helper). */textClaim?: { POST: Handler };textResult?: { POST: Handler };+ /** The words so far for a text job, and a slot saying why it takes no jobs for now. */+ textPartial?: { POST: Handler };+ textAway?: { POST: Handler };}export async function loadRoutes(): Promise<ComputerRoutes> {@@ -33,6 +36,8 @@ export async function loadRoutes(): Promise<ComputerRoutes> {release: (await import("@/app/api/gpu/computer/tasks/[id]/release/route")) as never,textClaim: (await import("@/app/api/gpu/computer/text/claim/route")) as never,textResult: (await import("@/app/api/gpu/computer/text/[id]/route")) as never,+ textPartial: (await import("@/app/api/gpu/computer/text/[id]/partial/route")) as never,+ textAway: (await import("@/app/api/gpu/computer/text/away/route")) as never,};}@@ -62,6 +67,8 @@ export function apiAs(routes: ComputerRoutes, cookie: string | null, extra: Recoif ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/outputs\/([^/]+)$/.exec(url.pathname))) return (method === "PUT" ? routes.outputs.PUT : routes.outputs.GET)(req, params({ id: m[1], n: m[2] }));if ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/release$/.exec(url.pathname))) return routes.release.POST(req, params({ id: m[1] }));if (url.pathname === "/api/gpu/computer/text/claim" && routes.textClaim) return routes.textClaim.POST(req, params({}));+ if (url.pathname === "/api/gpu/computer/text/away" && routes.textAway) return routes.textAway.POST(req, params({}));+ if ((m = /^\/api\/gpu\/computer\/text\/([^/]+)\/partial$/.exec(url.pathname)) && routes.textPartial) return routes.textPartial.POST(req, params({ id: decodeURIComponent(m[1]) }));if ((m = /^\/api\/gpu\/computer\/text\/([^/]+)$/.exec(url.pathname)) && routes.textResult) return routes.textResult.POST(req, params({ id: decodeURIComponent(m[1]) }));return new Response("no such route", { status: 404 });};diff --git a/tests/text-helper.test.ts b/tests/text-helper.test.tsindex 8ebee230..08139ed3 100644--- a/tests/text-helper.test.ts+++ b/tests/text-helper.test.ts@@ -33,6 +33,7 @@ const enhanceRoute = await import("@/app/api/enhance/route");const claimRoute = await import("@/app/api/gpu/computer/text/claim/route");const resultRoute = await import("@/app/api/gpu/computer/text/[id]/route");const partialRoute = await import("@/app/api/gpu/computer/text/[id]/partial/route");+const awayRoute = await import("@/app/api/gpu/computer/text/away/route");const { proxy } = await import("@/proxy");const { writeRestorePrompt } = await import("@/server/restore");@@ -501,7 +502,9 @@ describe("chat: turns, words as they come, ending early", () => {expect((await send({ lease: job.lease, text: "more" })).status).toBe(409);// A slot that says it takes chats gets one through the claim route too.const claimed = helper.askHelper({ task: "chat", system: "s", messages: turns, waitMs: 5000 });- const none = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "m", device: "cpu", wait: 300 }, undefined, auth_(w)));+ // An older worker (no chat flag) gets nothing; one that says it takes chats gets it.+ const older = addWorker();+ const none = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "m", device: "cpu", wait: 300 }, undefined, auth_(older)));expect(none.status).toBe(204);const r = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "m", device: "cpu", chat: true, wait: 3000 }, undefined, auth_(w)));const { job: j2 } = (await r.json()) as { job: { id: string; lease: string; messages: unknown } };@@ -586,3 +589,110 @@ describe("chat: turns, words as they come, ending early", () => {expect(places).toEqual({ a: [1, 2, 1], b: [2, 3, 2, 1], c: [1] });});});++describe("what a chat waits for: a slot ready, busy, coming back or gone", () => {+ const turns = [{ role: "user" as const, content: "Hi" }];+ const auth_ = (w: W) => ({ authorization: `Bearer ${w.token}` });+ const chatWorker = () => {+ const w = addWorker();+ helper.claimHelperJob(workerRow(w), { chat: true });+ return w;+ };+ const slotSeen = (w: W, ago: number) => db().prepare("UPDATE helper_slots SET seen_at = ? WHERE worker_id = ?").run(Date.now() - ago, w.id);++ it("ready while a slot asks; busy while every slot has a job; starting while one restarts or just went quiet; absent after", async () => {+ expect(helper.helperState()).toBe("absent");+ const w = chatWorker();+ expect(helper.helperState(Date.now(), { chat: true })).toBe("ready");+ const asked = helper.askHelper({ task: "chat", system: "s", messages: turns });+ const job = (await helper.claimHelperJob(workerRow(w), { chat: true }))!;+ expect(helper.helperState(Date.now(), { chat: true })).toBe("busy");+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Hello" });+ expect(await asked).toEqual({ text: "Hello" });+ // Its worker restarts on new code: coming back, whatever its last claim's age.+ expect(helper.noteHelperAway(workerRow(w), "updating")).toBe(true);+ expect(helper.helperLive(Date.now(), { chat: true })).toBe(false);+ expect(helper.helperState(Date.now(), { chat: true })).toBe("starting");+ // Paused (by hand or for its hours) or stopped: gone.+ helper.noteHelperAway(workerRow(w), "paused");+ expect(helper.helperState(Date.now(), { chat: true })).toBe("absent");+ expect(helper.noteHelperAway(workerRow(w), "elsewhere")).toBe(false);+ // Its next claim says it is back.+ helper.claimHelperJob(workerRow(w), { chat: true });+ expect(helper.helperState(Date.now(), { chat: true })).toBe("ready");+ // Quiet for a minute: coming back. Quiet for four, or paused on the website: gone.+ slotSeen(w, 60_000);+ expect(helper.helperState(Date.now(), { chat: true })).toBe("starting");+ pool.patchWorker(w.id, { paused: true });+ expect(helper.helperState(Date.now(), { chat: true })).toBe("absent");+ pool.patchWorker(w.id, { paused: false });+ slotSeen(w, 240_000);+ expect(helper.helperState(Date.now(), { chat: true })).toBe("absent");+ // A guest, or an account while hosted runs are off, may not use it at all.+ helper.claimHelperJob(workerRow(w), { chat: true });+ expect(runAsTenant({ kind: "guest" }, () => helper.freeHelperState(Date.now(), { chat: true }))).toBe("absent");+ expect(runAsTenant({ kind: "account", id: account }, () => helper.freeHelperState(Date.now(), { chat: true }))).toBe("absent");+ process.env.FUOBE_HOSTED_RUNS = "1";+ expect(runAsTenant({ kind: "account", id: account }, () => helper.freeHelperState(Date.now(), { chat: true }))).toBe("ready");+ });++ it("a chat waits for a slot that is coming back, and hears so; its slot's next claim takes it", async () => {+ const w = chatWorker();+ helper.noteHelperAway(workerRow(w), "updating");+ const states: string[] = [];+ const asked = helper.askHelper({ task: "chat", system: "s", messages: turns, onState: (s) => states.push(s) });+ await new Promise((r) => setTimeout(r, 400));+ expect(states).toEqual(["starting"]);+ // Another task still needs a slot that asks now.+ expect(await helper.askHelper({ task: "enhance", system: "s", user: "u" })).toEqual({ error: "busy" });+ // The worker is back on new code.+ const job = (await helper.claimHelperJob(workerRow(w), { chat: true }))!;+ await new Promise((r) => setTimeout(r, 300));+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Back" });+ expect(await asked).toEqual({ text: "Back" });+ expect(states).toEqual(["starting", "running"]);+ // While a slot asks, the job is in line.+ const seen: string[] = [];+ const inLine = helper.askHelper({ task: "chat", system: "s", messages: turns, onState: (s) => seen.push(s) });+ await new Promise((r) => setTimeout(r, 300));+ expect(seen).toEqual(["in-line"]);+ const j2 = (await helper.claimHelperJob(workerRow(w), { chat: true }))!;+ helper.finishHelperJob(workerRow(w), j2.id, { lease: j2.lease, text: "ok" });+ expect(await inLine).toEqual({ text: "ok" });+ });++ it("a chat waits up to 120 s, not 45; it ends at once when no slot is coming any more", async () => {+ expect(helper.HELPER_TIMES.chatWaitMs).toBe(120_000);+ const w = chatWorker();+ helper.noteHelperAway(workerRow(w), "updating");+ let t = Date.now();+ const start = t;+ const waited = helper.askHelper({ task: "chat", system: "s", messages: turns, now: () => t, sleep: async () => void (t += 10_000) });+ expect(await waited).toEqual({ error: "busy" });+ expect(t - start).toBeGreaterThanOrEqual(120_000);+ expect(t - start).toBeLessThan(140_000);+ // Coming back, then gone (its worker was paused): it doesn't wait out its time.+ helper.claimHelperJob(workerRow(w), { chat: true });+ helper.noteHelperAway(workerRow(w), "updating");+ const gone = helper.askHelper({ task: "chat", system: "s", messages: turns, waitMs: 60_000 });+ await new Promise((r) => setTimeout(r, 300));+ helper.noteHelperAway(workerRow(w), "stopped");+ const t0 = Date.now();+ expect(await gone).toEqual({ error: "busy" });+ expect(Date.now() - t0).toBeLessThan(2000);+ // Nothing coming at all: busy at once, nothing queued.+ expect(await helper.askHelper({ task: "chat", system: "s", messages: turns })).toEqual({ error: "busy" });+ expect(jobs()).toEqual([]);+ });++ it("the away route: a shared worker's slot only, a known reason only", async () => {+ const w = chatWorker();+ const send = (body: unknown, extra: Record<string, string> = auth_(w), who?: string) => awayRoute.POST(post("/api/gpu/computer/text/away", body, who, extra));+ expect((await send({ state: "updating" })).status).toBe(200);+ expect(helper.helperState(Date.now(), { chat: true })).toBe("starting");+ expect((await send({ state: "gone fishing" })).status).toBe(400);+ const browser = await send({ state: "stopped" }, { "sec-fetch-site": "same-origin", origin: "http://localhost:3000" }, "owner");+ expect(browser.status).not.toBe(200);+ expect(helper.helperState(Date.now(), { chat: true })).toBe("starting");+ });+});diff --git a/tests/worker-cpu-slot.test.ts b/tests/worker-cpu-slot.test.tsindex b94d2692..632d1054 100644--- a/tests/worker-cpu-slot.test.ts+++ b/tests/worker-cpu-slot.test.ts@@ -234,7 +234,7 @@ const standIn = (o: { steps: number; stepMs: number; uploadDir?: string }) => [];/** Start `fuobe worker run` in this process with a CPU slot (`cpuSlot`), its ComfyUIs stand-in processes of their own. */-function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: number }; cpu?: { steps: number; stepMs: number }; cpuSlot?: boolean; finishers?: unknown; shrinkPreview?: (b: Blob) => Promise<Blob | null>; textSlot?: Record<string, unknown>; text?: Record<string, unknown> } = {}) {+function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: number }; cpu?: { steps: number; stepMs: number }; cpuSlot?: boolean; finishers?: unknown; shrinkPreview?: (b: Blob) => Promise<Blob | null>; textSlot?: Record<string, unknown>; text?: Record<string, unknown>; codeWatch?: { check: (t: number) => boolean } } = {}) {const ctrl = new AbortController();const cfg = {site: SITE,@@ -271,6 +271,7 @@ function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: numbe...(o.finishers !== undefined && { finishers: o.finishers }),...(o.shrinkPreview && { shrinkPreview: o.shrinkPreview }),...(o.text && { text: o.text }),+ ...(o.codeWatch && { codeWatch: o.codeWatch }),});const r = { ctrl, done };running.push(r);@@ -697,4 +698,63 @@ describe("the worker program's text slot", () => {expect(pids.length).toBe(1);expect(p.logs.join("\n")).toContain("Starting llama-server on the CPU");});++ it("new code waits for the GPU's job: text jobs are answered meanwhile, a text job in hand ends before the restart, and the studio hears it comes back", async () => {+ const helper = await import("@/server/text-helper");+ const { spawn } = await import("node:child_process");+ const w = addWorker();+ const s = studio();+ const p = pc();+ const model = path.join(p.home, "model.gguf");+ fs.writeFileSync(model, "stand-in model");+ const server = path.join(p.home, "fake-llama.mjs");+ // A stand-in llama-server: words that ask to be slow take 4 s.+ fs.writeFileSync(+ server,+ [+ 'import http from "node:http";',+ "const arg = (n) => process.argv[process.argv.indexOf(n) + 1];",+ "http.createServer((req, res) => {",+ ' if (req.headers.authorization !== "Bearer " + arg("--api-key")) { res.writeHead(401); return res.end(); }',+ ' if (req.url === "/health") { res.writeHead(200); return res.end("{}"); }',+ ' let body = ""; req.on("data", (d) => (body += d));',+ ' req.on("end", () => { const b = JSON.parse(body); const words = b.messages.at(-1).content; setTimeout(() => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ choices: [{ message: { content: "[Verse] " + words } }] })); }, words.includes("slow") ? 4000 : 0); });',+ '}).listen(Number(arg("--port")), "127.0.0.1");',+ ].join("\n"),+ );+ let updating = false;+ const gpu = ownerTask(GPU_WORKFLOW);+ // A GPU job of about 5 s.+ const r = start(w, s, p, {+ gpu: { steps: 50, stepMs: 100 },+ codeWatch: { check: () => updating },+ textSlot: { server, model, sha256: crypto.createHash("sha256").update("stand-in model").digest("hex"), claimWaitMs: 1000 },+ text: {+ spawn: (_cmd: string, args: string[], o: object) => spawn(process.execPath, [server, ...args], o),+ kill: async (pid: number) => {+ try {+ process.kill(pid);+ } catch {}+ },+ },+ });+ let doneAt = 0;+ const done = r.done.then((v) => ((doneAt = Date.now()), v));+ await until(() => helper.helperLive() && row(gpu.id).state === "running", 30_000);+ // New code is installed while the GPU's job runs: the worker waits for it, and its text slot goes on.+ updating = true;+ await until(() => p.logs.some((l) => l.includes("restarting after this job")), 10_000);+ expect(await helper.askHelper({ task: "lyrics", system: "s", user: "rain", waitMs: 10_000 })).toEqual({ text: "[Verse] rain" });+ expect(row(gpu.id).state).toBe("running");+ // A slow text job still in hand when the GPU's job ends: the restart waits for its answer.+ let answeredAt = 0;+ const slow = await helper.askHelper({ task: "lyrics", system: "s", user: "slow rain", waitMs: 10_000 }).then((a) => ((answeredAt = Date.now()), a));+ expect(slow).toEqual({ text: "[Verse] slow rain" });+ expect(await done).toBe("update");+ expect((await ended(gpu.id)).state).toBe("done");+ expect(doneAt).toBeGreaterThanOrEqual(answeredAt);+ // The studio heard it is coming back on new code: a chat waits for it rather than being told it's busy.+ expect(db().prepare("SELECT away FROM helper_slots WHERE worker_id = ?").get(w.id)).toEqual({ away: "updating" });+ expect(helper.helperState(Date.now(), { chat: true })).toBe("starting");+ });});diff --git a/tests/worker-text-slot.test.ts b/tests/worker-text-slot.test.tsindex 1e07e6c2..2ffb4fbf 100644--- a/tests/worker-text-slot.test.ts+++ b/tests/worker-text-slot.test.ts@@ -11,7 +11,7 @@ import path from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { othersOf } from "../bin/lib/worker/gpu.mjs";import { parseCounters, splitMemory } from "../bin/lib/worker/local-work.mjs";-import { chatBody, contextOf, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, streamedWords, TextSlot, textSlotOf } from "../bin/lib/worker/text.mjs";+import { chatBody, contextOf, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, streamedWords, TextSlot, textSlotOf, textTurn } from "../bin/lib/worker/text.mjs";import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 30_000 });@@ -408,3 +408,63 @@ describe("chats and words as they come", () => {expect(site.partials).toEqual([]);});});++describe("while its worker restarts or pauses", () => {+ it("goes on while the worker waits for its GPU's job before new code; stops (saying why) when it is about to restart, or when paused", () => {+ const worker = { paused: false, insideHours: true, drain: false };+ expect(textTurn({ updating: false, gpuBusy: false, byHand: false, worker })).toEqual({ may: true, away: null });+ expect(textTurn({ updating: true, gpuBusy: true, byHand: false, worker })).toEqual({ may: true, away: null });+ expect(textTurn({ updating: true, gpuBusy: false, byHand: false, worker })).toEqual({ may: false, away: "updating" });+ expect(textTurn({ updating: false, gpuBusy: true, byHand: true, worker })).toEqual({ may: false, away: "paused" });+ expect(textTurn({ updating: false, gpuBusy: false, byHand: false, worker: { ...worker, paused: true } })).toEqual({ may: false, away: "paused" });+ expect(textTurn({ updating: false, gpuBusy: false, byHand: false, worker: { ...worker, insideHours: false } })).toEqual({ may: false, away: "paused" });+ expect(textTurn({ updating: true, gpuBusy: true, byHand: false, worker: { ...worker, drain: true } })).toEqual({ may: false, away: "paused" });+ // Before the studio's first answer: no claim, and nothing said.+ expect(textTurn({ updating: false, gpuBusy: false, byHand: false, worker: null })).toEqual({ may: false, away: null });+ });++ it("a claim that waits ends when it may not take jobs; the studio hears why once; a job in hand goes on to its answer", async () => {+ const aways: unknown[] = [];+ let claims = 0;+ let release: (() => void) | null = null;+ const answers: unknown[] = [];+ // The first claim waits until it is ended; the second gets a job.+ const call = async (p: string, init: RequestInit = {}) => {+ const body = JSON.parse(String(init.body ?? "{}"));+ if (p === "/api/gpu/computer/text/away") {+ aways.push(body.state);+ return Response.json({ ok: true });+ }+ if (p === "/api/gpu/computer/text/claim") {+ claims++;+ if (claims === 1) {+ return new Promise<Response>((_, reject) => init.signal!.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }));+ }+ if (claims === 2) return Response.json({ job: { id: "hlp_r", lease: "Lr", system: "", user: "slow", maxTokens: 50, stream: true } });+ return new Response(null, { status: 204 });+ }+ if (p.endsWith("/partial")) return Response.json({ ok: true });+ answers.push(body);+ release?.();+ return Response.json({ ok: true });+ };+ const { s, logs } = makeSlot(call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => claims === 1 && s.busy);+ expect(s.running).toBe(false);+ s.tick(Date.now(), { may: false, room: "cpu", away: "updating" });+ s.tick(Date.now(), { may: false, room: "cpu", away: "updating" });+ await until(s, Date.now, { may: false, room: "cpu", away: "updating" } as never, () => !s.busy);+ expect(aways).toEqual(["updating"]);+ expect(logs.join("\n")).not.toContain("A text job stopped");+ // Back: it claims again, and a job in hand runs on while the slot may not take another.+ await until(s, Date.now, { may: true, room: "cpu" }, () => s.running);+ s.tick(Date.now(), { may: false, room: "cpu", away: "paused" });+ expect(s.running).toBe(true);+ await new Promise<void>((r) => (release = r));+ expect(answers).toHaveLength(1);+ expect(aways).toEqual(["updating", "paused"]);+ // The worker ends for new code: the studio hears it is coming back.+ await s.end("updating");+ expect(aways).toEqual(["updating", "paused", "updating"]);+ });+});