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.

Accounts 2 fixes: a turned-off owner's jobs stop at the provider, and studios launch only as the owner

Claudeef662fd69294
diff --git a/src/server/faceless.ts b/src/server/faceless.ts
index dce0bb5d..23a5f68f 100644
--- a/src/server/faceless.ts
+++ b/src/server/faceless.ts
@@ -80,7 +80,7 @@ import { DocxError, docxText } from "./assist/docx";
import { PdfError, pdfText } from "./assist/pdf";
import { asSystem } from "./access/actor";
import { rethrowAccess } from "./access/errors";
-import { AccountOffError, rowOwner, runAsOwner } from "./access/permissions";
+import { rowOwner, runAsOwner } from "./access/permissions";
import { db } from "./db";
import { listElements } from "./elements";
import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";
@@ -1109,6 +1109,9 @@ function finalOf(ep: FacelessEpisode): Generation | null {
const brokenMessage = (g: Generation | null) =>
!g ? "A step was deleted — retry to make it again" : g.status === "canceled" ? "A step was cancelled — retry to make it again" : (g.error ?? "A step didn't finish — retry it");
+/** Who started an episode (its row's owner). */
+const episodeOwner = (id: string) => rowOwner(db().prepare("SELECT * FROM faceless_episodes WHERE id = ?").get(id) ?? {});
+
/**
* The episode's status from its generations (saved when it changes). Once stage one has finished, the
* first look starts stage two (advance).
@@ -1130,7 +1133,9 @@ function settle(ep: FacelessEpisode, gens?: Map<string, Generation | null>): Fac
if (ep.plan.awaiting) {
if (!active && !broken && ep.status !== "failed") {
try {
- return settle(advance(ep));
+ // Stage two starts as the person who started the episode, whoever's look noticed stage one had finished; when
+ // they're turned off it doesn't start, and the episode fails saying so.
+ return settle(runAsOwner(episodeOwner(ep.id), () => advance(ep)));
} catch (e) {
status = "failed";
error = (e as Error).message;
@@ -1157,11 +1162,10 @@ function sweep(): void {
const rows = db().prepare("SELECT * FROM faceless_episodes WHERE status = 'rendering' AND plan_json LIKE '%\"awaiting\":true%'").all() as EpisodeRow[];
for (const r of rows) {
try {
- // Stage two starts as the person who started the episode.
- runAsOwner(rowOwner(r), () => settle(toEpisode(r)));
+ // Stage two starts as the person who started the episode (settle).
+ settle(toEpisode(r));
} catch (e) {
- if (e instanceof AccountOffError) updateEpisodeRow(r.id, { status: "failed", error: e.message });
- else console.warn(`[faceless] couldn't continue ${r.id}: ${(e as Error).message}`);
+ console.warn(`[faceless] couldn't continue ${r.id}: ${(e as Error).message}`);
}
}
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 9824ad7a..49ab9017 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -1136,7 +1136,7 @@ async function advanceDependents(): Promise<void> {
owner = ownerActor(rowOwner(r));
} catch (e) {
if (!(e instanceof AccountOffError)) throw e;
- update(r.id, { status: "failed", error: e.message, message: null, completed_at: Date.now() });
+ await pauseForOwner(r, e.message);
continue;
}
await runAs(owner, () => advance(r));
@@ -1353,6 +1353,22 @@ export function ensureRunner(): void {
});
}
+/**
+ * A job whose owner was turned off or went dormant (§7.11): the provider's job is canceled first, so it stops running
+ * and charging, then the row fails with the reason, and steps waiting only to feed it are dropped before they're paid
+ * for (as a failed or canceled step does).
+ */
+async function pauseForOwner(r: Row, message: string): Promise<void> {
+ const model = getModel(r.model_id);
+ if (r.external_id && model && (r.status === "queued" || r.status === "running")) {
+ await provider(r.provider)
+ .cancel?.(pollContext(r, model))
+ .catch(() => {});
+ }
+ update(r.id, { status: "failed", error: message, message: null, completed_at: Date.now() });
+ dropUnused(depIds(r.depends_on));
+}
+
/** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. */
function sweepInterrupted(): void {
const rows = db()
@@ -1373,7 +1389,7 @@ async function pollGuarded(r: Row): Promise<void> {
// Polled, downloaded and saved as the person who started it.
await runAsOwner(rowOwner(r), () => pollOne(r));
} catch (e) {
- if (e instanceof AccountOffError) update(r.id, { status: "failed", error: e.message, completed_at: Date.now(), message: null });
+ if (e instanceof AccountOffError) await pauseForOwner(r, e.message);
else update(r.id, { message: `Poll error: ${(e as Error).message}` });
} finally {
polling.delete(r.id);
diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.ts
index 3c4f4d94..eba6daa3 100644
--- a/src/server/swap-studio.ts
+++ b/src/server/swap-studio.ts
@@ -46,8 +46,8 @@ import { cloudMaskCut, frozenTakePlan, planAnchor, planAssembly, planMask, planN
import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
import { ACCESS_PLACE } from "@/lib/model-access";
import { createPipeline } from "./chains";
-import { asSystem } from "./access/actor";
-import { AccountOffError, rowOwner, runAsOwner } from "./access/permissions";
+import { asSystem, runAs, type Actor } from "./access/actor";
+import { AccountOffError, ownerActor, rowOwner } from "./access/permissions";
import { db } from "./db";
import { cancelGeneration, getGeneration, previewChained } from "./generations";
import { isOffered, offeredLoras } from "./model-access";
@@ -327,9 +327,30 @@ function settle(p: SwapProject, look: Look): SwapProject {
return clips.some((c, i) => c !== p.clips[i]) ? { ...p, clips } : p;
}
-/** Read a project and bring it up to date (saved when anything changed). */
+/** Every take still waiting stops, saying why: it never launches (its project's owner was turned off). */
+function stopWaiting(p: SwapProject, reason: string): SwapProject {
+ if (!takesOf(p).some((t) => t.state === "waiting")) return p;
+ const stop = (t: SwapTake): SwapTake => (t.state === "waiting" ? { ...t, state: "stopped", reason, waitsOn: undefined } : t);
+ return { ...p, clips: p.clips.map((c) => ({ ...c, shots: c.shots.map((s) => (s.segments ? { ...s, segments: s.segments.map((g) => ({ ...g, takes: g.takes.map(stop) })) } : s)) })) };
+}
+
+/**
+ * Read a project and bring it up to date (saved when anything changed). Waiting takes launch as the person who started
+ * the project, whoever's read (the page's poll, the sweep) noticed they could; when that person is turned off they stop
+ * with the reason instead, so nothing launches for them and the sweep lets the project go.
+ */
export function advanceProject(id: string): SwapProject {
- return mutate(id, (p) => settle(p, lookup()));
+ const row = rowOf(id);
+ if (!row) return mustProject(id);
+ let owner: Actor;
+ try {
+ owner = ownerActor(rowOwner(row));
+ } catch (e) {
+ if (!(e instanceof AccountOffError)) throw e;
+ const reason = e.message;
+ return mutate(id, (p) => settle(stopWaiting(p, reason), lookup()));
+ }
+ return runAs(owner, () => mutate(id, (p) => settle(p, lookup())));
}
declare global {
@@ -344,14 +365,12 @@ export function ensureSwapStudioRunner(): void {
if (globalThis.__fuobeSwapStudioRunner) return;
const tick = () => {
try {
- const rows = db().prepare("SELECT * FROM swap_projects WHERE waiting > 0").all() as { id: string }[];
+ const rows = db().prepare("SELECT id FROM swap_projects WHERE waiting > 0").all() as { id: string }[];
for (const r of rows) {
try {
- // Waiting takes launch as the person who started the project.
- runAsOwner(rowOwner(r), () => advanceProject(r.id));
+ // Waiting takes launch as the person who started the project (or stop, saying why, when they're off).
+ advanceProject(r.id);
} catch (e) {
- // Its owner was turned off: the takes wait (their steps fail with the reason) until they're back.
- if (e instanceof AccountOffError) continue;
console.error(`[swap-studio] ${r.id}:`, (e as Error).message);
}
}
diff --git a/tests/runners-actor.test.ts b/tests/runners-actor.test.ts
index e330141d..c3e19598 100644
--- a/tests/runners-actor.test.ts
+++ b/tests/runners-actor.test.ts
@@ -8,6 +8,9 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type Anthropic from "@anthropic-ai/sdk";
+import type { EpisodeSettings } from "@/lib/catalog/faceless";
+import type { SwapProject } from "@/lib/catalog/swap-studio";
+import type { PollContext } from "@/server/providers/types";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-runners-actor-"));
@@ -19,6 +22,8 @@ process.env.OLLAMA_URL = "http://127.0.0.1:9";
const stubTimer = setInterval(() => {}, 60_000);
clearInterval(stubTimer);
globalThis.__fuobeScheduleRunner = { tick: () => {}, timer: stubTimer };
+globalThis.__fuobeFacelessRunner = { tick: () => {}, timer: stubTimer };
+globalThis.__fuobeSwapStudioRunner = stubTimer;
const { db } = await import("@/server/db");
const gens = await import("@/server/generations");
@@ -28,6 +33,9 @@ const { maybeActor, currentActor, runAs, asSystem, SYSTEM } = await import("@/se
const sched = await import("@/server/assist/schedules");
const agent = await import("@/server/assist/agent");
const { setSetting } = await import("@/server/settings");
+const swap = await import("@/server/swap-studio");
+const faceless = await import("@/server/faceless");
+const { newSegment, newShot, DEFAULT_SETTINGS } = await import("@/lib/catalog/swap-studio");
const { seedPerson, updatePerson, actor } = await import("./helpers/actors");
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -42,15 +50,15 @@ const who = () => {
};
let rows = 0;
-function storedRow(r: { status: string; externalId?: string; dependsOn?: string; outputs?: object[] }): string {
+function storedRow(r: { status: string; externalId?: string; dependsOn?: string; outputs?: object[]; request?: object; createdAt?: number }): string {
const id = `row-${++rows}`;
- const now = Date.now();
+ const now = r.createdAt ?? Date.now();
db()
.prepare(
`INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, depends_on, created_at, updated_at)
VALUES (?, 'image', 'nano-banana-pro', 'cloud', 'mock', 'generate', 'image', ?, ?, ?, ?, ?, ?, ?)`,
)
- .run(id, r.status, JSON.stringify({ modelId: "nano-banana-pro", prompt: "a lighthouse" }), JSON.stringify(r.outputs ?? []), r.externalId ?? null, r.dependsOn ?? null, now, now);
+ .run(id, r.status, JSON.stringify({ modelId: "nano-banana-pro", prompt: "a lighthouse", ...r.request }), JSON.stringify(r.outputs ?? []), r.externalId ?? null, r.dependsOn ?? null, now, now);
return id;
}
@@ -108,6 +116,38 @@ describe("the generations runner", () => {
expect(gens.getGeneration(id)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });
});
+ it("cancels the provider's job of an owner who was turned off, so it stops running and charging", async () => {
+ vi.spyOn(PROVIDERS.mock, "poll").mockResolvedValue({ state: "running" });
+ // The demo provider has nothing to cancel; a cloud one does.
+ const cancel = vi.fn<(ctx: PollContext) => Promise<void>>(async () => {});
+ PROVIDERS.mock.cancel = cancel;
+ const id = storedRow({ status: "running", externalId: "mock-cancel" });
+ updatePerson("u_owner", { status: "disabled" });
+ try {
+ await tickUntil(() => gens.getGeneration(id)?.status === "failed");
+ } finally {
+ delete PROVIDERS.mock.cancel;
+ }
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(cancel.mock.calls[0][0]).toMatchObject({ externalId: "mock-cancel" });
+ expect(gens.getGeneration(id)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });
+ });
+
+ it("drops the steps waiting only to feed a paused one, as a failed step does", async () => {
+ // A per-frame join: one lane failed, the other still waits on its own input (and is only for the join).
+ const t0 = Date.now() - 1000;
+ const input = storedRow({ status: "queued", createdAt: t0 });
+ const lane = storedRow({ status: "failed", createdAt: t0 });
+ const join = storedRow({ status: "queued", createdAt: t0 + 1, dependsOn: "" });
+ const waiting = storedRow({ status: "queued", createdAt: t0 + 2, dependsOn: input, request: { dropWhenUnused: true } });
+ db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(JSON.stringify([lane, waiting]), join);
+ updatePerson("u_owner", { status: "disabled" });
+ await tickUntil(() => gens.getGeneration(join)?.status === "failed");
+ expect(gens.getGeneration(join)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });
+ expect(gens.getGeneration(waiting)).toMatchObject({ status: "canceled", error: gens.DROPPED_UNUSED });
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(input);
+ });
+
it("fails a waiting step of a chain whose owner went dormant, and plans the next one as the owner", async () => {
const parent = storedRow({ status: "succeeded", outputs: [{ url: "/api/files/x.png", kind: "image" }] });
const child = storedRow({ status: "queued", dependsOn: parent });
@@ -117,6 +157,37 @@ describe("the generations runner", () => {
});
});
+describe("Faceless", () => {
+ const cloud: EpisodeSettings = {
+ engine: "cloud",
+ length: 20,
+ animation: "animated",
+ aspect: "16:9",
+ subtitles: true,
+ music: false,
+ styleId: "editorial-motion-graphics",
+ styleRefs: [],
+ voice: { kind: "preset", id: "Xb7hH8MSUJpSbSDYk0k2" },
+ elements: [],
+ };
+
+ it("doesn't start stage two for an owner who was turned off, whoever looks: the episode fails saying why", async () => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+ const ep = faceless.createEpisode({ kind: "explainer", topic: "Why bridges sway", settings: cloud, autoRender: true });
+ await faceless.scriptWritten(ep.id);
+ const plan = () => JSON.parse((db().prepare("SELECT plan_json FROM faceless_episodes WHERE id = ?").get(ep.id) as { plan_json: string }).plan_json);
+ // Stage one runs (demo jobs); nobody reads the episode and the sweep is off, so stage two waits for a look.
+ gens.ensureRunner();
+ await vi.waitFor(() => expect(Object.values(plan().ids as Record<string, string>).every((id) => gens.getGeneration(id)?.status === "succeeded")).toBe(true), { timeout: 60_000, interval: 200 });
+ expect(plan().awaiting).toBe(true);
+ updatePerson("u_owner", { status: "disabled" });
+ const v = runAs(actor(seedPerson(), "admin"), () => faceless.episodeView(ep.id));
+ expect(v.episode).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });
+ expect(plan().awaiting).toBe(true);
+ }, 90_000);
+});
+
describe("Assist", () => {
type Block = Anthropic.Beta.BetaContentBlock;
const done = (seen: unknown[]): import("@/server/assist/agent").ModelCall =>
@@ -173,3 +244,59 @@ describe("Assist", () => {
expect(sched.getSchedule(s.id)?.last).toMatchObject({ status: "failed", text: "Paused: the account that started this is off." });
});
});
+
+describe("Character Swap Studio", () => {
+ /** A project whose second segment's take waits for the first segment's take (still running). */
+ function waitingProject(): string {
+ // The first take's job keeps running (the server's own runner polls it too).
+ vi.spyOn(PROVIDERS.mock, "poll").mockResolvedValue({ state: "running" });
+ const running = storedRow({ status: "running", externalId: "mock-swap" });
+ const shot = { ...newShot(0, 96, DEFAULT_SETTINGS, true, () => 0.5), id: "shot-a" };
+ const [a, b] = [newSegment(shot, 0, 48, 0, () => 0.1), newSegment(shot, 48, 96, 1, () => 0.2)];
+ const take = (id: string, over: object) => ({ id, createdAt: 1, engine: "open", signature: "", dependencies: [], prompt: "", seed: 1, favourite: false, decision: "pending", notes: "", ...over });
+ const segments = [
+ { ...a, takes: [take("t1", { state: "launched", genId: running })] },
+ { ...b, takes: [take("t2", { state: "waiting", waitsOn: [{ segmentId: a.id, takeId: "t1" }], dependencies: [{ segmentId: a.id, takeId: "t1", frames: 8 }] })] },
+ ];
+ const clip = {
+ id: "clip-1",
+ name: "walk",
+ source: { url: "/api/files/uploads/x/walk.mp4", name: "walk.mp4", duration: 4, fps: 24, width: 1280, height: 720, hasAudio: true },
+ normalized: { url: "/api/files/outputs/x/walk24.mp4", genId: "g-norm" },
+ frames: 96,
+ cuts: [],
+ detected: null,
+ cutsReviewed: true,
+ shots: [{ ...shot, segments }],
+ transcript: null,
+ review: "pending",
+ reviewNotes: "",
+ assembly: null,
+ };
+ const id = `swap-${++rows}`;
+ const doc = { id, name: "Off", engine: "open", character: { image: "/api/files/uploads/x/hero.png", description: "a woman" }, defaults: DEFAULT_SETTINGS, clips: [clip], createdAt: 0, updatedAt: 0, revision: 1 };
+ db()
+ .prepare("INSERT INTO swap_projects (id, name, engine, data_json, revision, waiting, created_at, updated_at) VALUES (?, 'Off', 'open', ?, 1, 1, ?, ?)")
+ .run(id, JSON.stringify(doc), Date.now(), Date.now());
+ return id;
+ }
+ const takes = (p: SwapProject) => p.clips[0].shots[0].segments!.flatMap((g) => g.takes.map((t) => ({ id: t.id, state: t.state, reason: t.reason })));
+ const waitingCount = (id: string) => (db().prepare("SELECT waiting FROM swap_projects WHERE id = ?").get(id) as { waiting: number }).waiting;
+
+ it("keeps a take waiting while its owner is on, whoever looks at the project", () => {
+ const id = waitingProject();
+ const viewer = actor(seedPerson(), "member");
+ const p = runAs(viewer, () => swap.advanceProject(id));
+ expect(takes(p).find((t) => t.id === "t2")).toMatchObject({ state: "waiting" });
+ expect(waitingCount(id)).toBe(1);
+ });
+
+ it("stops the waiting takes of a project whose owner was turned off, saying why, so the sweep lets it go", () => {
+ const id = waitingProject();
+ updatePerson("u_owner", { status: "disabled" });
+ // A teammate's look (the page's poll) launches nothing for the owner.
+ const p = runAs(actor(seedPerson(), "admin"), () => swap.projectView(id)).project;
+ expect(takes(p).find((t) => t.id === "t2")).toEqual({ id: "t2", state: "stopped", reason: "Paused: the account that started this is off." });
+ expect(waitingCount(id)).toBe(0);
+ });
+});