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.

2.4 KB
Raw Blame
import { callerKey, principalOf, rateOf, relayAnswer, requestWorker } from "@/server/computer/http";
import { beat, cleanFacts, type BeatInput } from "@/server/computer/tasks";
import { cleanBeat, workerBeat } from "@/server/computer/pool";
import { noteWorkerFacts } from "@/server/computer/workers";

/** What a beat may weigh: the facts, with up to 20,000 LoRA names. */
const MAX_BYTES = 3 * 2 ** 20;

/**
 * "Use the ComfyUI on this computer": the person's Fuobe tab says it is there, every few seconds. The first computer to
 * beat runs the waiting jobs (another takes over when this one goes quiet for a minute, or when the person asks); the
 * answer says whether it does, how many wait, and which prompts to take off its ComfyUI. It may send its ComfyUI's
 * facts (the GPU, memory, version, LoRA names), never its command line.
 */
export async function POST(request: Request) {
  const principal = principalOf(request);
  if (principal instanceof Response) return principal;
  const limited = rateOf(callerKey(request, principal), "beat", 30);
  if (limited) return limited;
  const text = await request.text().catch(() => "");
  if (text.length > MAX_BYTES) return Response.json({ error: "Too much at once" }, { status: 413 });
  let body: BeatInput;
  try {
    body = JSON.parse(text) as BeatInput;
  } catch {
    return Response.json({ error: "Send JSON" }, { status: 400 });
  }
  const worker = requestWorker(request);
  // One of the owner's shared GPUs: its own beat (pool.ts).
  if (worker?.kind === "pool") {
    try {
      return Response.json(workerBeat(worker, cleanBeat(body)), { headers: { "Cache-Control": "no-store" } });
    } catch (e) {
      return relayAnswer(e);
    }
  }
  // A paired ComfyUI's facts are kept with it too (the person's list of paired ComfyUIs shows its GPU).
  if (worker && body?.facts !== undefined) {
    const facts = cleanFacts(body.facts);
    delete facts.loras;
    noteWorkerFacts(worker.id, facts);
  }
  try {
    return Response.json(beat(principal, { device: String(body?.device ?? ""), port: body?.port, facts: body?.facts, running: Array.isArray(body?.running) ? body.running : [], takeover: body?.takeover === true, stopped: Array.isArray(body?.stopped) ? body.stopped : [], ready: body?.ready !== false, ...(body?.why === "setting" && { why: "setting" as const }), listen: body?.listen === true }), {
      headers: { "Cache-Control": "no-store" },
    });
  } catch (e) {
    return relayAnswer(e);
  }
}