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.

New hosted models run for the owner until their first live call; stems saved to disk

Adarsh12cb622f48f1
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index a90a4099..e624f59c 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -515,7 +515,7 @@ SQLite (WAL). Migrations are an append-only list in `db.ts`, applied once each a
| 22 | no table (round 4 part 5, O7): deletes the saved Higgsfield key (`higgsfield.key`), turns a `cloud.provider` of `higgsfield` into `auto`, and marks Higgsfield ads `baked` (`ad_batches.route`, and `route` in `ad_creatives.meta_json` where that is valid JSON) |
| 23 | main's GPU pre-flight: `gpu_snapshots` (what a ComfyUI had at its last check, per target, the install or an account's own GPU, and per way it was read; only the facts the requirement index asks about), `gpu_audit` (every check) with index `gpu_audit_target`, and `generations.fix_json` (what a failed run was missing, so its tile offers "Fix it") |
| 24 | main's public sign-up: `assets.account_id` (an account's uploads and the files of its runs carry its id, the owner's stay NULL; files made before go by the run that made them) and indexes `assets_account`, `assets_rel` and `assets_generation` |
-| 26 | `assist_schedules.skill_json` (Skills W4: a task that runs a saved skill instead of a request, `{ name, values, sources }`: one set of the recipe's inputs as text, a file as its `/api/files/…` URL, and the file inputs that take the newest upload of their kind when the run starts; NULL for a request). It only adds a column, so an older build can still open the database; the column is in `ASSET_REFS`, so a file a task names survives Empty trash |
+| 26 | `assist_schedules.skill_json` (a task that runs a saved skill instead of a request, `{ name, values, sources }`: one set of the recipe's inputs as text, a file as its `/api/files/…` URL, and the file inputs that take the newest upload of their kind when the run starts; NULL for a request). It only adds a column, so an older build can still open the database; the column is in `ASSET_REFS`, so a file a task names survives Empty trash |
Round 4 part 3 adds no migration. It changes what some existing columns hold: `canvases.graph_json` is written as `{pages: [{id, name, graph}]}` and a row saved before reads as page 1 (`readPages`) until it is saved again (an older build can't read a board after that save); `runs_json`'s node runs gain `out`, `rows` and `rowSigs`; `generations.request_json` keeps the engine a Fuobe Original ran on; and output meta gains `finished`, `original`, `grade`, `overlay` and `crop`, with `meta.formats` and `meta.preview` now stored as local files.
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 3b2dfb00..abdd21f4 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -207,6 +207,14 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
menus don't offer Remove dialogue or Clean up dialogue to a guest or an account. Restore & colourise
and Remove a person (its mask preview and "Redo from here", `POST /api/remove-object/preview` and
`/reroll`, answer `own-gpu-tool` too) are left out of the Video tools tabs and the result menus for them.
+ A hosted model whose calls haven't yet passed a live run with a real key (`src/lib/catalog/hosted-untested.ts`:
+ MiniMax H3 Max's lip sync, relight, insert, looks and Turbo, H3 Lite and HighSpeed, Vidu Q4, the Mureka songs and
+ song tools, MiniMax Music 3, ElevenLabs Music, Lyria 3.5, the hosted voice cleaners, Meshy retexture, Tripo P2 and
+ Fuobe Animation's cloud half) answers `own-gpu-tool` for a guest or an account, even on its own key, and is left out
+ of its pickers; Audio → Extend & remix is left out of the Audio tabs. Each opens once a live call passes.
+ "Write the lyrics" and "Rewrite my prompt now" use the studio's AI helper and are hidden from guests and accounts.
+ A song's stems come back as one zip: for an account it is fetched from public addresses only, within what its files
+ have room for (128 MB at most, 256 MB unpacked), and each stem is saved to disk as it is unpacked.
- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.
A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403
(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.
diff --git a/src/components/studio/lyrics-editor.tsx b/src/components/studio/lyrics-editor.tsx
index 4102347e..478726c2 100644
--- a/src/components/studio/lyrics-editor.tsx
+++ b/src/components/studio/lyrics-editor.tsx
@@ -3,7 +3,7 @@
import { Loader2, Music2, PenLine, Sparkles, X } from "lucide-react";
import { useId, useRef, useState } from "react";
import { toast } from "sonner";
-import { writeLyrics } from "@/lib/api";
+import { useLikelyVisitor, writeLyrics } from "@/lib/api";
import type { ModelDef } from "@/lib/catalog/types";
import { INSTRUMENTAL, insertTag, isInstrumental, normalizeLyrics, promptWithLyrics, SECTION_TAGS, songLength, structureOf } from "@/lib/lyrics";
import { toastError } from "@/lib/refusals";
@@ -35,6 +35,8 @@ export function LyricsEditor({
const id = useId();
const area = useRef<HTMLTextAreaElement>(null);
const [writing, setWriting] = useState(false);
+ // "Write the lyrics" uses the install's AI helper, which guests and accounts can't call.
+ const visitor = useLikelyVisitor();
const spec = model.options.lyrics ?? {};
// Lyrics read after the description (Lyria 3.5) count with it.
const length = spec.inPrompt && value.trim() ? promptWithLyrics(idea, value).length : normalizeLyrics(value).length;
@@ -74,15 +76,17 @@ export function LyricsEditor({
{!spec.required && <span className="font-normal text-muted-foreground">optional</span>}
</label>
<span className="ml-auto flex items-center gap-1">
- <button
- type="button"
- onClick={write}
- disabled={writing}
- className="inline-flex h-7 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium text-brand-text hover:bg-brand-faint disabled:opacity-60"
- >
- {writing ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}
- {writing ? "Writing…" : "Write the lyrics"}
- </button>
+ {!visitor && (
+ <button
+ type="button"
+ onClick={write}
+ disabled={writing}
+ className="inline-flex h-7 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium text-brand-text hover:bg-brand-faint disabled:opacity-60"
+ >
+ {writing ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}
+ {writing ? "Writing…" : "Write the lyrics"}
+ </button>
+ )}
{!spec.required && !spec.instrumentalModel && (
<button
type="button"
diff --git a/src/components/studio/settings-panel.tsx b/src/components/studio/settings-panel.tsx
index 6c102f09..14a62946 100644
--- a/src/components/studio/settings-panel.tsx
+++ b/src/components/studio/settings-panel.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
+import { useLikelyVisitor } from "@/lib/api";
import { FORMAT_INFO } from "@/lib/av/formats";
import { OPERATION_LABELS, type GenParams, type ModelDef, type Operation, type VideoFormat } from "@/lib/catalog/types";
import { colormapLabel, durationLabel, formatOf, hiddenChanges, MATTE_OUTPUT_LABELS, settingsSummary, videoToolNote, type SettingsShape } from "@/lib/composer";
@@ -236,6 +237,8 @@ function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePro
const opts = model?.options ?? {};
const d = model?.defaults ?? {};
const [advanced, setAdvanced] = useState(p.seed !== undefined || !!negativePrompt);
+ // "Rewrite my prompt now" uses the install's AI helper, which guests and accounts can't call.
+ const visitor = useLikelyVisitor();
return (
<div className="space-y-4">
{extras && <div className="flex flex-wrap gap-1.5 sm:hidden">{extras}</div>}
@@ -342,14 +345,16 @@ function SettingsBody({ model, op, shape, params: p, setP, setExtra, negativePro
)}
{shape.enhance && (
<Toggle label="Enhance prompt" hint="Rewrites your prompt with more detail before it runs" checked={!!p.enhancePrompt} onChange={(v) => setP({ enhancePrompt: v })}>
- <button
- type="button"
- onClick={onRewrite}
- disabled={enhancing}
- className="mt-1 inline-flex items-center gap-1 rounded text-[12px] font-medium text-brand-text outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-60"
- >
- {enhancing ? <Loader2 className="size-3 animate-spin" /> : <Wand2 className="size-3" />} Rewrite my prompt now
- </button>
+ {!visitor && (
+ <button
+ type="button"
+ onClick={onRewrite}
+ disabled={enhancing}
+ className="mt-1 inline-flex items-center gap-1 rounded text-[12px] font-medium text-brand-text outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-60"
+ >
+ {enhancing ? <Loader2 className="size-3 animate-spin" /> : <Wand2 className="size-3" />} Rewrite my prompt now
+ </button>
+ )}
</Toggle>
)}
</div>
diff --git a/src/lib/catalog/hosted-untested.ts b/src/lib/catalog/hosted-untested.ts
new file mode 100644
index 00000000..53afa8c0
--- /dev/null
+++ b/src/lib/catalog/hosted-untested.ts
@@ -0,0 +1,85 @@
+/**
+ * Hosted routes whose requests have not yet been sent with a real key: their payloads follow the providers' schemas
+ * and are unit-tested, but no live call has passed. They run for the owner; for an account (on its own fal.ai or
+ * Replicate key) they open once a live call passes and the entry is taken off these lists. Until then a visitor's run
+ * is refused (`own-gpu-tool`, generations.ts) and the models are left out of its pickers (hostedUntestedSummary).
+ * Pure data and logic (client and server).
+ */
+import type { AccessSummary } from "../model-access";
+import type { Engine, ModelDef, ModelRoute } from "./types";
+
+/** Endpoints, on any model that uses them. */
+export const HOSTED_UNTESTED_ENDPOINTS: ReadonlySet<string> = new Set([
+ // MiniMax H3 Max: lip sync, relight, insert, the five looks, Turbo; H3 Lite and HighSpeed (Replicate).
+ "minimax/h3-max/lip-sync/image-to-video",
+ "minimax/h3-max/relight",
+ "minimax/h3-max/insert-video",
+ "minimax/h3-max/styles/16bit-pixel",
+ "minimax/h3-max/styles/hand-drawn",
+ "minimax/h3-max/styles/low-poly",
+ "minimax/h3-max/styles/retro-toon-70s",
+ "minimax/h3-max/styles/vhs",
+ "minimax/h3-max-turbo/text-to-video",
+ "minimax/h3-max-turbo/image-to-video",
+ "minimax/h3-max-turbo/reference-to-video",
+ "minimax/h3-max-turbo/extend-video",
+ "minimax/h3-lite",
+ "minimax/h3-highspeed",
+ // Vidu Q4.
+ "fal-ai/vidu/q4/image-to-video",
+ "fal-ai/vidu/q4/reference-to-video",
+ // Songs: Mureka 9 / 9.5 / 8 and its song tools (extend, remix, stems, the upload they send a song through first),
+ // MiniMax Music 3, ElevenLabs Music v2.5, Lyria 3.5.
+ "mureka/v9.5/generate/song",
+ "mureka/v9/generate/song",
+ "mureka/v9.5/generate/instrumental",
+ "mureka/v9/generate/instrumental",
+ "mureka/v8/song/extend",
+ "mureka/v8/song/remix",
+ "mureka/api/song/stem",
+ "mureka/api/files/upload",
+ "minimax/music-3",
+ "elevenlabs/music/v2.5",
+ "google/lyria-3.5",
+ // Voice cleaners.
+ "veed/clean-audio",
+ "fal-ai/deepfilternet3",
+ // 3D: Idol, Meshy retexture, Tripo P2.
+ "speridlabs/idol",
+ "meshy/v7/retexture",
+ "meshy/v6/retexture",
+ "tripo3d/p2/image-to-3d",
+]);
+
+/** Models whose hosted routes are new even where the endpoint isn't (Fuobe Animation's LoRA run on Wan 2.2 A14B). */
+export const HOSTED_UNTESTED_MODELS: ReadonlySet<string> = new Set(["fuobe-animation"]);
+
+const hosted = (r: Pick<ModelRoute, "provider">) => r.provider === "fal" || r.provider === "replicate";
+
+/** Whether this route of this model is a hosted call that hasn't been sent with a real key yet. */
+export function hostedUntested(modelId: string, route: Pick<ModelRoute, "provider" | "endpoint">): boolean {
+ return hosted(route) && (HOSTED_UNTESTED_ENDPOINTS.has(route.endpoint) || HOSTED_UNTESTED_MODELS.has(modelId));
+}
+
+/**
+ * A visitor's picker summary with these left out: a model with nothing else to run on is off; a Fuobe Original whose
+ * cloud half is all untested keeps its other engine.
+ */
+export function hostedUntestedSummary(models: ModelDef[], base: AccessSummary | undefined): AccessSummary {
+ const off = new Set(base?.off ?? []);
+ const engines: Record<string, Engine[]> = { ...(base?.engines ?? {}) };
+ for (const m of models) {
+ if (off.has(m.id) || !m.routes.some((r) => hostedUntested(m.id, r))) continue;
+ const left = m.routes.filter((r) => !hostedUntested(m.id, r));
+ if (!left.length) {
+ off.add(m.id);
+ continue;
+ }
+ if (m.engines && m.engines.length > 1 && !left.some(hosted)) {
+ const on = (engines[m.id] ?? m.engines).filter((e) => e !== "cloud");
+ if (on.length) engines[m.id] = on;
+ else off.add(m.id);
+ }
+ }
+ return { off: [...off], ...(Object.keys(engines).length && { engines }) };
+}
diff --git a/src/lib/hubs.ts b/src/lib/hubs.ts
index abbf3822..da50c7ce 100644
--- a/src/lib/hubs.ts
+++ b/src/lib/hubs.ts
@@ -38,7 +38,7 @@ export const HUB_MODES: Record<HubKind, HubMode[]> = {
{ id: "split", label: "Split soundtrack", selfHostedOnly: true },
{ id: "sfx", label: "Sound effects" },
{ id: "music", label: "Music" },
- { id: "song", label: "Extend & remix" },
+ { id: "song", label: "Extend & remix", ownerOnly: true },
{ id: "loop", label: "Loop / extend" },
{ id: "join", label: "Join" },
{ id: "video", label: "Sound for video" },
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 799dda1b..0871b516 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -7,6 +7,8 @@ import { accountGpu, type Account, type AccountGpu } from "./auth";
import type { OwnerGpuView } from "@/lib/connections";
import { runnerFacts, type Principal } from "./computer/tasks";
import { offeredSummary } from "./model-access";
+import { MODELS } from "@/lib/catalog";
+import { hostedUntestedSummary } from "@/lib/catalog/hosted-untested";
import { PROVIDERS } from "./providers";
import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
@@ -215,7 +217,8 @@ export async function visitorStatus(account: Account | null) {
if (b) viewer.balance = b;
}
const configured = (id: string) => (id === "comfyui" ? (gpu ? !!live?.online : true) : isCloudProvider(id) && keys.includes(id));
- const access = keys.length ? offeredSummary() : undefined;
+ // With keys: the hosted routes no live call has passed yet are left out too (they run for the owner only).
+ const access = keys.length ? hostedUntestedSummary(MODELS, offeredSummary()) : undefined;
return {
providers: Object.fromEntries(Object.values(PROVIDERS).map((p) => [p.id, { label: p.id === "comfyui" ? "Your GPU" : p.label, configured: configured(p.id) }])),
demoMode: "off",
diff --git a/src/server/assist/schedules.ts b/src/server/assist/schedules.ts
index 180995ac..4dc5c7dd 100644
--- a/src/server/assist/schedules.ts
+++ b/src/server/assist/schedules.ts
@@ -40,7 +40,7 @@ import { getProject } from "./projects";
* Claude's reply, where neither mode can hold them back.
* A run the server missed (it was off) happens once when it's back, not once per missed time.
*
- * A task can run a saved skill instead (Skills W4, `skill`): each run is still a chat, with the same approval and cap,
+ * A task can run a saved skill instead (`skill`): each run is still a chat, with the same approval and cap,
* but no model plans it — a fixed reply (skillCall) makes one run_skill call with the task's values, and a file input
* set to "newest upload" reads the newest upload of its kind when the run starts.
*/
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 69b8af5f..ad78142d 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -88,6 +88,7 @@ import type { PollContext, PollResult, ProviderAdapter, RemoteOutput } from "./p
import { mediaFacts } from "./media-facts";
import { renderPathVideo } from "./path-render";
import { songFormat, songToolProblem } from "@/lib/lyrics";
+import { hostedUntested } from "@/lib/catalog/hosted-untested";
import { modelToFinish, startModelFinish, startTurntable, stopModelFinish, type OutputStore } from "./model3d-finish";
import { cropPicture, isCropWindow } from "./crop-picture";
import { convertMask, decodePng, encodePng } from "./png";
@@ -99,7 +100,7 @@ import { placeInLine, poolWaitMs, runOnPool } from "./hosted";
import { sweepBilling } from "./billing-outbox";
import { moderationConfigured } from "./moderation";
import { holdForCheck, sweepOutputChecks } from "./output-checks";
-import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
+import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir, scratchOutputFile } from "./storage";
interface Row {
id: string;
@@ -718,6 +719,17 @@ function portraitProblem(plan: ReturnType<typeof planGeneration>, req: Generatio
*/
export const mentionElements = () => (tenant() ? [] : listElements());
+/**
+ * A guest's or an account's candidates without the hosted routes no live call has passed yet (hosted-untested.ts): those
+ * run for the owner only. With nothing else to run on, the run is refused as a tool that isn't available here.
+ */
+function triedRoutes(m: ModelDef, routes: ModelRoute[]): ModelRoute[] {
+ if (!tenant()) return routes;
+ const tried = routes.filter((r) => !hostedUntested(m.id, r));
+ if (routes.length && !tried.length) throw new AccountRunError({ error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });
+ return tried;
+}
+
/** Resolve mentions and drawings, plan, enforce the engine mode and pick a provider route. */
function prepare(original: GenerationRequest) {
// @element mentions become reference images / LoRAs; the stored request keeps the mentions for "Reuse".
@@ -759,7 +771,7 @@ function prepare(original: GenerationRequest) {
if (access.dropped.length) plan = { ...plan, loras: access.loras, prompt: withoutTriggers(plan.prompt, plan.loras.filter((l) => !access.loras.some((k) => k.file === l.file)), access.loras) };
else if (access.loras.some((l, i) => l !== plan.loras[i])) plan = { ...plan, loras: access.loras };
// A preset can route to another model than the one asked for: its routes that are on (or the switch that's off).
- const { route, demo } = chooseRoute(offeredRoutes(plan.model, routesFor(plan.model, plan.op)), req.inputs?.images?.length ?? 0, plan.loras, seconds, !!worded.demo);
+ const { route, demo } = chooseRoute(triedRoutes(plan.model, offeredRoutes(plan.model, routesFor(plan.model, plan.op))), req.inputs?.images?.length ?? 0, plan.loras, seconds, !!worded.demo);
// Qwen-Image 2.1's Options → Speed loads its speed's LoRA in the graph: that LoRA switched off holds the speed.
const tier = route.provider === "comfyui" ? speedLora(route.endpoint, plan.params.extra) : undefined;
if (tier && offeredLoras([{ file: tier.file }]).dropped.length) {
@@ -2197,6 +2209,11 @@ async function pollOne(r: Row): Promise<void> {
} catch (e) {
if (account) {
for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);
+ // Stems unpacked to the scratch folder and not saved go now, not at the next sweep.
+ for (const rest of res.outputs as RichOutput[]) {
+ const left = rest.url ? scratchOutputFile(rest.url) : null;
+ if (left) fs.rmSync(left, { force: true });
+ }
const why = e instanceof AccountFilesFull ? e.message : "We couldn't save this result. Press Retry.";
update(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null });
return;
@@ -2511,17 +2528,24 @@ async function persistAccountOutput(o: RichOutput, generationId: string, account
};
}
+/** A result the provider already wrote to the scratch folder (a song's stems): the file, as the type the provider gave. */
+function scratchOutput(o: RichOutput): { path: string; contentType?: string } | null {
+ const file = scratchOutputFile(o.url);
+ return file ? { path: file, contentType: o.contentType } : null;
+}
+
/**
- * A result a computer sent in (its task received and checked it, src/server/computer): moved into the files folder as it
- * is, no second copy, as the type its bytes said. An account's counts against its files first.
+ * A result a computer sent in (its task received and checked it, src/server/computer), or one the provider wrote to the
+ * scratch folder: moved into the files folder as it is, no second copy, as the type its bytes said. An account's counts
+ * against its files first (a result over its room is removed).
*/
async function persistRelayOutput(o: RichOutput, generationId: string, account: string | undefined, linked: Record<string, unknown> | undefined): Promise<OutputFile> {
- const file = relayFile(o.url);
+ const file = o.url.startsWith("scratch:") ? scratchOutput(o) : relayFile(o.url);
if (!file) throw new Error("The result isn't here any more");
const from = file.path;
const contentType = o.contentType ?? file.contentType ?? "application/octet-stream";
const size = fs.statSync(from).size;
- if (account) roomFor(account, size);
+ if (account) roomFor(account, size, o.url.startsWith("scratch:") ? from : undefined);
const asset = adoptFile({ from, contentType: account ? accountType(contentType) : contentType, source: "generation", generationId, ...(account && { accountId: account }) });
const meta = relinkMain(linked, o.url, asset.url);
const text = o.text ?? (asset.kind === "text" && asset.size <= MAX_INLINE_TEXT * 4 ? fs.readFileSync(absolutePath(asset.relPath), "utf8") : undefined);
@@ -2538,7 +2562,7 @@ async function persistRelayOutput(o: RichOutput, generationId: string, account:
async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {
const linked = await persistArtifacts(o.meta, generationId, o.url);
const account = tenantAccount();
- if (o.url?.startsWith("relay:")) return persistRelayOutput(o, generationId, account, linked);
+ if (o.url?.startsWith("relay:") || o.url?.startsWith("scratch:")) return persistRelayOutput(o, generationId, account, linked);
if (account && o.url && /^https?:\/\//.test(o.url)) return persistAccountOutput(o, generationId, account, linked);
let data: Buffer;
let contentType = o.contentType;
diff --git a/src/server/gpu/readiness-service.ts b/src/server/gpu/readiness-service.ts
index 4b4700d3..239e8ac5 100644
--- a/src/server/gpu/readiness-service.ts
+++ b/src/server/gpu/readiness-service.ts
@@ -5,8 +5,8 @@ import { fixPlan } from "@/lib/gpu/plan";
import { badgeOf, deviceLabel, needTargets, rankOf, shortGpu, summaryOf, toolReadiness, type ReadinessContext } from "@/lib/gpu/readiness";
import type { BadgeMap, FixPlan, GpuInventory, GpuProblem, ReadinessReport, RequirementIndex, StudioRow, ToolReadiness, ToolRef } from "@/lib/gpu/types";
import { vramGb } from "@/lib/gpu/requirements";
-import { chooseH3Tier, deviceOf, tierOnCard, tierRowNote, H3_TIER_MODEL } from "@/lib/gpu/h3-tier";
-import { isOffered } from "../model-access";
+import { chooseH3Tier, deviceOf, tierOnCard, tierRowNote } from "@/lib/gpu/h3-tier";
+import { tierOpen } from "../h3-gpu";
import { getSetting } from "../settings";
import { loadIndex } from "./index-file";
import { probe, readSnapshot, saveViews, checkWait, type Snapshot } from "./snapshots";
@@ -28,7 +28,7 @@ export function contextFor(t: ReadTarget): ReadinessContext {
* under 32 GB and that build is switched on in Models & licences. A studio row keeps only the modes the build has.
*/
export function onCard(tool: Tool, inv: GpuInventory, idx: RequirementIndex) {
- return tierOnCard(tool.workflows, inv, idx, { studio: tool.ref.startsWith("studio:"), allowed: (tier) => isOffered(H3_TIER_MODEL[tier], "open") });
+ return tierOnCard(tool.workflows, inv, idx, { studio: tool.ref.startsWith("studio:"), allowed: tierOpen });
}
export function readinessOf(tool: Tool, inv: GpuInventory, idx: RequirementIndex, ctx: ReadinessContext): ToolReadiness {
@@ -63,7 +63,7 @@ export function buildViews(inv: GpuInventory, idx: RequirementIndex, ctx: Readin
if (summary.gpu) badges.gpu = shortGpu(summary.gpu);
if (summary.vramGb) badges.vramGb = summary.vramGb;
const h3 = chooseH3Tier(deviceOf(inv)).tier;
- if (h3 !== "standard" && isOffered(H3_TIER_MODEL[h3], "open")) badges.h3Tier = h3;
+ if (h3 !== "standard" && tierOpen(h3)) badges.h3Tier = h3;
for (const tool of openModelTools()) {
const b = badgeOf(readinessOf(tool, inv, idx, ctx));
if (b) badges.models[tool.ref.slice("model:".length)] = b;
diff --git a/src/server/h3-gpu.ts b/src/server/h3-gpu.ts
index 4dbd9176..d2a74761 100644
--- a/src/server/h3-gpu.ts
+++ b/src/server/h3-gpu.ts
@@ -1,10 +1,11 @@
import "server-only";
-import { deviceOf, H3_TIER_GRAPH, H3_TIER_MODEL, h3TierFor, H3_TIER_PARAM, TIER_BEST_NOTE, TIER_DECODER_NOTE, TIER_NOTES, tierChoice, tierGraphFor, tierOfGraph, SOL_VAE, type H3TierChoice } from "@/lib/gpu/h3-tier";
+import { deviceOf, H3_TIER_GRAPH, H3_TIER_MODEL, h3TierFor, H3_TIER_PARAM, TIER_BEST_NOTE, TIER_DECODER_NOTE, TIER_NOTES, tierChoice, tierGraphFor, tierOfGraph, SOL_VAE, type H3Tier, type H3TierChoice } from "@/lib/gpu/h3-tier";
import { getModel } from "@/lib/catalog";
import { preflightOn } from "./gpu/index-file";
import { readSnapshot } from "./gpu/snapshots";
import { runTarget } from "./gpu/target";
import { isOffered, offReason } from "./model-access";
+import { loadManifest } from "./providers/comfyui";
import { tenantAccount } from "./tenant";
/**
@@ -14,7 +15,7 @@ import { tenantAccount } from "./tenant";
* - A tier asked for: that tier, with the file the card's last check calls for (refused, naming the switch, when Settings →
* Models & licences has it off). Trim asked for on a start-frame mode keeps the full model (Trim has text to video only).
* - Auto: the tier the last GPU check's card gets (FastH3 V2 on 16-31 GB, Trim on 12-15 GB or 8-15 GB on Blackwell), when its
- * switch is on; a CPU, no reading, an unknown card, 32 GB or more, or a card no build fits keep the full model, which the
+ * switch is on and ComfyUI has accepted its graph (the manifest's `validated`); a CPU, no reading, an unknown card, 32 GB or more, or a card no build fits keep the full model, which the
* pre-flight then judges as it does today. Auto routes to a smaller build before its files are there: they are pinned and
* the pre-flight offers them, where the full model could never run on that card.
* - An orbit keeps the Orbit LoRA graph (full model only).
@@ -29,6 +30,22 @@ export interface H3GpuChoice {
note?: string;
}
+declare global {
+ /** Tests only: every smaller H3 build's graph counts as accepted. */
+ var __fuobeTestH3Accepted: boolean | undefined;
+}
+
+/** Whether ComfyUI has accepted a graph of the library (the manifest's `validated`). */
+export function acceptedGraph(id: string): boolean {
+ if (process.env.VITEST === "true" && globalThis.__fuobeTestH3Accepted) return true;
+ return loadManifest().workflows.some((w) => w.id === id && w.validated === true);
+}
+
+/** A smaller H3 build Auto may pick: switched on in Models & licences, and every graph of it accepted by ComfyUI. */
+export function tierOpen(tier: Exclude<H3Tier, "standard">): boolean {
+ return isOffered(H3_TIER_MODEL[tier], "open") && Object.values(H3_TIER_GRAPH).every((t) => !t[tier] || acceptedGraph(t[tier]));
+}
+
/** The last GPU check's card for a run in the current scope, when the pre-flight has one. */
function lastCard() {
if (!preflightOn()) return undefined;
@@ -41,7 +58,7 @@ function lastCard() {
* Options → GPU tier for a MiniMax H3 run on `endpoint` (the route's graph before variants), or undefined when the run takes no
* tier either way (another model, an orbit, a graph with no smaller build). A FastH3 graph itself keeps its own tier. `has`: is a graph in the library.
*/
-export function h3Gpu(endpoint: string, extra: Record<string, unknown>, has: (id: string) => boolean): H3GpuChoice | undefined {
+export function h3Gpu(endpoint: string, extra: Record<string, unknown>, has: (id: string) => boolean, validated: (id: string) => boolean = acceptedGraph): H3GpuChoice | undefined {
// A FastH3 graph run directly (its hidden model named in the request): its build is fixed, and the file is still the card's,
// chosen here, never one the request names.
const own = tierOfGraph(endpoint);
@@ -54,6 +71,8 @@ export function h3Gpu(endpoint: string, extra: Record<string, unknown>, has: (id
const graph = tierGraphFor(endpoint, choice.tier, has);
// Trim on a start-frame mode: the tier has no graph for it, so the full model runs.
if (!graph) return { gpuTier: "standard" };
+ // Auto routes to a smaller build only once ComfyUI has accepted its graph; until then only Options → GPU tier runs it.
+ if (asked !== choice.tier && !validated(graph)) return { gpuTier: "standard" };
const model = H3_TIER_MODEL[choice.tier];
if (!isOffered(model, "open")) {
if (asked !== choice.tier) return { gpuTier: "standard" };
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index 0a1f220e..deddd1b4 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -1,10 +1,14 @@
import "server-only";
+import fs from "node:fs";
import { createFalClient } from "@fal-ai/client";
import { loraEndpointFor, routeLoraField } from "@/lib/catalog/loras";
import { buildPayload, extractOutputs, noOutputsError } from "@/lib/catalog/payload";
import { accountKeyError, balanceRefusal, cloudKey, missingKeyError, originOf, redactKey, standIn } from "../provider-keys";
-import { tenant } from "../tenant";
+import { tenant, tenantAccount } from "../tenant";
import { unzip } from "../unzip";
+import { ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";
+import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";
+import { newScratchOutput } from "../storage";
import type { FieldMap } from "@/lib/catalog/types";
import { ProviderError, type ProviderAdapter } from "./types";
@@ -75,30 +79,76 @@ async function bytesWithin(res: Response, max: number): Promise<Buffer> {
return Buffer.concat(chunks, total);
}
-/** The stems a song tool answers with in one zip (Mureka's zip_url), one result each, named by their file (meta.stem). */
+/** An account's stems: a smaller zip and less unpacked than the owner's, and never more than its files have room for. */
+const ACCOUNT_STEMS_MAX_BYTES = 128 * 1024 * 1024;
+const ACCOUNT_STEMS_UNPACKED_BYTES = 256 * 1024 * 1024;
+
+/**
+ * The stems a song tool answers with in one zip (Mureka's zip_url), one result each, named by their file (meta.stem).
+ * Each stem is written to the scratch folder as it is unpacked (a `scratch:` result, moved into the run's files when it
+ * is saved), never held as a data: URL. An account's zip comes from public addresses only (fetchPublic), within what its
+ * files have room for.
+ */
export async function stemsFromZip(
zipUrl: string,
limits: { maxBytes?: number; waitMs?: number } = {},
): Promise<{ url: string; kind: "audio"; contentType: string; meta: { stem: string } }[]> {
- const maxBytes = limits.maxBytes ?? STEMS_MAX_BYTES;
+ const account = tenantAccount();
+ let maxBytes = limits.maxBytes ?? (account ? ACCOUNT_STEMS_MAX_BYTES : STEMS_MAX_BYTES);
+ let unpacked = account ? ACCOUNT_STEMS_UNPACKED_BYTES : 2 * maxBytes;
+ let left = Infinity;
+ if (account) {
+ left = accountTotalBytes(account) - accountUsage(account).total;
+ if (left <= 0) throw new Error(filesFullMessage(account));
+ if (!diskHasRoom()) throw new Error(ACCOUNT_MESSAGES.diskLow);
+ maxBytes = Math.min(maxBytes, left);
+ unpacked = Math.min(unpacked, left);
+ }
+ const waitMs = limits.waitMs ?? STEMS_WAIT_MS;
+ const tooBig = () => new Error(account && left <= maxBytes ? filesFullMessage(account) : "The stems download is larger than Fuobe keeps from one result");
let zipped: Buffer;
try {
- const res = await fetch(zipUrl, { signal: AbortSignal.timeout(limits.waitMs ?? STEMS_WAIT_MS) });
- if (!res.ok) throw new Error(`The stems couldn't be downloaded (${res.status})`);
+ // The stand-in fal.ai (tests and `next dev`) is on this machine: only it skips the public-address check.
+ const res =
+ account && originOf(zipUrl) !== standIn("fal")
+ ? await fetchPublic(zipUrl, {}, { maxBytes, deadlineMs: waitMs, timeoutMs: Math.min(waitMs, 60_000) })
+ : await fetch(zipUrl, { signal: AbortSignal.timeout(waitMs) });
+ if (!res.ok) {
+ discardBody(res);
+ throw new Error(`The stems couldn't be downloaded (${res.status})`);
+ }
zipped = await bytesWithin(res, maxBytes);
} catch (e) {
- const name = (e as Error).name;
- if (name === "TimeoutError" || name === "AbortError") throw new Error("The stems took too long to download. Try again.");
+ const err = e as Error;
+ if (err.name === "TimeoutError" || err.name === "AbortError") throw new Error("The stems took too long to download. Try again.");
+ if (err instanceof RemoteFetchError && /took over|Timed out/.test(err.message)) throw new Error("The stems took too long to download. Try again.");
+ if (err instanceof RemoteFetchError && /^The answer was over/.test(err.message)) throw tooBig();
+ if (/^The stems download is larger/.test(err.message)) throw tooBig();
throw e;
}
- const files = (await unzip(zipped, { maxBytes: 2 * maxBytes })).filter((f) => AUDIO_FILE.test(f.name));
- if (!files.length) throw new Error("The stems archive held no audio");
- return files.map((f) => {
- const ext = AUDIO_FILE.exec(f.name)![1].toLowerCase();
- const contentType = AUDIO_TYPES[ext] ?? "audio/mpeg";
- const stem = f.name.split("/").pop()!.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").trim().toLowerCase();
- return { url: `data:${contentType};base64,${f.data.toString("base64")}`, kind: "audio" as const, contentType, meta: { stem } };
- });
+ const outputs: { url: string; kind: "audio"; contentType: string; meta: { stem: string } }[] = [];
+ const written: string[] = [];
+ try {
+ await unzip(zipped, {
+ maxBytes: unpacked,
+ only: (name) => AUDIO_FILE.test(name),
+ onEntry: (name, data) => {
+ const ext = AUDIO_FILE.exec(name)![1].toLowerCase();
+ const contentType = AUDIO_TYPES[ext] ?? "audio/mpeg";
+ const stem = name.split("/").pop()!.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").trim().toLowerCase();
+ const out = newScratchOutput(ext);
+ written.push(out.file);
+ fs.writeFileSync(out.file, data);
+ outputs.push({ url: out.url, kind: "audio", contentType, meta: { stem } });
+ },
+ });
+ } catch (e) {
+ for (const f of written) fs.rmSync(f, { force: true });
+ if (account && left <= unpacked && /more than Fuobe keeps/.test((e as Error).message)) throw new Error(filesFullMessage(account));
+ throw e;
+ }
+ if (!outputs.length) throw new Error("The stems archive held no audio");
+ return outputs;
}
const AUDIO_FILE = /\.(mp3|wav|flac|m4a|ogg)$/i;
diff --git a/src/server/storage.ts b/src/server/storage.ts
index e9834bfe..efa17fe5 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -211,6 +211,26 @@ export function scratchDir(): string {
return dir;
}
+/**
+ * A provider's result already written to the scratch folder (a song's stems, unpacked from their zip there): its run
+ * keeps it as `scratch:<name>`, and saving the run moves the file in (adoptFile), counted against an account's room
+ * like any other result. The name is random and long, so a provider's answer can't point at another run's file.
+ */
+const SCRATCH_OUTPUT = /^scratch:(out-[A-Za-z0-9_-]{21}\.[a-z0-9]{1,5})$/;
+
+export function newScratchOutput(ext: string): { file: string; url: string } {
+ const name = `out-${nanoid(21)}.${ext.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 5) || "bin"}`;
+ return { file: path.join(scratchDir(), name), url: `scratch:${name}` };
+}
+
+/** The file a `scratch:` result names, when it is still there. */
+export function scratchOutputFile(url: string): string | null {
+ const m = SCRATCH_OUTPUT.exec(url);
+ if (!m) return null;
+ const file = path.join(scratchDir(), m[1]);
+ return fs.existsSync(file) ? file : null;
+}
+
export function getAsset(id: string): Asset | null {
const row = db().prepare("SELECT * FROM assets WHERE id = ?").get(id) as AssetRow | undefined;
return row ? toAsset(row) : null;
diff --git a/src/server/unzip.ts b/src/server/unzip.ts
index 7f8e90fe..8e45cd57 100644
--- a/src/server/unzip.ts
+++ b/src/server/unzip.ts
@@ -10,9 +10,13 @@ const inflate = promisify(inflateRaw);
* Bounded by what is actually unpacked, never by what the headers claim: at most `maxFiles` entries and `maxBytes` of
* unpacked data (each entry inflates into what is left of that budget, off the event loop). Entries that share or overlap
* their bytes, run past the archive, or unpack to a length other than the one declared are refused, so a crafted archive
- * can't multiply one small entry into many large files.
+ * can't multiply one small entry into many large files. With `only`, other entries are skipped unread; with `onEntry`,
+ * each entry goes to it as soon as it is unpacked and isn't kept, so one entry at a time is in memory.
*/
-export async function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: number } = {}): Promise<{ name: string; data: Buffer }[]> {
+export async function unzip(
+ buf: Buffer,
+ o: { maxFiles?: number; maxBytes?: number; only?: (name: string) => boolean; onEntry?: (name: string, data: Buffer) => void | Promise<void> } = {},
+): Promise<{ name: string; data: Buffer }[]> {
const maxFiles = o.maxFiles ?? 64;
const maxBytes = o.maxBytes ?? 512 * 1024 * 1024;
const tooMuch = () => new Error("The archive unpacks to more than Fuobe keeps from one result");
@@ -49,6 +53,7 @@ export async function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: numb
const name = buf.subarray(at + 46, at + 46 + nameLen).toString("utf8");
at += 46 + nameLen + extraLen + commentLen;
if (name.endsWith("/") || name.startsWith("__MACOSX/") || name.split("/").pop()!.startsWith("._")) continue;
+ if (o.only && !o.only(name)) continue;
if (flags & 0x1) throw new Error("The archive is password-protected");
if (local + 30 > dirStart || buf.readUInt32LE(local) !== 0x04034b50) throw damaged();
const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
@@ -74,7 +79,8 @@ export async function unzip(buf: Buffer, o: { maxFiles?: number; maxBytes?: numb
total += data.length;
if (total > maxBytes) throw tooMuch();
if (data.length !== size) throw damaged();
- out.push({ name, data });
+ if (o.onEntry) await o.onEntry(name, data);
+ else out.push({ name, data });
}
return out;
}
diff --git a/tests/cli-run.test.ts b/tests/cli-run.test.ts
index 02f26cb4..7eb61cb6 100644
--- a/tests/cli-run.test.ts
+++ b/tests/cli-run.test.ts
@@ -130,7 +130,7 @@ beforeAll(async () => {
const name = /name:\s*(\S+)/.exec(md)![1];
return send(201, { skill: { name, title: name }, skipped: [], replaced: false });
}
- // A skill that runs by itself (W4): its recipe, a price per row, a run per row, and its zip.
+ // A skill that runs by itself: its recipe, a price per row, a run per row, and its zip.
const skill = /^\/api\/assist\/skills\/weekly-promo\/(recipe|verify|estimate|run|download)$/.exec(url.pathname)?.[1];
if (skill === "recipe") return send(200, PROMO);
if (skill === "verify") return send(200, { ok: true, engines: [{ engine: "cloud", plan: { ok: true, errors: [] } }] });
@@ -423,7 +423,7 @@ describe("fuobe CLI against a Fuobe server", () => {
});
});
-describe("fuobe skills: a skill that runs by itself (W4)", () => {
+describe("fuobe skills: a skill that runs by itself", () => {
const posts = (what: string) => seen.filter((s) => s.method === "POST" && s.path === `/api/assist/skills/weekly-promo/${what}`);
it("params lists the inputs; estimate prices with stand-ins and uploads nothing", async () => {
diff --git a/tests/e2e/schedule-skill.mjs b/tests/e2e/schedule-skill.mjs
index c7ea9d5b..3a26fbcb 100644
--- a/tests/e2e/schedule-skill.mjs
+++ b/tests/e2e/schedule-skill.mjs
@@ -1,4 +1,4 @@
-// Skills W4 in a real browser (demo mode: no keys, ComfyUI unreachable). A skill with a recipe is seeded over the API.
+// A scheduled task that runs a saved skill, in a real browser (demo mode: no keys, ComfyUI unreachable). A skill with a recipe is seeded over the API.
// On Scheduled, "Schedule a task" → What to run: A skill → pick it: its inputs come from its Run form, a file input
// starts on "Newest upload (when it runs)" and can take a file instead, and the price shows before saving. Saved, the
// task reads "/<skill> Product photo: your newest image upload · …"; Run now makes a chat whose plan waits for approval
diff --git a/tests/h3-any-gpu.test.ts b/tests/h3-any-gpu.test.ts
index 260350c6..34aa5cf4 100644
--- a/tests/h3-any-gpu.test.ts
+++ b/tests/h3-any-gpu.test.ts
@@ -1,7 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { afterAll, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { GenInput } from "@/lib/catalog/types";
import type { ComfyWorkflow, ManifestWorkflow } from "@/lib/comfy";
import type { GpuInventory, RequirementIndex } from "@/lib/gpu/types";
@@ -169,25 +169,38 @@ describe("Auto and Options → GPU tier, decided once per run", () => {
it("routes a smaller card to its build, with its file; keeps the full model otherwise", () => {
try {
dropSnapshots("install");
- expect(h3Gpu("minimax-h3-t2v", {}, has)).toEqual({ gpuTier: "standard" });
+ expect(h3Gpu("minimax-h3-t2v", {}, has, has)).toEqual({ gpuTier: "standard" });
checked({ gb: 16, name: RTX4070 });
- expect(h3Gpu("minimax-h3-t2v", {}, has)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.int8.file, note: T.TIER_NOTES.fast });
+ expect(h3Gpu("minimax-h3-t2v", {}, has, has)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.int8.file, note: T.TIER_NOTES.fast });
checked({ gb: 16, name: RTX5060 });
- expect(h3Gpu("minimax-h3-i2v", {}, has)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.nvfp4.file });
+ expect(h3Gpu("minimax-h3-i2v", {}, has, has)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.nvfp4.file });
checked({ gb: 12, name: RTX4070, torch: "2.9.1+cu128" });
- expect(h3Gpu("minimax-h3-t2v", {}, has)).toMatchObject({ gpuTier: "trim", unet: T.TRIM_FILES.fp8.file, note: T.TIER_NOTES.trim });
+ expect(h3Gpu("minimax-h3-t2v", {}, has, has)).toMatchObject({ gpuTier: "trim", unet: T.TRIM_FILES.fp8.file, note: T.TIER_NOTES.trim });
// Trim has no start-frame graph: the full model (the pre-flight then says it needs a bigger GPU).
- expect(h3Gpu("minimax-h3-i2v", {}, has)).toEqual({ gpuTier: "standard" });
+ expect(h3Gpu("minimax-h3-i2v", {}, has, has)).toEqual({ gpuTier: "standard" });
checked({ gb: 32, name: RTX4090 });
- expect(h3Gpu("minimax-h3-t2v", {}, has)).toEqual({ gpuTier: "standard" });
+ expect(h3Gpu("minimax-h3-t2v", {}, has, has)).toEqual({ gpuTier: "standard" });
// Best and Fast decode on a smaller build say they need 32 GB.
checked({ gb: 16, name: RTX4070 });
- expect(h3Gpu("minimax-h3-t2v", { quality: "best", vae: T.SOL_VAE }, has)?.note).toMatch(/Best needs a 32 GB GPU.*Fast decode needs a 32 GB GPU/);
+ expect(h3Gpu("minimax-h3-t2v", { quality: "best", vae: T.SOL_VAE }, has, has)?.note).toMatch(/Best needs a 32 GB GPU.*Fast decode needs a 32 GB GPU/);
// Asked for: on any card; an orbit and another model take no tier.
checked({ gb: 48, name: RTX4090 });
- expect(h3Gpu("minimax-h3-t2v", { gpuTier: "trim" }, has)).toMatchObject({ gpuTier: "trim", unet: T.TRIM_FILES.int8.file });
- expect(h3Gpu("minimax-h3-i2v", { orbit: true }, has)).toBeUndefined();
- expect(h3Gpu("qwen-image-21-t2i", {}, has)).toBeUndefined();
+ expect(h3Gpu("minimax-h3-t2v", { gpuTier: "trim" }, has, has)).toMatchObject({ gpuTier: "trim", unet: T.TRIM_FILES.int8.file });
+ expect(h3Gpu("minimax-h3-i2v", { orbit: true }, has, has)).toBeUndefined();
+ expect(h3Gpu("qwen-image-21-t2i", {}, has, has)).toBeUndefined();
+ } finally {
+ dropSnapshots("install");
+ }
+ });
+
+ it("keeps Auto on the full model until ComfyUI has accepted the smaller build's graph; asking for it still runs it", () => {
+ checked({ gb: 16, name: RTX4070 });
+ try {
+ const accepted = (id: string) => entry(id)?.validated === true;
+ expect(accepted("minimax-h3-fast-t2v")).toBe(false);
+ expect(h3Gpu("minimax-h3-t2v", {}, has, accepted)).toEqual({ gpuTier: "standard" });
+ expect(h3Gpu("minimax-h3-t2v", {}, has)).toEqual({ gpuTier: "standard" });
+ expect(h3Gpu("minimax-h3-t2v", { gpuTier: "fast" }, has, accepted)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.int8.file });
} finally {
dropSnapshots("install");
}
@@ -197,8 +210,8 @@ describe("Auto and Options → GPU tier, decided once per run", () => {
checked({ gb: 16, name: RTX4070 });
try {
changeAccess([{ kind: "model", id: "oss-minimax-h3-fast", on: false }]);
- expect(h3Gpu("minimax-h3-t2v", {}, has)).toEqual({ gpuTier: "standard" });
- expect(() => h3Gpu("minimax-h3-t2v", { gpuTier: "fast" }, has)).toThrow(/(turned|switched) off in Settings → Models & licences/);
+ expect(h3Gpu("minimax-h3-t2v", {}, has, has)).toEqual({ gpuTier: "standard" });
+ expect(() => h3Gpu("minimax-h3-t2v", { gpuTier: "fast" }, has, has)).toThrow(/(turned|switched) off in Settings → Models & licences/);
} finally {
changeAccess([{ kind: "reset" }]);
dropSnapshots("install");
@@ -213,7 +226,7 @@ describe("Auto and Options → GPU tier, decided once per run", () => {
try {
const run = (extra: Record<string, unknown> = {}) => previewGeneration({ feature: "video", modelId: "oss-minimax-h3", prompt: "a lighthouse at dusk", params: { aspectRatio: "16:9", duration: 5, extra } });
checked({ gb: 12, name: RTX4070 });
- const trim = run({ unet: "something-else.safetensors" });
+ const trim = run({ gpuTier: "trim", unet: "something-else.safetensors" });
expect(trim).toMatchObject({ demo: false, h3: { gpuTier: "trim", unet: T.TRIM_FILES.int8.file }, route: { provider: "comfyui", endpoint: "minimax-h3-t2v" } });
expect(trim.notes).toContain(T.TIER_NOTES.trim);
checked({ gb: 32, name: RTX4090 });
@@ -224,7 +237,7 @@ describe("Auto and Options → GPU tier, decided once per run", () => {
checked({ gb: 16, name: RTX5060 });
const direct = previewGeneration({ feature: "video", modelId: "oss-minimax-h3-trim", prompt: "a lighthouse at dusk", params: { aspectRatio: "16:9", duration: 5, extra: { unet: "something-else.safetensors" } } });
expect(direct).toMatchObject({ h3: { gpuTier: "trim", unet: T.TRIM_FILES.nvfp4.file }, route: { provider: "comfyui", endpoint: "minimax-h3-trim-t2v" } });
- expect(h3Gpu("minimax-h3-fast-i2v", { unet: "something-else.safetensors", gpuTier: "trim" }, has)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.nvfp4.file });
+ expect(h3Gpu("minimax-h3-fast-i2v", { unet: "something-else.safetensors", gpuTier: "trim" }, has, has)).toMatchObject({ gpuTier: "fast", unet: T.FAST_FILES.nvfp4.file });
} finally {
g.__fuobeComfyReach = before;
setSetting("demoMode", "auto");
@@ -282,6 +295,9 @@ describe("the GPU pre-flight", () => {
});
describe("the pre-flight board", () => {
+ // The board once ComfyUI has accepted the smaller builds' graphs (until then Auto keeps the full model, as runs do).
+ beforeAll(() => void (globalThis.__fuobeTestH3Accepted = true));
+ afterAll(() => void (globalThis.__fuobeTestH3Accepted = undefined));
const ctx = { account: false, computer: false, isolatedUrl: false };
const row = (href: string, inv: GpuInventory) => buildViews(inv, index, ctx).report.studios.find((r) => r.href === href)!;
diff --git a/tests/hosted-untested.test.ts b/tests/hosted-untested.test.ts
new file mode 100644
index 00000000..a4a61864
--- /dev/null
+++ b/tests/hosted-untested.test.ts
@@ -0,0 +1,107 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+/**
+ * Hosted routes no live call has passed yet (src/lib/catalog/hosted-untested.ts) run for the owner only: an account's
+ * run of one, even on its own fal.ai key, answers 403 own-gpu-tool before anything is sent, and its pickers leave the
+ * model out. A Fuobe Original whose cloud half is untested keeps its open engine.
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-hosted-untested-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ENGINE_MODE;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (u: RequestInfo | URL) => {
+ fetched.push(String(u));
+ return new Response("not stubbed", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const keys = await import("@/server/account-keys");
+const generationsRoute = await import("@/app/api/generations/route");
+const { saveFile } = await import("@/server/storage");
+const { MODELS, getModel } = await import("@/lib/catalog");
+const { HOSTED_UNTESTED_ENDPOINTS, HOSTED_UNTESTED_MODELS, hostedUntested, hostedUntestedSummary } = await import("@/lib/catalog/hosted-untested");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { HUB_MODES } = await import("@/lib/hubs");
+
+let cookie = "";
+let account = "";
+beforeAll(() => {
+ auth.setPassword("install password");
+ account = auth.createAccount("[email protected]", "long enough").id;
+ keys.saveAccountKey(account, "fal", "acct-fal-untested");
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(account).value}`;
+});
+afterAll(() => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const post = (body: unknown) => {
+ const text = JSON.stringify(body);
+ return generationsRoute.POST(
+ new Request("http://localhost:3000/api/generations", {
+ method: "POST",
+ headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) },
+ body: text,
+ }) as never,
+ );
+};
+
+describe("hosted routes without a live call", () => {
+ it("lists only endpoints and models the catalog has", () => {
+ const endpoints = new Set(MODELS.flatMap((m) => m.routes.map((r) => r.endpoint)));
+ // The song tools' upload is a call inside a run, not a route of its own.
+ for (const e of HOSTED_UNTESTED_ENDPOINTS) if (e !== "mureka/api/files/upload") expect(endpoints.has(e), e).toBe(true);
+ for (const id of HOSTED_UNTESTED_MODELS) expect(getModel(id), id).toBeDefined();
+ expect(hostedUntested("anything", { provider: "comfyui", endpoint: "minimax/h3-lite" })).toBe(false);
+ expect(hostedUntested("fuobe-animation", { provider: "comfyui", endpoint: "wan22-inbetween-anisora" })).toBe(false);
+ });
+
+ it.each([
+ ["mureka-stems", { feature: "song-tools" }],
+ ["lyria-3-5", { feature: "audio" }],
+ ["elevenlabs-music-2-5", { feature: "audio" }],
+ ] as const)("refuses an account's %s run on its own key, sending nothing", async (modelId, extra) => {
+ const song = saveFile({ data: Buffer.from("ID3song"), contentType: "audio/mpeg", source: "upload", accountId: account }).url;
+ fetched.length = 0;
+ const r = await post({ ...extra, modelId, engine: "cloud", prompt: "a slow jazz song", ...(modelId === "mureka-stems" && { inputs: { audio: song } }) });
+ expect(r.status, await r.clone().text()).toBe(403);
+ expect((await r.json()).code).toBe("own-gpu-tool");
+ expect(fetched.filter((u) => /fal\.(run|ai|media)/.test(u))).toHaveLength(0);
+ });
+
+ it("still prices a hosted model that has had its live call, on the account's key", async () => {
+ const r = await generationsRoute.POST(
+ new Request("http://localhost:3000/api/generations?preview=1", {
+ method: "POST",
+ headers: { cookie, host: "localhost:3000", "content-type": "application/json" },
+ body: JSON.stringify({ feature: "audio", modelId: "sonilo-music", engine: "cloud", prompt: "a slow jazz song" }),
+ }) as never,
+ );
+ expect(r.status, await r.clone().text()).toBe(200);
+ const priced = await post({ feature: "audio", modelId: "lyria-3-5", engine: "cloud", prompt: "a slow jazz song" });
+ expect(priced.status).toBe(403);
+ });
+
+ it("leaves them out of an account's pickers; an Original keeps its open engine", async () => {
+ const summary = hostedUntestedSummary(MODELS, undefined);
+ for (const id of ["mureka-extend", "mureka-remix", "mureka-stems", "lyria-3-5", "vidu-q4", "tripo-p2", "minimax-h3-max-turbo"]) expect(summary.off, id).toContain(id);
+ expect(summary.off).not.toContain("fuobe-animation");
+ expect(summary.engines?.["fuobe-animation"]).toEqual(["open"]);
+ const status = await visitorStatus(auth.accountById(account)!);
+ expect(status.access?.off).toContain("mureka-stems");
+ expect(HUB_MODES.audio.find((m) => m.id === "song")?.ownerOnly).toBe(true);
+ });
+});
diff --git a/tests/music3-open.test.ts b/tests/music3-open.test.ts
index 94454036..ea8b10af 100644
--- a/tests/music3-open.test.ts
+++ b/tests/music3-open.test.ts
@@ -21,7 +21,8 @@ const { buildLicenceList, licenceInfo, workflowLicence } = await import("@/lib/l
const { setSetting } = await import("@/server/settings");
const { falProvider, stemsFromZip } = await import("@/server/providers/fal");
const { zip } = await import("@/server/zip");
-const { saveFile } = await import("@/server/storage");
+const { saveFile, scratchOutputFile } = await import("@/server/storage");
+const { runAsTenant } = await import("@/server/tenant");
const { createGenerations, getGeneration } = await import("@/server/generations");
const { unzip } = await import("@/server/unzip");
@@ -215,7 +216,21 @@ describe("the fal provider's song tools", () => {
["vocals", "audio/mpeg", "audio"],
["drums", "audio/wav", "audio"],
]);
- expect(Buffer.from(r.outputs[0].url.split(",")[1], "base64").toString()).toBe("ID3vocals");
+ // Each stem is a file in the scratch folder, not a data: URL held in memory.
+ expect(r.outputs.every((o) => /^scratch:out-[\w-]{21}\.(mp3|wav)$/.test(o.url))).toBe(true);
+ expect(fs.readFileSync(scratchOutputFile(r.outputs[0].url)!, "utf8")).toBe("ID3vocals");
+ expect(scratchOutputFile("scratch:../db.sqlite")).toBeNull();
+ });
+
+ it("unpacks an account's stems within its limits, and refuses an account's zip from this machine", async () => {
+ const asAccount = <T,>(fn: () => Promise<T>) => runAsTenant({ kind: "account", id: "acct-stems-test" }, fn);
+ // The stand-in fal.ai: read, and unpacked to scratch files as for the owner.
+ const outs = await asAccount(() => stemsFromZip(`${base}/stems.zip`));
+ expect(outs.map((o) => o.meta.stem)).toEqual(["vocals", "drums"]);
+ expect(outs.every((o) => scratchOutputFile(o.url))).toBe(true);
+ await expect(asAccount(() => stemsFromZip(`${base}/stems.zip`, { maxBytes: 16 }))).rejects.toThrow(/larger than Fuobe keeps/);
+ // Any other address on this machine: refused before anything is read.
+ await expect(asAccount(() => stemsFromZip("http://127.0.0.1:9/stems.zip"))).rejects.toThrow(/won't fetch/);
});
it("reads an archive's files, and refuses a damaged or oversized one", async () => {