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: chat turns, words as they come, and ending early
Adarsh71785d1ec008
diff --git a/bin/lib/worker/text.mjs b/bin/lib/worker/text.mjsindex 4ac68412..1ebd8ed9 100644--- a/bin/lib/worker/text.mjs+++ b/bin/lib/worker/text.mjs@@ -3,24 +3,31 @@// 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. Any GGUF chat model works;-// with `mmproj` (its vision projector) it also takes jobs with pictures.+// with `mmproj` (its vision projector) it also takes jobs with pictures. It takes chats too (their turns as real turns),+// and for a job that asks it sends the words so far as they come; the studio's answer to them can tell it to stop.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 };+export const TEXT_DEFAULTS = { context: 16_384, idleMin: 10, gpuMinFreeMb: 8000, cpu: true, threads: 8, startMs: 180_000, answerMs: 120_000, claimWaitMs: 20_000 };++/** A job that sends its words as they come: how often it sends them, how often it says it is alive with none, its whole time. */+export const STREAM_TIMES = { partialMs: 250, aliveMs: 2000, maxMs: 300_000 };/** The graphics memory a GPU server is counted with before its log says (weights, cache and buffers of a small model). */export const TEXT_GPU_GUESS_MB = 6500;/**- * How each model family is asked: its chat template's switches (thinking off where the template has one) and the- * sampling its card gives. worker.json's `textSlot.chat` ({ kwargs, sampling }) overrides them.+ * How each model family is asked: its chat template's switches (thinking off where the template has one), the sampling+ * its card gives, and the context its server starts with at least (a chat's turns need room). worker.json's+ * `textSlot.chat` ({ kwargs, sampling, context }) overrides them.*/export const FAMILIES = [{ match: /nemotron/i, kwargs: { enable_thinking: false }, sampling: { temperature: 1.0, top_p: 0.95 } },+ // Gemma 4 E2B keeps most of its layers' cache to a short window, so a long context costs little memory.+ { match: /gemma-?4-?e2b/i, kwargs: { enable_thinking: false }, sampling: { temperature: 1.0, top_p: 0.95, top_k: 64 }, context: 32_768 },{ match: /gemma/i, kwargs: { enable_thinking: false }, sampling: { temperature: 1.0, top_p: 0.95, top_k: 64 } },{ match: /qwen3-?vl/i, kwargs: null, sampling: { temperature: 0.7, top_p: 0.8, top_k: 20, presence_penalty: 1.5 } },];@@ -31,9 +38,16 @@ export function familyOf(slot) {const name = slot.name ?? path.basename(slot.model ?? "");const fam = FAMILIES.find((x) => x.match.test(name)) ?? PLAIN;const chat = slot.chat && typeof slot.chat === "object" ? slot.chat : {};- return { kwargs: chat.kwargs === undefined ? fam.kwargs : chat.kwargs, sampling: { ...fam.sampling, ...(chat.sampling ?? {}) } };+ const context = Number.isInteger(chat.context) ? chat.context : (fam.context ?? null);+ return { kwargs: chat.kwargs === undefined ? fam.kwargs : chat.kwargs, sampling: { ...fam.sampling, ...(chat.sampling ?? {}) }, context };}+/**+ * The context its server starts with: worker.json's (or the default), raised to the family's where that is larger, so a+ * worker.json written when the default was smaller still has room for a chat. At most 131072.+ */+export const contextOf = (slot) => Math.min(131_072, Math.max(slot.context ?? TEXT_DEFAULTS.context, familyOf(slot).context ?? 0));+/** The model name the studio hears with each claim: textSlot.name, else the file's name without .gguf. */export const modelName = (slot) => String(slot.name ?? path.basename(slot.model ?? "").replace(/\.gguf$/i, "")).toLowerCase().slice(0, 120);@@ -127,7 +141,7 @@ export function serverArgs(slot, o) {"--host", "127.0.0.1","--port", String(o.port),"--api-key", o.key,- "-c", String(slot.context),+ "-c", String(contextOf(slot)),"-ngl", o.device === "gpu" ? "99" : "0","-np", "1","-t", String(slot.threads),@@ -162,25 +176,69 @@ export function jobOf(body) {}images = j.images;}- return { id: j.id, lease: j.lease, system: j.system, user: j.user, maxTokens, json: j.json === true, images };+ // A chat's turns: the person's and the model's, the newest the person's.+ let messages = null;+ if (j.messages !== undefined) {+ if (!Array.isArray(j.messages) || !j.messages.length || j.messages.length > CHAT_LIMITS.turns) return null;+ let chars = 0;+ for (const m of j.messages) {+ if (!m || (m.role !== "user" && m.role !== "assistant") || typeof m.content !== "string") return null;+ chars += m.content.length;+ }+ if (chars > CHAT_LIMITS.chars || j.messages.at(-1).role !== "user") return null;+ messages = j.messages.map((m) => ({ role: m.role, content: m.content }));+ }+ const sampling = {};+ for (const [k, [lo, hi]] of Object.entries(SAMPLING_BOUNDS)) {+ const v = j.sampling?.[k];+ if (typeof v === "number" && Number.isFinite(v)) sampling[k] = Math.min(hi, Math.max(lo, v));+ }+ return { id: j.id, lease: j.lease, system: j.system, user: j.user, maxTokens, json: j.json === true, images, messages, sampling, stream: j.stream === true };}-/** The request body for one job: the family's template switches and sampling, the pictures before the words. */+/** What a chat may carry (the studio sends at most 24,000 characters of turns). */+const CHAT_LIMITS = { turns: 200, chars: 32_000 };+/** The sampling a job may ask for, each inside these bounds. */+const SAMPLING_BOUNDS = { temperature: [0, 2], top_p: [0.05, 1] };++/**+ * The request body for one job: the family's template switches and sampling (the job's own over them), a chat's turns+ * as real turns, the pictures before the words of the newest turn.+ */export function chatBody(job, slot = {}) {const fam = familyOf(slot);const pictures = job.images ?? [];- const content = pictures.length ? [...pictures.map((b) => ({ type: "image_url", image_url: { url: `data:image/jpeg;base64,${b}` } })), { type: "text", text: job.user }] : job.user;+ const turns = job.messages?.length ? job.messages : [{ role: "user", content: job.user }];+ const last = turns.length - 1;+ const withPictures = (text) => (pictures.length ? [...pictures.map((b) => ({ type: "image_url", image_url: { url: `data:image/jpeg;base64,${b}` } })), { type: "text", text }] : text);return {model: modelName(slot),- messages: [...(job.system ? [{ role: "system", content: job.system }] : []), { role: "user", content }],+ messages: [...(job.system ? [{ role: "system", content: job.system }] : []), ...turns.map((m, n) => ({ role: m.role, content: n === last ? withPictures(m.content) : m.content }))],max_tokens: job.maxTokens,...fam.sampling,- stream: false,+ ...job.sampling,+ stream: !!job.stream,...(fam.kwargs && { chat_template_kwargs: fam.kwargs }),...(job.json && { response_format: { type: "json_object" } }),};}+/** The words in one server-sent event line of a streamed answer ("" for anything else). */+export function streamedWords(line) {+ if (!line.startsWith("data:")) return "";+ const data = line.slice(5).trim();+ if (!data || data === "[DONE]") return "";+ try {+ const c = JSON.parse(data)?.choices?.[0]?.delta?.content;+ return typeof c === "string" ? c : "";+ } catch {+ return "";+ }+}++/** The worker's stop for a job whose caller went: its answer isn't sent. */+class Stopped extends Error {}+export class TextSlot {/*** @param {object} slot textSlotOf's answer@@ -265,7 +323,7 @@ export class TextSlot {}async claimAndRun(device) {- const res = await this.d.call("/api/gpu/computer/text/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: modelName(this.slot), device, vision: !!this.slot.mmproj, wait: this.slot.claimWaitMs }), signal: this.ending.signal });+ const res = await this.d.call("/api/gpu/computer/text/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: modelName(this.slot), device, vision: !!this.slot.mmproj, chat: true, wait: this.slot.claimWaitMs }), signal: this.ending.signal });if (res.status === 204 || !res.ok) {await res.body?.cancel().catch(() => {});return false;@@ -278,6 +336,9 @@ export class TextSlot {await this.ensure(device);answer = { text: await this.complete(job) };} catch (e) {+ this.lastJobAt = this.now();+ // The person went: the studio ended the job, so there is nothing to send.+ if (e instanceof Stopped) return true;answer = { error: String(e.message ?? e).slice(0, 200) };this.log(`Text job ${job.id} has no answer: ${answer.error}`);}@@ -292,6 +353,7 @@ export class TextSlot {const s = this.server;if (!s) throw new Error("llama-server isn't running");const f = this.d.fetch ?? fetch;+ if (job.stream) return this.completeStreaming(job, s, f);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}` },@@ -305,6 +367,88 @@ export class TextSlot {return text;}+ /**+ * The answer's words as they come: the words so far go to the studio every quarter second while they grow (and every+ * 2 s while none come, so it knows the job is alive). When the studio answers that the job isn't this slot's any more,+ * the request ends, and llama-server stops writing.+ */+ async completeStreaming(job, s, f) {+ const t = STREAM_TIMES;+ const ctl = new AbortController();+ let stopped = false;+ let why = null;+ const end = (reason) => {+ why ??= reason;+ ctl.abort();+ };+ const cap = setTimeout(() => end("the answer took too long"), t.maxMs);+ // No words for answerMs (the prompt's own reading included): it ends.+ let idle = setTimeout(() => end("llama-server went quiet"), this.slot.answerMs);+ let text = "";+ let sent = "";+ let sentAt = 0;+ let posting = null;+ const post = () => {+ if (posting || stopped || (text === sent && this.now() - sentAt < t.aliveMs)) return;+ const words = text;+ sentAt = this.now();+ posting = this.d+ .call(`/api/gpu/computer/text/${encodeURIComponent(job.id)}/partial`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: job.lease, text: words }) })+ .then(async (res) => {+ // Only the studio's own word stops it: a studio without this call (404) or a busy moment changes nothing.+ const b = res.status === 409 ? await res.json().catch(() => null) : (await res.body?.cancel().catch(() => {}), null);+ if (b?.stop === true) {+ stopped = true;+ end("stopped");+ } else if (res.ok) sent = words;+ })+ .catch(() => {})+ .finally(() => (posting = null));+ };+ const tick = setInterval(post, t.partialMs);+ const ending = () => end("the worker is ending");+ this.ending.signal.addEventListener("abort", ending, { once: true });+ try {+ 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, this.slot)),+ signal: ctl.signal,+ });+ if (!r.ok) {+ await r.body?.cancel().catch(() => {});+ throw new Error(`llama-server answered ${r.status}`);+ }+ const reader = r.body.getReader();+ const decoder = new TextDecoder();+ let buf = "";+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ clearTimeout(idle);+ idle = setTimeout(() => end("llama-server went quiet"), this.slot.answerMs);+ buf += decoder.decode(value, { stream: true });+ const lines = buf.split("\n");+ buf = lines.pop();+ for (const line of lines) text += streamedWords(line.trim());+ }+ text += streamedWords((buf + decoder.decode()).trim());+ } catch (e) {+ if (stopped) throw new Stopped("stopped");+ if (why) throw new Error(why);+ throw e;+ } finally {+ this.ending.signal.removeEventListener("abort", ending);+ clearInterval(tick);+ clearTimeout(cap);+ clearTimeout(idle);+ await posting;+ }+ if (stopped) throw new Stopped("stopped");+ if (!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;diff --git a/src/app/api/gpu/computer/text/[id]/partial/route.ts b/src/app/api/gpu/computer/text/[id]/partial/route.tsnew file mode 100644index 00000000..be7a3abc--- /dev/null+++ b/src/app/api/gpu/computer/text/[id]/partial/route.ts@@ -0,0 +1,30 @@+import { connection } from "next/server";+import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";+import { HELPER_LIMITS, partialHelperJob } 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 words so far for its text job (`{ lease, text }`), a few times a second while it writes.+ * 409 with `stop: true`: the job isn't its own any more (the person went, or it ended), so the slot stops writing.+ */+export async function POST(request: Request, ctx: RouteContext<"/api/gpu/computer/text/[id]/partial">) {+ 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-partial", 600);+ if (limited) return limited;+ const { id } = await ctx.params;+ const raw = await request.text().catch(() => "");+ // The words in JSON, with room for escapes: anything bigger isn't a partial answer.+ if (raw.length > HELPER_LIMITS.textBytes * 2 + 1024) return answer(413, { error: "Too long." });+ let body: { lease?: unknown; text?: unknown } = {};+ try {+ body = (JSON.parse(raw) ?? {}) as typeof body;+ } catch {}+ const r = partialHelperJob(worker, id, body);+ if (r === "bad") return answer(400, { error: "Send { lease, text }." });+ return r === "ok" ? answer(200, { ok: true }) : answer(409, { error: "That text job isn't this worker's any more.", stop: true });+}diff --git a/src/app/api/gpu/computer/text/claim/route.ts b/src/app/api/gpu/computer/text/claim/route.tsindex b79072c8..5fc14bde 100644--- a/src/app/api/gpu/computer/text/claim/route.ts+++ b/src/app/api/gpu/computer/text/claim/route.ts@@ -6,7 +6,8 @@ const no = (status: number, error: string) => Response.json({ error }, { status,/*** 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.+ * (or `wait` ms, less): the job, or 204. A slot that says `chat: true` also takes chats (their turns, and it sends+ * the words so far to text/:id/partial).*/export async function POST(request: Request) {await connection();@@ -16,13 +17,13 @@ export async function POST(request: 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; vision?: unknown; wait?: unknown };+ const body = ((await request.json().catch(() => null)) ?? {}) as { model?: unknown; device?: unknown; vision?: unknown; chat?: 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(body.vision === true) ? claimHelperJob(worker, body, Date.now(), first) : null;+ const job = first || helperWaiting(body.vision === true, body.chat === true) ? 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/server/db.ts b/src/server/db.tsindex c1e66f8d..1dd6237f 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1187,7 +1187,17 @@ function open(): Database.Database {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);- for (const [table, column, type] of [["helper_jobs", "images_json", "TEXT"], ["helper_slots", "vision", "INTEGER NOT NULL DEFAULT 0"]]) {+ for (const [table, column, type] of [+ ["helper_jobs", "images_json", "TEXT"],+ ["helper_slots", "vision", "INTEGER NOT NULL DEFAULT 0"],+ // Chat: its turns, its own sampling, the words so far as its slot sends them, and the slots that take chats.+ ["helper_jobs", "messages_json", "TEXT"],+ ["helper_jobs", "sampling_json", "TEXT"],+ ["helper_jobs", "stream", "INTEGER NOT NULL DEFAULT 0"],+ ["helper_jobs", "partial", "TEXT"],+ ["helper_jobs", "partial_at", "INTEGER"],+ ["helper_slots", "chat", "INTEGER NOT NULL DEFAULT 0"],+ ]) {if (!(db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column)) addColumn(db, `ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}// Skills: the runs that wait across studios. A data folder that ran claude/fuobe-parity-4's earlier build of this@@ -1317,7 +1327,12 @@ const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (done_at INTEGER,text TEXT,error TEXT,- images_json TEXT+ images_json TEXT,+ messages_json TEXT,+ sampling_json TEXT,+ stream INTEGER NOT NULL DEFAULT 0,+ partial TEXT,+ partial_at INTEGER);CREATE INDEX IF NOT EXISTS helper_jobs_line ON helper_jobs(state, created_at);CREATE TABLE IF NOT EXISTS helper_slots (@@ -1325,7 +1340,8 @@ const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (seen_at INTEGER NOT NULL,model TEXT,device TEXT,- vision INTEGER NOT NULL DEFAULT 0+ vision INTEGER NOT NULL DEFAULT 0,+ chat INTEGER NOT NULL DEFAULT 0);`;export function db(): Database.Database {diff --git a/src/server/text-helper.ts b/src/server/text-helper.tsindex 44cdf5a3..66d4fbff 100644--- a/src/server/text-helper.ts+++ b/src/server/text-helper.ts@@ -12,10 +12,11 @@ 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.+ * GPU job; the caller waits for the answer, and the row is deleted once read. A chat sends its turns, and a slot that+ * takes chats sends the words so far as they come.*/-export type HelperTask = "lyrics" | "enhance" | "soul" | "write" | "translate" | "describe" | "restore" | "recipe";+export type HelperTask = "lyrics" | "enhance" | "soul" | "write" | "translate" | "describe" | "restore" | "recipe" | "chat";/** The most tokens a task may write. */export const HELPER_TASKS: Record<HelperTask, { maxTokens: number }> = {@@ -27,6 +28,7 @@ export const HELPER_TASKS: Record<HelperTask, { maxTokens: number }> = {describe: { maxTokens: 200 },restore: { maxTokens: 500 },recipe: { maxTokens: 1500 },+ chat: { maxTokens: 900 },};export const isHelperTask = (v: unknown): v is HelperTask => typeof v === "string" && Object.hasOwn(HELPER_TASKS, v);@@ -38,8 +40,10 @@ export const HELPER_TIMES = {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. */+ /** A claimed job with no answer (for a job that streams: no new words) after this fails. */runMs: 90_000,+ /** A job that streams ends after this, however its words come. */+ streamMaxMs: 300_000,/** Rows older than this are deleted. */keepMs: 10 * 60_000,pollMs: 200,@@ -54,10 +58,52 @@ export const HELPER_LIMITS = {waitingEach: 2,guest: { perMinute: 4, perHour: 20 },account: { perMinute: 8, perHour: 60 },+ /** Chat counts on its own key, apart from the studio's tasks. */+ chat: { perMinute: 12, perHour: 300 },+ /** A chat's turns: how many, and their words together (the caller trims older turns itself). */+ chatTurns: 200,+ chatChars: 24_000,/** Pictures a job may carry: how many, how big each may come in, and as the small JPEG it is sent as. */pictures: { count: 4, inputBytes: 20 * 2 ** 20, longEdge: 1024, outputBytes: 512 * 1024 },};+/** One turn of a chat. */+export interface HelperMessage {+ role: "user" | "assistant";+ content: string;+}++/** The sampling a job may ask for, each inside these bounds. */+export const HELPER_SAMPLING = { temperature: [0, 2], top_p: [0.05, 1] } as const;++export type HelperSampling = { temperature?: number; top_p?: number };++/** A job's own sampling, inside safe bounds; null when it asks for none (the model family's then). */+export function helperSampling(s: HelperSampling | undefined | null): HelperSampling | null {+ if (!s || typeof s !== "object") return null;+ const out: HelperSampling = {};+ for (const k of ["temperature", "top_p"] as const) {+ const v = s[k];+ if (typeof v === "number" && Number.isFinite(v)) out[k] = Math.min(HELPER_SAMPLING[k][1], Math.max(HELPER_SAMPLING[k][0], v));+ }+ return Object.keys(out).length ? out : null;+}++/** Why these chat turns can't be sent, or null: user and assistant turns, the newest the person's, within the limits. */+export function helperMessagesProblem(messages: unknown): string | null {+ if (!Array.isArray(messages) || !messages.length) return "no turns";+ if (messages.length > HELPER_LIMITS.chatTurns) return "too many turns";+ let chars = 0;+ for (const m of messages as Partial<HelperMessage>[]) {+ if (!m || typeof m !== "object" || (m.role !== "user" && m.role !== "assistant") || typeof m.content !== "string") return "a turn isn't a user or assistant turn with words";+ chars += m.content.length;+ }+ if (chars > HELPER_LIMITS.chatChars) return "too long";+ const last = messages[messages.length - 1] as HelperMessage;+ if (last.role !== "user" || !last.content.trim()) return "the newest turn isn't the person's";+ return null;+}+/** Whose job: "owner", "acct:<id>", or "guest:<address key>". */export type HelperWho = string;@@ -76,7 +122,7 @@ interface JobRow {user: string;max_tokens: number;json: number;- state: "waiting" | "running" | "done" | "failed";+ state: "waiting" | "running" | "done" | "failed" | "canceled";worker_id: string | null;lease: string | null;created_at: number;@@ -85,6 +131,11 @@ interface JobRow {text: string | null;error: string | null;images_json: string | null;+ messages_json: string | null;+ sampling_json: string | null;+ stream: number | null;+ partial: string | null;+ partial_at: number | null;}/** A job as a text slot gets it. */@@ -96,8 +147,14 @@ export interface HelperJob {user: string;maxTokens: number;json: boolean;- /** Small JPEGs, as base64, for a slot whose model sees pictures. */+ /** Small JPEGs, as base64, for a slot whose model sees pictures (a chat's go with its newest turn). */images?: string[];+ /** A chat's turns, sent as they are after the system words (only to a slot that takes chats). */+ messages?: HelperMessage[];+ /** The job's own sampling, over the model family's. */+ sampling?: HelperSampling;+ /** The slot sends the words so far as they come (POST /api/gpu/computer/text/:id/partial). */+ stream?: true;}const json = <T,>(s: string | null, fallback: T): T => {@@ -122,16 +179,19 @@ export function textEligible(w: WorkerRow, now = Date.now()): boolean {);}-/** A text slot asked for a job in the last moments, from a worker that may take one (`vision`: one whose model sees pictures). */-export function helperLive(now = Date.now(), o: { vision?: boolean } = {}): boolean {+/**+ * A text slot asked for a job in the last moments, from a worker that may take one (`vision`: one whose model sees+ * pictures; `chat`: one that takes chats).+ */+export function helperLive(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): boolean {const rows = db()- .prepare(`SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?${o.vision ? " AND s.vision = 1" : ""}`)+ .prepare(`SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?${o.vision ? " AND s.vision = 1" : ""}${o.chat ? " AND s.chat = 1" : ""}`).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 an account's call only while hosted runs are on (a guest's never: sign up first). */-export function freeHelperOn(now = Date.now(), o: { vision?: boolean } = {}): boolean {+export function freeHelperOn(now = Date.now(), o: { vision?: boolean; chat?: boolean } = {}): boolean {const t = tenant();return (!t || (t.kind === "account" && hostedRunsOn())) && helperLive(now, o);}@@ -176,39 +236,86 @@ export function sweepHelper(now = Date.now()): void {db().prepare("DELETE FROM helper_jobs WHERE created_at < ?").run(now - HELPER_TIMES.keepMs);}+/** The jobs a slot may take: one with pictures only where its model sees them, a chat only where the slot takes chats. */+const takes = (vision: boolean, chat: boolean) => `${vision ? "" : " AND images_json IS NULL"}${chat ? "" : " AND messages_json IS NULL"}`;++/** The line's order: people's jobs first, then the owner's, oldest first. */+const OWNER_LAST = "CASE WHEN who = 'owner' THEN 1 ELSE 0 END";+/*** 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.+ * slot as live either way. `chat`: the slot takes chats (turns, and words sent as they come); an older worker never+ * says so, and gets the same jobs as before.*/-export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: unknown; vision?: unknown } = {}, now = Date.now(), note = true): HelperJob | null {+export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: unknown; vision?: unknown; chat?: 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;const vision = slot.vision === true ? 1 : 0;+ const chat = slot.chat === true ? 1 : 0;if (note) {d.prepare(- "INSERT INTO helper_slots (worker_id, seen_at, model, device, vision) VALUES (?, ?, ?, ?, ?) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device, vision = excluded.vision",- ).run(w.id, now, model, device, vision);+ "INSERT INTO helper_slots (worker_id, seen_at, model, device, vision, chat) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(worker_id) DO UPDATE SET seen_at = excluded.seen_at, model = excluded.model, device = excluded.device, vision = excluded.vision, chat = excluded.chat",+ ).run(w.id, now, model, device, vision, chat);}const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow | undefined;if (!fresh || !textEligible(fresh, now)) return null;- // A job with pictures goes only to a slot whose model sees them.- const row = d.prepare(`SELECT * FROM helper_jobs WHERE state = 'waiting'${vision ? "" : " AND images_json IS NULL"} ORDER BY CASE WHEN who = 'owner' THEN 1 ELSE 0 END, created_at LIMIT 1`).get() as JobRow | undefined;+ const row = d.prepare(`SELECT * FROM helper_jobs WHERE state = 'waiting'${takes(!!vision, !!chat)} ORDER BY ${OWNER_LAST}, created_at, id 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);const images = json<string[] | null>(row.images_json, null);- return { id: row.id, lease, task: row.task, system: row.system, user: row.user, maxTokens: row.max_tokens, json: !!row.json, ...(images?.length && { images }) };+ const messages = json<HelperMessage[] | null>(row.messages_json, null);+ const sampling = json<HelperSampling | null>(row.sampling_json, null);+ return {+ id: row.id,+ lease,+ task: row.task,+ system: row.system,+ user: row.user,+ maxTokens: row.max_tokens,+ json: !!row.json,+ ...(images?.length && { images }),+ ...(messages?.length && { messages }),+ ...(sampling && { sampling }),+ ...(row.stream ? { stream: true as const } : {}),+ };}).immediate();}-/** Is any text job waiting (a quick read before a claim)? */-export const helperWaiting = (vision = false): boolean => !!db().prepare(`SELECT 1 FROM helper_jobs WHERE state = 'waiting'${vision ? "" : " AND images_json IS NULL"} LIMIT 1`).get();+/** Is any text job waiting that this slot may take (a quick read before a claim)? */+export const helperWaiting = (vision = false, chat = false): boolean => !!db().prepare(`SELECT 1 FROM helper_jobs WHERE state = 'waiting'${takes(vision, chat)} LIMIT 1`).get();++/** Where a waiting job stands in the line: 1 is next. Null once it isn't waiting. */+export function helperPosition(id: string): number | null {+ const d = db();+ const row = d.prepare(`SELECT ${OWNER_LAST} AS rank, created_at, state FROM helper_jobs WHERE id = ?`).get(id) as { rank: number; created_at: number; state: string } | undefined;+ if (!row || row.state !== "waiting") return null;+ const ahead = d+ .prepare(`SELECT COUNT(*) AS n FROM helper_jobs WHERE state = 'waiting' AND (${OWNER_LAST} < ? OR (${OWNER_LAST} = ? AND (created_at < ? OR (created_at = ? AND id < ?))))`)+ .get(row.rank, row.rank, row.created_at, row.created_at, id) as { n: number };+ return ahead.n + 1;+}/** 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();+/** Words so far: a reasoning block that hasn't ended yet goes too. */+const tidyPartial = (s: string) => tidyHelperText(s.replace(/<think>(?![\s\S]*<\/think>)[\s\S]*$/, ""));++/**+ * A text slot's words so far for its job, with the lease its claim gave. "ok": kept. "stop": not its job any more (the+ * caller went, or the job ended), so the slot stops writing. "bad": not words it may send.+ */+export function partialHelperJob(w: WorkerRow, id: string, body: { lease?: unknown; text?: unknown }, now = Date.now()): "ok" | "stop" | "bad" {+ if (typeof body.lease !== "string" || typeof body.text !== "string" || Buffer.byteLength(body.text) > HELPER_LIMITS.textBytes) return "bad";+ const r = db()+ .prepare("UPDATE helper_jobs SET partial = ?, partial_at = ? WHERE id = ? AND worker_id = ? AND lease = ? AND state = 'running'")+ .run(tidyPartial(body.text), now, id, w.id, body.lease);+ return r.changes === 1 ? "ok" : "stop";+}+/** 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;@@ -230,16 +337,29 @@ const rateOf = (who: HelperWho) => (who.startsWith("acct:") ? HELPER_LIMITS.accoexport interface AskHelper {task: HelperTask;system: string;- user: string;+ /** The words to answer (a chat sends `messages` instead). */+ user?: string;+ /**+ * A chat's turns, oldest first, the newest the person's: sent as real turns after `system`, only to a slot that takes+ * chats. At most HELPER_LIMITS.chatChars of words in all (the caller trims older turns itself).+ */+ messages?: HelperMessage[];+ /** The job's own sampling, kept inside HELPER_SAMPLING; the model family's when unset. */+ sampling?: HelperSampling;json?: boolean;- /** Pictures for a model that sees them (only a slot that does takes the job). */+ /** Pictures for a model that sees them (only a slot that does takes the job). A chat takes one, with its newest turn. */images?: { data: Buffer; contentType: string }[];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;+ /** The caller went: the job ends, and a slot writing it stops at its next words. */signal?: AbortSignal;+ /** The words so far, each time more come (only from a slot that sends them; the whole answer still comes back). */+ onText?: (soFar: string) => void;+ /** Where the job stands in the line while it waits (1 is next), each time that changes. */+ onQueue?: (position: number) => void;now?: () => number;sleep?: (ms: number) => Promise<void>;}@@ -251,22 +371,33 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {const who = o.who ?? helperWho();// A guest signs up first: no moderation call, no job.if (who.startsWith("guest:")) return { error: "sign-in" };+ // A chat's turns: checked here, before anything is counted or queued.+ const chat = o.messages !== undefined;+ if (chat) {+ const problem = helperMessagesProblem(o.messages);+ if (problem) return { error: "failed", message: `The conversation can't be sent: ${problem}.` };+ if ((o.images?.length ?? 0) > 1) return { error: "failed", message: "A chat turn takes one picture." };+ }const d = db();sweepHelper(now());const vision = !!o.images?.length;- if (!helperLive(now(), { vision })) return { error: "busy" };+ if (!helperLive(now(), { vision, chat })) return { error: "busy" };const pictures = vision ? await helperPictures(o.images!) : null;if (vision && !pictures) return { error: "failed" };if (who !== "owner" && o.counted !== false) {- 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) {+ // Chat has its own key, so a long talk never uses up the studio's rewrites (and the other way round).+ const [name, r] = o.task === "chat" ? ["helper-chat", HELPER_LIMITS.chat] : ["helper", rateOf(who)];+ for (const [key, limit, ms] of [[`${name}:${who}:m`, r.perMinute, 60_000], [`${name}:${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);+ // A chat's newest turn is its words for moderation (the turns before it were checked when they were sent).+ const user = (chat ? o.messages![o.messages!.length - 1].content : (o.user ?? "")).slice(0, HELPER_LIMITS.userChars);+ const sampling = helperSampling(o.sampling);+ const stream = chat || !!o.onText;const id = `hlp_${crypto.randomBytes(9).toString("base64url")}`;const account = who.startsWith("acct:") ? who.slice(5) : null;let checkOutputs = false;@@ -284,7 +415,9 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {checkOutputs = a.checkOutputs !== false;}const created = now();- d.prepare("INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, json, state, created_at, images_json) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?, ?)").run(+ d.prepare(+ "INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, json, state, created_at, images_json, messages_json, sampling_json, stream) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?, ?, ?, ?, ?)",+ ).run(id,who,o.task,@@ -294,15 +427,25 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {o.json ? 1 : 0,created,pictures ? JSON.stringify(pictures) : null,+ chat ? JSON.stringify(o.messages!.map((m) => ({ role: m.role, content: m.content }))) : null,+ sampling ? JSON.stringify(sampling) : null,+ stream ? 1 : 0,);const waitMs = o.waitMs ?? 45_000;- const drop = () => d.prepare("DELETE FROM helper_jobs WHERE id = ?").run(id);+ // A caller's hook never stops the wait.+ const tell = <T,>(f: ((v: T) => void) | undefined, v: T) => {+ try {+ f?.(v);+ } catch {}+ };+ let shown = "";+ let place = 0;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 || row.state === "failed" || row.state === "canceled") return { error: row?.error === "busy" ? "busy" : "failed" };if (row.state === "done" && row.text) {if (checkOutputs) {const bytes = Buffer.from(row.text);@@ -311,15 +454,28 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {}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 === "waiting") {+ if (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 (o.onQueue) {+ const p = helperPosition(id);+ if (p && p !== place) tell(o.onQueue, (place = p));+ }+ }+ if (row.state === "running") {+ if (row.partial && row.partial !== shown) tell(o.onText, (shown = row.partial));+ // A slot that sends its words has the time again with each; an older one has it from its claim.+ const claimed = row.claimed_at ?? t;+ if (t - Math.max(claimed, row.partial_at ?? 0) >= HELPER_TIMES.runMs || t - claimed >= HELPER_TIMES.streamMaxMs) return { error: "failed" };}- if (row.state === "running" && t - (row.claimed_at ?? t) >= HELPER_TIMES.runMs) return { error: "failed" };await sleep(HELPER_TIMES.pollMs);}} finally {- drop();+ // A job its slot is still writing is marked canceled, and the slot stops at its next words (the sweep deletes the+ // row later). Any other row goes now.+ if (d.prepare("UPDATE helper_jobs SET state = 'canceled' WHERE id = ? AND state = 'running'").run(id).changes === 0) d.prepare("DELETE FROM helper_jobs WHERE id = ?").run(id);}}diff --git a/tests/text-helper.test.ts b/tests/text-helper.test.tsindex 74dd920b..8ebee230 100644--- a/tests/text-helper.test.ts+++ b/tests/text-helper.test.ts@@ -32,6 +32,7 @@ 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 partialRoute = await import("@/app/api/gpu/computer/text/[id]/partial/route");const { proxy } = await import("@/proxy");const { writeRestorePrompt } = await import("@/server/restore");@@ -375,3 +376,213 @@ describe("the AI helper's order and the lyrics route", () => {expect(off.status).toBe(403);});});++describe("chat: turns, words as they come, ending early", () => {+ const turns = [+ { role: "user" as const, content: "Hi, I'm Ria." },+ { role: "assistant" as const, content: "Hello Ria!" },+ { role: "user" as const, content: "What's my name?" },+ ];+ const auth_ = (w: W) => ({ authorization: `Bearer ${w.token}` });+ /** A worker whose slot takes chats, noted live. */+ const chatWorker = () => {+ const w = addWorker();+ helper.claimHelperJob(workerRow(w), { chat: true, vision: true });+ return w;+ };+ const nextChat = async (w: W, ms = 5000) => {+ const end = Date.now() + ms;+ for (;;) {+ const job = helper.claimHelperJob(workerRow(w), { chat: true, vision: true });+ if (job || Date.now() > end) return job;+ await new Promise((r) => setTimeout(r, 25));+ }+ };+ const row = (id: string) => db().prepare("SELECT state, partial FROM helper_jobs WHERE id = ?").get(id) as { state: string; partial: string | null } | undefined;++ it("checks the turns: user and assistant only, the newest the person's, at most 24,000 characters; nothing is queued for a bad one", async () => {+ expect(helper.helperMessagesProblem(turns)).toBeNull();+ expect(helper.helperMessagesProblem([])).toBe("no turns");+ expect(helper.helperMessagesProblem(turns.slice(0, 2))).toBe("the newest turn isn't the person's");+ expect(helper.helperMessagesProblem([{ role: "system", content: "x" }, turns[2]])).toMatch(/user or assistant/);+ expect(helper.helperMessagesProblem([{ role: "user", content: "x".repeat(helper.HELPER_LIMITS.chatChars + 1) }])).toBe("too long");+ expect(helper.helperMessagesProblem([{ role: "user", content: "x".repeat(helper.HELPER_LIMITS.chatChars) }])).toBeNull();+ expect(helper.helperMessagesProblem(Array(helper.HELPER_LIMITS.chatTurns + 1).fill(turns[2]))).toBe("too many turns");+ chatWorker();+ expect(await helper.askHelper({ task: "chat", system: "s", messages: [{ role: "user", content: "x".repeat(24_001) }] })).toMatchObject({ error: "failed", message: expect.stringContaining("too long") });+ const png = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#fff" } }).png().toBuffer();+ const two = [{ data: png, contentType: "image/png" }, { data: png, contentType: "image/png" }];+ expect(await helper.askHelper({ task: "chat", system: "s", messages: turns, images: two })).toMatchObject({ error: "failed" });+ expect(jobs()).toEqual([]);+ });++ it("a chat goes only to a slot that takes chats, as real turns with its own sampling (in bounds), one picture with it", async () => {+ const old = addWorker();+ helper.claimHelperJob(workerRow(old));+ // Only an older slot is live: busy at once, nothing queued.+ expect(helper.helperLive(Date.now(), { chat: true })).toBe(false);+ expect(await helper.askHelper({ task: "chat", system: "s", messages: turns })).toEqual({ error: "busy" });+ const w = chatWorker();+ const png = await sharp({ create: { width: 2000, height: 1000, channels: 3, background: "#c33" } }).png().toBuffer();+ const asked = helper.askHelper({ task: "chat", system: "Be kind.", messages: turns, sampling: { temperature: 5, top_p: 0.5 }, images: [{ data: png, contentType: "image/png" }] });+ await new Promise((r) => setTimeout(r, 50));+ // The older slot never gets it.+ expect(helper.claimHelperJob(workerRow(old), { vision: true })).toBeNull();+ const job = await nextChat(w);+ expect(job).toMatchObject({ task: "chat", system: "Be kind.", user: "What's my name?", messages: turns, sampling: { temperature: 2, top_p: 0.5 }, stream: true, maxTokens: 900 });+ expect(job!.images).toHaveLength(1);+ helper.finishHelperJob(workerRow(w), job!.id, { lease: job!.lease, text: "You're Ria." });+ expect(await asked).toEqual({ text: "You're Ria." });+ });++ it("the words so far reach the caller as they come, only with the job's lease; the whole answer still comes back", async () => {+ const w = chatWorker();+ const other = chatWorker();+ const seen: string[] = [];+ const asked = helper.askHelper({ task: "chat", system: "s", messages: turns, onText: (t) => seen.push(t) });+ const job = (await nextChat(w))!;+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: "not its lease", text: "x" })).toBe("stop");+ expect(helper.partialHelperJob(workerRow(other), job.id, { lease: job.lease, text: "x" })).toBe("stop");+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease })).toBe("bad");+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "x".repeat(helper.HELPER_LIMITS.textBytes + 1) })).toBe("bad");+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "" })).toBe("ok");+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "<think>hmm" })).toBe("ok");+ await new Promise((r) => setTimeout(r, 300));+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "You're" })).toBe("ok");+ await new Promise((r) => setTimeout(r, 300));+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "You're Ria" })).toBe("ok");+ await new Promise((r) => setTimeout(r, 300));+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "You're Ria." });+ expect(await asked).toEqual({ text: "You're Ria." });+ // An unfinished reasoning block and empty words are never shown.+ expect(seen).toEqual(["You're", "You're Ria"]);+ expect(jobs()).toEqual([]);+ });++ it("the caller goes: a waiting job is gone, a running one is canceled and its slot is told to stop; its answer isn't taken", async () => {+ const w = chatWorker();+ const early = new AbortController();+ const waiting = helper.askHelper({ task: "chat", system: "s", messages: turns, signal: early.signal });+ await new Promise((r) => setTimeout(r, 50));+ early.abort();+ expect(await waiting).toEqual({ error: "failed" });+ expect(jobs()).toEqual([]);+ const late = new AbortController();+ const running = helper.askHelper({ task: "chat", system: "s", messages: turns, signal: late.signal });+ const job = (await nextChat(w))!;+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Once upon" })).toBe("ok");+ late.abort();+ expect(await running).toEqual({ error: "failed" });+ expect(row(job.id)?.state).toBe("canceled");+ expect(helper.partialHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Once upon a time" })).toBe("stop");+ expect(helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "Once upon a time." })).toBe(false);+ // A canceled job doesn't count as waiting, and the sweep takes it later.+ helper.sweepHelper(Date.now() + helper.HELPER_TIMES.keepMs + 1000);+ expect(row(job.id)).toBeUndefined();+ });++ it("the partial route: the slot's lease or stop; a browser can't", async () => {+ const w = chatWorker();+ const asked = helper.askHelper({ task: "chat", system: "s", messages: turns, waitMs: 5000 });+ const job = (await nextChat(w))!;+ const ctx = { params: Promise.resolve({ id: job.id }) } as never;+ const send = (body: unknown, who?: string, extra = auth_(w)) => partialRoute.POST(post(`/api/gpu/computer/text/${job.id}/partial`, body, who, extra), ctx);+ const wrong = await send({ lease: "x", text: "no" });+ expect(wrong.status).toBe(409);+ expect(await wrong.json()).toMatchObject({ stop: true });+ expect((await send({ lease: job.lease, text: "You" })).status).toBe(200);+ expect(row(job.id)?.partial).toBe("You");+ expect((await send({ lease: job.lease, text: 5 })).status).toBe(400);+ const browser = await send({ lease: job.lease, text: "x" }, "owner", { "sec-fetch-site": "same-origin", origin: "http://localhost:3000" } as never);+ expect(browser.status).not.toBe(200);+ expect((await resultRoute.POST(post(`/api/gpu/computer/text/${job.id}`, { lease: job.lease, text: "You're Ria." }, undefined, auth_(w)), ctx)).status).toBe(200);+ expect(await asked).toEqual({ text: "You're Ria." });+ // Ended: the next words are told to stop.+ expect((await send({ lease: job.lease, text: "more" })).status).toBe(409);+ // A slot that says it takes chats gets one through the claim route too.+ const claimed = helper.askHelper({ task: "chat", system: "s", messages: turns, waitMs: 5000 });+ const none = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "m", device: "cpu", wait: 300 }, undefined, auth_(w)));+ expect(none.status).toBe(204);+ const r = await claimRoute.POST(post("/api/gpu/computer/text/claim", { model: "m", device: "cpu", chat: true, wait: 3000 }, undefined, auth_(w)));+ const { job: j2 } = (await r.json()) as { job: { id: string; lease: string; messages: unknown } };+ expect(j2.messages).toEqual(turns);+ helper.finishHelperJob(workerRow(w), j2.id, { lease: j2.lease, text: "ok" });+ expect(await claimed).toEqual({ text: "ok" });+ });++ it("a slot that never sends words so far (an older worker) still answers a streamed job whole; its time runs from its claim", async () => {+ const w = chatWorker();+ const seen: string[] = [];+ const asked = helper.askHelper({ task: "enhance", system: "s", user: "a cat", onText: (t) => seen.push(t) });+ // An older slot claims as it always did (no chat flag): a plain job with a stream flag it ignores.+ const job = (await nextJob(w))!;+ expect(job).toMatchObject({ task: "enhance", user: "a cat", stream: true });+ expect(job.messages).toBeUndefined();+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: "a cat, golden light" });+ expect(await asked).toEqual({ text: "a cat, golden light" });+ expect(seen).toEqual([]);+ // The worker updates: its slot says it takes chats again.+ expect(helper.claimHelperJob(workerRow(w), { chat: true })).toBeNull();+ // Time: with no words sent, a running job fails runMs after its claim; each new word gives it that time again.+ // A clock that moves 20 s with each look once the job is claimed.+ let t = 1_000_000;+ let taken: Awaited<ReturnType<typeof nextChat>> = null;+ let sends = 0;+ let talk = false;+ const sleep = async () => {+ await new Promise((r) => setTimeout(r, 5));+ if (!taken) return;+ t += 20_000;+ // Words every 20 s, for 4 minutes; then none.+ if (talk && sends++ < 12) helper.partialHelperJob(workerRow(w), taken.id, { lease: taken.lease, text: `w${sends}` }, t);+ };+ const quiet = helper.askHelper({ task: "chat", system: "s", messages: turns, now: () => t, sleep });+ taken = await nextChat(w);+ db().prepare("UPDATE helper_jobs SET claimed_at = ? WHERE id = ?").run(t, taken!.id);+ expect(await quiet).toEqual({ error: "failed" });+ expect(t - 1_000_000).toBeGreaterThanOrEqual(helper.HELPER_TIMES.runMs);+ expect(t - 1_000_000).toBeLessThanOrEqual(helper.HELPER_TIMES.runMs + 20_000);+ t = 2_000_000;+ taken = null;+ talk = true;+ const talky = helper.askHelper({ task: "chat", system: "s", messages: turns, now: () => t, sleep });+ taken = await nextChat(w);+ db().prepare("UPDATE helper_jobs SET claimed_at = ? WHERE id = ?").run(t, taken!.id);+ expect(await talky).toEqual({ error: "failed" });+ // It went on well past runMs while words came, and ended once they stopped.+ expect(t - 2_000_000).toBeGreaterThan(240_000);+ expect(t - 2_000_000).toBeLessThanOrEqual(helper.HELPER_TIMES.streamMaxMs + 20_000);+ });++ it("chat has its own limits apart from the studio's: an account's 12 a minute; a guest is asked to sign in", async () => {+ chatWorker();+ const who = `acct:${account}`;+ for (let i = 0; i < helper.HELPER_LIMITS.account.perMinute; i++) expect(await helper.askHelper({ task: "enhance", system: "s", user: "u", who, waitMs: 30 })).not.toMatchObject({ error: "limit" });+ expect(await helper.askHelper({ task: "enhance", system: "s", user: "u", who, waitMs: 30 })).toMatchObject({ error: "limit" });+ // The studio's limit is used up; chat still answers.+ for (let i = 0; i < helper.HELPER_LIMITS.chat.perMinute; i++) expect(await helper.askHelper({ task: "chat", system: "s", messages: turns, who, waitMs: 30 })).toEqual({ error: "busy" });+ expect(await helper.askHelper({ task: "chat", system: "s", messages: turns, who, waitMs: 30 })).toMatchObject({ error: "limit", retryAfterS: expect.any(Number) });+ expect(helper.HELPER_LIMITS.chat).toEqual({ perMinute: 12, perHour: 300 });+ expect(await helper.askHelper({ task: "chat", system: "s", messages: turns, who: "guest:203.0.113.9" })).toEqual({ error: "sign-in" });+ expect(runAsTenant({ kind: "guest" }, () => helper.freeHelperOn(Date.now(), { chat: true }))).toBe(false);+ });++ it("while it waits, the caller hears its place in the line (1 is next), people's jobs before the owner's", async () => {+ const w = chatWorker();+ const places: Record<string, number[]> = { a: [], b: [], c: [] };+ const a = helper.askHelper({ task: "chat", system: "s", messages: turns, onQueue: (p) => places.a.push(p), waitMs: 10_000 });+ await new Promise((r) => setTimeout(r, 20));+ const b = helper.askHelper({ task: "chat", system: "s", messages: turns, onQueue: (p) => places.b.push(p), waitMs: 10_000 });+ await new Promise((r) => setTimeout(r, 20));+ const c = runAsTenant({ kind: "account", id: account }, () => helper.askHelper({ task: "chat", system: "s", messages: turns, onQueue: (p) => places.c.push(p), waitMs: 10_000 }));+ await new Promise((r) => setTimeout(r, 400));+ expect(places).toEqual({ a: [1, 2], b: [2, 3], c: [1] });+ for (let i = 0; i < 3; i++) {+ const job = (await nextChat(w))!;+ await new Promise((r) => setTimeout(r, 400));+ helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: `answer ${i}` });+ }+ expect(await Promise.all([a, b, c])).toEqual([{ text: "answer 1" }, { text: "answer 2" }, { text: "answer 0" }]);+ expect(places).toEqual({ a: [1, 2, 1], b: [2, 3, 2, 1], c: [1] });+ });+});diff --git a/tests/worker-text-slot.test.ts b/tests/worker-text-slot.test.tsindex 57994809..1e07e6c2 100644--- a/tests/worker-text-slot.test.ts+++ b/tests/worker-text-slot.test.ts@@ -11,7 +11,7 @@ import path from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { othersOf } from "../bin/lib/worker/gpu.mjs";import { parseCounters, splitMemory } from "../bin/lib/worker/local-work.mjs";-import { chatBody, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, TextSlot, textSlotOf } from "../bin/lib/worker/text.mjs";+import { chatBody, contextOf, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, streamedWords, TextSlot, textSlotOf } from "../bin/lib/worker/text.mjs";import { tempDir } from "./helpers/temp-dir";vi.setConfig({ testTimeout: 30_000 });@@ -30,6 +30,7 @@ const JPEG_B64 = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0/** 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";+import fs from "node:fs";const arg = (n) => process.argv[process.argv.indexOf(n) + 1];const port = Number(arg("--port"));const key = arg("--api-key");@@ -44,9 +45,31 @@ http.createServer((req, res) => {const b = JSON.parse(body);const last = b.messages.at(-1).content;const parts = Array.isArray(last) ? last : [{ type: "text", text: last }];- const content = JSON.stringify({ host: req.headers.host, ngl: arg("-ngl"), mmproj: process.argv.includes("--mmproj"), cuda: process.env.CUDA_VISIBLE_DEVICES ?? null, token: process.env.FUOBE_WORKER_TOKEN ?? null, kwargs: b.chat_template_kwargs ?? null, temperature: b.temperature, user: parts.find((p) => p.type === "text").text, pictures: parts.filter((p) => p.type === "image_url").map((p) => p.image_url.url.slice(0, 23)), max: b.max_tokens });- res.writeHead(200, { "content-type": "application/json" });- res.end(JSON.stringify({ choices: [{ message: { content } }] }));+ const content = JSON.stringify({ host: req.headers.host, ngl: arg("-ngl"), ctx: arg("-c"), mmproj: process.argv.includes("--mmproj"), cuda: process.env.CUDA_VISIBLE_DEVICES ?? null, token: process.env.FUOBE_WORKER_TOKEN ?? null, kwargs: b.chat_template_kwargs ?? null, temperature: b.temperature, top_p: b.top_p, user: parts.find((p) => p.type === "text").text, pictures: parts.filter((p) => p.type === "image_url").map((p) => p.image_url.url.slice(0, 23)), max: b.max_tokens, stream: b.stream, turns: b.messages.map((m) => m.role + ":" + (Array.isArray(m.content) ? m.content.map((p) => p.type).join("+") : m.content)) });+ if (!b.stream) {+ res.writeHead(200, { "content-type": "application/json" });+ return res.end(JSON.stringify({ choices: [{ message: { content } }] }));+ }+ // Streamed: the words in pieces, a tenth of a second apart; a request that ends early is noted beside it.+ res.writeHead(200, { "content-type": "text/event-stream" });+ const pieces = content.match(/[\\s\\S]{1,12}/g);+ let n = 0;+ let ended = false;+ res.on("close", () => {+ if (n < pieces.length) fs.writeFileSync("closed.txt", String(n));+ ended = true;+ });+ const event = (o) => "data: " + JSON.stringify(o) + "\\n\\n";+ const next = () => {+ if (ended) return;+ if (n >= pieces.length) {+ res.write(event({ choices: [{ delta: {}, finish_reason: "stop" }] }));+ return res.end("data: [DONE]\\n\\n");+ }+ res.write(event({ choices: [{ delta: { content: pieces[n++] } }] }));+ setTimeout(next, Number(process.env.FAKE_PIECE_MS ?? 100));+ };+ next();});}).listen(port, "127.0.0.1");`;@@ -68,9 +91,11 @@ const kill = async (pid: number) => {};/** 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; images?: string[] }[]) {+type LineJob = { id: string; lease: string; user: string; maxTokens: number; system?: string; json?: boolean; images?: string[]; messages?: { role: string; content: string }[]; sampling?: Record<string, number>; stream?: boolean };+function studio(line: LineJob[], o: { partial?: (body: { lease: string; text: string }, n: number) => Response } = {}) {const answers: { id: string; body: Record<string, unknown> }[] = [];const claims: Record<string, unknown>[] = [];+ const partials: { id: string; text: string }[] = [];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") {@@ -78,6 +103,11 @@ function studio(line: { id: string; lease: string; user: string; maxTokens: numbconst job = line.shift();return job ? Response.json({ job: { system: "Be brief.", json: false, ...job } }) : new Response(null, { status: 204 });}+ const pm = /^\/api\/gpu\/computer\/text\/([^/]+)\/partial$/.exec(p);+ if (pm) {+ partials.push({ id: decodeURIComponent(pm[1]), text: String(body.text) });+ return o.partial ? o.partial(body as { lease: string; text: string }, partials.length) : Response.json({ ok: true });+ }const m = /^\/api\/gpu\/computer\/text\/([^/]+)$/.exec(p);if (m) {answers.push({ id: decodeURIComponent(m[1]), body });@@ -85,7 +115,7 @@ function studio(line: { id: string; lease: string; user: string; maxTokens: numb}return new Response(null, { status: 404 });};- return { call, answers, claims };+ return { call, answers, claims, partials };}const slots: InstanceType<typeof TextSlot>[] = [];@@ -157,7 +187,7 @@ describe("the text slot's parts", () => {expect(qwen).toMatchObject({ temperature: 0.7, top_p: 0.8, top_k: 20, presence_penalty: 1.5 });expect(qwen.messages[1].content).toEqual([{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${JPEG_B64}` } }, { type: "text", text: "U" }]);// worker.json may set them itself.- expect(familyOf({ model: "other.gguf", chat: { kwargs: { reasoning: "off" }, sampling: { temperature: 0.2 } } })).toEqual({ kwargs: { reasoning: "off" }, sampling: { temperature: 0.2, top_p: 0.9 } });+ expect(familyOf({ model: "other.gguf", chat: { kwargs: { reasoning: "off" }, sampling: { temperature: 0.2 } } })).toEqual({ kwargs: { reasoning: "off" }, sampling: { temperature: 0.2, top_p: 0.9 }, context: null });expect(modelName({ model: "a/b/Gemma-4-E4B-it-Q4_0.gguf" })).toBe("gemma-4-e4b-it-q4_0");// A picture is a JPEG as base64, never an address or a file.const one = (images: unknown) => jobOf({ job: { id: "j", lease: "l", system: "", user: "U", maxTokens: 10, images } });@@ -217,7 +247,7 @@ describe("the text slot", () => {const said = JSON.parse(String(a.body.text));expect(said).toMatchObject({ ngl: "99", cuda: null, token: null, kwargs: null, user: "Write a chorus", max: 200, pictures: [], mmproj: false });expect(said.host).toMatch(/^127\.0\.0\.1:\d+$/);- expect(site.claims[0]).toMatchObject({ model: "model", device: "gpu", vision: false });+ expect(site.claims[0]).toMatchObject({ model: "model", device: "gpu", vision: false, chat: true });expect(s.own().pids).toHaveLength(1);expect(s.own().mb).toBe(3698);});@@ -287,3 +317,94 @@ describe("the text slot", () => {expect(logs.join("\n")).toContain("SHA-256 doesn't match");});});++describe("chats and words as they come", () => {+ const turns = [+ { role: "user", content: "Hi, I'm Ria." },+ { role: "assistant", content: "Hello Ria!" },+ { role: "user", content: "What's my name?" },+ ];++ it("reads a chat's turns and its own sampling (kept in bounds); a chat that isn't one is dropped", () => {+ const base = { id: "j", lease: "l", system: "", user: "What's my name?", maxTokens: 900 };+ expect(jobOf({ job: { ...base, messages: turns, sampling: { temperature: 9, top_p: 0 }, stream: true } })).toMatchObject({ messages: turns, sampling: { temperature: 2, top_p: 0.05 }, stream: true });+ // An older studio's job: no turns, no sampling of its own, no stream.+ expect(jobOf({ job: base })).toMatchObject({ messages: null, sampling: {}, stream: false });+ expect(jobOf({ job: { ...base, messages: [] } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: [{ role: "system", content: "x" }, turns[2]] } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: turns.slice(0, 2) } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: [{ role: "user", content: "x".repeat(32_001) }] } })).toBeNull();+ expect(jobOf({ job: { ...base, messages: Array(201).fill(turns[2]) } })).toBeNull();+ });++ it("sends the turns as real turns after the system words, a picture with the newest turn only, the job's sampling over the family's", () => {+ const job = jobOf({ job: { id: "j", lease: "l", system: "S", user: "What's my name?", maxTokens: 900, messages: turns, images: [JPEG_B64], sampling: { temperature: 0.3 }, stream: true } })!;+ const b = chatBody(job, { model: "gemma-4-E2B-it-Q6_K.gguf" });+ expect(b).toMatchObject({ temperature: 0.3, top_p: 0.95, top_k: 64, stream: true, max_tokens: 900, chat_template_kwargs: { enable_thinking: false } });+ expect(b.messages.map((m: { role: string }) => m.role)).toEqual(["system", "user", "assistant", "user"]);+ expect(b.messages[1].content).toBe("Hi, I'm Ria.");+ expect(b.messages[3].content).toEqual([{ type: "image_url", image_url: { url: `data:image/jpeg;base64,${JPEG_B64}` } }, { type: "text", text: "What's my name?" }]);+ });++ it("starts Gemma 4 E2B's server with room for a chat even where worker.json still says 8192; another model keeps worker.json's own", () => {+ const gemma = textSlotOf({ server: "s", modelDir: "X:/llm", context: 8192 })!;+ expect(contextOf(gemma)).toBe(32_768);+ expect(serverArgs(gemma, { port: 31000, key: "k", device: "cpu" })).toEqual(expect.arrayContaining(["-c", "32768"]));+ expect(contextOf(textSlotOf({ server: "s", modelDir: "X:/llm", context: 65_536 })!)).toBe(65_536);+ expect(contextOf(textSlotOf({ server: "s", model: "m.gguf", sha256: "a".repeat(64), context: 8192 })!)).toBe(8192);+ expect(contextOf(textSlotOf({ server: "s", model: "m.gguf", sha256: "a".repeat(64) })!)).toBe(16_384);+ // worker.json may set the family's context itself.+ expect(contextOf(textSlotOf({ server: "s", modelDir: "X:/llm", context: 4096, chat: { context: 16_384 } })!)).toBe(16_384);+ });++ it("reads streamed words from the server's events", () => {+ expect(streamedWords('data: {"choices":[{"delta":{"content":"Hel"}}]}')).toBe("Hel");+ expect(streamedWords("data: [DONE]")).toBe("");+ expect(streamedWords(": ping")).toBe("");+ expect(streamedWords("data: {broken")).toBe("");+ });++ it("says it takes chats; streams a chat's words to the studio as they come, then sends the whole answer with its lease", async () => {+ const site = studio([{ id: "hlp_c", lease: "Lc", user: "What's my name?", maxTokens: 900, messages: turns, stream: true }]);+ const { s } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 1);+ expect(site.claims[0]).toMatchObject({ chat: true });+ const final = String(site.answers[0].body.text);+ expect(JSON.parse(final)).toMatchObject({ stream: true, turns: ["system:Be brief.", "user:Hi, I'm Ria.", "assistant:Hello Ria!", "user:What's my name?"] });+ expect(site.answers[0].body.lease).toBe("Lc");+ // The words so far grow, each the start of the answer.+ const words = site.partials.map((p) => p.text).filter(Boolean);+ expect(words.length).toBeGreaterThanOrEqual(2);+ for (const w of words) expect(final.startsWith(w)).toBe(true);+ expect(new Set(site.partials.map((p) => p.id))).toEqual(new Set(["hlp_c"]));+ });++ it("stops writing when the studio says the job isn't its own any more: the request ends early and no answer is sent", async () => {+ const site = studio([{ id: "hlp_s", lease: "Ls", user: "long", maxTokens: 900, messages: [{ role: "user", content: "long" }], stream: true }], {+ partial: (_b, n) => (n >= 2 ? Response.json({ error: "gone", stop: true }, { status: 409 }) : Response.json({ ok: true })),+ });+ const { s, logs } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.partials.length >= 2 && !s.busy);+ expect(site.answers).toEqual([]);+ // The stand-in notes the request that ended before its last words.+ for (let i = 0; i < 100 && !fs.existsSync(path.join(s.dir, "closed.txt")); i++) await new Promise((r) => setTimeout(r, 20));+ expect(fs.existsSync(path.join(s.dir, "closed.txt"))).toBe(true);+ expect(logs.join("\n")).not.toContain("has no answer");+ });++ it("a studio without the partial call (404) or a busy moment (429) changes nothing: the whole answer still goes", async () => {+ const site = studio([{ id: "hlp_o", lease: "Lo", user: "x", maxTokens: 900, stream: true }], { partial: (_b, n) => new Response(null, { status: n % 2 ? 404 : 429 }) });+ const { s } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 1);+ expect(JSON.parse(String(site.answers[0].body.text))).toMatchObject({ stream: true, user: "x" });+ expect(site.partials.length).toBeGreaterThanOrEqual(1);+ });++ it("an older studio's job (no stream) is answered whole, with no partial calls", async () => {+ const site = studio([{ id: "hlp_n", lease: "Ln", user: "plain", maxTokens: 100 }]);+ const { s } = makeSlot(site.call);+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 1);+ expect(JSON.parse(String(site.answers[0].body.text))).toMatchObject({ stream: false, user: "plain", turns: ["system:Be brief.", "user:plain"] });+ expect(site.partials).toEqual([]);+ });+});