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
Free text helper: lyrics and prompt rewrites run on the workers' text slot
Adarsh5bc7098cd058
diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjsindex 19d5c738..a7cf5209 100644--- a/bin/lib/worker/gpu.mjs+++ b/bin/lib/worker/gpu.mjs@@ -63,6 +63,13 @@ export async function readGpu(cmd = "nvidia-smi") {return { ...g, apps };}+/** The first GPU's memory in MB (`--query-gpu=memory.total`), or null when nvidia-smi can't say. */+export async function readGpuTotal(cmd = "nvidia-smi") {+ const [bin, ...pre] = Array.isArray(cmd) ? cmd : [cmd];+ const line = String((await run(bin, [...pre, "--query-gpu=memory.total", "--format=csv,noheader,nounits"])) ?? "").split(/\r?\n/).find((l) => l.trim());+ return num(line);+}+/** `nvidia-smi --query-gpu=compute_cap --format=csv,noheader` → the first GPU's generation ("8.9"), or null. */export function parseGpuGen(text) {const line = String(text ?? "").split(/\r?\n/).map((l) => l.trim()).find(Boolean);@@ -96,10 +103,12 @@ export function isDesktop(name) {* torch's allocator aren't in it, and the read gives null when ComfyUI is slow to answer.*/export function ownOf(own, apps = []) {- if (!own.running) return { mb: 0, sure: true };+ // The text slot's server (text.mjs) is the worker's own too: its own number when nvidia-smi gives one, else what it said.+ const extra = (own.extraPids ?? []).reduce((n, pid) => n + (apps.find((a) => a.pid === pid && a.usedMb !== null)?.usedMb ?? 0), 0) || (own.extraMb ?? 0);+ if (!own.running) return { mb: extra, sure: true };const app = own.pid ? apps.find((a) => a.pid === own.pid && a.usedMb !== null) : null;- if (app) return { mb: app.usedMb, sure: true };- return { mb: (own.mb ?? 0) + CONTEXT_ALLOWANCE_MB, sure: false };+ if (app) return { mb: app.usedMb + extra, sure: true };+ return { mb: (own.mb ?? 0) + CONTEXT_ALLOWANCE_MB + extra, sure: false };}/**@@ -111,7 +120,7 @@ export function ownOf(own, apps = []) {export function othersOf(reading, own, busyVramMb) {const mine = ownOf(own, reading.apps);const othersMb = Math.max(0, reading.usedMb - mine.mb);- const others = reading.apps.filter((a) => a.pid !== own.pid && !isDesktop(a.name));+ const others = reading.apps.filter((a) => a.pid !== own.pid && !(own.extraPids ?? []).includes(a.pid) && !isDesktop(a.name));const loud = others.find((a) => a.usedMb !== null && a.usedMb > busyVramMb);const busy = othersMb > busyVramMb || !!loud;const who = loud?.name ?? others.find((a) => a.usedMb === null || a.usedMb > 0)?.name ?? (busy ? "another program" : null);diff --git a/bin/lib/worker/local-work.mjs b/bin/lib/worker/local-work.mjsindex 20f85336..1ce29dc1 100644--- a/bin/lib/worker/local-work.mjs+++ b/bin/lib/worker/local-work.mjs@@ -132,7 +132,7 @@ const isPython = (name) => /^python(w|3(\.\d+)?)?(\.exe)?$/i.test(String(name ??*/export function workPids(listing, o) {const [lo, hi] = Array.isArray(o.ports) && o.ports.length === 2 ? o.ports.map(Number) : DEFAULT_PORTS;- const own = new Set([o.ownPid].filter(Boolean));+ const own = new Set([o.ownPid, ...(o.extraPids ?? [])].filter(Boolean));for (const l of listing?.listeners ?? []) if (o.ownPort && l.port === o.ownPort) own.add(l.pid);const excludePorts = new Set((o.excludePorts ?? []).map(Number));const excludePids = new Set((o.excludePids ?? []).map(Number));@@ -176,7 +176,7 @@ export function splitMemory(o) {const fallback = ownOf(o.own, o.apps);const fallbackMb = fallback.mb;if (o.counters && o.listing) {- const { own, work } = workPids(o.listing, { ports: o.ports, ownPid: o.own.pid, ownPort: o.own.port, excludePorts: o.excludePorts, excludePids: o.excludePids });+ const { own, work } = workPids(o.listing, { ports: o.ports, ownPid: o.own.pid, ownPort: o.own.port, extraPids: o.own.extraPids, excludePorts: o.excludePorts, excludePids: o.excludePids });const gpu = pickGpu(o.counters, o.gpu);const mine = o.counters.filter((c) => c.gpu === gpu);const sum = (pids) => mine.filter((c) => pids.has(c.pid)).reduce((n, c) => n + c.mb, 0);@@ -196,7 +196,7 @@ export function splitMemory(o) {if (o.lock !== null && o.lock !== undefined && owners.some((w) => String(o.lock).toLowerCase().startsWith(w))) {return { ownMb: fallbackMb, ownSure: fallback.sure, workMb: rest, othersMb: 0, who: null, work: { pids: [], port: null, lock: true }, source: "lock" };}- const named = o.apps?.find((a) => a.pid !== o.own.pid && (a.usedMb === null || a.usedMb > 0) && !isDesktop(a.name))?.name;+ const named = o.apps?.find((a) => a.pid !== o.own.pid && !(o.own.extraPids ?? []).includes(a.pid) && (a.usedMb === null || a.usedMb > 0) && !isDesktop(a.name))?.name;return { ownMb: fallbackMb, ownSure: fallback.sure, workMb: 0, othersMb: rest, who: o.lock !== null && o.lock !== undefined ? "another program" : (named ?? "another program"), work: { pids: [], port: null }, source: o.lock !== null && o.lock !== undefined ? "lock" : "total" };}diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex ec0ebaea..f29ed012 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -17,6 +17,9 @@// light CPU work (joins, trims, adding sound, loops, Ken Burns, filters) on a second ComfyUI of its own that runs on the// CPU only, and finishing jobs (finish.mjs: the 3D finish, camera paths) with its own code. Every picture of an account's// job is made again from its pixels before anything reads it (picture.mjs).+//+// The text slot (worker.json `textSlot`, text.mjs): the studio's free text helper, answered by a llama.cpp server the+// worker starts itself, on the GPU when there is room, else on the CPU. Its memory counts as the worker's own.import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";@@ -25,7 +28,7 @@ import { StayAwake } from "./awake.mjs";import { allowedNodes, cleanJob, emptyFolders, graphCheck, inputRules } from "./checks.mjs";import { folders, GuardMissing, OwnComfy, PortBusy } from "./comfy.mjs";import { ffmpegOf, PROTOCOL, protocolOf, readControl, saveConfig, savedConfig, writeControl, writeStatus } from "./config.mjs";-import { BRIEF_COOL_DOWN_MS, BRIEF_EVERY_MS, BRIEF_PAUSE_MS, GpuWatch, MID_JOB_GRACE_MS, othersOf, readGpu, readGpuGen } from "./gpu.mjs";+import { BRIEF_COOL_DOWN_MS, BRIEF_EVERY_MS, BRIEF_PAUSE_MS, GpuWatch, MID_JOB_GRACE_MS, othersOf, readGpu, readGpuGen, readGpuTotal } from "./gpu.mjs";import { Hold } from "./hold.mjs";import { inventoryHash, missingModelDirs, modelFiles, packFolders, runtimeFileList } from "./inventory.mjs";import { freeLocal, localIdle, readCounters, readListeners, readLock, splitMemory, unknownHolder } from "./local-work.mjs";@@ -37,6 +40,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 { SiteTurns, writeSite } from "./turns.mjs";import { CodeWatch } from "./update.mjs";@@ -540,6 +544,19 @@ async function work(saved, deps, owner) {};log(`It has a CPU slot: light CPU work${finish.kinds.length ? ` and finishing jobs (${finish.kinds.join(", ")})` : ""} run beside its GPU's job.`);}+ // The text slot: its own claims for the studio's text jobs, beside the GPU's job and the CPU slot's.+ const textCfg = textSlotOf(cfg.textSlot);+ if (textCfg?.problem) log(`${textCfg.problem}: its text slot is off.`);+ const text = textCfg && !textCfg.problem ? (deps.textSlot ?? new TextSlot(textCfg, { call, log, workDir: cfg.workDir, home: deps.home, now, sleep, env: deps.env, ...deps.text })) : null;+ const gpuTotalMb = text ? await (deps.readGpuTotal ?? (deps.readGpu ? async () => null : () => readGpuTotal(cfg.nvidiaSmi)))().catch(() => null) : null;+ let lastUsedMb = null;+ /** Where a new start of the text slot's server may run: the GPU while nothing else holds it and there is room, else the CPU. */+ const textRoom = () => {+ const held = gpu.paused || gpu.busyInARow > 0 || (!!turns && (split?.workMb ?? 0) > busyMb && turn.siteWaiting === 0);+ if (held) return "cpu";+ if (text.server?.device === "gpu") return "gpu";+ return gpuTotalMb !== null && lastUsedMb !== null && gpuTotalMb - lastUsedMb >= textCfg.gpuMinFreeMb ? "gpu" : "cpu";+ };let cpuRunner = null;let busyCpu = false;let cpuJob = Promise.resolve();@@ -808,7 +825,7 @@ async function work(saved, deps, owner) {updating = true;log("New worker code is installed: restarting after this job.");}- if (updating && !busyJob && !busyCpu) break;+ if (updating && !busyJob && !busyCpu && !text?.busy) break;// Its own switch, and --for running out.let control = readControl(deps.home);if (control.paused && control.until && t >= control.until) {@@ -826,7 +843,9 @@ async function work(saved, deps, owner) {lastGpuAt = t;const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);if (reading) {- const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null, job: busyJob && jobUsesGpu };+ const mine = text?.own() ?? { pids: [], mb: 0 };+ const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null, job: busyJob && jobUsesGpu, extraPids: mine.pids, extraMb: mine.mb };+ lastUsedMb = reading.usedMb;let verdict;if (turns) {split = await splitNow(t, reading, own);@@ -1016,6 +1035,11 @@ 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.+ 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() });+ }// Kept results the studio never took are deleted after a day.if (t - holdCheckedAt >= 60_000) {holdCheckedAt = t;@@ -1049,6 +1073,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();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.mjsnew file mode 100644index 00000000..4a7a7f94--- /dev/null+++ b/bin/lib/worker/text.mjs@@ -0,0 +1,323 @@+// The text slot (worker.json `textSlot`): the studio's free text helper (src/server/text-helper.ts). It asks for one+// text job at a time, beside the GPU's job and the CPU slot's, and answers it with a llama.cpp server that it starts+// itself: 127.0.0.1 only, a random port, a new key at each start, the model checked against its SHA-256 first. The+// server starts at the first job and stops after `idleMin` minutes with none, on a pause, and when the worker ends. It+// runs on the GPU when there is room, else on the CPU (`cpu`), and changes only between jobs.+import crypto from "node:crypto";+import { spawn as spawnChild } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { comfyEnv, killTree, pickPort, RotatingLog } from "./comfy.mjs";++export const TEXT_DEFAULTS = { context: 8192, idleMin: 10, gpuMinFreeMb: 8000, cpu: true, threads: 8, startMs: 180_000, answerMs: 120_000, claimWaitMs: 20_000 };++/** The graphics memory a GPU server is counted with before its log says (weights, cache and buffers of a 4B model). */+export const TEXT_GPU_GUESS_MB = 5500;++/** The model name the studio hears with each claim. */+export const TEXT_MODEL = "nemotron-3.5-bolt-e4b";++const SHA = /^[0-9a-f]{64}$/i;++/** worker.json's `textSlot` with defaults, or { problem } when it can't be used, or null when it isn't set. */+export function textSlotOf(raw) {+ if (!raw || typeof raw !== "object") return null;+ const s = { ...TEXT_DEFAULTS, ...raw };+ if (typeof s.server !== "string" || !s.server) return { problem: "textSlot needs `server`, the path of llama-server" };+ if (typeof s.model !== "string" || !s.model) return { problem: "textSlot needs `model`, the path of the GGUF file" };+ if (typeof s.sha256 !== "string" || !SHA.test(s.sha256)) return { problem: "textSlot needs `sha256`, the model file's SHA-256" };+ if (s.serverSha256 !== undefined && (typeof s.serverSha256 !== "string" || !SHA.test(s.serverSha256))) return { problem: "textSlot's `serverSha256` isn't a SHA-256" };+ const num = (v, lo, hi, d) => (Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Math.round(Number(v)))) : d);+ return {+ ...s,+ context: num(s.context, 1024, 65_536, TEXT_DEFAULTS.context),+ idleMin: num(s.idleMin, 1, 24 * 60, TEXT_DEFAULTS.idleMin),+ gpuMinFreeMb: num(s.gpuMinFreeMb, 0, 1_000_000, TEXT_DEFAULTS.gpuMinFreeMb),+ threads: num(s.threads, 1, 256, TEXT_DEFAULTS.threads),+ claimWaitMs: num(s.claimWaitMs, 0, TEXT_DEFAULTS.claimWaitMs, TEXT_DEFAULTS.claimWaitMs),+ cpu: s.cpu !== false,+ };+}++/** A file's SHA-256, read in pieces. */+export function fileSha256(file) {+ return new Promise((resolve, reject) => {+ const h = crypto.createHash("sha256");+ fs.createReadStream(file)+ .on("data", (d) => h.update(d))+ .on("error", reject)+ .on("end", () => resolve(h.digest("hex")));+ });+}++/**+ * Does the file have this SHA-256? Hashed once for each size and change time (kept in `cacheFile`), so a restart doesn't+ * read 6 GB again.+ */+export async function fileMatches(file, sha256, cacheFile, hash = fileSha256) {+ let st;+ try {+ st = fs.statSync(file);+ } catch {+ return false;+ }+ let cache = {};+ try {+ cache = JSON.parse(fs.readFileSync(cacheFile, "utf8")) ?? {};+ } catch {}+ const key = path.resolve(file);+ const known = cache[key];+ let sum = known && known.size === st.size && known.mtimeMs === st.mtimeMs ? known.sha256 : null;+ if (!sum) {+ sum = await hash(file);+ cache[key] = { size: st.size, mtimeMs: st.mtimeMs, sha256: sum };+ try {+ fs.writeFileSync(cacheFile, JSON.stringify(cache), { mode: 0o600 });+ } catch {}+ }+ return sum.toLowerCase() === sha256.toLowerCase();+}++/** llama-server's arguments for one start. */+export function serverArgs(slot, o) {+ return [+ "-m", slot.model,+ "--host", "127.0.0.1",+ "--port", String(o.port),+ "--api-key", o.key,+ "-c", String(slot.context),+ "-ngl", o.device === "gpu" ? "99" : "0",+ "-np", "1",+ "-t", String(slot.threads),+ "--jinja",+ "--no-webui",+ "--alias", TEXT_MODEL,+ ];+}++/** The graphics memory llama-server says it took (its CUDA buffers, in MB), from its log. */+export function cudaMbOf(logText) {+ let mb = 0;+ for (const m of String(logText).matchAll(/CUDA\d+ [\w ]*?buffer size\s*=\s*([\d.]+) MiB/g)) mb += Number(m[1]);+ return Math.round(mb);+}++/** A text job as the studio sends it, checked; null when it isn't one. */+export function jobOf(body) {+ const j = body?.job;+ if (!j || typeof j !== "object") return null;+ const str = (v, max) => typeof v === "string" && v.length <= max;+ if (!str(j.id, 80) || !j.id || !str(j.lease, 80) || !j.lease || !str(j.system, 16_000) || !str(j.user, 16_000) || !j.user) return null;+ const maxTokens = Number(j.maxTokens);+ if (!Number.isInteger(maxTokens) || maxTokens < 1 || maxTokens > 8192) return null;+ return { id: j.id, lease: j.lease, system: j.system, user: j.user, maxTokens, json: j.json === true };+}++/** The request body for one job: thinking off, the model card's sampling. */+export function chatBody(job) {+ return {+ model: TEXT_MODEL,+ messages: [+ ...(job.system ? [{ role: "system", content: job.system }] : []),+ { role: "user", content: job.user },+ ],+ max_tokens: job.maxTokens,+ temperature: 1.0,+ top_p: 0.95,+ stream: false,+ chat_template_kwargs: { enable_thinking: false },+ ...(job.json && { response_format: { type: "json_object" } }),+ };+}++export class TextSlot {+ /**+ * @param {object} slot textSlotOf's answer+ * @param {object} deps { call (the studio, with the worker's token), log, workDir, home, now, sleep, spawn, fetch, env }+ */+ constructor(slot, deps) {+ this.slot = slot;+ this.d = deps;+ this.now = deps.now ?? Date.now;+ this.log = deps.log ?? (() => {});+ this.dir = path.join(deps.workDir, "text");+ this.ok = null;+ this.checking = null;+ this.server = null;+ this.busy = false;+ this.job = Promise.resolve();+ this.lastJobAt = 0;+ this.missedAt = -Infinity;+ // Ends a claim that waits for a job when the worker stops.+ this.ending = new AbortController();+ }++ /** The model (and the server, when worker.json gives its SHA-256) checked once, in the background. */+ check() {+ if (this.ok !== null || this.checking) return;+ const cache = path.join(this.d.home ?? this.d.workDir, "text-checks.json");+ const hash = this.d.hash;+ this.checking = (async () => {+ const model = await fileMatches(this.slot.model, this.slot.sha256, cache, hash);+ const server = fs.existsSync(this.slot.server) && (!this.slot.serverSha256 || (await fileMatches(this.slot.server, this.slot.serverSha256, cache, hash)));+ this.ok = model && server;+ this.log(this.ok ? "Its text slot is ready: the model's SHA-256 matches." : `Its text slot is off: ${!model ? "the model file is missing or its SHA-256 doesn't match" : "llama-server is missing or its SHA-256 doesn't match"}.`);+ })()+ .catch((e) => {+ this.ok = false;+ this.log(`Its text slot is off: ${e.message}`);+ })+ .finally(() => (this.checking = null));+ }++ /** The processes and graphics memory that are the worker's own (the GPU's watch never counts them as another program). */+ own() {+ const s = this.server;+ // Until its log says what it took, a fair guess for this model on the GPU.+ return s?.device === "gpu" ? { pids: s.pid ? [s.pid] : [], mb: s.vramMb || TEXT_GPU_GUESS_MB } : { pids: [], mb: 0 };+ }++ /**+ * 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.+ */+ tick(t, { may, room }) {+ if (!may) {+ if (this.server && !this.busy) void this.stop("paused");+ return;+ }+ this.check();+ if (!this.ok || this.busy) return;+ if (this.server && t - this.lastJobAt >= this.slot.idleMin * 60_000) {+ void this.stop("idle");+ return;+ }+ // A running server keeps its device; a new start goes where there is room (the CPU only when worker.json allows it).+ const device = this.server?.device ?? (room === "gpu" ? "gpu" : this.slot.cpu ? "cpu" : null);+ if (!device) return;+ // The device it would start on now differs: it stops after this job, and starts there for the next one.+ if (this.server && room && room !== this.server.device && !(room === "cpu" && !this.slot.cpu)) {+ void this.stop("device");+ return;+ }+ if (t - this.missedAt < 3000) return;+ this.busy = true;+ this.job = this.claimAndRun(device)+ .then((had) => (this.missedAt = had ? -Infinity : this.now()))+ .catch((e) => {+ this.missedAt = this.now();+ if (!this.ending.signal.aborted) this.log(`A text job stopped: ${e.message}`);+ })+ .finally(() => (this.busy = false));+ }++ 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: TEXT_MODEL, device, wait: this.slot.claimWaitMs }), signal: this.ending.signal });+ if (res.status === 204 || !res.ok) {+ await res.body?.cancel().catch(() => {});+ return false;+ }+ const job = jobOf(await res.json().catch(() => null));+ if (!job) return false;+ let answer;+ try {+ await this.ensure(device);+ answer = { text: await this.complete(job) };+ } catch (e) {+ answer = { error: String(e.message ?? e).slice(0, 200) };+ this.log(`Text job ${job.id} has no answer: ${answer.error}`);+ }+ this.lastJobAt = this.now();+ const sent = await this.d.call(`/api/gpu/computer/text/${encodeURIComponent(job.id)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: job.lease, ...answer }) });+ await sent.body?.cancel().catch(() => {});+ return true;+ }++ /** The answer's words from its server. */+ async complete(job) {+ const s = this.server;+ if (!s) throw new Error("llama-server isn't running");+ const f = this.d.fetch ?? fetch;+ const r = await f(`http://127.0.0.1:${s.port}/v1/chat/completions`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${s.key}` },+ body: JSON.stringify(chatBody(job)),+ signal: AbortSignal.timeout(this.slot.answerMs),+ });+ if (!r.ok) throw new Error(`llama-server answered ${r.status}`);+ const body = await r.json();+ const text = body?.choices?.[0]?.message?.content;+ if (typeof text !== "string" || !text.trim()) throw new Error("llama-server gave no text");+ return text;+ }++ /** Its server on this device, started now when it isn't (another device's is stopped first). */+ async ensure(device) {+ if (this.server?.device === device && this.server.alive) return;+ if (this.server) await this.stop("device");+ fs.mkdirSync(this.dir, { recursive: true });+ const port = await pickPort(null);+ const key = crypto.randomBytes(24).toString("base64url");+ const env = { ...comfyEnv(this.d.env ?? process.env), ...(device === "cpu" && { CUDA_VISIBLE_DEVICES: "-1" }) };+ const logFile = path.join(this.dir, "llama-server.log");+ const out = new RotatingLog(logFile, { maxBytes: 5 * 2 ** 20 });+ let head = "";+ const spawn = this.d.spawn ?? spawnChild;+ const child = spawn(this.slot.server, serverArgs(this.slot, { port, key, device }), { cwd: this.dir, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });+ const s = { child, pid: child.pid, port, key, device, alive: true, vramMb: 0, log: out };+ const take = (b) => {+ out.write(b);+ if (head.length < 200_000) head += b.toString("utf8");+ if (device === "gpu") s.vramMb = cudaMbOf(head);+ };+ child.stdout?.on("data", take);+ child.stderr?.on("data", take);+ child.once("exit", (code) => {+ s.alive = false;+ out.close();+ if (this.server === s) {+ this.server = null;+ if (!s.stopping) this.log(`llama-server stopped (exit ${code}).`);+ }+ });+ child.once("error", (e) => {+ s.alive = false;+ if (this.server === s) this.server = null;+ 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.`);+ 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;+ while (this.now() < end) {+ if (!s.alive) throw new Error("llama-server stopped while it started");+ const r = await f(`http://127.0.0.1:${port}/health`, { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(5000) }).catch(() => null);+ if (r?.ok) {+ await r.body?.cancel().catch(() => {});+ return;+ }+ await r?.body?.cancel().catch(() => {});+ await sleep(500);+ }+ await this.stop("start");+ throw new Error("llama-server didn't get ready in time");+ }++ /** Stop its server (it frees its memory). */+ async stop(why = "stop") {+ const s = this.server;+ if (!s) return;+ this.server = null;+ s.stopping = true;+ if (why === "idle") this.log("No text job for a while: llama-server stops and frees its memory.");+ 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() {+ this.ending.abort();+ await Promise.race([this.job, new Promise((r) => setTimeout(r, 10_000).unref?.())]);+ await this.stop("end");+ }+}diff --git a/src/app/api/enhance/route.ts b/src/app/api/enhance/route.tsindex a3d1d537..bc333a17 100644--- a/src/app/api/enhance/route.ts+++ b/src/app/api/enhance/route.ts@@ -2,6 +2,26 @@ import { enhancePrompt, writeLyrics } from "@/server/enhance";import { getModel } from "@/lib/catalog";import { appliesOwnStyle } from "@/lib/catalog/applied-style";import type { MediaKind, Operation } from "@/lib/catalog/types";+import { ownGpuToolMessage } from "@/lib/guest-access";+import { LoginGuard, requestViewer } from "@/server/auth";+import { hostedRunsOn } from "@/server/hosted-switch";+import { runAsTenant, type Tenant } from "@/server/tenant";+import type { HelperAnswer } from "@/server/text-helper";++type HelperTrouble = Exclude<HelperAnswer, { text: string }>;++/** Why no lyrics came, in words, with a code the page reads ("no-llm" offers Settings → AI helper to the owner). */+function noLyrics(owner: boolean, why: HelperTrouble | null): Response {+ const headers = { "Cache-Control": "no-store" };+ if (why?.error === "limit") {+ return Response.json({ error: "You've written a lot of lyrics just now. Try again in a minute, or type your own.", code: "helper-limit" }, { status: 429, headers: { ...headers, "Retry-After": String(why.retryAfterS ?? 60) } });+ }+ if (why?.error === "blocked") return Response.json({ error: why.message || "These lyrics can't be written here.", code: "helper-blocked" }, { status: 403, headers });+ if (owner && !why) {+ return Response.json({ error: "Writing lyrics needs an AI helper. Set up Claude or a local model in Settings → AI helper, or type your own.", code: "no-llm" }, { status: 503, headers });+ }+ return Response.json({ error: "Writing lyrics is busy right now. Try again in a moment, or type your own.", code: owner ? "no-llm" : "helper-busy" }, { status: 503, headers });+}export async function POST(request: Request) {const { prompt, kind, op, target, seconds, max, modelId } = (await request.json().catch(() => ({}))) as {@@ -16,14 +36,25 @@ export async function POST(request: Request) {modelId?: string;};if (!prompt?.trim()) return Response.json({ error: "Empty prompt" }, { status: 400 });+ // A visitor (only while hosted runs are on: the proxy lets nothing else through) gets the free helper, as itself.+ const viewer = requestViewer(request);+ const owner = viewer.kind === "owner";+ if (!owner && !hostedRunsOn()) return Response.json({ error: ownGpuToolMessage(false), code: "own-gpu-tool" }, { status: 403 });+ const as: Tenant | null = viewer.kind === "account" ? { kind: "account", id: viewer.account.id } : viewer.kind === "guest" ? { kind: "guest" } : null;+ const guestKey = viewer.kind === "guest" ? LoginGuard.clientKey(request.headers) : undefined;+ const run = <T,>(fn: () => Promise<T>) => (as ? runAsTenant(as, fn) : fn());+ const words = owner ? prompt : prompt.slice(0, 4000);+ const key = guestKey === LoginGuard.DIRECT ? "shared" : guestKey;try {if (target === "lyrics") {- const lyrics = await writeLyrics(prompt.slice(0, 4000), { seconds: Number(seconds) || undefined, max: Number(max) || undefined });- if (!lyrics) return Response.json({ error: "Writing lyrics needs the AI helper: pick Claude or a local model in Settings → AI helper", code: "no-llm" }, { status: 503 });+ let why: HelperTrouble | null = null;+ const helper = { guestKey: key, onHelper: (a: HelperTrouble) => (why = a) };+ const lyrics = await run(() => writeLyrics(words.slice(0, 4000), { seconds: Number(seconds) || undefined, max: Number(max) || undefined, helper }));+ if (!lyrics) return noLyrics(owner, why);return Response.json({ lyrics });}const ownStyle = !!modelId && !!getModel(modelId)?.routes.some(appliesOwnStyle);- return Response.json({ prompt: await enhancePrompt(prompt, kind ?? "image", op ?? "t2i", { ownStyle }) });+ return Response.json({ prompt: await run(() => enhancePrompt(words, kind ?? "image", op ?? "t2i", { ownStyle }, { guestKey: key, waitMs: 45_000 })) });} catch (e) {return Response.json({ error: (e as Error).message }, { status: 502 });}diff --git a/src/app/api/gpu/computer/text/[id]/route.ts b/src/app/api/gpu/computer/text/[id]/route.tsnew file mode 100644index 00000000..acc5b7c2--- /dev/null+++ b/src/app/api/gpu/computer/text/[id]/route.ts@@ -0,0 +1,19 @@+import { connection } from "next/server";+import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";+import { finishHelperJob } 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 sends the answer to its text job (`{ lease, text }`), or why it has none (`{ lease, error }`). */+export async function POST(request: Request, ctx: RouteContext<"/api/gpu/computer/text/[id]">) {+ 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-result", 60);+ if (limited) return limited;+ const { id } = await ctx.params;+ const body = ((await request.json().catch(() => null)) ?? {}) as { lease?: unknown; text?: unknown; error?: unknown };+ return finishHelperJob(worker, id, body) ? answer(200, { ok: true }) : answer(409, { error: "That text job isn't this worker's any more." });+}diff --git a/src/app/api/gpu/computer/text/claim/route.ts b/src/app/api/gpu/computer/text/claim/route.tsnew file mode 100644index 00000000..670af379--- /dev/null+++ b/src/app/api/gpu/computer/text/claim/route.ts@@ -0,0 +1,30 @@+import { connection } from "next/server";+import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";+import { claimHelperJob, helperWaiting, HELPER_TIMES } from "@/server/text-helper";++const no = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });++/**+ * A worker's text slot asks for the free helper's next text job (src/server/text-helper.ts). It waits up to 20 s for one+ * (or `wait` ms, less): the job, or 204.+ */+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 no(403, "Only a shared worker takes text jobs.");+ const limited = rateOf(callerKey(request, principal), "claim-text", 60);+ if (limited) return limited;+ const body = ((await request.json().catch(() => null)) ?? {}) as { model?: unknown; device?: unknown; wait?: unknown };+ const asked = Number(body.wait);+ const wait = Number.isFinite(asked) ? Math.max(0, Math.min(HELPER_TIMES.claimWaitMs, asked)) : HELPER_TIMES.claimWaitMs;+ const end = Date.now() + wait;+ // The slot is noted live on the first look; later looks read the line first and claim only when a job waits.+ for (let first = true; ; first = false) {+ const job = first || helperWaiting() ? claimHelperJob(worker, body, Date.now(), first) : null;+ if (job) return Response.json({ job }, { headers: { "Cache-Control": "no-store" } });+ if (Date.now() >= end || request.signal.aborted) return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });+ await new Promise((r) => setTimeout(r, HELPER_TIMES.pollMs));+ }+}diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.tsindex 4ca40248..d1306a44 100644--- a/src/app/api/status/route.ts+++ b/src/app/api/status/route.ts@@ -8,6 +8,8 @@ import { llmBackends } from "@/server/providers/llm";import { nothingConnected, type EngineModeName } from "@/lib/connections";import { getSetting, setSetting } from "@/server/settings";import { offeredSummary } from "@/server/model-access";+import { placeName } from "@/server/place-name";+import { helperKnown, helperLive } from "@/server/text-helper";/** Which providers are usable right now — drives badges, the demo-mode notice and Home's first-run guide. */export async function GET(request?: Request) {@@ -46,7 +48,8 @@ export async function GET(request?: Request) {...(ownerGpu && { ownerGpu }),// Settings → Models & licences: the models switched off, so pickers leave them out (absent while everything is on)....(access && { access }),- // The text LLM: the AI helper setting, whether Claude takes text steps, and the local server (no keys).- llm: { helper: aiHelper(), claude: llmBackends({ endpoint: "auto" })[0] === "claude", ...local },+ // The text LLM: the AI helper setting, whether Claude takes text steps, the local server (no keys), and the free+ // helper on the workers' text slots (with the name visitors read for them).+ llm: { helper: aiHelper(), claude: llmBackends({ endpoint: "auto" })[0] === "claude", ...local, free: { live: helperLive(), known: helperKnown(), label: placeName() } },});}diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 3a3b4129..e238b510 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -705,7 +705,16 @@ export function SettingsForm({ prices }: { prices?: string }) {value={(get("enhanceProvider")?.value || "auto").replace(/^ollama$/, "local")}onChange={set("enhanceProvider")}options={[- { value: "auto", label: "Automatic", hint: "Claude when a key is set, then a local model, then the offline rewriter." },+ {+ value: "auto",+ label: "Automatic",+ hint: status?.llm?.free?.known+ ? `Claude when a key is set, then a local model, then ${status.llm.free.label} (free), then the offline rewriter.`+ : "Claude when a key is set, then a local model, then the offline rewriter.",+ },+ ...(status?.llm?.free?.known || get("enhanceProvider")?.value === "free"+ ? [{ value: "free", label: `${status?.llm?.free?.label ?? "Your workers"} (free)`, hint: "A small open model on your workers' text slots. Nothing goes to a paid API." }]+ : []),{ value: "anthropic", label: "Claude", hint: "Claude through your Anthropic key (paid per use)." },{ value: "local", label: "Local model only", hint: "A local, open-source model (Ollama, LM Studio, Unsloth Studio or your own server). Claude is never called." },{ value: "none", label: "Offline rewriter", hint: "Built-in rules, no LLM. Text steps (translate, write) are off." },diff --git a/src/components/studio/lyrics-editor.tsx b/src/components/studio/lyrics-editor.tsxindex 478726c2..c641ef47 100644--- a/src/components/studio/lyrics-editor.tsx+++ b/src/components/studio/lyrics-editor.tsx@@ -1,9 +1,10 @@"use client";import { Loader2, Music2, PenLine, Sparkles, X } from "lucide-react";+import { useRouter } from "next/navigation";import { useId, useRef, useState } from "react";import { toast } from "sonner";-import { useLikelyVisitor, writeLyrics } from "@/lib/api";+import { useTextHelper, writeLyrics } from "@/lib/api";import type { ModelDef } from "@/lib/catalog/types";import { INSTRUMENTAL, insertTag, isInstrumental, normalizeLyrics, promptWithLyrics, SECTION_TAGS, songLength, structureOf } from "@/lib/lyrics";import { toastError } from "@/lib/refusals";@@ -14,7 +15,7 @@ const CHIPS = ["Verse", "Chorus", "Pre-Chorus", "Bridge", "Intro", "Outro", "Ins/*** Audio → Music's lyrics, for a model that sings them (ModelOptions.lyrics): the words with their section tags, chips that- * put a tag on a line of its own at the cursor, "Write the lyrics" (the install's AI helper, from the song's description),+ * put a tag on a line of its own at the cursor, "Write the lyrics" (the AI helper, from the song's description),* and how many characters the model takes. The draft keeps the words while you switch models; only one that sings gets them.*/export function LyricsEditor({@@ -35,8 +36,9 @@ export function LyricsEditor({const id = useId();const area = useRef<HTMLTextAreaElement>(null);const [writing, setWriting] = useState(false);- // "Write the lyrics" uses the install's AI helper, which guests and accounts can't call.- const visitor = useLikelyVisitor();+ // "Write the lyrics": the owner's AI helper, or for a visitor the studio's free helper.+ const helper = useTextHelper();+ const router = useRouter();const spec = model.options.lyrics ?? {};// Lyrics read after the description (Lyria 3.5) count with it.const length = spec.inPrompt && value.trim() ? promptWithLyrics(idea, value).length : normalizeLyrics(value).length;@@ -62,7 +64,9 @@ export function LyricsEditor({try {onChange(await writeLyrics(idea, { seconds, max: spec.max }));} catch (e) {- toastError(e);+ // Nothing set up to write them: one click to Settings → AI helper.+ if ((e as { code?: string }).code === "no-llm") toast.error((e as Error).message, { action: { label: "Set up", onClick: () => router.push("/settings#text-ai") } });+ else toastError(e);} finally {setWriting(false);}@@ -76,7 +80,7 @@ export function LyricsEditor({{!spec.required && <span className="font-normal text-muted-foreground">optional</span>}</label><span className="ml-auto flex items-center gap-1">- {!visitor && (+ {helper && (<buttontype="button"onClick={write}diff --git a/src/components/studio/settings-panel.tsx b/src/components/studio/settings-panel.tsxindex 3b23bcc2..3548fc30 100644--- a/src/components/studio/settings-panel.tsx+++ b/src/components/studio/settings-panel.tsx@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";-import { useLikelyVisitor } from "@/lib/api";+import { useLikelyVisitor, useTextHelper } from "@/lib/api";import { OwnSetupChip } from "@/components/own-setup";import { wantsH3TwoK } from "@/lib/catalog/regenerate";import { FORMAT_INFO } from "@/lib/av/formats";@@ -324,8 +324,9 @@ function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativeProconst opts = model?.options ?? {};const d = model?.defaults ?? {};const [advanced, setAdvanced] = useState(p.seed !== undefined || !!negativePrompt);- // "Rewrite my prompt now" uses the install's AI helper, which guests and accounts can't call.const visitor = useLikelyVisitor();+ // "Rewrite my prompt now": the owner's AI helper, or for a visitor the studio's free helper.+ const helper = useTextHelper();// What this operation's routes send (route-takes.ts): a ratio, size or length they don't make stays in view, muted, and// says why with the closest one they do; a seed, negative prompt or sound switch they don't read says so.const takes: OpTakes = useMemo(() => opTakes(model, op), [model, op]);@@ -445,7 +446,7 @@ function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePro)}{shape.enhance && (<Toggle label="Enhance prompt" hint="Rewrites your prompt with more detail before it runs" checked={!!p.enhancePrompt} onChange={(v) => setP({ enhancePrompt: v })}>- {!visitor && (+ {helper && (<buttontype="button"onClick={onRewrite}diff --git a/src/lib/api.ts b/src/lib/api.tsindex 9f1986b3..9536a32c 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -945,7 +945,9 @@ export interface StatusInfo {cloudProvider: string;/** The text LLM: Settings → AI helper, whether Claude takes text steps, and the local model server in use. */llm?: {- helper: "auto" | "anthropic" | "local" | "none";+ helper: "auto" | "anthropic" | "local" | "free" | "none";+ /** The free helper on the workers' text slots: answering now, seen today, and the name for it. */+ free?: { live: boolean; known: boolean; label: string };claude: boolean;/** Settings' local server: "auto" or the one pinned. */provider: string;@@ -990,6 +992,8 @@ export interface StatusInfo {prefer?: "pool";/** The name visitors read for this install's GPUs ("Runs on Our GPUs", src/lib/place-name.ts). Only with `hosted`. */placeName?: string;+ /** The free text helper writes for this visitor ("Write the lyrics", "Rewrite my prompt now"). Only with `hosted`. */+ helper?: true;/*** Where the account's runs go, as it picked (only with `hosted`, only to that account; none: the install's GPUs).* "key" starts its engine switch on Cloud (src/lib/engine-pref.ts).@@ -1073,6 +1077,16 @@ export function usePlaceName(): Place | null {return v?.hosted ? placeOf(v.placeName) : null;}+/**+ * May this viewer use the text helper's buttons ("Write the lyrics", "Rewrite my prompt now"): the owner always (the+ * server says what to set up when nothing answers), a visitor when the studio's free helper writes for it.+ */+export function useTextHelper(): boolean {+ const s = useStatus().data;+ const visitor = useLikelyVisitor();+ return visitor ? !!s?.viewer?.helper : true;+}+/** What an uploaded clip's header says: length, size, frame rate and sound (empty for formats the server can't read). */export interface ClipFacts {duration?: number;diff --git a/src/lib/assist-models.ts b/src/lib/assist-models.tsindex adb38c52..b661a9df 100644--- a/src/lib/assist-models.ts+++ b/src/lib/assist-models.ts@@ -44,7 +44,7 @@ export interface World {/** Settings → Engine: Open source only. */openOnly: boolean;/** Settings → AI helper → Use: "none" turns Assist's models off; "local" makes Free (local first) the default; "anthropic" allows Claude on Open source only. */- helper: "auto" | "anthropic" | "local" | "none";+ helper: "auto" | "anthropic" | "local" | "free" | "none";/** Settings → AI helper → Smart plans with: "auto", or "provider|model". */smartPlan: string;/** Settings → AI helper → Free uses. */diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 49fb20ac..0b4d3166 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -419,6 +419,11 @@ export function ownGpuRun(method: string, pathname: string): boolean {*/const POOL_TOOL_RUNS: readonly RegExp[] = [/^\/api\/palettes\/lock$/];+/** The free text helper's routes (src/server/text-helper.ts): a visitor may call them while hosted runs are on, within the route's own limits. */+const HELPER_ROUTES: readonly RegExp[] = [/^\/api\/enhance$/];++export const helperRoute = (method: string, pathname: string): boolean => method === "POST" && HELPER_ROUTES.some((r) => r.test(pathname));+export function poolToolRun(method: string, pathname: string): boolean {return method === "POST" && POOL_TOOL_RUNS.some((r) => r.test(pathname));}diff --git a/src/proxy.ts b/src/proxy.tsindex fb6f21c5..775e597f 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -26,6 +26,7 @@ import {LIBRARY_MESSAGE,ownGpuToolMessage,ownerOnly,+ helperRoute,ownGpuRun,poolToolRun,} from "@/lib/guest-access";@@ -216,6 +217,8 @@ function guest(request: NextRequest): NextResponse {if (isPriceCheck(method, pathname, search, hostedRunsOn())) return priceCheck(request, `guest:${LoginGuard.clientKey(request.headers)}`);if (isAssistChange(method, pathname)) return assistOwner();if (anyoneMayReport(method, pathname)) return pass(request);+ // The free text helper (lyrics, a prompt rewrite): while hosted runs are on, its route counts a guest's own limits.+ if (helperRoute(method, pathname) && hostedRunsOn()) return pass(request);// What an account may send, the library, the owner's settings and the studios' runs: signing up is the next step.// A tool run made only on this install's GPUs counts as one of them with hosted runs on, and as a tool that isn't// available here without them.@@ -292,6 +295,7 @@ function account(request: NextRequest, who: Account): NextResponse {if (accountMayChange(request.method, pathname, search)) return pass(request);if (isAssistChange(request.method, pathname)) return assistOwner();if (isLibraryChange(request.method, pathname)) return NextResponse.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });+ if (helperRoute(request.method, pathname) && hostedRunsOn()) return pass(request);// A tool its own GPU or key wouldn't run says so first: "Connect your GPU" only for what a GPU or a key unlocks. A tool// run made only on this install's GPUs (the palette lock) goes to its route with hosted runs on, and is refused so// without them, as before.diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.tsindex 038bdc35..f7a4c9a5 100644--- a/src/server/account-gpu.ts+++ b/src/server/account-gpu.ts@@ -18,6 +18,7 @@ import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";import { poolHasFiles, poolReady, poolTakes } from "./hosted";import { placeName } from "./place-name";+import { helperKnown } from "./text-helper";import { poolOwnModels, poolOwnPresets, type PresetPress } from "./pool-own-setup";import { ranOwnFirst, runOnOf, type RunOn } from "./run-on";import { poolRulesOf, type PoolRules, type PresetModel } from "@/lib/pool-rules";@@ -345,6 +346,8 @@ export interface VisitorView {prefer?: "pool";/** The name visitors read for this install's GPUs ("Runs on Our GPUs"; src/server/place-name.ts). Only with `hosted`. */placeName?: string;+ /** The free text helper writes for this visitor ("Write the lyrics", "Rewrite my prompt now"). Only with `hosted`. */+ helper?: true;/*** Where the account's runs go, as it picked (run-on.ts; only with `hosted`, only to that account). Absent: the* install's default. `runKey`: with "key", the provider whose key runs them.@@ -455,6 +458,8 @@ export async function visitorStatus(account: Account | null) {if (p?.hosted && p.prefer === "pool") viewer.prefer = "pool";// What the visitor reads for this install's GPUs ("Runs on {name}"): the policy's name, else the install's.if (p?.hosted) viewer.placeName = placeName(p);+ // The free text helper (lyrics, a prompt rewrite) on this install's workers.+ if (p?.hosted && helperKnown()) viewer.helper = true;const card = p?.hosted && typeof p.cardText === "string" ? p.cardText.trim().slice(0, 40) : "";if (card) viewer.cardText = card;// The account's own pick of where its runs go, and whether the one-time note is for it (it had runs on its own GPUdiff --git a/src/server/db.ts b/src/server/db.tsindex 8a81b046..f1ace827 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1185,6 +1185,8 @@ function open(): Database.Database {db.exec(ADMIN_TABLES);// The runs let in whose rows are still being made (pool-limits.ts openAdmission): not a numbered migration either.db.exec(ADMISSION_TABLES);+ // The free text helper's line and the workers' text slots (text-helper.ts): not a numbered migration either.+ db.exec(HELPER_TABLES);// Skills: the runs that wait across studios. A data folder that ran claude/fuobe-parity-4's earlier build of this// feature (its numbered migration at place 27, a skill_runs with no engine column and runs kept in another shape)// keeps that table under another name, so these runs start from an empty table. Nothing is deleted.@@ -1295,6 +1297,32 @@ const ADMISSION_TABLES = `CREATE TABLE IF NOT EXISTS open_admissions ();CREATE INDEX IF NOT EXISTS open_admissions_account ON open_admissions(account, at);`;+/** Text jobs for the workers' text slots, and when each slot last asked for one (src/server/text-helper.ts). */+const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (+ id TEXT PRIMARY KEY,+ who TEXT NOT NULL,+ task TEXT NOT NULL,+ system TEXT NOT NULL,+ user TEXT NOT NULL,+ max_tokens INTEGER NOT NULL,+ json INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL,+ worker_id TEXT,+ lease TEXT,+ created_at INTEGER NOT NULL,+ claimed_at INTEGER,+ done_at INTEGER,+ text TEXT,+ error TEXT+ );+ CREATE INDEX IF NOT EXISTS helper_jobs_line ON helper_jobs(state, created_at);+ CREATE TABLE IF NOT EXISTS helper_slots (+ worker_id TEXT PRIMARY KEY,+ seen_at INTEGER NOT NULL,+ model TEXT,+ device TEXT+ );`;+export function db(): Database.Database {globalThis.__fuobeDb ??= open();return globalThis.__fuobeDb;diff --git a/src/server/enhance.ts b/src/server/enhance.tsindex ad590aec..a714a185 100644--- a/src/server/enhance.ts+++ b/src/server/enhance.ts@@ -6,10 +6,12 @@ import { normalizeLyrics } from "@/lib/lyrics";import { activeLocal, aiHelper, chatLocal, type JsonSpec } from "./llm";import { engineMode, getSetting } from "./settings";import { tenant } from "./tenant";+import { askHelper, freeHelperOn, helperWho, type HelperAnswer, type HelperTask } from "./text-helper";/*** "Enhance prompt": rewrite a short idea into a rich, model-friendly prompt.- * Order: Claude (if an Anthropic key is set) → a local model (Ollama, LM Studio, Unsloth Studio…) → offline heuristic.+ * Order: Claude (if an Anthropic key is set) → a local model (Ollama, LM Studio, Unsloth Studio…) → the free helper on+ * the workers' text slots (src/server/text-helper.ts) → offline heuristic.*/const SYSTEM = `You rewrite short creative ideas into prompts for image and video generation models.@@ -83,6 +85,14 @@ export interface LlmTextOptions {timeoutMs?: number;/** The open engine: a local model, never Claude (the AI helper set to Offline still means none). */ollamaOnly?: boolean;+ /** A task the free helper takes: with one, a visitor's call and an install with nothing else set may use it. */+ task?: HelperTask;+ /** A guest's address key, for the free helper's limits. */+ guestKey?: string;+ /** How long a free helper's job may wait for a text slot. */+ waitMs?: number;+ /** Hears why the free helper gave no text. */+ onHelper?: (a: Exclude<HelperAnswer, { text: string }>) => void;}/** The local model in use (Ollama, LM Studio, Unsloth Studio or the custom server), thinking off where the server allows it. */@@ -106,12 +116,16 @@ async function viaLocal(system: string, user: string, images: LlmImage[], opts:* Which LLM llmText would ask right now (Claude is the one that costs money). "ollama" means a local* model, whichever server runs it (Ollama, LM Studio, Unsloth Studio or the custom one: Settings → AI helper).*/-export function llmTextBackend(): "claude" | "ollama" | null {- // An account's run or a visitor's price check never uses the install's AI helper (its LLM, its Claude key): the- // offline wording (heuristicEnhance) is used instead.- if (tenant()) return null;+export function llmTextBackend(): "claude" | "ollama" | null;+export function llmTextBackend(task?: HelperTask): "claude" | "ollama" | "free" | null;+export function llmTextBackend(task?: HelperTask): "claude" | "ollama" | "free" | null {+ // An account's run or a visitor's price check never uses the install's AI helper (its LLM, its Claude key): the free+ // helper for a task it takes, else the offline wording (heuristicEnhance).+ const free = !!task && freeHelperOn();+ if (tenant()) return free ? "free" : null;const choice = aiHelper();if (choice === "none") return null;+ if (choice === "free") return free ? "free" : "ollama";if (choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"))) return "claude";return "ollama";}@@ -128,9 +142,22 @@ export async function llmText(system: string, user: string, a: LlmImage[] | LlmTconst images: LlmImage[] = Array.isArray(a) ? a : [];const opts: LlmTextOptions = Array.isArray(a) ? b : a;// The open engine never calls a paid API: a local model, unless the AI helper is off.- const backend = opts.ollamaOnly && llmTextBackend() === "claude" ? "ollama" : llmTextBackend();+ const first = llmTextBackend(opts.task);+ const backend = opts.ollamaOnly && first === "claude" ? "ollama" : first;if (backend === "claude") return viaClaude(system, user, images).catch(() => null);- if (backend === "ollama") return viaLocal(system, user, images, opts).catch(() => null);+ if (backend === "ollama") {+ const local = await viaLocal(system, user, images, opts).catch(() => null);+ // Automatic (or the free helper, set but not answering a moment ago): the free helper when no local model answers.+ if (local !== null || !opts.task || !["auto", "free"].includes(aiHelper()) || !freeHelperOn()) return local;+ } else if (backend !== "free") return null;+ return viaFree(system, user, opts);+}++/** The free helper's answer (it reads the words only), or null with the reason told to `onHelper`. */+async function viaFree(system: string, user: string, opts: LlmTextOptions): Promise<string | null> {+ const a = await askHelper({ task: opts.task!, system, user, json: !!opts.json, who: helperWho(opts.guestKey), waitMs: opts.waitMs }).catch((): HelperAnswer => ({ error: "failed" }));+ if ("text" in a) return a.text;+ opts.onHelper?.(a);return null;}@@ -195,7 +222,7 @@ const SOUL_SYSTEM =export async function enhanceSoulWords(words: string): Promise<string> {const w = words.trim();if (!w || w.split(/\s+/).length >= 60) return words;- const out = (await llmText(SOUL_SYSTEM, w))?.trim().replace(/^["“]|["”]$/g, "").replace(/[.\s]+$/, "");+ const out = (await llmText(SOUL_SYSTEM, w, { task: "soul", waitMs: 30_000 }))?.trim().replace(/^["“]|["”]$/g, "").replace(/[.\s]+$/, "");return out && out.length > w.length ? out : words;}@@ -212,11 +239,11 @@ Rules:* Lyrics for a song described in `idea`, about as long as `seconds` of music and at most `max` characters, from whichever* LLM the install allows (Claude or a local model); null when none answers. Tags are normalized (src/lib/lyrics.ts).*/-export async function writeLyrics(idea: string, o: { seconds?: number; max?: number } = {}): Promise<string | null> {+export async function writeLyrics(idea: string, o: { seconds?: number; max?: number; helper?: Pick<LlmTextOptions, "guestKey" | "onHelper"> } = {}): Promise<string | null> {const seconds = o.seconds && o.seconds > 0 ? Math.min(600, o.seconds) : 120;const sections = seconds <= 45 ? "one verse and one chorus" : seconds <= 100 ? "a verse, a chorus, a second verse and the chorus again" : "a full song (two or three verses, the chorus after each, a bridge)";const room = o.max ? ` Stay under ${Math.floor(o.max * 0.9)} characters.` : "";- const text = await llmText(LYRICS_SYSTEM, `Write lyrics for this song, about ${Math.round(seconds / 60 * 10) / 10} minutes long: ${sections}.${room}\n\n${idea.trim()}`);+ const text = await llmText(LYRICS_SYSTEM, `Write lyrics for this song, about ${Math.round(seconds / 60 * 10) / 10} minutes long: ${sections}.${room}\n\n${idea.trim()}`, { task: "lyrics", waitMs: 75_000, ...o.helper });const words = normalizeLyrics(text?.replace(/^```\w*\n?|```$/g, ""));if (!words) return null;return o.max && words.length > o.max ? trimLyrics(words, o.max) : words;@@ -229,8 +256,8 @@ export function trimLyrics(words: string, max: number): string {return out.length > max ? out.slice(0, max).trimEnd() : out;}-export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation, hints: EnhanceHints = {}): Promise<string> {- return (await llmText(SYSTEM, instruction(prompt, kind, op, hints))) ?? heuristicEnhance(prompt, kind, op, hints);+export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation, hints: EnhanceHints = {}, helper: Pick<LlmTextOptions, "guestKey" | "waitMs"> = {}): Promise<string> {+ return (await llmText(SYSTEM, instruction(prompt, kind, op, hints), { task: "enhance", waitMs: 30_000, ...helper })) ?? heuristicEnhance(prompt, kind, op, hints);}/**diff --git a/src/server/llm/servers.ts b/src/server/llm/servers.tsindex 3cc52e6e..84e0b7cc 100644--- a/src/server/llm/servers.ts+++ b/src/server/llm/servers.ts@@ -8,9 +8,9 @@ export const LOCAL_LABELS: Record<LocalKind, string> = { ollama: "Ollama", lmstuexport const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);/** Settings → AI helper. The old value "ollama" means a local model only, whichever server runs it. */-export function aiHelper(): "auto" | "anthropic" | "local" | "none" {+export function aiHelper(): "auto" | "anthropic" | "local" | "free" | "none" {const v = getSetting("enhanceProvider");- return v === "ollama" ? "local" : (v as "auto" | "anthropic" | "local" | "none");+ return v === "ollama" ? "local" : (v as "auto" | "anthropic" | "local" | "free" | "none");}/** The local server Settings pins (null: Automatic). */diff --git a/src/server/moderation.ts b/src/server/moderation.tsindex 52c459de..7c7bbf38 100644--- a/src/server/moderation.ts+++ b/src/server/moderation.ts@@ -81,7 +81,7 @@ export async function checkRun(input: RunCheckInput): Promise<CheckRunAnswer> {}/** Check one output. No service: show. No answer: wait (asked again later). */-export async function checkOutput(file: { bytes: Buffer; contentType: string; generationId: string; account: string | null; assetId: string; kind: "image" | "video" | "audio"; sha256: string }): Promise<CheckOutputAnswer> {+export async function checkOutput(file: { bytes: Buffer; contentType: string; generationId: string; account: string | null; assetId: string; kind: "image" | "video" | "audio" | "text"; sha256: string }): Promise<CheckOutputAnswer> {const t = target();if (!t) return { decision: "show" };try {diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.tsindex b2604316..cc2c8590 100644--- a/src/server/providers/llm.ts+++ b/src/server/providers/llm.ts@@ -6,7 +6,10 @@ import { cueText, parseCues, toSrt, type Cue } from "@/lib/cues";import type { GenInput, ModelRoute, Operation } from "@/lib/catalog/types";import { HOSTED_PROVIDERS, testHosted } from "../llm/hosted";import { aiHelper, chatLocal, checkLocal, emptyReply, LOCAL_LABELS, localLabel, localProblem, localReady, localServers, localWhat, pinnedKind, probeLocal, type JsonSpec, type LocalKind, type Ready } from "../llm";+import { placeName } from "../place-name";import { engineMode, getSetting } from "../settings";+import { tenant } from "../tenant";+import { askHelper, freeHelperOn, type HelperAnswer } from "../text-helper";import { toDataUri } from "../storage";import { comfyProvider } from "./comfyui";import type { PollResult, ProviderAdapter, RemoteOutput } from "./types";@@ -22,7 +25,7 @@ import type { PollResult, ProviderAdapter, RemoteOutput } from "./types";* loses a job that was still writing (it fails as interrupted and can be retried).*/-type Backend = "claude" | "local" | "comfyui";+type Backend = "claude" | "local" | "free" | "comfyui";/** The ComfyUI model and workflow open-source translations fall back to without Ollama. */export const COMFY_TRANSLATE_MODEL = "oss-qwen35-translate";@@ -66,8 +69,13 @@ export function llmBackends(route: LlmRoute): Backend[] {const out: Backend[] = [];const claude = route.endpoint !== "ollama" && !!getSetting("anthropicKey") && (choice === "anthropic" || (choice === "auto" && engineMode() !== "open"));if (claude) out.push("claude");- if ((route.endpoint === "ollama" || choice !== "anthropic") && localReady()) out.push("local");- else if (route.endpoint === "ollama" && route.op === "translate" && comfyProvider.isConfigured()) out.push("comfyui");+ const local = (route.endpoint === "ollama" || choice !== "anthropic") && !!localReady();+ // The free helper on the workers' text slots: Automatic's after a local model, first when picked, and a visitor's.+ const free = (choice === "auto" || choice === "free" || !!tenant()) && freeHelperOn();+ if (free && choice === "free") out.push("free");+ if (local) out.push("local");+ if (free && choice !== "free") out.push("free");+ if (!local && route.endpoint === "ollama" && route.op === "translate" && comfyProvider.isConfigured()) out.push("comfyui");return out;}@@ -93,8 +101,8 @@ export const llmUsesClaude = (route: Pick<ModelRoute, "endpoint">) => llmBackend// ---------------------------------------------------------------------------// Calls-const BACKEND_LABEL: Record<Exclude<Backend, "local">, string> = { claude: "Claude", comfyui: "Qwen3.5 on ComfyUI" };-const backendLabel = (b: Backend, job?: LlmJob) => (b === "local" ? (job?.local?.server.label ?? localLabel()) : BACKEND_LABEL[b]);+const BACKEND_LABEL: Record<Exclude<Backend, "local" | "free">, string> = { claude: "Claude", comfyui: "Qwen3.5 on ComfyUI" };+const backendLabel = (b: Backend, job?: LlmJob) => (b === "local" ? (job?.local?.server.label ?? localLabel()) : b === "free" ? placeName() : BACKEND_LABEL[b]);async function viaClaude(system: string, user: string, signal: AbortSignal): Promise<string> {const client = new Anthropic({ apiKey: getSetting("anthropicKey") });@@ -195,9 +203,24 @@ async function viaComfy(system: string, user: string, signal: AbortSignal): Prom}}+/** Words for a free helper's answer that came without text. */+function helperTrouble(a: Exclude<HelperAnswer, { text: string }>): string {+ if (a.error === "blocked") return a.message || "This text can't be written here.";+ if (a.error === "busy") return "The writer is busy right now. Press Retry in a moment.";+ return "The writer couldn't finish this text. Press Retry.";+}++/** The free helper (src/server/text-helper.ts): a run's step, counted by the run's own limits. */+async function viaFree(system: string, user: string, job: LlmJob, json?: JsonSpec): Promise<string> {+ const a = await askHelper({ task: job.task ?? "write", system, user, json: !!json, counted: false, waitMs: 120_000, signal: job.abort.signal });+ if ("text" in a) return a.text;+ throw new Error(helperTrouble(a));+}+const CALL: Record<Backend, (system: string, user: string, job: LlmJob, json?: JsonSpec) => Promise<string>> = {claude: (system, user, job) => viaClaude(system, user, job.abort.signal),local: viaLocal,+ free: viaFree,comfyui: (system, user, job) => viaComfy(system, user, job.abort.signal),};@@ -319,6 +342,8 @@ interface LlmJob {backend?: Backend;/** The local server the job runs on (chosen when it starts). */local?: Ready | null;+ /** The free helper's task for its calls. */+ task?: "write" | "translate";outputs?: RemoteOutput[];error?: string;abort: AbortController;@@ -430,7 +455,7 @@ export const llmProvider: ProviderAdapter = {const id = `llm_${nanoid(10)}`;// The local server is fixed when the job starts: its calls all go to the same one.const local = backends.includes("local") ? localReady() : null;- const job: LlmJob = { state: "running", abort: new AbortController(), at: Date.now(), backend: backends[0], local };+ const job: LlmJob = { state: "running", abort: new AbortController(), at: Date.now(), backend: backends[0], local, task: route.op === "translate" ? "translate" : "write" };all.set(id, job);runJob(route.op, input, backends, job).then((outputs) => Object.assign(job, { state: "succeeded", outputs }),diff --git a/src/server/settings.ts b/src/server/settings.tsindex dcb0bba6..2398bafe 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -115,7 +115,7 @@ export const SETTINGS = {*/demoMode: { key: "demo.mode", env: "FUOBE_DEMO_MODE", default: "off", options: ["off", "on", "auto"] },/** Settings → AI helper: Claude, a local model, or offline. "ollama" is the old name of "local" and still means it. */- enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "local", "ollama", "none"] },+ enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "local", "ollama", "free", "none"] },/** Which local model server: "auto" uses the first that answers (Ollama, LM Studio, Unsloth Studio, then the custom URL). */llmProvider: { key: "llm.provider", env: "FUOBE_LLM_PROVIDER", default: "auto", options: ["auto", "ollama", "lmstudio", "unsloth", "custom"] },ollamaUrl: { key: "ollama.url", env: "OLLAMA_URL", default: "http://127.0.0.1:11434" },diff --git a/src/server/text-helper.ts b/src/server/text-helper.tsnew file mode 100644index 00000000..91e1b611--- /dev/null+++ b/src/server/text-helper.ts@@ -0,0 +1,267 @@+import "server-only";+import crypto from "node:crypto";+import { hoursAt, parseHours } from "@/lib/worker-hours";+import { db } from "./db";+import { hostedRunsOn } from "./hosted-switch";+import { checkOutput, checkRun, moderationConfigured } from "./moderation";+import { hit } from "./rate";+import { tenant } from "./tenant";+import type { WorkerRow } from "./computer/workers";++/**+ * The free text helper: short text jobs (lyrics, a prompt rewrite, a chain's text step) run on a small open model in the+ * workers' text slots (`fuobe worker`, worker.json `textSlot`). A job waits in its own line (helper_jobs), never behind a+ * GPU job; the caller waits for the answer, and the row is deleted once read.+ */++export type HelperTask = "lyrics" | "enhance" | "soul" | "write" | "translate";++/** The most tokens a task may write. */+export const HELPER_TASKS: Record<HelperTask, { maxTokens: number }> = {+ lyrics: { maxTokens: 1200 },+ enhance: { maxTokens: 400 },+ soul: { maxTokens: 400 },+ write: { maxTokens: 4000 },+ translate: { maxTokens: 4000 },+};++export const isHelperTask = (v: unknown): v is HelperTask => typeof v === "string" && Object.hasOwn(HELPER_TASKS, v);++export const HELPER_TIMES = {+ /** A text slot that asked for a job this recently is live. */+ liveMs: 45_000,+ /** A text slot seen this recently means the install has the helper (visitors see its buttons). */+ knownMs: 24 * 60 * 60_000,+ /** How long one claim waits for a job. */+ claimWaitMs: 20_000,+ /** A claimed job with no answer after this fails. */+ runMs: 90_000,+ /** Rows older than this are deleted. */+ keepMs: 10 * 60_000,+ pollMs: 200,+ freshBeatMs: 30_000,+};++export const HELPER_LIMITS = {+ userChars: 6000,+ systemChars: 8000,+ textBytes: 64 * 1024,+ waitingAll: 60,+ waitingEach: 2,+ guest: { perMinute: 4, perHour: 20 },+ account: { perMinute: 8, perHour: 60 },+};++/** Whose job: "owner", "acct:<id>", or "guest:<address key>". */+export type HelperWho = string;++/** Whose a call is, from the request's tenant (a guest's address key comes from its route). */+export function helperWho(guestKey?: string): HelperWho {+ const t = tenant();+ if (!t) return "owner";+ return t.kind === "account" ? `acct:${t.id}` : `guest:${guestKey ?? "shared"}`;+}++interface JobRow {+ id: string;+ who: string;+ task: string;+ system: string;+ user: string;+ max_tokens: number;+ json: number;+ state: "waiting" | "running" | "done" | "failed";+ worker_id: string | null;+ lease: string | null;+ created_at: number;+ claimed_at: number | null;+ done_at: number | null;+ text: string | null;+ error: string | null;+}++/** A job as a text slot gets it. */+export interface HelperJob {+ id: string;+ lease: string;+ task: HelperTask;+ system: string;+ user: string;+ maxTokens: number;+ json: boolean;+}++const json = <T,>(s: string | null, fallback: T): T => {+ try {+ return s ? (JSON.parse(s) as T) : fallback;+ } catch {+ return fallback;+ }+};++/** May this worker take a text job now: a pool worker the website hasn't paused, not draining, inside its hours, heard from. */+export function textEligible(w: WorkerRow, now = Date.now()): boolean {+ return (+ w.kind === "pool" &&+ !w.revoked_at &&+ !(w.expires_at && w.expires_at <= now) &&+ !w.paused_server &&+ !w.drain &&+ !!w.seen_at &&+ now - w.seen_at <= HELPER_TIMES.freshBeatMs &&+ hoursAt(parseHours(json<unknown>(w.hours_json, null)), now).inside+ );+}++/** A text slot asked for a job in the last moments, from a worker that may take one. */+export function helperLive(now = Date.now()): 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 >= ?")+ .all(now - HELPER_TIMES.liveMs) as WorkerRow[];+ return rows.some((w) => textEligible(w, now));+}++/** May this call use the free helper now: it is live, and a visitor's call only while hosted runs are on. */+export const freeHelperOn = (now = Date.now()): boolean => (!tenant() || hostedRunsOn()) && helperLive(now);++/** The install has a text slot (one asked for a job today). */+export function helperKnown(now = Date.now()): boolean {+ return !!db().prepare("SELECT 1 FROM helper_slots WHERE seen_at >= ? LIMIT 1").get(now - HELPER_TIMES.knownMs);+}++/** Delete what no one waits for any more. */+export function sweepHelper(now = Date.now()): void {+ db().prepare("DELETE FROM helper_jobs WHERE created_at < ?").run(now - HELPER_TIMES.keepMs);+}++/**+ * The next job for this worker's text slot, or null: people's jobs first, then the owner's, oldest first. Notes the+ * slot as live either way.+ */+export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: unknown } = {}, now = Date.now(), note = true): HelperJob | null {+ const d = db();+ return d.transaction(() => {+ const model = typeof slot.model === "string" ? slot.model.slice(0, 120) : null;+ const device = slot.device === "gpu" || slot.device === "cpu" ? slot.device : null;+ if (note) d.prepare("INSERT INTO helper_slots (worker_id, seen_at, model, device) VALUES (?, ?, ?, ?) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device").run(w.id, now, model, device);+ const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow | undefined;+ if (!fresh || !textEligible(fresh, now)) return null;+ const row = d.prepare("SELECT * FROM helper_jobs WHERE state = 'waiting' ORDER BY CASE WHEN who = 'owner' THEN 1 ELSE 0 END, created_at LIMIT 1").get() as JobRow | undefined;+ if (!row || !isHelperTask(row.task)) return null;+ const lease = crypto.randomBytes(16).toString("base64url");+ d.prepare("UPDATE helper_jobs SET state = 'running', worker_id = ?, lease = ?, claimed_at = ? WHERE id = ? AND state = 'waiting'").run(w.id, lease, now, row.id);+ return { id: row.id, lease, task: row.task, system: row.system, user: row.user, maxTokens: row.max_tokens, json: !!row.json };+ }).immediate();+}++/** Is any text job waiting (a quick read before a claim)? */+export const helperWaiting = (): boolean => !!db().prepare("SELECT 1 FROM helper_jobs WHERE state = 'waiting' LIMIT 1").get();++/** What a model may leave around its answer: a reasoning block, a code fence around JSON. */+export const tidyHelperText = (s: string) => s.replace(/<think>[\s\S]*?<\/think>/g, "").trim();++/** A text slot's answer for its job (only with the lease its claim gave). False: not its job any more. */+export function finishHelperJob(w: WorkerRow, id: string, body: { lease?: unknown; text?: unknown; error?: unknown }, now = Date.now()): boolean {+ if (typeof body.lease !== "string") return false;+ let text: string | null = null;+ let error: string | null = null;+ if (typeof body.text === "string" && Buffer.byteLength(body.text) <= HELPER_LIMITS.textBytes) text = tidyHelperText(body.text);+ if (!text) error = typeof body.error === "string" && body.error ? body.error.slice(0, 200) : "no-text";+ const r = db()+ .prepare("UPDATE helper_jobs SET state = ?, text = ?, error = ?, done_at = ? WHERE id = ? AND worker_id = ? AND lease = ? AND state = 'running'")+ .run(text ? "done" : "failed", text, error, now, id, w.id, body.lease);+ return r.changes === 1;+}++export type HelperAnswer = { text: string } | { error: "busy" | "limit" | "blocked" | "failed"; message?: string; retryAfterS?: number };++const rateOf = (who: HelperWho) => (who.startsWith("acct:") ? HELPER_LIMITS.account : who === "guest:shared" ? { perMinute: HELPER_LIMITS.guest.perMinute * 10, perHour: HELPER_LIMITS.guest.perHour * 10 } : HELPER_LIMITS.guest);++export interface AskHelper {+ task: HelperTask;+ system: string;+ user: string;+ json?: boolean;+ who?: HelperWho;+ /** False: a step of a run, which the run's own limits already count. */+ counted?: boolean;+ /** How long the job may wait for a text slot (the answer's own time comes after). */+ waitMs?: number;+ signal?: AbortSignal;+ now?: () => number;+ sleep?: (ms: number) => Promise<void>;+}++/** Ask the free helper and wait for its answer. Never throws for the helper's own trouble: the answer says what went wrong. */+export async function askHelper(o: AskHelper): Promise<HelperAnswer> {+ const now = o.now ?? Date.now;+ const sleep = o.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));+ const who = o.who ?? helperWho();+ const d = db();+ sweepHelper(now());+ if (!helperLive(now())) return { error: "busy" };+ if (who !== "owner" && o.counted !== false) {+ const r = rateOf(who);+ for (const [key, limit, ms] of [[`helper:${who}:m`, r.perMinute, 60_000], [`helper:${who}:h`, r.perHour, 3_600_000]] as const) {+ const h = hit(key, limit, ms);+ if (!h.ok) return { error: "limit", retryAfterS: h.retryAfterS };+ }+ }+ const waiting = d.prepare("SELECT COUNT(*) AS n, SUM(CASE WHEN who = ? THEN 1 ELSE 0 END) AS mine FROM helper_jobs WHERE state IN ('waiting','running')").get(who) as { n: number; mine: number | null };+ if (waiting.n >= HELPER_LIMITS.waitingAll || (who !== "owner" && (waiting.mine ?? 0) >= HELPER_LIMITS.waitingEach)) return { error: "busy" };+ const user = o.user.slice(0, HELPER_LIMITS.userChars);+ const id = `hlp_${crypto.randomBytes(9).toString("base64url")}`;+ const account = who.startsWith("acct:") ? who.slice(5) : null;+ let checkOutputs = false;+ if (who !== "owner" && moderationConfigured()) {+ const a = await checkRun({+ requestId: id,+ account: account ? { id: account } : null,+ run: { place: "pool", model: "text-helper", op: o.task, app: null, preset: null, studio: o.task, kind: "text", engine: "open", provider: "llm", jobs: 1, outputsPerJob: 1, megapixels: null, seconds: null, fps: null, loras: 0, inputs: { image: 0, video: 0, audio: 0 }, lane: null, providerUsd: null },+ prompt: user,+ negative: null,+ inputs: [],+ consent: null,+ });+ if (!a.allowed) return a.code === "paused" ? { error: "busy" } : { error: "blocked", message: a.text };+ checkOutputs = a.checkOutputs !== false;+ }+ const created = now();+ d.prepare("INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, json, state, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?)").run(+ id,+ who,+ o.task,+ o.system.slice(0, HELPER_LIMITS.systemChars),+ user,+ HELPER_TASKS[o.task].maxTokens,+ o.json ? 1 : 0,+ created,+ );+ const waitMs = o.waitMs ?? 45_000;+ const drop = () => d.prepare("DELETE FROM helper_jobs WHERE id = ?").run(id);+ try {+ for (;;) {+ if (o.signal?.aborted) return { error: "failed" };+ const row = d.prepare("SELECT * FROM helper_jobs WHERE id = ?").get(id) as JobRow | undefined;+ const t = now();+ if (!row || row.state === "failed") return { error: row?.error === "busy" ? "busy" : "failed" };+ if (row.state === "done" && row.text) {+ if (checkOutputs) {+ const bytes = Buffer.from(row.text);+ const c = await checkOutput({ bytes, contentType: "text/plain; charset=utf-8", generationId: id, account, assetId: id, kind: "text", sha256: crypto.createHash("sha256").update(bytes).digest("hex") });+ if (c.decision !== "show") return c.decision === "hide" && c.text ? { error: "blocked", message: c.text } : { error: "failed" };+ }+ return { text: row.text };+ }+ if (row.state === "waiting" && t - created >= waitMs) {+ // Nobody took it in time: it ends here, so a slot that comes late doesn't run it.+ 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 (row.state === "running" && t - (row.claimed_at ?? t) >= HELPER_TIMES.runMs) return { error: "failed" };+ await sleep(HELPER_TIMES.pollMs);+ }+ } finally {+ drop();+ }+}diff --git a/tests/helpers/computer-tab.ts b/tests/helpers/computer-tab.tsindex 4b530213..cac4ddd5 100644--- a/tests/helpers/computer-tab.ts+++ b/tests/helpers/computer-tab.ts@@ -18,6 +18,9 @@ export interface ComputerRoutes {report: { POST: Handler };outputs: { PUT: Handler; GET: Handler };release: { POST: Handler };+ /** The text slot's claim and answer (the free text helper). */+ textClaim?: { POST: Handler };+ textResult?: { POST: Handler };}export async function loadRoutes(): Promise<ComputerRoutes> {@@ -28,6 +31,8 @@ export async function loadRoutes(): Promise<ComputerRoutes> {report: (await import("@/app/api/gpu/computer/tasks/[id]/report/route")) as never,outputs: (await import("@/app/api/gpu/computer/tasks/[id]/outputs/[n]/route")) as never,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,};}@@ -56,6 +61,8 @@ export function apiAs(routes: ComputerRoutes, cookie: string | null, extra: Recoif ((m = /^\/api\/gpu\/computer\/tasks\/([^/]+)\/report$/.exec(url.pathname))) return routes.report.POST(req, params({ id: m[1] }));if ((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 ((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 });};return Object.assign(api, { calls });diff --git a/tests/text-helper.test.ts b/tests/text-helper.test.tsnew file mode 100644index 00000000..dc6c7e23--- /dev/null+++ b/tests/text-helper.test.ts@@ -0,0 +1,267 @@+/**+ * The free text helper (src/server/text-helper.ts): text jobs wait in their own line for the workers' text slots, people's+ * jobs first; only the slot that claimed a job (with its lease) answers it; a job nobody takes in time ends as busy; a+ * visitor's calls have their own limits. Then the AI helper's order (Claude → a local model → the free helper) and the+ * lyrics route for the owner, an account and a guest. A stand-in slot answers here: no model, no GPU.+ */+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 30_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-text-helper-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_MODERATION_URL;++const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const pool = await import("@/server/computer/pool");+const helper = await import("@/server/text-helper");+const { llmTextBackend, llmText } = await import("@/server/enhance");+const { runAsTenant } = await import("@/server/tenant");+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 { proxy } = await import("@/proxy");++type WorkerRow = import("@/server/computer/workers").WorkerRow;+type W = { id: string; token: string };+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;+const jobs = () => db().prepare("SELECT id, state FROM helper_jobs").all() as { id: string; state: string }[];++/** A worker the owner added and resumed, all day, that beat just now. */+function addWorker(): W {+ const w = pool.addWorker(`pc-${Math.random().toString(36).slice(2, 8)}`);+ pool.patchWorker(w.id, { paused: false, hours: { always: true } });+ beat(w);+ return w;+}+const beat = (w: W) =>+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 3, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));++/** The next job this worker's text slot gets, waiting for one to come (at most `ms`). */+async function nextJob(w: W, ms = 5000) {+ const end = Date.now() + ms;+ for (;;) {+ const job = helper.claimHelperJob(workerRow(w), { model: "test", device: "gpu" });+ if (job || Date.now() > end) return job;+ await new Promise((r) => setTimeout(r, 25));+ }+}++/** A stand-in text slot: it answers every job it gets with `answer(job)`, until stopped. */+function standIn(w: W, answer: (job: NonNullable<Awaited<ReturnType<typeof nextJob>>>) => string) {+ let on = true;+ const seen: string[] = [];+ const done = (async () => {+ while (on) {+ const job = helper.claimHelperJob(workerRow(w), { model: "test", device: "gpu" });+ if (job) {+ seen.push(job.task);+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: answer(job) });+ } else await new Promise((r) => setTimeout(r, 25));+ }+ })();+ return {+ seen,+ stop: async () => {+ on = false;+ await done;+ },+ };+}++const cookies: Record<string, string> = {};+let account = "";+beforeAll(() => {+ auth.setPassword("install password");+ account = auth.createAccount("[email protected]", "long enough").id;+ cookies.account = `${auth.SESSION_COOKIE}=${auth.createSession(account).value}`;+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ // No local model answers here (Ollama's address goes nowhere), and Automatic has no Claude key.+ setSetting("ollamaUrl", "http://127.0.0.1:9");+});+beforeEach(() => {+ resetRates();+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("DELETE FROM helper_jobs").run();+ db().prepare("DELETE FROM helper_slots").run();+ setSetting("enhanceProvider", "auto");+});+afterEach(() => {+ delete process.env.FUOBE_HOSTED_RUNS;+});++const post = (url: string, body: unknown, who?: string, extra: Record<string, string> = {}) =>+ new Request(`http://localhost:3000${url}`, { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json", ...(who && { cookie: cookies[who] }), ...extra }, body: JSON.stringify(body) });+const viaProxy = (url: string, who?: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json", ...(who && { cookie: cookies[who] }) }, body: "{}" }));+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";++describe("the text slots' line", () => {+ it("a job waits for a text slot, which answers it with its lease; the words come back once and the row goes", async () => {+ const w = addWorker();+ expect(helper.helperLive()).toBe(false);+ expect(helper.claimHelperJob(workerRow(w))).toBeNull();+ expect(helper.helperLive()).toBe(true);+ const asked = helper.askHelper({ task: "lyrics", system: "Write lyrics.", user: "A song about rain" });+ const job = await nextJob(w);+ expect(job).toMatchObject({ task: "lyrics", system: "Write lyrics.", user: "A song about rain", maxTokens: 1200, json: false });+ expect(helper.finishHelperJob(workerRow(w), job!.id, { lease: "not its lease", text: "no" })).toBe(false);+ expect(helper.finishHelperJob(workerRow(w), job!.id, { lease: job!.lease, text: "<think>hmm</think>\n[Verse]\nRain on the glass" })).toBe(true);+ expect(await asked).toEqual({ text: "[Verse]\nRain on the glass" });+ expect(jobs()).toEqual([]);+ // Answered once: the same lease again finds nothing.+ expect(helper.finishHelperJob(workerRow(w), job!.id, { lease: job!.lease, text: "again" })).toBe(false);+ });++ it("people's jobs go before the owner's, and another worker can't answer a job it didn't take", async () => {+ const w = addWorker();+ const other = addWorker();+ helper.claimHelperJob(workerRow(w));+ const owner = helper.askHelper({ task: "enhance", system: "s", user: "owner's", waitMs: 5000 });+ await new Promise((r) => setTimeout(r, 10));+ const person = runAsTenant({ kind: "account", id: account }, () => helper.askHelper({ task: "enhance", system: "s", user: "account's", waitMs: 5000 }));+ await new Promise((r) => setTimeout(r, 10));+ const first = await nextJob(w);+ expect(first?.user).toBe("account's");+ expect(helper.finishHelperJob(workerRow(other), first!.id, { lease: first!.lease, text: "x" })).toBe(false);+ helper.finishHelperJob(workerRow(w), first!.id, { lease: first!.lease, text: "for the account" });+ const second = await nextJob(w);+ expect(second?.user).toBe("owner's");+ helper.finishHelperJob(workerRow(w), second!.id, { lease: second!.lease, error: "llama-server answered 500" });+ expect(await person).toEqual({ text: "for the account" });+ expect(await owner).toEqual({ error: "failed" });+ });++ it("a job nobody takes in time ends as busy, and a slot that comes late gets nothing", async () => {+ const w = addWorker();+ helper.claimHelperJob(workerRow(w));+ expect(await helper.askHelper({ task: "soul", system: "s", user: "u", waitMs: 300 })).toEqual({ error: "busy" });+ expect(helper.claimHelperJob(workerRow(w))).toBeNull();+ expect(jobs()).toEqual([]);+ });++ it("no live slot: busy at once; a worker paused on the website, draining or silent takes nothing", async () => {+ expect(await helper.askHelper({ task: "lyrics", system: "s", user: "u" })).toEqual({ error: "busy" });+ const w = addWorker();+ helper.claimHelperJob(workerRow(w));+ pool.patchWorker(w.id, { paused: true });+ expect(helper.helperLive()).toBe(false);+ pool.patchWorker(w.id, { paused: false });+ expect(helper.helperLive()).toBe(true);+ db().prepare("UPDATE relay_workers SET seen_at = ? WHERE id = ?").run(Date.now() - 60_000, w.id);+ expect(helper.helperLive()).toBe(false);+ beat(w);+ pool.patchWorker(w.id, { drain: true });+ expect(helper.textEligible(workerRow(w))).toBe(false);+ });++ it("a visitor's calls have limits: a minute's and its waiting jobs; a run's own steps aren't counted", async () => {+ const w = addWorker();+ helper.claimHelperJob(workerRow(w));+ const who = "guest:203.0.113.9";+ for (let i = 0; i < helper.HELPER_LIMITS.guest.perMinute; i++) expect(await helper.askHelper({ task: "enhance", system: "s", user: "u", who, waitMs: 30 })).toEqual({ error: "busy" });+ expect(await helper.askHelper({ task: "enhance", system: "s", user: "u", who, waitMs: 30 })).toMatchObject({ error: "limit" });+ expect(await helper.askHelper({ task: "write", system: "s", user: "u", who, waitMs: 30, counted: false })).toEqual({ error: "busy" });+ // Two of its own jobs waiting at once, at most.+ resetRates();+ const a = helper.askHelper({ task: "enhance", system: "s", user: "1", who, waitMs: 400 });+ const b = helper.askHelper({ task: "enhance", system: "s", user: "2", who, waitMs: 400 });+ await new Promise((r) => setTimeout(r, 20));+ expect(await helper.askHelper({ task: "enhance", system: "s", user: "3", who, waitMs: 400 })).toEqual({ error: "busy" });+ await Promise.all([a, b]);+ });+});++describe("the text slot's routes", () => {+ const auth_ = (w: W) => ({ authorization: `Bearer ${w.token}` });++ it("a shared worker's slot claims (204 when nothing comes) and answers with its lease; a browser can't", async () => {+ const w = addWorker();+ const none = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "nemotron", device: "gpu", wait: 0 }, undefined, auth_(w)));+ expect(none.status).toBe(204);+ const asked = helper.askHelper({ task: "lyrics", system: "s", user: "song" });+ const r = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "nemotron", device: "gpu", wait: 5000 }, undefined, auth_(w)));+ expect(r.status).toBe(200);+ const { job } = (await r.json()) as { job: { id: string; lease: string; user: string } };+ expect(job.user).toBe("song");+ const ctx = { params: Promise.resolve({ id: job.id }) } as never;+ expect((await resultRoute.POST(post(`/api/gpu/computer/text/${job.id}`, { lease: "x", text: "no" }, undefined, auth_(w)), ctx)).status).toBe(409);+ expect((await resultRoute.POST(post(`/api/gpu/computer/text/${job.id}`, { lease: job.lease, text: "[Chorus]\nla" }, undefined, auth_(w)), ctx)).status).toBe(200);+ expect(await asked).toEqual({ text: "[Chorus]\nla" });+ const browser = await claimRoute.POST(post("/api/gpu/computer/text/claim", { wait: 0 }, "owner", { "sec-fetch-site": "same-origin", origin: "http://localhost:3000" }));+ expect(browser.status).not.toBe(200);+ expect(browser.status).not.toBe(204);+ });+});++describe("the AI helper's order and the lyrics route", () => {+ it("a visitor gets the free helper only for a task it takes, and only while hosted runs are on", () => {+ const w = addWorker();+ helper.claimHelperJob(workerRow(w));+ runAsTenant({ kind: "account", id: account }, () => {+ expect(llmTextBackend()).toBeNull();+ expect(llmTextBackend("lyrics")).toBeNull();+ process.env.FUOBE_HOSTED_RUNS = "1";+ expect(llmTextBackend("lyrics")).toBe("free");+ expect(llmTextBackend()).toBeNull();+ });+ // The owner: Automatic still says Claude or a local model first; "free" picks it.+ expect(llmTextBackend("lyrics")).toBe("ollama");+ setSetting("enhanceProvider", "free");+ expect(llmTextBackend("lyrics")).toBe("free");+ setSetting("enhanceProvider", "none");+ expect(llmTextBackend("lyrics")).toBeNull();+ });++ it("Automatic with no local model answering: the free helper writes; without a task, nothing does", async () => {+ const w = addWorker();+ const slot = standIn(w, () => "A rich rewrite");+ expect(await llmText("s", "u", { task: "enhance" })).toBe("A rich rewrite");+ expect(await llmText("s", "u")).toBeNull();+ await slot.stop();+ });++ it("lyrics: a guest and an account get them from the free helper while hosted runs are on", async () => {+ process.env.FUOBE_HOSTED_RUNS = "1";+ const w = addWorker();+ const slot = standIn(w, (job) => (job.task === "lyrics" ? "[verse] Neon rain\n[chorus] Hold on" : "?"));+ expect(passed(await viaProxy("/api/enhance"))).toBe(true);+ expect(passed(await viaProxy("/api/enhance", "account"))).toBe(true);+ for (const who of [undefined, "account"]) {+ const r = await enhanceRoute.POST(post("/api/enhance", { prompt: "A synthwave song about rain", target: "lyrics", seconds: 30 }, who));+ expect(r.status).toBe(200);+ expect(((await r.json()) as { lyrics: string }).lyrics).toBe("[Verse]\nNeon rain\n\n[Chorus]\nHold on");+ }+ const rewrite = await enhanceRoute.POST(post("/api/enhance", { prompt: "a cat", kind: "image", op: "t2i" }));+ expect(((await rewrite.json()) as { prompt: string }).prompt).toBe("?");+ expect(slot.seen).toEqual(["lyrics", "lyrics", "enhance"]);+ await slot.stop();+ });++ it("never a dead end: busy words for a visitor, the way to set one up for the owner, and the proxy without hosted runs", async () => {+ process.env.FUOBE_HOSTED_RUNS = "1";+ const busy = await enhanceRoute.POST(post("/api/enhance", { prompt: "a song", target: "lyrics" }));+ expect(busy.status).toBe(503);+ expect(await busy.json()).toEqual({ error: "Writing lyrics is busy right now. Try again in a moment, or type your own.", code: "helper-busy" });+ // A rewrite always comes back: the offline one when the helper is busy.+ const rewrite = await enhanceRoute.POST(post("/api/enhance", { prompt: "a cat" }, "account"));+ expect(((await rewrite.json()) as { prompt: string }).prompt).toMatch(/^a cat\. /);+ const owner = await enhanceRoute.POST(post("/api/enhance", { prompt: "a song", target: "lyrics" }, "owner"));+ expect(owner.status).toBe(503);+ expect(await owner.json()).toMatchObject({ code: "no-llm", error: expect.stringContaining("Settings → AI helper") });+ delete process.env.FUOBE_HOSTED_RUNS;+ const off = await viaProxy("/api/enhance");+ expect(passed(off)).toBe(false);+ expect(off.status).toBe(403);+ });+});diff --git a/tests/worker-cpu-slot.test.ts b/tests/worker-cpu-slot.test.tsindex 3a2ff3e1..b94d2692 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> } = {}) {+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> } = {}) {const ctrl = new AbortController();const cfg = {site: SITE,@@ -248,6 +248,7 @@ function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: numbestallMin: 10,ffmpeg: null,cpuSlot: o.cpuSlot !== false,+ ...(o.textSlot && { textSlot: o.textSlot }),};const done = runWorker(cfg, {fetch: router(w, s),@@ -269,6 +270,7 @@ function start(w: W, s: Studio, p: Pc, o: { gpu?: { steps: number; stepMs: numbeallLanes,...(o.finishers !== undefined && { finishers: o.finishers }),...(o.shrinkPreview && { shrinkPreview: o.shrinkPreview }),+ ...(o.text && { text: o.text }),});const r = { ctrl, done };running.push(r);@@ -649,3 +651,50 @@ describe("live previews from the worker", () => {expect(a[a.length - 1]).toBe("out.jpg");});});++describe("the worker program's text slot", () => {+ it("answers the free helper's text job beside its other slots, with its own server on 127.0.0.1", 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");+ 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); res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ choices: [{ message: { content: "[Verse] " + b.messages.at(-1).content } }] })); });',+ '}).listen(Number(arg("--port")), "127.0.0.1");',+ ].join("\n"),+ );+ const pids: number[] = [];+ start(w, s, p, {+ textSlot: { server, model, sha256: crypto.createHash("sha256").update("stand-in model").digest("hex"), claimWaitMs: 1000 },+ text: {+ spawn: (_cmd: string, args: string[], o: object) => {+ const child = spawn(process.execPath, [server, ...args], o);+ if (child.pid) pids.push(child.pid);+ return child;+ },+ kill: async (pid: number) => {+ try {+ process.kill(pid);+ } catch {}+ },+ },+ });+ await until(() => helper.helperLive(), 30_000);+ const answer = await helper.askHelper({ task: "lyrics", system: "Write lyrics.", user: "rain on neon", waitMs: 20_000 });+ expect(answer).toEqual({ text: "[Verse] rain on neon" });+ expect(pids.length).toBe(1);+ expect(p.logs.join("\n")).toContain("Starting llama-server on the CPU");+ });+});diff --git a/tests/worker-text-slot.test.ts b/tests/worker-text-slot.test.tsnew file mode 100644index 00000000..a3bca045--- /dev/null+++ b/tests/worker-text-slot.test.ts@@ -0,0 +1,226 @@+/**+ * The worker's text slot (bin/lib/worker/text.mjs): it takes the studio's text jobs only with a model whose SHA-256+ * matches, starts its own llama-server (a stand-in here) on 127.0.0.1 with a new key, on the GPU or the CPU, answers each+ * job with its lease, stops the server when idle or paused, and its graphics memory counts as the worker's own. No model,+ * no GPU, no llama.cpp.+ */+import crypto from "node:crypto";+import { spawn } from "node:child_process";+import fs from "node:fs";+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, cudaMbOf, fileMatches, jobOf, serverArgs, TEXT_MODEL, TextSlot, textSlotOf } from "../bin/lib/worker/text.mjs";+import { tempDir } from "./helpers/temp-dir";++vi.setConfig({ testTimeout: 30_000 });++const dir = tempDir("fuobe-text-slot-");+const sha = (b: Buffer | string) => crypto.createHash("sha256").update(b).digest("hex");+const MODEL = Buffer.from("GGUF stand-in model bytes");+const modelFile = path.join(dir, "model.gguf");+fs.writeFileSync(modelFile, MODEL);++/** A stand-in llama-server: its buffers on stderr, /health and /v1/chat/completions behind its key, the request echoed back. */+const FAKE = `+import http from "node:http";+const arg = (n) => process.argv[process.argv.indexOf(n) + 1];+const port = Number(arg("--port"));+const key = arg("--api-key");+const gpu = arg("-ngl") !== "0";+if (gpu) process.stderr.write("load_tensors: CUDA0 model buffer size = 3577.50 MiB\\nllama_kv_cache: CUDA0 KV buffer size = 120.00 MiB\\nload_tensors: CUDA_Host model buffer size = 2400.00 MiB\\n");+http.createServer((req, res) => {+ if (req.headers.authorization !== "Bearer " + key) { res.writeHead(401); return res.end(); }+ if (req.url === "/health") { res.writeHead(200, { "content-type": "application/json" }); return res.end("{}"); }+ let body = "";+ req.on("data", (d) => (body += d));+ req.on("end", () => {+ const b = JSON.parse(body);+ const content = JSON.stringify({ host: req.headers.host, ngl: arg("-ngl"), cuda: process.env.CUDA_VISIBLE_DEVICES ?? null, token: process.env.FUOBE_WORKER_TOKEN ?? null, thinking: b.chat_template_kwargs.enable_thinking, user: b.messages.at(-1).content, max: b.max_tokens });+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ choices: [{ message: { content } }] }));+ });+}).listen(port, "127.0.0.1");+`;+const fakeFile = path.join(dir, "fake-llama.mjs");+fs.writeFileSync(fakeFile, FAKE);++const started: { args: string[]; pid?: number }[] = [];+/** Starts the stand-in where the slot would start llama-server. */+const fakeSpawn = (cmd: string, args: string[], o: Parameters<typeof spawn>[2]) => {+ expect(cmd).toBe(fakeFile);+ const child = spawn(process.execPath, [fakeFile, ...args], o);+ started.push({ args, pid: child.pid });+ return child;+};+const kill = async (pid: number) => {+ try {+ process.kill(pid);+ } catch {}+};++/** The studio, as the slot's calls reach it: one job at a time from `line`, answers kept in `answers`. */+function studio(line: { id: string; lease: string; user: string; maxTokens: number; system?: string; json?: boolean }[]) {+ const answers: { id: string; body: Record<string, unknown> }[] = [];+ const claims: Record<string, unknown>[] = [];+ const call = async (p: string, init: RequestInit = {}) => {+ const body = JSON.parse(String(init.body ?? "{}")) as Record<string, unknown>;+ if (p === "/api/gpu/computer/text/claim") {+ claims.push(body);+ const job = line.shift();+ return job ? Response.json({ job: { system: "Be brief.", json: false, ...job } }) : new Response(null, { status: 204 });+ }+ const m = /^\/api\/gpu\/computer\/text\/([^/]+)$/.exec(p);+ if (m) {+ answers.push({ id: decodeURIComponent(m[1]), body });+ return Response.json({ ok: true });+ }+ return new Response(null, { status: 404 });+ };+ return { call, answers, claims };+}++const slots: InstanceType<typeof TextSlot>[] = [];+afterEach(async () => {+ for (const s of slots.splice(0)) await s.end();+});++function makeSlot(call: (p: string, init?: RequestInit) => Promise<Response>, o: { sha256?: string; clock?: { t: number } } = {}) {+ const slot = textSlotOf({ server: fakeFile, model: modelFile, sha256: o.sha256 ?? sha(MODEL), idleMin: 1 })!;+ const work = fs.mkdtempSync(path.join(dir, "work-"));+ const logs: string[] = [];+ const s = new TextSlot(slot, { call, log: (l: string) => logs.push(l), workDir: work, home: work, spawn: fakeSpawn, kill, env: { ...process.env, FUOBE_WORKER_TOKEN: "fuobe_wkr_secret" }, ...(o.clock && { now: () => o.clock!.t }) });+ slots.push(s);+ return { s, logs };+}++/** Tick until `done` says so (a second of the worker's loop is a few ms here). */+async function until(s: InstanceType<typeof TextSlot>, t: () => number, o: { may: boolean; room: "gpu" | "cpu" | null }, done: () => boolean, ms = 15_000) {+ const end = Date.now() + ms;+ while (!done()) {+ if (Date.now() > end) throw new Error("timed out");+ s.tick(t(), o);+ await new Promise((r) => setTimeout(r, 20));+ }+}++describe("the text slot's parts", () => {+ it("reads worker.json's textSlot with defaults, and says what is missing", () => {+ expect(textSlotOf(undefined)).toBeNull();+ expect(textSlotOf({ model: "m", sha256: "a".repeat(64) })).toEqual({ problem: expect.stringContaining("server") });+ expect(textSlotOf({ server: "s", model: "m", sha256: "nope" })).toEqual({ problem: expect.stringContaining("sha256") });+ expect(textSlotOf({ server: "s", model: "m", sha256: "a".repeat(64), context: 999_999, threads: 0 })).toMatchObject({ context: 65_536, threads: 1, idleMin: 10, gpuMinFreeMb: 8000, cpu: true });+ });++ it("starts llama-server on 127.0.0.1 with its key, all layers on the GPU or none, never port 8188", () => {+ const slot = textSlotOf({ server: "s", model: "m.gguf", sha256: "a".repeat(64) })!;+ const gpu = serverArgs(slot, { port: 31000, key: "k", device: "gpu" });+ expect(gpu).toEqual(expect.arrayContaining(["--host", "127.0.0.1", "--port", "31000", "--api-key", "k", "--jinja", "--no-webui", "--alias", TEXT_MODEL]));+ expect(gpu[gpu.indexOf("-ngl") + 1]).toBe("99");+ const cpu = serverArgs(slot, { port: 31000, key: "k", device: "cpu" });+ expect(cpu[cpu.indexOf("-ngl") + 1]).toBe("0");+ expect(gpu.join(" ")).not.toContain("8188");+ });++ it("asks with thinking off and the card's sampling, JSON when the job asks; a job that isn't one is dropped", () => {+ const b = chatBody({ id: "j", lease: "l", system: "S", user: "U", maxTokens: 300, json: true });+ expect(b).toMatchObject({ max_tokens: 300, temperature: 1, top_p: 0.95, chat_template_kwargs: { enable_thinking: false }, response_format: { type: "json_object" } });+ expect(b.messages).toEqual([{ role: "system", content: "S" }, { role: "user", content: "U" }]);+ expect(jobOf({ job: { id: "j", lease: "l", system: "", user: "U", maxTokens: 10 } })).toMatchObject({ id: "j", json: false });+ expect(jobOf({ job: { id: "j", lease: "l", system: "", user: "U", maxTokens: 99_999 } })).toBeNull();+ expect(jobOf({ job: { id: "j", lease: "", system: "", user: "U", maxTokens: 10 } })).toBeNull();+ expect(jobOf(null)).toBeNull();+ });++ it("reads its CUDA buffers from its log (host memory doesn't count)", () => {+ expect(cudaMbOf("x CUDA0 model buffer size = 3577.50 MiB\ny CUDA0 KV buffer size = 120.00 MiB\nz CUDA_Host model buffer size = 2400.00 MiB\nw CUDA0 compute buffer size = 300.25 MiB")).toBe(3998);+ expect(cudaMbOf("nothing")).toBe(0);+ });++ it("hashes the model once for each size and change time", async () => {+ let reads = 0;+ const hash = async (f: string) => {+ reads++;+ return sha(fs.readFileSync(f));+ };+ const cache = path.join(dir, "checks.json");+ expect(await fileMatches(modelFile, sha(MODEL), cache, hash)).toBe(true);+ expect(await fileMatches(modelFile, sha(MODEL).toUpperCase(), cache, hash)).toBe(true);+ expect(reads).toBe(1);+ expect(await fileMatches(modelFile, "b".repeat(64), cache, hash)).toBe(false);+ expect(await fileMatches(path.join(dir, "missing.gguf"), sha(MODEL), cache, hash)).toBe(false);+ });++ it("its server's memory is the worker's own: no pause for another program", () => {+ const reading = { usedMb: 5200, tempC: 50, apps: [{ pid: 777, name: "llama-server.exe", usedMb: null }] };+ const own = { running: false, mb: 0, pid: null, port: null, job: false };+ expect(othersOf(reading, own, 1024).busy).toBe(true);+ expect(othersOf(reading, { ...own, extraPids: [777], extraMb: 4200 }, 1024)).toMatchObject({ busy: false, othersMb: 1000 });+ const MB = 2 ** 20;+ const counter = (pid: number, mb: number) => [`"\\\\PC\\GPU Process Memory(pid_${pid}_luid_0x00000000_0x0000D1B5_phys_0)\\Dedicated Usage"`, `"${(mb * MB).toFixed(6)}"`];+ const rows = [counter(777, 4300), counter(900, 2000)];+ const counters = parseCounters(["", `"(PDH-CSV 4.0)",${rows.map((r) => r[0]).join(",")}`, `"11/04/2026 09:00:00.000",${rows.map((r) => r[1]).join(",")}`, ""].join("\r\n"));+ const listing = { listeners: [{ port: 31337, pid: 900 }], names: { "900": "python", "777": "llama-server" } };+ const s = splitMemory({ usedMb: 7000, counters, listing, own: { pid: 900, port: 31337, running: true, mb: 100, extraPids: [777], extraMb: 4200 }, ports: [8188, 8199], baselineMb: 600 });+ expect(s).toMatchObject({ ownMb: 6300, othersMb: 100 });+ });+});++describe("the text slot", () => {+ it("answers a job on the GPU with its lease: thinking off, its own key, no worker token in its server's environment", async () => {+ const site = studio([{ id: "hlp_1", lease: "L1", user: "Write a chorus", maxTokens: 200 }]);+ const { s } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "gpu" }, () => site.answers.length === 1);+ const a = site.answers[0];+ expect(a.id).toBe("hlp_1");+ expect(a.body.lease).toBe("L1");+ const said = JSON.parse(String(a.body.text));+ expect(said).toMatchObject({ ngl: "99", cuda: null, token: null, thinking: false, user: "Write a chorus", max: 200 });+ expect(said.host).toMatch(/^127\.0\.0\.1:\d+$/);+ expect(site.claims[0]).toMatchObject({ model: TEXT_MODEL, device: "gpu" });+ expect(s.own().pids).toHaveLength(1);+ expect(s.own().mb).toBe(3698);+ });++ it("a GPU that isn't free: the next start runs on the CPU only, and an idle server stops", async () => {+ const clock = { t: Date.now() };+ const site = studio([+ { id: "hlp_a", lease: "La", user: "one", maxTokens: 50 },+ { id: "hlp_b", lease: "Lb", user: "two", maxTokens: 50 },+ ]);+ const { s, logs } = makeSlot(site.call, { clock });+ await until(s, () => clock.t, { may: true, room: "gpu" }, () => site.answers.length === 1);+ // The GPU is taken now: its server stops between jobs and starts again on the CPU.+ await until(s, () => clock.t, { may: true, room: "cpu" }, () => site.answers.length === 2);+ expect(JSON.parse(String(site.answers[1].body.text))).toMatchObject({ ngl: "0", cuda: "-1" });+ expect(s.own()).toEqual({ pids: [], mb: 0 });+ expect(started.slice(-2).map((x) => x.args[x.args.indexOf("-ngl") + 1])).toEqual(["99", "0"]);+ // Ten idle minutes: it stops.+ await until(s, () => clock.t, { may: true, room: "cpu" }, () => !s.busy);+ clock.t += 61_000;+ s.tick(clock.t, { may: true, room: "cpu" });+ expect(s.server).toBeNull();+ expect(logs.join("\n")).toContain("frees its memory");+ });++ it("paused: no claim, and its server stops; a model that doesn't match its SHA-256 keeps the slot off", async () => {+ const site = studio([{ id: "hlp_p", lease: "Lp", user: "x", maxTokens: 50 }]);+ const { s } = makeSlot(site.call);+ for (let i = 0; i < 5; i++) {+ s.tick(Date.now(), { may: false, room: "gpu" });+ await new Promise((r) => setTimeout(r, 20));+ }+ expect(site.claims).toHaveLength(0);+ const bad = studio([{ id: "hlp_q", lease: "Lq", user: "x", maxTokens: 50 }]);+ const { s: off, logs } = makeSlot(bad.call, { sha256: "c".repeat(64) });+ for (let i = 0; i < 30 && off.ok === null; i++) {+ off.tick(Date.now(), { may: true, room: "gpu" });+ await new Promise((r) => setTimeout(r, 20));+ }+ off.tick(Date.now(), { may: true, room: "gpu" });+ expect(off.ok).toBe(false);+ expect(bad.claims).toHaveLength(0);+ expect(logs.join("\n")).toContain("SHA-256 doesn't match");+ });+});