Python
history: a progress bar of our own, read from the raw event stream
neuregex5b66d20409cb
diff --git a/server/history.ts b/server/history.tsindex 21e33c8..e638651 100644--- a/server/history.ts+++ b/server/history.ts@@ -10,7 +10,7 @@ import { extname, join } from "node:path";import { randomBytes } from "node:crypto";import type { ComfyEvent } from "@comfyorg/sdk";import { isFileInput, type App } from "./registry.ts";-import type { FileValue, Values } from "./runner.ts";+import type { FileValue, Frame, Values } from "./runner.ts";export type Status = "starting" | "queued" | "running" | "succeeded" | "failed" | "canceled" | "expired" | "lost";const TERMINAL = new Set<Status>(["succeeded", "failed", "canceled", "expired", "lost"]);@@ -50,6 +50,18 @@ export type JobLike = {cancel(signal?: AbortSignal): Promise<unknown>;};++/** What the history needs to know about an app: its declared output nodes, how many nodes its workflow+ * has (for the progress bar) and the class of a node id (for the "KSampler 4/8" label). */+export type AppInfo = { outputs: string[]; nodes: number; classOf: (id: string) => string | null };++export type HistoryOptions = {+ onContact?: () => void;+ appInfo?: (appId: string) => AppInfo | undefined;+ /** The raw event stream of a job, read without the SDK (see Meter). Absent: job.events() is used. */+ frames?: (jobId: string, signal: AbortSignal) => AsyncIterable<Frame>;+};+type Live = {job?: JobLike;cancelRequested?: boolean;@@ -58,6 +70,46 @@ type Live = {preview: { bytes: Uint8Array; type: string; n: number } | null;};+/**+ * Our own progress figure, because the stream's `value` cannot be shown as it comes. comfy-api-proxy derives it+ * from ComfyUI's progress_state, which only lists the nodes touched so far: after the first node finishes and+ * before the next starts the frame says 1/1 = 1.0. The SDK's job.events() then drops every later frame as+ * "going backwards" (first web runs through the gateway, 23 oct: the bar sat at 100 % for two minutes). So the+ * bar is (nodes finished + the running node's step fraction) / the workflow's node count, never backwards and+ * never full before the job ends. Per-node `progress` frames (nodes_total 0) carry the sampler steps.+ */+export class Meter {+ private done = 0;+ private total: number;+ private classOf: (id: string) => string | null;+ value = 0;+ step: number | null = null;+ steps: number | null = null;+ node: string | null = null;++ constructor(expectedNodes: number, classOf: (id: string) => string | null = () => null) {+ this.total = Math.max(1, expectedNodes);+ this.classOf = classOf;+ }++ /** Feed one progress snapshot (an SSE frame's data or the SDK's Progress); returns the figure to show. */+ feed(d: { value?: unknown; nodes_done?: unknown; nodes_total?: unknown; step?: unknown; steps?: unknown; current_node?: unknown }) {+ const n = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? x : null);+ const nodesTotal = n(d.nodes_total) ?? 0;+ if (nodesTotal > 0) {+ this.done = Math.max(this.done, n(d.nodes_done) ?? 0);+ this.total = Math.max(this.total, nodesTotal);+ }+ const step = n(d.step), steps = n(d.steps);+ const inNode = steps && steps > 0 && step !== null ? Math.min(1, Math.max(0, step / steps)) : 0;+ this.value = Math.max(this.value, Math.min(0.99, (this.done + inNode) / this.total));+ if (steps && steps > 1) { this.step = step; this.steps = steps; } else if (nodesTotal > 0) { this.step = null; this.steps = null; }+ const id = typeof d.current_node === "string" ? d.current_node : null;+ if (id) this.node = this.classOf(id) ?? this.node;+ return { value: this.value, step: this.step, steps: this.steps, node: this.node };+ }+}+const ID = /^\d{8}-\d{9}-[0-9a-f]{4}$/;const EXT: Record<string, string> = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif",@@ -151,13 +203,14 @@ export class History {readonly dir: string;private onContact: () => void;- private outputNodes: (appId: string) => string[];+ private appInfo: (appId: string) => AppInfo | undefined;+ private frames?: (jobId: string, signal: AbortSignal) => AsyncIterable<Frame>;- /** outputNodes(app): the nodes app.json declares as outputs, in order; [] means "keep every media output". */- constructor(dir: string, onContact: () => void = () => {}, outputNodes: (appId: string) => string[] = () => []) {+ constructor(dir: string, opts: HistoryOptions = {}) {this.dir = dir;- this.onContact = onContact;- this.outputNodes = outputNodes;+ this.onContact = opts.onContact ?? (() => {});+ this.appInfo = opts.appInfo ?? (() => undefined);+ this.frames = opts.frames;mkdirSync(dir, { recursive: true });}@@ -219,20 +272,38 @@ export class History {if (s === "running") entry.started ??= new Date().toISOString();this.save(entry);};+ const info = this.appInfo(entry.app);+ const meter = new Meter(info?.nodes ?? 0, info?.classOf);const stop = new AbortController();// live progress from the event stream; the poll in wait() below stays the source of truthconst stream = (async () => {try {- for await (const ev of job.events(stop.signal)) {- this.onContact();- if (ev.kind === "progress") {- live.progress = { value: Number(ev.value) || 0, step: ev.step, steps: ev.steps, node: ev.currentNodeClass };- setStatus("running");- } else if (ev.kind === "preview") {- live.preview = { bytes: ev.data, type: ev.contentType || "image/jpeg", n: (live.preview?.n ?? 0) + 1 };- } else if (ev.kind === "statusChange") {- live.queue = ev.queuePosition;- setStatus(normStatus(ev.status));+ if (this.frames) {+ for await (const f of this.frames(job.id, stop.signal)) {+ this.onContact();+ if (f.event === "progress") {+ live.progress = meter.feed(f.data);+ setStatus("running");+ } else if (f.event === "preview" && typeof f.data.data_base64 === "string") {+ live.preview = { bytes: Buffer.from(f.data.data_base64, "base64"), type: String(f.data.content_type || "image/jpeg"), n: (live.preview?.n ?? 0) + 1 };+ } else if (f.event === "status") {+ live.queue = typeof f.data.queue_position === "number" ? f.data.queue_position : null;+ setStatus(normStatus(String(f.data.status ?? "")));+ }+ }+ } else {+ for await (const ev of job.events(stop.signal)) {+ this.onContact();+ if (ev.kind === "progress") {+ live.progress = meter.feed({ nodes_done: ev.nodesDone, nodes_total: ev.nodesTotal, step: ev.step, steps: ev.steps, current_node: ev.currentNode });+ if (ev.currentNodeClass) live.progress.node = ev.currentNodeClass;+ setStatus("running");+ } else if (ev.kind === "preview") {+ live.preview = { bytes: ev.data, type: ev.contentType || "image/jpeg", n: (live.preview?.n ?? 0) + 1 };+ } else if (ev.kind === "statusChange") {+ live.queue = ev.queuePosition;+ setStatus(normStatus(ev.status));+ }}}} catch {@@ -244,8 +315,10 @@ export class History {setStatus(normStatus(job.status));if (job.queuePosition !== undefined) live.queue = job.queuePosition ?? live.queue;const p = job.progress;- if (p && (!live.progress || p.value > live.progress.value)) {- live.progress = { value: p.value, step: p.step, steps: p.steps, node: p.currentNodeClass };+ if (p && (p.step !== null || (p.value > 0 && p.value > meter.value))) {+ // a backend whose poll carries a live snapshot (comfy-api-proxy's does not: 0, 0/0)+ live.progress = meter.feed({ nodes_done: p.value * (info?.nodes ?? 0), nodes_total: info?.nodes ?? 0, step: p.step, steps: p.steps });+ if (p.currentNodeClass) live.progress.node = p.currentNodeClass;}}, 1000);@@ -278,7 +351,7 @@ export class History {if (entry.status === "succeeded") {const folder = join(this.dir, entry.id);let n = 0;- for (const out of pickOutputs(job.outputs, this.outputNodes(entry.app))) {+ for (const out of pickOutputs(job.outputs, info?.outputs ?? [])) {try {const bytes = await out.toBytes();const ext = safeExt(out.name, out.contentType);@@ -393,8 +466,13 @@ export class History {if (!ID.test(id)) return null;try {const entry = JSON.parse(readFileSync(join(this.dir, id, "meta.json"), "utf-8")) as Entry;- // entries saved before mediaKind() carry the SDK's type: fix them as they are read+ // entries saved before mediaKind() and pickOutputs() carry the SDK's type and every output the backend+ // listed, the given clip first: fix them as they are read (the files stay on disk)for (const o of entry.outputs ?? []) o.type = mediaKind(extname(o.file).toLowerCase(), o.type);+ if (entry.outputs?.length > 1) {+ entry.outputs = pickOutputs(entry.outputs.map((o) => ({ ...o, nodeId: o.node })), this.appInfo(entry.app)?.outputs ?? [])+ .map(({ nodeId: _, ...o }) => o);+ }return entry;} catch {return null;diff --git a/server/runner.ts b/server/runner.tsindex 03e93d3..496e222 100644--- a/server/runner.ts+++ b/server/runner.ts@@ -212,4 +212,70 @@ export class Runner {jobs() {return this.comfy.jobs;}++ /**+ * The job's event stream (GET /api/v2/jobs/{id}/events) read as it comes, frame by frame, without the SDK's+ * job.events(): that one drops any progress frame lower than the last, and comfy-api-proxy's first frames+ * can say 1.0 (history.ts, Meter). Reconnects while the signal is alive; a stream that answers anything+ * but 200 (the job is gone) ends quietly: the poll decides.+ */+ async *frames(jobId: string, signal: AbortSignal): AsyncIterable<Frame> {+ const url = `${this.baseUrl}/api/v2/jobs/${encodeURIComponent(jobId)}/events`;+ const headers = { accept: "text/event-stream", ...(this.token ? { authorization: `Bearer ${this.token}` } : {}) };+ let failures = 0;+ while (!signal.aborted) {+ let res: Response;+ try {+ res = await this.doFetch(url, { headers, signal });+ } catch {+ if (signal.aborted || ++failures > 20) return;+ await new Promise((r) => setTimeout(r, Math.min(10_000, 1000 * failures)));+ continue;+ }+ if (res.status !== 200 || !res.body) return;+ failures = 0;+ try {+ yield* parseSse(res.body);+ } catch {+ if (signal.aborted) return;+ }+ if (!signal.aborted) await new Promise((r) => setTimeout(r, 1000));+ }+ }+}++export type Frame = { event: string; data: Record<string, unknown> };++/** Server-sent events, as the spec reads them: `event:` and `data:` lines, a blank line ends a frame. */+export async function* parseSse(body: ReadableStream<Uint8Array>): AsyncIterable<Frame> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buf = "", event = "message", data: string[] = [];+ const flush = (): Frame | null => {+ const out = data.length ? { event, data: safeJson(data.join("\n")) } : null;+ event = "message"; data = [];+ return out;+ };+ for (;;) {+ const { value, done } = await reader.read();+ buf += done ? "\n\n" : decoder.decode(value, { stream: true });+ let nl: number;+ while ((nl = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, nl).replace(/\r$/, "");+ buf = buf.slice(nl + 1);+ if (line === "") { const f = flush(); if (f) yield f; }+ else if (line.startsWith("event:")) event = line.slice(6).trim();+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));+ }+ if (done) return;+ }+}++function safeJson(text: string): Record<string, unknown> {+ try {+ const v = JSON.parse(text);+ return v && typeof v === "object" ? (v as Record<string, unknown>) : { value: v };+ } catch {+ return { text };+ }}diff --git a/server/server.ts b/server/server.tsindex 09f5665..cc53f97 100644--- a/server/server.ts+++ b/server/server.ts@@ -44,7 +44,16 @@ const WARM_MS = 9 * 60 * 1000;let lastContact = 0;let waking: { since: number; error?: string } | null = null;const contact = () => { lastContact = Date.now(); };-const history = new History(join(root, "out", "history"), contact, (id) => (apps.find((a) => a.id === id)?.outputs ?? []).map((o) => o.node));+const history = new History(join(root, "out", "history"), {+ onContact: contact,+ appInfo: (id) => {+ const app = apps.find((a) => a.id === id);+ if (!app) return undefined;+ const graph = app.graph ?? {};+ return { outputs: app.outputs.map((o) => o.node), nodes: Object.keys(graph).length, classOf: (n) => graph[n]?.class_type ?? null };+ },+ frames: (jobId, signal) => getRunner().frames(jobId, signal),+});const flags = new Flags(join(root, "lab", "flags.json"), apps);const MIME: Record<string, string> = {diff --git a/test/history.test.ts b/test/history.test.tsindex 87f1e53..c11aaab 100644--- a/test/history.test.ts+++ b/test/history.test.ts@@ -6,7 +6,8 @@ import { join } from "node:path";import type { ComfyEvent } from "@comfyorg/sdk";import { loadRegistry } from "../server/registry.ts";import { resolveValues } from "../server/runner.ts";-import { History, pickOutputs, type JobLike } from "../server/history.ts";+import { History, Meter, pickOutputs, type JobLike } from "../server/history.ts";+import { parseSse, type Frame } from "../server/runner.ts";const { apps } = loadRegistry();const byId = (id: string) => apps.find((a) => a.id === id)!;@@ -87,6 +88,55 @@ test("the app's declared output nodes come first; the backend also lists what Loassert.deepEqual(pickOutputs([given, made], ["999"]), [given, made], "a wrong declaration still shows the results");});+test("the progress bar is ours: nodes finished over the workflow's node count, never backwards, never full", () => {+ const m = new Meter(20, (id) => ({ "3": "KSampler" })[id] ?? null);+ // comfy-api-proxy's first progress_state: the one node touched so far has finished → it says 1/1 = 1.0+ assert.equal(m.feed({ value: 1, nodes_done: 1, nodes_total: 1, step: null, steps: null }).value, 0.05);+ // a per-node frame (nodes_total 0) carries the sampler steps of the running node+ const p = m.feed({ value: 0.5, nodes_done: 0, nodes_total: 0, step: 4, steps: 8, current_node: "3" });+ assert.deepEqual(p, { value: 0.075, step: 4, steps: 8, node: "KSampler" });+ // a lower frame after a drop does not move it back+ assert.equal(m.feed({ value: 0.1, nodes_done: 0, nodes_total: 0, step: 1, steps: 8 }).value, 0.075);+ // all nodes done but the job not over yet: 0.99, not 1+ assert.equal(m.feed({ value: 1, nodes_done: 20, nodes_total: 20 }).value, 0.99);+});++test("a job is followed through the raw event stream when the history has one", async () => {+ const { history, done } = tempHistory();+ const sent: Frame[] = [+ { event: "status", data: { status: "running", queue_position: null } },+ { event: "progress", data: { value: 1, nodes_done: 1, nodes_total: 1 } },+ { event: "progress", data: { value: 0.25, nodes_done: 0, nodes_total: 0, step: 2, steps: 8, current_node: "3" } },+ ];+ const seen: number[] = [];+ let entryId = "";+ const withFrames = new History(history.dir, {+ appInfo: () => ({ outputs: ["9"], nodes: 10, classOf: () => "KSampler" }),+ frames: async function* (jobId) { assert.equal(jobId, "job-1"); for (const f of sent) { yield f; seen.push(withFrames.get(entryId)!.progress?.value ?? -1); await new Promise((r) => setTimeout(r, 1)); } },+ });+ try {+ const app = byId("z-image");+ const entry = withFrames.start(app, resolveValues(app, { prompt: "a fox" }));+ entryId = entry.id;+ const ended = await withFrames.follow(entry, fakeJob("succeeded"));+ assert.equal(ended.status, "succeeded");+ assert.deepEqual(seen, [-1, 0.1, 0.125], "1/1 reads as one node of ten, then the sampler's 2/8 adds a quarter node");+ } finally { done(); }+});++test("server-sent events are read frame by frame, across chunk boundaries", async () => {+ const text = "event: progress\ndata: {\"value\": 0.5}\n\n: comment\nevent: preview\ndata: {\"data_base64\": \"AA==\",\ndata: \"content_type\": \"image/jpeg\"}\n\ndata: tail";+ const chunks = [text.slice(0, 17), text.slice(17, 40), text.slice(40)];+ const body = new ReadableStream<Uint8Array>({ start(c) { for (const ch of chunks) c.enqueue(new TextEncoder().encode(ch)); c.close(); } });+ const frames: Frame[] = [];+ for await (const f of parseSse(body)) frames.push(f);+ assert.deepEqual(frames, [+ { event: "progress", data: { value: 0.5 } },+ { event: "preview", data: { data_base64: "AA==", content_type: "image/jpeg" } },+ { event: "message", data: { text: "tail" } },+ ]);+});+test("a failed job keeps the node and the message", async () => {const { history, done } = tempHistory();try {