Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Free helper: pictures for a vision model, Gemma 4 E2B-it as the text slot's default

Adarshffd1eee807cb
diff --git a/bin/lib/worker/text.mjs b/bin/lib/worker/text.mjs
index 4a7a7f94..4ac68412 100644
--- a/bin/lib/worker/text.mjs
+++ b/bin/lib/worker/text.mjs
@@ -2,7 +2,8 @@
// 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.
+// 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.
import crypto from "node:crypto";
import { spawn as spawnChild } from "node:child_process";
import fs from "node:fs";
@@ -11,22 +12,63 @@ 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 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;
-/** The model name the studio hears with each claim. */
-export const TEXT_MODEL = "nemotron-3.5-bolt-e4b";
+/**
+ * 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.
+ */
+export const FAMILIES = [
+ { match: /nemotron/i, kwargs: { enable_thinking: false }, sampling: { temperature: 1.0, top_p: 0.95 } },
+ { 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 } },
+];
+const PLAIN = { kwargs: null, sampling: { temperature: 0.7, top_p: 0.9 } };
+
+/** The family settings for a model file (or textSlot.name), with worker.json's own. */
+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 ?? {}) } };
+}
+
+/** 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);
+
+/** A picture a job may carry: a JPEG as base64, at most this long. */
+const PICTURE_B64_MAX = 700_000;
const SHA = /^[0-9a-f]{64}$/i;
+/**
+ * The model a text slot runs when worker.json gives only `modelDir`: Gemma 4 E2B-it (Q6_K) with its vision projector, from
+ * unsloth/gemma-4-E2B-it-GGUF at commit 0314792d7f1f7e229411f620751375812bb9faf2. Any field worker.json sets wins.
+ */
+export const TEXT_DEFAULT_MODEL = {
+ model: "gemma-4-E2B-it-Q6_K.gguf",
+ sha256: "f7b8980ecc1c115898fd8d9a3d421d90becbac984194a44b478669c26815843d",
+ mmproj: "mmproj-F16.gguf",
+ mmprojSha256: "140be8d7849741f88c50757d529b84373ee8e27052cc2236855b537f4a8215fa",
+};
+
/** 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.modelDir === "string" && s.modelDir) {
+ const d = TEXT_DEFAULT_MODEL;
+ if (s.model === undefined) Object.assign(s, { model: path.join(s.modelDir, d.model), sha256: s.sha256 ?? d.sha256 });
+ if (s.mmproj === undefined) Object.assign(s, { mmproj: path.join(s.modelDir, d.mmproj), mmprojSha256: s.mmprojSha256 ?? d.mmprojSha256 });
+ }
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" };
+ if (s.mmproj !== undefined && (typeof s.mmproj !== "string" || !s.mmproj || typeof s.mmprojSha256 !== "string" || !SHA.test(s.mmprojSha256))) {
+ return { problem: "textSlot's `mmproj` needs `mmprojSha256`, the projector file's 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,
@@ -91,7 +133,8 @@ export function serverArgs(slot, o) {
"-t", String(slot.threads),
"--jinja",
"--no-webui",
- "--alias", TEXT_MODEL,
+ "--alias", modelName(slot),
+ ...(slot.mmproj ? ["--mmproj", slot.mmproj] : []),
];
}
@@ -110,22 +153,30 @@ export function jobOf(body) {
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 };
+ let images = [];
+ if (j.images !== undefined) {
+ if (!Array.isArray(j.images) || j.images.length > 4) return null;
+ for (const b of j.images) {
+ // A JPEG as base64 only, never an address: llama-server would fetch a URL or read a file.
+ if (typeof b !== "string" || b.length > PICTURE_B64_MAX || !/^[A-Za-z0-9+/]+={0,2}$/.test(b) || !b.startsWith("/9j/")) return null;
+ }
+ images = j.images;
+ }
+ return { id: j.id, lease: j.lease, system: j.system, user: j.user, maxTokens, json: j.json === true, images };
}
-/** The request body for one job: thinking off, the model card's sampling. */
-export function chatBody(job) {
+/** The request body for one job: the family's template switches and sampling, the pictures before the words. */
+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;
return {
- model: TEXT_MODEL,
- messages: [
- ...(job.system ? [{ role: "system", content: job.system }] : []),
- { role: "user", content: job.user },
- ],
+ model: modelName(slot),
+ messages: [...(job.system ? [{ role: "system", content: job.system }] : []), { role: "user", content }],
max_tokens: job.maxTokens,
- temperature: 1.0,
- top_p: 0.95,
+ ...fam.sampling,
stream: false,
- chat_template_kwargs: { enable_thinking: false },
+ ...(fam.kwargs && { chat_template_kwargs: fam.kwargs }),
...(job.json && { response_format: { type: "json_object" } }),
};
}
@@ -160,8 +211,10 @@ export class TextSlot {
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"}.`);
+ const mmproj = !this.slot.mmproj || (await fileMatches(this.slot.mmproj, this.slot.mmprojSha256, cache, hash));
+ this.ok = model && server && mmproj;
+ const why = !model ? "the model file is missing or its SHA-256 doesn't match" : !mmproj ? "the mmproj file is missing or its SHA-256 doesn't match" : "llama-server is missing or its SHA-256 doesn't match";
+ this.log(this.ok ? `Its text slot is ready (${modelName(this.slot)}${this.slot.mmproj ? ", with pictures" : ""}): the SHA-256 matches.` : `Its text slot is off: ${why}.`);
})()
.catch((e) => {
this.ok = false;
@@ -212,7 +265,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: TEXT_MODEL, device, 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, wait: this.slot.claimWaitMs }), signal: this.ending.signal });
if (res.status === 204 || !res.ok) {
await res.body?.cancel().catch(() => {});
return false;
@@ -221,6 +274,7 @@ export class TextSlot {
if (!job) return false;
let answer;
try {
+ if (job.images.length && !this.slot.mmproj) throw new Error("this slot's model doesn't take pictures");
await this.ensure(device);
answer = { text: await this.complete(job) };
} catch (e) {
@@ -241,7 +295,7 @@ export class TextSlot {
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)),
+ body: JSON.stringify(chatBody(job, this.slot)),
signal: AbortSignal.timeout(this.slot.answerMs),
});
if (!r.ok) throw new Error(`llama-server answered ${r.status}`);
diff --git a/src/app/api/gpu/computer/text/claim/route.ts b/src/app/api/gpu/computer/text/claim/route.ts
index 670af379..b79072c8 100644
--- a/src/app/api/gpu/computer/text/claim/route.ts
+++ b/src/app/api/gpu/computer/text/claim/route.ts
@@ -16,13 +16,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; wait?: unknown };
+ const body = ((await request.json().catch(() => null)) ?? {}) as { model?: unknown; device?: unknown; vision?: 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;
+ const job = first || helperWaiting(body.vision === 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/components/restore/hooks.ts b/src/components/restore/hooks.ts
index 86627f36..aafacfb9 100644
--- a/src/components/restore/hooks.ts
+++ b/src/components/restore/hooks.ts
@@ -44,7 +44,7 @@ export interface RestoreEstimate {
export interface PromptAnswer {
prompt: string;
negative: string;
- by: "claude" | "local" | "offline";
+ by: "claude" | "local" | "free" | "offline";
why?: string;
}
diff --git a/src/components/restore/restore-tool.tsx b/src/components/restore/restore-tool.tsx
index 2d3ed145..dacfe238 100644
--- a/src/components/restore/restore-tool.tsx
+++ b/src/components/restore/restore-tool.tsx
@@ -28,7 +28,7 @@ import { cn } from "@/lib/utils";
import { grabFrames, useRestoreActions, useRestoreEstimate, type RestoreBody } from "./hooks";
const LIMITS = `MP4, MOV, WebM, MKV or AVI · up to ${RESTORE.maxSeconds / 60} minutes · ${RESTORE.maxBytes / 1024 / 1024 / 1024} GB`;
-const BY: Record<string, string> = { claude: "Written by Claude from your frames", local: "Written by a local model", offline: "Fuobe's template: edit it to fit your footage", you: "Your words" };
+const BY: Record<string, string> = { claude: "Written by Claude from your frames", local: "Written by a local model", free: "Written from your frames", offline: "Fuobe's template: edit it to fit your footage", you: "Your words" };
const DEFAULT_NEGATIVE = restoreNegative();
interface Run {
diff --git a/src/server/db.ts b/src/server/db.ts
index f1ace827..c1e66f8d 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1187,6 +1187,9 @@ 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"]]) {
+ 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
// 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.
@@ -1313,14 +1316,16 @@ const HELPER_TABLES = `CREATE TABLE IF NOT EXISTS helper_jobs (
claimed_at INTEGER,
done_at INTEGER,
text TEXT,
- error TEXT
+ error TEXT,
+ images_json 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
+ device TEXT,
+ vision INTEGER NOT NULL DEFAULT 0
);`;
export function db(): Database.Database {
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index a714a185..04e3e415 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -93,6 +93,10 @@ export interface LlmTextOptions {
waitMs?: number;
/** Hears why the free helper gave no text. */
onHelper?: (a: Exclude<HelperAnswer, { text: string }>) => void;
+ /** Hears who answered. */
+ onAnswer?: (by: "claude" | "local" | "free") => void;
+ /** The pictures help but aren't needed: a free helper that reads words only may answer without them. */
+ imagesOptional?: boolean;
}
/** The local model in use (Ollama, LM Studio, Unsloth Studio or the custom server), thinking off where the server allows it. */
@@ -141,21 +145,35 @@ export async function llmText(system: string, user: string, images?: LlmImage[],
export async function llmText(system: string, user: string, a: LlmImage[] | LlmTextOptions = [], b: LlmTextOptions = {}): Promise<string | null> {
const images: LlmImage[] = Array.isArray(a) ? a : [];
const opts: LlmTextOptions = Array.isArray(a) ? b : a;
+ const said = (by: "claude" | "local" | "free", text: string | null) => {
+ if (text !== null) opts.onAnswer?.(by);
+ return text;
+ };
// The open engine never calls a paid API: a local model, unless the AI helper is off.
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") {
+ if (backend === "claude") return said("claude", await viaClaude(system, user, images).catch(() => null));
+ const free = freeFor(images, opts);
+ if (backend === "ollama" || (backend === "free" && !free.on && !tenant())) {
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;
+ if (local !== null || !opts.task || !["auto", "free"].includes(aiHelper())) return said("local", local);
} else if (backend !== "free") return null;
- return viaFree(system, user, opts);
+ if (!free.on) return null;
+ return said("free", await viaFree(system, user, free.pictures, 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" }));
+/** The free helper for this call: a slot whose model sees pictures when the call has some (unless they are optional). */
+function freeFor(images: LlmImage[], opts: LlmTextOptions): { on: boolean; pictures: LlmImage[] } {
+ if (!opts.task) return { on: false, pictures: [] };
+ if (images.length && freeHelperOn(Date.now(), { vision: true })) return { on: true, pictures: images };
+ if (images.length && !opts.imagesOptional) return { on: false, pictures: [] };
+ return { on: freeHelperOn(), pictures: [] };
+}
+
+/** The free helper's answer, or null with the reason told to `onHelper`. */
+async function viaFree(system: string, user: string, images: LlmImage[], opts: LlmTextOptions): Promise<string | null> {
+ const a = await askHelper({ task: opts.task!, system, user, json: !!opts.json, images, who: helperWho(opts.guestKey), waitMs: opts.waitMs }).catch((): HelperAnswer => ({ error: "failed" }));
if ("text" in a) return a.text;
opts.onHelper?.(a);
return null;
@@ -288,3 +306,6 @@ Rules:
export function ideogramCaption(words: string, size: { width?: number; height?: number } = {}): Promise<string> {
return writeCaption(words, size, (request) => llmText(IDEOGRAM_SYSTEM, request, { json: "object", ollamaOnly: true }));
}
+
+/** The owner's AI helper may fall back to the free helper (Automatic, or the free helper picked), one that sees pictures when asked. */
+export const freeHelperFallback = (o: { vision?: boolean } = {}): boolean => ["auto", "free"].includes(aiHelper()) && freeHelperOn(Date.now(), o);
diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.ts
index e333bb20..3ea5001f 100644
--- a/src/server/genjutsu.ts
+++ b/src/server/genjutsu.ts
@@ -61,7 +61,7 @@ import { planSegments, type PlanStep } from "@/lib/catalog/shorts";
import type { Engine, Generation, GenerationRequest, PixelPoint, ProviderId } from "@/lib/catalog/types";
import { silenceWriter } from "./canvas";
import { createPipeline } from "./chains";
-import { llmText, llmTextBackend } from "./enhance";
+import { freeHelperFallback, llmText, llmTextBackend } from "./enhance";
import { AccountRunError, ConnectComfyError, createGenerations, previewChained, previewGeneration } from "./generations";
import { db } from "./db";
import { genjutsuLive } from "./genjutsu-live";
@@ -779,7 +779,9 @@ export async function describeCharacter(body: z.infer<typeof DescribeSchema>): P
// A local model is asked on your GPU's engine (and when no Anthropic key is set): its server has to be running.
const backend = llmTextBackend();
const local = backend === "ollama" || (backend === "claude" && body.engine === "open");
- if (getSetting("demoMode") === "on" || !backend || (local && !(await probeOllama()))) {
+ // The free helper on the workers' text slots, when its model sees pictures.
+ const free = !!backend && freeHelperFallback({ vision: true });
+ if (getSetting("demoMode") === "on" || ((!backend || (local && !(await probeOllama()))) && !free)) {
throw new ShortsError("Describing needs a text model: add an Anthropic key, or run a vision model in Ollama, LM Studio or Unsloth Studio (Settings → AI helper)", 422);
}
let file: Awaited<ReturnType<typeof readRef>>;
@@ -789,7 +791,7 @@ export async function describeCharacter(body: z.infer<typeof DescribeSchema>): P
throw new ShortsError("Couldn't read the character picture — add it again", 422);
}
if (!/^image\/(png|jpeg|webp|gif)$/.test(file.contentType)) throw new ShortsError("Describe works on a PNG, JPEG or WebP picture", 422);
- const answer = await llmText(DESCRIBE_SYSTEM, "Describe the character in this picture.", [{ data: file.data, contentType: file.contentType }], { ollamaOnly: body.engine === "open" });
+ const answer = await llmText(DESCRIBE_SYSTEM, "Describe the character in this picture.", [{ data: file.data, contentType: file.contentType }], { ollamaOnly: body.engine === "open", task: "describe", waitMs: 45_000 });
const description = cleanDescription(answer);
if (!description) throw new ShortsError(body.engine === "open" ? `${cap(localLabel())} didn't describe the picture — it needs a vision model (qwen3-vl, gemma3…)` : "The text model didn't answer — try again, or describe your character in your own words", 422);
return { description };
diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.ts
index 7d4d3b10..83379d12 100644
--- a/src/server/recipe-builder.ts
+++ b/src/server/recipe-builder.ts
@@ -1162,7 +1162,7 @@ async function leafStills(draft: SkillDraft): Promise<LlmImage[]> {
* slots in the prompts, a title, a description, when to use it and a SKILL.md body. Malformed output is ignored (null).
*/
export async function nameDraft(draft: SkillDraft, asked: string[] = []): Promise<Naming | null> {
- if (!llmTextBackend()) return null;
+ if (!llmTextBackend("recipe")) return null;
const record = {
steps: draft.recipe.steps.map((s) => {
const d = draft.steps.find((x) => x.key === s.key);
@@ -1177,7 +1177,7 @@ export async function nameDraft(draft: SkillDraft, asked: string[] = []): Promis
...(asked.length && { asked: asked.slice(-6).map((w) => cut(w, 600)) }),
};
const images = await leafStills(draft);
- const text = await llmText(NAMING_SYSTEM, `${images.length ? "The pictures are the results the person kept.\n" : ""}The record:\n${JSON.stringify(record, null, 2)}`, images);
+ const text = await llmText(NAMING_SYSTEM, `${images.length ? "The pictures are the results the person kept.\n" : ""}The record:\n${JSON.stringify(record, null, 2)}`, images, { task: "recipe", imagesOptional: true, waitMs: 60_000 });
return parseNaming(text, draft);
}
diff --git a/src/server/restore.ts b/src/server/restore.ts
index 343a6b35..98f3b815 100644
--- a/src/server/restore.ts
+++ b/src/server/restore.ts
@@ -23,7 +23,7 @@ import type { PlanStep } from "@/lib/catalog/shorts";
import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { ACCESS_PLACE } from "@/lib/model-access";
import { createPipeline } from "./chains";
-import { llmText, llmTextBackend } from "./enhance";
+import { freeHelperFallback, llmText, llmTextBackend } from "./enhance";
import { previewChained } from "./generations";
import { gatedFileReady, gatedHint } from "./loras";
import { isOffered, offeredModel } from "./model-access";
@@ -122,7 +122,7 @@ export interface PromptAnswer {
prompt: string;
negative: string;
/** Claude, a local model (Settings → AI helper: Ollama, LM Studio, Unsloth Studio or another server), or the template. */
- by: "claude" | "local" | "offline";
+ by: "claude" | "local" | "free" | "offline";
why?: string;
}
@@ -139,12 +139,22 @@ export async function writeRestorePrompt(body: z.infer<typeof PromptSchema>): Pr
if (!textModel || !offeredModel(textModel)) return offline(`the text model is switched off in ${ACCESS_PLACE}`);
const backend = llmTextBackend();
const local = backend === "ollama" || (backend === "claude" && body.engine === "open");
+ // The free helper on the workers' text slots, when its model sees pictures (or, with no frames, any).
+ const free = !!backend && freeHelperFallback({ vision: body.frames.length > 0 });
if (!backend) return offline("no AI helper is set up (Settings → AI helper)");
- if (local && !(await probeLocal())) return offline(`${localWhat()} isn't running`);
+ if (local && !free && !(await probeLocal())) return offline(`${localWhat()} isn't running`);
const images = body.frames.map((f) => ({ data: Buffer.from(f.split(",")[1], "base64"), contentType: f.slice(5, f.indexOf(";")) }));
- const answer = parsePromptAnswer(await llmText(PROMPT_SYSTEM, promptRequest({ hint: body.hint, frames: images.length, seconds: body.seconds }), images, { ollamaOnly: body.engine === "open" }));
+ let by: PromptAnswer["by"] = local ? "local" : "claude";
+ const answer = parsePromptAnswer(
+ await llmText(PROMPT_SYSTEM, promptRequest({ hint: body.hint, frames: images.length, seconds: body.seconds }), images, {
+ ollamaOnly: body.engine === "open",
+ task: "restore",
+ waitMs: 45_000,
+ onAnswer: (who) => (by = who),
+ }),
+ );
if (!answer) return offline(local ? `${localLabel()} didn't answer (it needs a model that sees pictures for the frames: qwen3-vl, gemma3…)` : "the text model didn't answer");
- return { ...answer, by: local ? "local" : "claude" };
+ return { ...answer, by };
}
// ---------------------------------------------------------------------------
diff --git a/src/server/text-helper.ts b/src/server/text-helper.ts
index 91e1b611..5ee04bbd 100644
--- a/src/server/text-helper.ts
+++ b/src/server/text-helper.ts
@@ -1,5 +1,6 @@
import "server-only";
import crypto from "node:crypto";
+import sharp from "sharp";
import { hoursAt, parseHours } from "@/lib/worker-hours";
import { db } from "./db";
import { hostedRunsOn } from "./hosted-switch";
@@ -14,7 +15,7 @@ import type { WorkerRow } from "./computer/workers";
* GPU job; the caller waits for the answer, and the row is deleted once read.
*/
-export type HelperTask = "lyrics" | "enhance" | "soul" | "write" | "translate";
+export type HelperTask = "lyrics" | "enhance" | "soul" | "write" | "translate" | "describe" | "restore" | "recipe";
/** The most tokens a task may write. */
export const HELPER_TASKS: Record<HelperTask, { maxTokens: number }> = {
@@ -23,6 +24,9 @@ export const HELPER_TASKS: Record<HelperTask, { maxTokens: number }> = {
soul: { maxTokens: 400 },
write: { maxTokens: 4000 },
translate: { maxTokens: 4000 },
+ describe: { maxTokens: 200 },
+ restore: { maxTokens: 500 },
+ recipe: { maxTokens: 1500 },
};
export const isHelperTask = (v: unknown): v is HelperTask => typeof v === "string" && Object.hasOwn(HELPER_TASKS, v);
@@ -50,6 +54,8 @@ export const HELPER_LIMITS = {
waitingEach: 2,
guest: { perMinute: 4, perHour: 20 },
account: { perMinute: 8, perHour: 60 },
+ /** 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 },
};
/** Whose job: "owner", "acct:<id>", or "guest:<address key>". */
@@ -78,6 +84,7 @@ interface JobRow {
done_at: number | null;
text: string | null;
error: string | null;
+ images_json: string | null;
}
/** A job as a text slot gets it. */
@@ -89,6 +96,8 @@ export interface HelperJob {
user: string;
maxTokens: number;
json: boolean;
+ /** Small JPEGs, as base64, for a slot whose model sees pictures. */
+ images?: string[];
}
const json = <T,>(s: string | null, fallback: T): T => {
@@ -113,16 +122,46 @@ 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. */
-export function helperLive(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 {
const rows = db()
- .prepare("SELECT w.* FROM helper_slots s JOIN relay_workers w ON w.id = s.worker_id WHERE s.seen_at >= ?")
+ .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" : ""}`)
.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);
+export const freeHelperOn = (now = Date.now(), o: { vision?: boolean } = {}): boolean => (!tenant() || hostedRunsOn()) && helperLive(now, o);
+
+/**
+ * Pictures as the helper takes them: at most four, each from a file the caller already read for the person, made again
+ * as a JPEG of at most 1024 px on its long side, with no metadata. Null when one can't be read or stays too big.
+ */
+export async function helperPictures(images: { data: Buffer; contentType: string }[]): Promise<string[] | null> {
+ const p = HELPER_LIMITS.pictures;
+ if (images.length > p.count || images.some((i) => !/^image\/(png|jpeg|webp|gif)$/.test(i.contentType) || i.data.length > p.inputBytes)) return null;
+ const out: string[] = [];
+ for (const i of images) {
+ let jpeg: Buffer | null = null;
+ for (const quality of [82, 65, 50]) {
+ const b = await sharp(i.data, { animated: false, limitInputPixels: 64 * 2 ** 20 })
+ .rotate()
+ .resize({ width: p.longEdge, height: p.longEdge, fit: "inside", withoutEnlargement: true })
+ .flatten({ background: "#ffffff" })
+ .jpeg({ quality })
+ .toBuffer()
+ .catch(() => null);
+ if (!b) return null;
+ if (b.length <= p.outputBytes) {
+ jpeg = b;
+ break;
+ }
+ }
+ if (!jpeg) return null;
+ out.push(jpeg.toString("base64"));
+ }
+ return out;
+}
/** The install has a text slot (one asked for a job today). */
export function helperKnown(now = Date.now()): boolean {
@@ -138,24 +177,31 @@ export function sweepHelper(now = Date.now()): void {
* 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 {
+export function claimHelperJob(w: WorkerRow, slot: { model?: unknown; device?: unknown; vision?: 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 vision = slot.vision === 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);
+ }
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;
+ // 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;
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 };
+ 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 }) };
}).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();
+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();
/** 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();
@@ -182,6 +228,8 @@ export interface AskHelper {
system: string;
user: string;
json?: boolean;
+ /** Pictures for a model that sees them (only a slot that does takes the job). */
+ images?: { data: Buffer; contentType: string }[];
who?: HelperWho;
/** False: a step of a run, which the run's own limits already count. */
counted?: boolean;
@@ -199,7 +247,10 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {
const who = o.who ?? helperWho();
const d = db();
sweepHelper(now());
- if (!helperLive(now())) return { error: "busy" };
+ const vision = !!o.images?.length;
+ if (!helperLive(now(), { vision })) 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) {
@@ -217,17 +268,17 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {
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 },
+ 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: pictures?.length ?? 0, video: 0, audio: 0 }, lane: null, providerUsd: null },
prompt: user,
negative: null,
- inputs: [],
+ inputs: (pictures ?? []).map((b, n) => ({ n, kind: "image" as const, sha256: crypto.createHash("sha256").update(Buffer.from(b, "base64")).digest("hex"), preview: null })),
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(
+ d.prepare("INSERT INTO helper_jobs (id, who, task, system, user, max_tokens, json, state, created_at, images_json) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?, ?)").run(
id,
who,
o.task,
@@ -236,6 +287,7 @@ export async function askHelper(o: AskHelper): Promise<HelperAnswer> {
HELPER_TASKS[o.task].maxTokens,
o.json ? 1 : 0,
created,
+ pictures ? JSON.stringify(pictures) : null,
);
const waitMs = o.waitMs ?? 45_000;
const drop = () => d.prepare("DELETE FROM helper_jobs WHERE id = ?").run(id);
diff --git a/tests/text-helper.test.ts b/tests/text-helper.test.ts
index dc6c7e23..a06843d9 100644
--- a/tests/text-helper.test.ts
+++ b/tests/text-helper.test.ts
@@ -6,6 +6,7 @@
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
+import sharp from "sharp";
import { tempDir } from "./helpers/temp-dir";
vi.setConfig({ testTimeout: 30_000 });
@@ -31,6 +32,7 @@ const enhanceRoute = await import("@/app/api/enhance/route");
const claimRoute = await import("@/app/api/gpu/computer/text/claim/route");
const resultRoute = await import("@/app/api/gpu/computer/text/[id]/route");
const { proxy } = await import("@/proxy");
+const { writeRestorePrompt } = await import("@/server/restore");
type WorkerRow = import("@/server/computer/workers").WorkerRow;
type W = { id: string; token: string };
@@ -48,22 +50,22 @@ 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) {
+async function nextJob(w: W, ms = 5000, vision = false) {
const end = Date.now() + ms;
for (;;) {
- const job = helper.claimHelperJob(workerRow(w), { model: "test", device: "gpu" });
+ const job = helper.claimHelperJob(workerRow(w), { model: "test", device: "gpu", vision });
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) {
+function standIn(w: W, answer: (job: NonNullable<Awaited<ReturnType<typeof nextJob>>>) => string, vision = false) {
let on = true;
const seen: string[] = [];
const done = (async () => {
while (on) {
- const job = helper.claimHelperJob(workerRow(w), { model: "test", device: "gpu" });
+ const job = helper.claimHelperJob(workerRow(w), { model: "test", device: "gpu", vision });
if (job) {
seen.push(job.task);
helper.finishHelperJob(workerRow(w), job.id, { lease: job.lease, text: answer(job) });
@@ -182,6 +184,57 @@ describe("the text slots' line", () => {
});
});
+describe("pictures for a slot that sees them", () => {
+ const big = () => sharp({ create: { width: 3000, height: 2000, channels: 3, background: "#c33" } }).png().toBuffer();
+
+ it("only a slot whose model sees pictures takes the job, which carries them as JPEGs of at most 1024 px", async () => {
+ const text = addWorker();
+ const sees = addWorker();
+ helper.claimHelperJob(workerRow(text), { vision: false });
+ expect(helper.helperLive(Date.now(), { vision: true })).toBe(false);
+ expect(await helper.askHelper({ task: "describe", system: "s", user: "Describe her.", images: [{ data: await big(), contentType: "image/png" }] })).toEqual({ error: "busy" });
+ helper.claimHelperJob(workerRow(sees), { vision: true });
+ const asked = helper.askHelper({ task: "describe", system: "s", user: "Describe her.", images: [{ data: await big(), contentType: "image/png" }] });
+ await new Promise((r) => setTimeout(r, 50));
+ expect(helper.claimHelperJob(workerRow(text), { vision: false })).toBeNull();
+ const job = await nextJob(sees, 5000, true);
+ expect(job?.images).toHaveLength(1);
+ const meta = await sharp(Buffer.from(job!.images![0], "base64")).metadata();
+ expect(meta).toMatchObject({ format: "jpeg", width: 1024, height: 683 });
+ expect(meta.exif).toBeUndefined();
+ helper.finishHelperJob(workerRow(sees), job!.id, { lease: job!.lease, text: "a woman in red" });
+ expect(await asked).toEqual({ text: "a woman in red" });
+ });
+
+ it("refuses more than four pictures, or a file that isn't a picture", async () => {
+ const w = addWorker();
+ helper.claimHelperJob(workerRow(w), { vision: true });
+ const png = await big();
+ expect(await helper.helperPictures(Array(5).fill({ data: png, contentType: "image/png" }))).toBeNull();
+ expect(await helper.helperPictures([{ data: Buffer.from("<svg/>"), contentType: "image/svg+xml" }])).toBeNull();
+ expect(await helper.helperPictures([{ data: Buffer.from("not a png"), contentType: "image/png" }])).toBeNull();
+ });
+
+ it("a picture task: the free helper when its model sees them, the words alone where pictures are optional, else no answer", async () => {
+ const pic = [{ data: await big(), contentType: "image/png" }];
+ const w = addWorker();
+ const words = standIn(w, (job) => `saw ${job.images?.length ?? 0}`);
+ expect(await llmText("s", "u", pic, { task: "describe" })).toBeNull();
+ expect(await llmText("s", "u", pic, { task: "recipe", imagesOptional: true })).toBe("saw 0");
+ await words.stop();
+ db().prepare("DELETE FROM helper_slots").run();
+ const sees = standIn(w, (job) => (job.task === "restore" ? "PROMPT: a 1950s street in Mumbai, soft daylight\nNEGATIVE: cars, phones" : `saw ${job.images?.length ?? 0}`), true);
+ let by = "";
+ expect(await llmText("s", "u", pic, { task: "describe", onAnswer: (b) => (by = b) })).toBe("saw 1");
+ expect(by).toBe("free");
+ // Restore's prompt writer for the owner, with no Claude key and no local model: the free helper reads the frames.
+ const frame = `data:image/jpeg;base64,${(await sharp(await big()).jpeg().resize(320).toBuffer()).toString("base64")}`;
+ const r = await writeRestorePrompt({ engine: "cloud", frames: [frame], hint: "1950s Mumbai" });
+ expect(r).toMatchObject({ by: "free", prompt: expect.stringContaining("1950s street") });
+ await sees.stop();
+ });
+});
+
describe("the text slot's routes", () => {
const auth_ = (w: W) => ({ authorization: `Bearer ${w.token}` });
diff --git a/tests/worker-text-slot.test.ts b/tests/worker-text-slot.test.ts
index a3bca045..57994809 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, fileMatches, jobOf, serverArgs, TEXT_MODEL, TextSlot, textSlotOf } from "../bin/lib/worker/text.mjs";
+import { chatBody, cudaMbOf, familyOf, fileMatches, jobOf, modelName, serverArgs, TextSlot, textSlotOf } from "../bin/lib/worker/text.mjs";
import { tempDir } from "./helpers/temp-dir";
vi.setConfig({ testTimeout: 30_000 });
@@ -21,6 +21,11 @@ const sha = (b: Buffer | string) => crypto.createHash("sha256").update(b).digest
const MODEL = Buffer.from("GGUF stand-in model bytes");
const modelFile = path.join(dir, "model.gguf");
fs.writeFileSync(modelFile, MODEL);
+const PROJ = Buffer.from("mmproj stand-in bytes");
+const projFile = path.join(dir, "mmproj.gguf");
+fs.writeFileSync(projFile, PROJ);
+/** A tiny JPEG's base64 (what the studio sends a slot that sees pictures). */
+const JPEG_B64 = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1]).toString("base64");
/** A stand-in llama-server: its buffers on stderr, /health and /v1/chat/completions behind its key, the request echoed back. */
const FAKE = `
@@ -37,7 +42,9 @@ http.createServer((req, res) => {
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 });
+ 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 } }] }));
});
@@ -61,7 +68,7 @@ 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 }[]) {
+function studio(line: { id: string; lease: string; user: string; maxTokens: number; system?: string; json?: boolean; images?: string[] }[]) {
const answers: { id: string; body: Record<string, unknown> }[] = [];
const claims: Record<string, unknown>[] = [];
const call = async (p: string, init: RequestInit = {}) => {
@@ -86,8 +93,8 @@ 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 })!;
+function makeSlot(call: (p: string, init?: RequestInit) => Promise<Response>, o: { sha256?: string; clock?: { t: number }; extra?: Record<string, unknown> } = {}) {
+ const slot = textSlotOf({ server: fakeFile, model: modelFile, sha256: o.sha256 ?? sha(MODEL), idleMin: 1, ...o.extra })!;
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 }) });
@@ -113,20 +120,52 @@ describe("the text slot's parts", () => {
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("with only a model folder, runs Gemma 4 E2B-it with its projector, pinned by SHA-256; worker.json's own files win", () => {
+ const d = textSlotOf({ server: "s", modelDir: "X:/llm" })!;
+ expect(d).toMatchObject({ model: path.join("X:/llm", "gemma-4-E2B-it-Q6_K.gguf"), sha256: "f7b8980ecc1c115898fd8d9a3d421d90becbac984194a44b478669c26815843d", mmproj: path.join("X:/llm", "mmproj-F16.gguf"), mmprojSha256: "140be8d7849741f88c50757d529b84373ee8e27052cc2236855b537f4a8215fa" });
+ expect(familyOf(d)).toMatchObject({ kwargs: { enable_thinking: false }, sampling: { temperature: 1, top_p: 0.95, top_k: 64 } });
+ const own = textSlotOf({ server: "s", modelDir: "X:/llm", model: "X:/llm/custom.gguf", sha256: "e".repeat(64) })!;
+ expect(own).toMatchObject({ model: "X:/llm/custom.gguf", mmproj: path.join("X:/llm", "mmproj-F16.gguf") });
+ expect(textSlotOf({ server: "s", modelDir: "X:/llm", model: "X:/llm/other.gguf" })).toEqual({ problem: expect.stringContaining("sha256") });
+ });
+
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).toEqual(expect.arrayContaining(["--host", "127.0.0.1", "--port", "31000", "--api-key", "k", "--jinja", "--no-webui", "--alias", "m"]));
+ expect(gpu).not.toContain("--mmproj");
+ const vl = textSlotOf({ server: "s", model: "X:/llm/Qwen3VL-8B-Instruct-Q4_K_M.gguf", sha256: "a".repeat(64), mmproj: "X:/llm/mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf", mmprojSha256: "b".repeat(64) })!;
+ const withProj = serverArgs(vl, { port: 31000, key: "k", device: "gpu" });
+ expect(withProj[withProj.indexOf("--mmproj") + 1]).toBe("X:/llm/mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf");
+ expect(withProj[withProj.indexOf("--alias") + 1]).toBe("qwen3vl-8b-instruct-q4_k_m");
+ expect(textSlotOf({ server: "s", model: "m", sha256: "a".repeat(64), mmproj: "p.gguf" })).toEqual({ problem: expect.stringContaining("mmprojSha256") });
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 });
+ it("asks each family with its own template switches and sampling, pictures before the words; a job that isn't one is dropped", () => {
+ const job = { id: "j", lease: "l", system: "S", user: "U", maxTokens: 300, json: true, images: [] };
+ const b = chatBody(job, { model: "X:/llm/Nemotron-3.5-Bolt-E4B-Q4_K_M.gguf" });
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(chatBody(job, { model: "gemma-4-E4B-it-Q4_0.gguf" })).toMatchObject({ top_k: 64, chat_template_kwargs: { enable_thinking: false } });
+ // Qwen3-VL Instruct has no thinking switch: none is sent.
+ const qwen = chatBody({ ...job, images: [JPEG_B64] }, { model: "Qwen3VL-4B-Instruct-Q4_K_M.gguf" });
+ expect(qwen).not.toHaveProperty("chat_template_kwargs");
+ 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(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 } });
+ expect(one([JPEG_B64])?.images).toEqual([JPEG_B64]);
+ expect(one(["https://example.com/a.jpg"])).toBeNull();
+ expect(one(["file:///C:/secret.jpg"])).toBeNull();
+ expect(one([Buffer.from("PNG...").toString("base64")])).toBeNull();
+ expect(one(Array(5).fill(JPEG_B64))).toBeNull();
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();
@@ -176,9 +215,9 @@ describe("the text slot", () => {
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).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: TEXT_MODEL, device: "gpu" });
+ expect(site.claims[0]).toMatchObject({ model: "model", device: "gpu", vision: false });
expect(s.own().pids).toHaveLength(1);
expect(s.own().mb).toBe(3698);
});
@@ -204,6 +243,30 @@ describe("the text slot", () => {
expect(logs.join("\n")).toContain("frees its memory");
});
+ it("with mmproj it says it sees pictures, starts its server with the projector and sends the pictures", async () => {
+ const site = studio([{ id: "hlp_v", lease: "Lv", user: "Describe her.", maxTokens: 100, images: [JPEG_B64] }]);
+ const { s } = makeSlot(site.call, { extra: { mmproj: projFile, mmprojSha256: sha(PROJ), name: "Qwen3VL-8B-Instruct" } });
+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 1);
+ expect(site.claims[0]).toMatchObject({ model: "qwen3vl-8b-instruct", vision: true });
+ const said = JSON.parse(String(site.answers[0].body.text));
+ expect(said).toMatchObject({ mmproj: true, kwargs: null, temperature: 0.7, user: "Describe her.", pictures: ["data:image/jpeg;base64,"] });
+ const bad = studio([]);
+ const { s: off, logs } = makeSlot(bad.call, { extra: { mmproj: projFile, mmprojSha256: "d".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));
+ }
+ expect(off.ok).toBe(false);
+ expect(logs.join("\n")).toContain("mmproj");
+ });
+
+ it("a picture job on a slot without mmproj gets no answer, only why", async () => {
+ const site = studio([{ id: "hlp_t", lease: "Lt", user: "Describe her.", maxTokens: 100, images: [JPEG_B64] }]);
+ const { s } = makeSlot(site.call);
+ await until(s, Date.now, { may: true, room: "cpu" }, () => site.answers.length === 1);
+ expect(site.answers[0].body).toEqual({ lease: "Lt", error: "this slot's model doesn't take pictures" });
+ });
+
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);