import { REQUIRED_NODES, type ComfyPrompt } from "./graph"; export const COMFY_URL = (process.env.COMFY_URL ?? "http://127.0.0.1:8188").replace(/\/$/, ""); export const IS_MOCK = process.env.COMFY_MOCK === "1"; export const DEFAULT_CHECKPOINT = process.env.YUE2_CHECKPOINT ?? "yue2_3b_int8_convrot.safetensors"; export const DEFAULT_ENCODER = process.env.SHEETSAGE_ENCODER ?? "sheetsage2_bf16.safetensors"; export function authHeaders(): Record { const token = process.env.COMFY_TOKEN; return token ? { Authorization: `Bearer ${token}` } : {}; } async function comfyFetch(path: string, init: RequestInit = {}): Promise { return fetch(`${COMFY_URL}${path}`, { ...init, cache: "no-store", headers: { ...authHeaders(), ...(init.headers ?? {}) }, }); } export interface ObjectInfoSummary { checkpoints: string[]; audioEncoders: string[]; loras: string[]; missingNodes: string[]; } export async function fetchObjectInfo(): Promise { const res = await comfyFetch("/object_info"); if (!res.ok) throw new Error(`ComfyUI returned ${res.status} for /object_info`); const info = (await res.json()) as Record; const checkpoints = comboOptions(info, "CheckpointLoaderSimple", "ckpt_name"); const audioEncoders = comboOptions(info, "AudioEncoderLoader", "audio_encoder_name"); const loras = comboOptions(info, "LoraLoader", "lora_name"); const missingNodes = REQUIRED_NODES.filter((name) => !(name in info)); return { checkpoints, audioEncoders, loras, missingNodes }; } interface ComfyNodeInfo { input?: { required?: Record; optional?: Record }; } function comboOptions( info: Record, nodeName: string, inputName: string, ): string[] { const spec = info[nodeName]?.input?.required?.[inputName] ?? info[nodeName]?.input?.optional?.[inputName]; if (!Array.isArray(spec)) return []; const first = spec[0]; return Array.isArray(first) ? first.filter((v): v is string => typeof v === "string") : []; } export interface QueuedPrompt { promptId: string; queuePosition: number; } export async function queuePrompt(prompt: ComfyPrompt, clientId: string): Promise { const res = await comfyFetch("/prompt", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt, client_id: clientId }), }); const body = await res.json().catch(() => ({})); if (!res.ok) { throw new Error(describePromptError(body) ?? `ComfyUI rejected the prompt (${res.status})`); } return { promptId: String(body.prompt_id), queuePosition: Number(body.number ?? 0) }; } function describePromptError(body: unknown): string | null { if (!body || typeof body !== "object") return null; const record = body as Record; const nodeErrors = record.node_errors as Record | undefined; if (nodeErrors) { const messages = Object.entries(nodeErrors).flatMap(([node, detail]) => (detail.errors ?? []).map((e) => `${node}: ${e.message ?? "invalid input"}`), ); if (messages.length) return messages.join(" / "); } const error = record.error as { message?: string } | string | undefined; if (typeof error === "string") return error; if (error?.message) return error.message; return null; } export interface HistoryResult { audio: { filename: string; subfolder: string; type: string } | null; texts: Record; status: "success" | "error" | "pending"; error: string | null; } export async function fetchHistory(promptId: string): Promise { const res = await comfyFetch(`/history/${promptId}`); if (!res.ok) return null; const history = (await res.json()) as Record; const entry = history[promptId]; if (!entry) return null; let audio: HistoryResult["audio"] = null; const texts: Record = {}; for (const [nodeId, output] of Object.entries(entry.outputs ?? {})) { const files = output.audio ?? output.audios; if (files?.length && !audio) { audio = { filename: files[0].filename, subfolder: files[0].subfolder ?? "", type: files[0].type ?? "output", }; } if (output.text?.length) texts[nodeId] = output.text.join("\n"); } const statusStr = entry.status?.status_str; return { audio, texts, status: statusStr === "error" ? "error" : entry.status?.completed ? "success" : "pending", error: extractHistoryError(entry), }; } interface HistoryEntry { outputs?: Record< string, { audio?: { filename: string; subfolder?: string; type?: string }[]; audios?: { filename: string; subfolder?: string; type?: string }[]; text?: string[]; } >; status?: { status_str?: string; completed?: boolean; messages?: [string, Record][]; }; } function extractHistoryError(entry: HistoryEntry): string | null { for (const [event, data] of entry.status?.messages ?? []) { if (event === "execution_error") { const message = typeof data.exception_message === "string" ? data.exception_message : null; const node = typeof data.node_type === "string" ? data.node_type : "a node"; if (message) return `${node}: ${message}`; } } return null; } export async function uploadAudio(file: File): Promise { const form = new FormData(); form.append("image", file, file.name); form.append("type", "input"); form.append("overwrite", "true"); const res = await comfyFetch("/upload/image", { method: "POST", body: form }); if (!res.ok) throw new Error(`Upload failed (${res.status})`); const body = (await res.json()) as { name: string; subfolder?: string }; return body.subfolder ? `${body.subfolder}/${body.name}` : body.name; } export async function viewAudio( filename: string, subfolder: string, type: string, ): Promise { const query = new URLSearchParams({ filename, subfolder, type }); return comfyFetch(`/view?${query.toString()}`); } export async function interrupt(): Promise { await comfyFetch("/interrupt", { method: "POST" }).catch(() => undefined); } export async function ping(): Promise { try { const res = await comfyFetch("/system_stats"); return res.ok; } catch { return false; } } export interface QueueState { running: string[]; pending: string[]; } /** Used when the websocket cannot be reached, to tell queued from running. */ export async function fetchQueue(): Promise { try { const res = await comfyFetch("/queue"); if (!res.ok) return null; const body = (await res.json()) as { queue_running?: unknown[][]; queue_pending?: unknown[][] }; const ids = (rows: unknown[][] | undefined) => (rows ?? []).map((row) => String(row[1])).filter(Boolean); return { running: ids(body.queue_running), pending: ids(body.queue_pending) }; } catch { return null; } } export function wsUrl(clientId: string): string { const base = COMFY_URL.replace(/^http/, "ws"); return `${base}/ws?clientId=${encodeURIComponent(clientId)}`; }