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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Merge branch 'r3fix/canvas' into claude/fuobe-parity-3
Claude16595c0a552f
diff --cc src/lib/api.tsindex c5992bdf,7f3e840d..4bf366d4--- a/src/lib/api.ts+++ b/src/lib/api.ts@@@ -15,10 -15,8 +16,11 @@@ importparseSse,shareById,sharePagesById,+ streamResponse,+ toChannelMessage,toStreamEvent,+ type CanvasViewLike,+ type ChannelMessage,type Pages,type StreamEvent,} from "./generation-stream";@@@ -87,253 -93,90 +97,254 @@@ function cached(qc: QueryClient, id: streturn best;}-const patched = (g: Generation, patch: Partial<Generation>): Generation => ({ ...g, ...patch, updatedAt: Math.max(Date.now(), g.updatedAt + 1) });+/**+ * A local edit, applied before the server answers. It keeps the server's updatedAt (the browser's+ * clock may be ahead of the server's, and a copy stamped with it would make the reducers drop the+ * server's own events for that row as "late"); events at or after that time replace it.+ */+const patched = (g: Generation, patch: Partial<Generation>): Generation => ({ ...g, ...patch });// --- Live updates (GET /api/generations/stream, built by the runtime) -------------------------+//+// One stream per browser, not one per tab: over HTTP/1.1 a browser opens at most ~6 connections+// to a host, so a stream held open in every tab would leave the 6th tab unable to load anything.+// The tabs elect a leader with the Web Locks API: the leader reads the stream and passes every+// event (and whether it's connected) to the other tabs on a BroadcastChannel. Without Web Locks+// (an http:// address other than localhost) each tab reads its own. Either way a tab that has been+// hidden for 30 s lets go (its stream, or its place in line to lead) and catches up when shown.++const LOCK = "fuobe-generation-stream";+const CHANNEL = "fuobe-generations";+const HIDDEN_GRACE_MS = 30_000;++interface ClientStreamState {+ connected: boolean;+ everConnected: boolean;+ /** Mounted views showing generations in this tab. */+ subscribers: number;+ listeners: Set<() => void>;+ /** Raw event listeners (views that keep their own caches: useGenerationEvents). */+ handlers: Set<(ev: StreamEvent) => void>;+ client: QueryClient | null;+ /** Taking part: leading, or listening to the leader and waiting in line. */+ running: boolean;+ leader: boolean;+ abort: AbortController | null;+ timer: ReturnType<typeof setTimeout> | null;+ attempt: number;+ /** Our place in line for the lock (aborted to withdraw). */+ ticket: AbortController | null;+ /** Gives the lock back. */+ release: (() => void) | null;+ channel: BroadcastChannel | null;+ hiddenTimer: ReturnType<typeof setTimeout> | null;+ stopTimer: ReturnType<typeof setTimeout> | null;+ hooked: boolean;+}++declare global {+ // On window, so a hot-reloaded module keeps the lock and stream it already holds.+ var __fuobeClientStream: ClientStreamState | undefined;+}++const live = (): ClientStreamState =>+ (globalThis.__fuobeClientStream ??= {+ connected: false,+ everConnected: false,+ subscribers: 0,+ listeners: new Set(),+ handlers: new Set(),+ client: null,+ running: false,+ leader: false,+ abort: null,+ timer: null,+ attempt: 0,+ ticket: null,+ release: null,+ channel: null,+ hiddenTimer: null,+ stopTimer: null,+ hooked: false,+ });-const live = {- connected: false,- everConnected: false,- subscribers: 0,- listeners: new Set<() => void>(),- abort: null as AbortController | null,- timer: null as ReturnType<typeof setTimeout> | null,- attempt: 0,- client: null as QueryClient | null,-};+const shared = () => typeof navigator !== "undefined" && !!navigator.locks && typeof BroadcastChannel !== "undefined";++function post(m: ChannelMessage) {+ try {+ live().channel?.postMessage(m);+ } catch {}+}function setLive(v: boolean) {- if (live.connected === v) return;- live.connected = v;- live.listeners.forEach((l) => l());+ const s = live();+ if (s.connected === v) return;+ const catchUp = needsCatchUp(s.connected, v, s.everConnected);+ s.connected = v;+ if (v) s.everConnected = true;+ if (s.leader) post({ type: "state", connected: v });+ // Back after a drop: whatever changed meanwhile.+ if (catchUp && s.client) {+ void s.client.invalidateQueries({ queryKey: ["generations"] });+ void s.client.invalidateQueries({ queryKey: ["library"] });++ void s.client.invalidateQueries({ queryKey: ["canvases"] });+ }+ s.listeners.forEach((l) => l());}-function scheduleReconnect(missing: boolean) {- setLive(false);- live.abort = null;- if (!live.subscribers) return;- live.timer = setTimeout(connect, backoff(live.attempt++, missing));+function receive(ev: StreamEvent) {+ const s = live();+ if (s.client) applyEvent(s.client, ev);+ s.handlers.forEach((h) => h(ev));}+/** Read the stream (this tab's own, or as the leader for every tab). */async function connect() {- live.timer = null;- if (live.abort || !live.subscribers || !live.client) return;+ const s = live();+ s.timer = null;+ if (s.abort || !s.running || !s.client || (shared() && !s.leader)) return;const ctrl = new AbortController();- live.abort = ctrl;+ s.abort = ctrl;+ let retryIn = 0;try {const res = await fetch("/api/generations/stream", { headers: { Accept: "text/event-stream" }, signal: ctrl.signal, cache: "no-store" });- if (!res.ok || !res.body || !res.headers.get("content-type")?.includes("text/event-stream")) {- // No stream on this server (yet): keep polling, look again in a few minutes.- return scheduleReconnect(res.status === 404 || res.ok);- }- live.attempt = 0;- setLive(true);- // Back after a drop: catch up on whatever changed while we were away.- if (live.everConnected) {- void live.client.invalidateQueries({ queryKey: ["generations"] });- void live.client.invalidateQueries({ queryKey: ["library"] });- void live.client.invalidateQueries({ queryKey: ["canvases"] });- }- live.everConnected = true;- const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();- let buf = "";- for (;;) {- const { value, done } = await reader.read();- if (done) break;- const parsed = parseSse(buf + value);- buf = parsed.rest;- for (const m of parsed.events) {- const ev = toStreamEvent(m);- if (ev && live.client) applyEvent(live.client, ev);+ const next = streamResponse({ ok: res.ok, status: res.status, contentType: res.headers.get("content-type"), hasBody: !!res.body }, s.attempt++);+ if (!next.open || !res.body) {+ void res.body?.cancel().catch(() => {});+ retryIn = next.open ? backoff(s.attempt) : next.retryIn;+ } else {+ s.attempt = 0;+ setLive(true);+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();+ let buf = "";+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ const parsed = parseSse(buf + value);+ buf = parsed.rest;+ for (const m of parsed.events) {+ const ev = toStreamEvent(m);+ if (!ev) continue;+ receive(ev);+ if (s.leader) post({ type: "event", ev });+ }}+ retryIn = backoff(s.attempt++);}} catch {if (ctrl.signal.aborted) return;+ retryIn = backoff(s.attempt++);+ }+ if (s.abort !== ctrl) return;+ s.abort = null;+ setLive(false);+ if (s.running && (!shared() || s.leader)) s.timer = setTimeout(() => void connect(), retryIn);+}++/** Wait in line for the lock; holding it, read the stream for every tab until we let go. */+function lead() {+ const s = live();+ const ticket = new AbortController();+ s.ticket = ticket;+ navigator.locks+ .request(LOCK, { signal: ticket.signal }, () => {+ // Withdrawn meanwhile: give it straight back.+ if (s.ticket !== ticket || !s.running) return;+ s.ticket = null;+ return new Promise<void>((resolve) => {+ s.leader = true;+ s.release = resolve;+ // Whatever the last leader said: our own stream decides now (and catches up when it opens).+ setLive(false);+ void connect();+ });+ })+ .catch(() => {});+}++function openChannel() {+ const s = live();+ const ch = new BroadcastChannel(CHANNEL);+ ch.onmessage = (e: MessageEvent) => {+ const m = toChannelMessage(e.data);+ if (!m) return;+ if (m.type === "hello") {+ if (s.leader) post({ type: "state", connected: s.connected });+ return;+ }+ if (s.leader) return;+ if (m.type === "state") setLive(m.connected);+ else receive(m.ev);+ };+ s.channel = ch;+ post({ type: "hello" });+}++function start() {+ const s = live();+ if (s.running || !s.client) return;+ s.running = true;+ if (shared()) {+ openChannel();+ lead();+ } else void connect();+}++function stop() {+ const s = live();+ if (!s.running) return;+ s.running = false;+ s.ticket?.abort();+ s.ticket = null;+ s.abort?.abort();+ s.abort = null;+ if (s.timer) clearTimeout(s.timer);+ s.timer = null;+ setLive(false);+ s.leader = false;+ const release = s.release;+ s.release = null;+ release?.();+ s.channel?.close();+ s.channel = null;+}++function onVisibility() {+ const s = live();+ if (document.visibilityState === "hidden") {+ s.hiddenTimer ??= setTimeout(() => {+ s.hiddenTimer = null;+ stop();+ }, HIDDEN_GRACE_MS);+ return;}- if (live.abort === ctrl) scheduleReconnect(false);+ if (s.hiddenTimer) clearTimeout(s.hiddenTimer);+ s.hiddenTimer = null;+ if (s.subscribers) start();}- /** Share one stream between every list on the page (and every tab); returns whether it's connected. */- function useGenerationStream(): boolean {-/** Share one stream between every list on the page (and canvas boards); returns whether it's connected. */++/** Share one stream between every list on the page (and every tab, and canvas boards); returns whether it's connected. */+ export function useGenerationStream(): boolean {const qc = useQueryClient();useEffect(() => {- live.client = qc;- live.subscribers++;- if (!live.abort && !live.timer) void connect();+ const s = live();+ s.client = qc;+ s.subscribers++;+ if (s.stopTimer) clearTimeout(s.stopTimer);+ s.stopTimer = null;+ if (!s.hooked) {+ s.hooked = true;+ document.addEventListener("visibilitychange", onVisibility);+ }+ // A tab opened in the background waits until it's shown.+ if (document.visibilityState !== "hidden") start();return () => {- live.subscribers--;- if (live.subscribers) return;+ s.subscribers--;+ if (s.subscribers) return;// Keep it through quick remounts (route changes); drop it when nothing shows generations.- setTimeout(() => {- if (live.subscribers) return;- live.abort?.abort();- live.abort = null;- if (live.timer) clearTimeout(live.timer);- live.timer = null;- setLive(false);+ s.stopTimer = setTimeout(() => {+ s.stopTimer = null;+ if (!s.subscribers) stop();}, 5000);};}, [qc]);