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.

Live updates: one stream per browser; cursor paging, batched bulk, no client clock

Claude01fee1e3c3d5
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 0296bfdf..8dfe803a 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -1,13 +1,28 @@
"use client";
import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
-import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
+import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { toast } from "sonner";
import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";
import type { ElementKind, StudioElement } from "./catalog/elements";
import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";
-import { applyToList, applyToPages, applyToThread, backoff, parseSse, shareById, sharePagesById, toStreamEvent, type Pages, type StreamEvent } from "./generation-stream";
-import { filterToSearch, type FeedFilter, type Folder } from "./library";
+import {
+ applyToList,
+ applyToPages,
+ applyToThread,
+ backoff,
+ needsCatchUp,
+ parseSse,
+ shareById,
+ sharePagesById,
+ streamResponse,
+ toChannelMessage,
+ toStreamEvent,
+ type ChannelMessage,
+ type Pages,
+ type StreamEvent,
+} from "./generation-stream";
+import { cursorAfter, filterToSearch, type FeedFilter, type Folder } from "./library";
export interface Asset {
id: string;
@@ -72,102 +87,285 @@ function cached(qc: QueryClient, id: string): Generation | undefined {
return 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"] });
+ }
+ 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"] });
- }
- 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; returns whether it's connected. */
+/** Share one stream between every list on the page (and every tab); returns whether it's connected. */
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]);
return useSyncExternalStore(
(cb) => {
- live.listeners.add(cb);
- return () => live.listeners.delete(cb);
+ const s = live();
+ s.listeners.add(cb);
+ return () => s.listeners.delete(cb);
},
- () => live.connected,
+ () => live().connected,
() => false,
);
}
+/**
+ * Listen to the shared live stream (one per browser) from a view with its own caches, instead of
+ * opening another EventSource. Returns whether it's connected; poll when it isn't.
+ */
+export function useGenerationEvents(onEvent: (ev: StreamEvent) => void): boolean {
+ const ref = useRef(onEvent);
+ useEffect(() => {
+ ref.current = onEvent;
+ });
+ useEffect(() => {
+ const h = (ev: StreamEvent) => ref.current(ev);
+ const s = live();
+ s.handlers.add(h);
+ return () => void s.handlers.delete(h);
+ }, []);
+ return useGenerationStream();
+}
+
// --- Lists ----------------------------------------------------------------------------------
function feedKey(f: FeedFilter) {
@@ -193,14 +391,11 @@ export function useLibrary(filter: FeedFilter) {
const f = { ...filter, limit: filter.limit ?? LIBRARY_PAGE };
return useInfiniteQuery({
queryKey: ["library", f] as const,
- initialPageParam: undefined as number | undefined,
+ initialPageParam: undefined as string | undefined,
queryFn: async ({ pageParam }) =>
(await json<{ items: Generation[] }>(await fetch(`/api/generations${f.trashed ? "/trash" : ""}?${filterToSearch(f, pageParam)}`))).items,
- getNextPageParam: (last) => {
- if (last.length < f.limit) return undefined;
- const tail = last.at(-1)!;
- return f.trashed ? (tail.deletedAt ?? undefined) : tail.createdAt;
- },
+ // The last row's timestamp and id: rows sharing a timestamp across the page boundary aren't skipped.
+ getNextPageParam: (last) => (last.length < f.limit ? undefined : cursorAfter(last.at(-1)!, f.trashed)),
placeholderData: keepPreviousData,
structuralSharing: sharePagesById,
refetchInterval: (q) => pollEvery(q.state.data?.pages.flat(), connected),
@@ -248,12 +443,17 @@ export function useCreateGeneration() {
export type BulkAction = "trash" | "restore" | "delete" | "favorite" | "unfavorite" | "move";
+/** The bulk endpoint takes this many ids per request. */
+export const BULK_MAX = 500;
+
+/** One bulk action, sent in batches of BULK_MAX (a select-all after a few "Load more" can be bigger). */
async function bulkRequest(action: BulkAction, ids: string[], folderId?: string | null): Promise<number> {
- return (
- await json<{ count: number }>(
- await fetch("/api/generations/bulk", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action, ids, folderId }) }),
- )
- ).count;
+ let n = 0;
+ for (let i = 0; i < ids.length; i += BULK_MAX) {
+ const body = JSON.stringify({ action, ids: ids.slice(i, i + BULK_MAX), folderId });
+ n += (await json<{ count: number }>(await fetch("/api/generations/bulk", { method: "POST", headers: { "Content-Type": "application/json" }, body }))).count;
+ }
+ return n;
}
/** Stable result actions (one object per QueryClient), so memoized tiles don't re-render. */
@@ -287,8 +487,12 @@ export function useGenerationActions() {
};
const restore = (gs: Generation[]) => run(gs, { deletedAt: null }, "restore");
const trash = (gs: Generation[], what?: string) => {
+ // The server cancels jobs still rendering: say so.
+ const active = gs.filter((g) => isActive(cached(qc, g.id) ?? g)).length;
const p = run(gs, { deletedAt: Date.now() }, "trash");
- toast(what ?? (gs.length === 1 ? "Moved to Trash" : `${gs.length} moved to Trash`), {
+ const said =
+ gs.length === 1 ? (active ? "Canceled and moved to Trash" : "Moved to Trash") : `${gs.length} moved to Trash${active ? ` · ${active} canceled` : ""}`;
+ toast(what ?? said, {
id: "trash-undo",
duration: 6000,
action: { label: "Undo", onClick: () => void p.then(() => restore(gs)) },
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
index 1d93e66c..d3cedd78 100644
--- a/src/lib/generation-stream.ts
+++ b/src/lib/generation-stream.ts
@@ -8,10 +8,9 @@
*/
import { replaceEqualDeep } from "@tanstack/react-query";
import type { Generation } from "./catalog/types";
-import { byNewest, matchesFilter, type FeedFilter } from "./library";
+import { byDeleted, byNewest, matchesFilter, type FeedFilter } from "./library";
/** Lists are newest first; the Trash is most recently deleted first. */
-const byDeleted = (a: Generation, b: Generation) => (b.deletedAt ?? 0) - (a.deletedAt ?? 0) || byNewest(a, b);
const orderFor = (f: FeedFilter) => (f.trashed ? byDeleted : byNewest);
export type StreamEvent = { type: "generation"; generation: Generation } | { type: "deleted"; id: string };
@@ -162,3 +161,40 @@ export function sharePagesById(prev: unknown, next: unknown): unknown {
export function backoff(attempt: number, missing = false): number {
return missing ? 300_000 : Math.min(30_000, 1000 * 2 ** Math.max(0, attempt));
}
+
+/**
+ * What to do with the stream endpoint's answer: read it, or try again later. A 404, or a page that
+ * isn't an event stream, means this server has no stream: polling carries on, and it looks again in
+ * 5 minutes. Other failures back off from 1 s.
+ */
+export function streamResponse(res: { ok: boolean; status: number; contentType: string | null; hasBody: boolean }, attempt: number): { open: true } | { open: false; retryIn: number } {
+ if (res.ok && res.hasBody && res.contentType?.includes("text/event-stream")) return { open: true };
+ return { open: false, retryIn: backoff(attempt, res.status === 404 || res.ok) };
+}
+
+/**
+ * Whether going live needs a catch-up refetch: on every (re)connection but the first, since events
+ * may have been missed while the stream was down (a drop, a hand-over between tabs, a hidden tab).
+ */
+export function needsCatchUp(was: boolean, now: boolean, everConnected: boolean): boolean {
+ return now && !was && everConnected;
+}
+
+/**
+ * What tabs say to each other on the BroadcastChannel. One tab (the leader) reads the stream and
+ * passes on every event and its connection state; a tab that joins says hello to get the state.
+ */
+export type ChannelMessage = { type: "event"; ev: StreamEvent } | { type: "state"; connected: boolean } | { type: "hello" };
+
+export function toChannelMessage(data: unknown): ChannelMessage | null {
+ if (!data || typeof data !== "object") return null;
+ const m = data as Record<string, unknown>;
+ if (m.type === "hello") return { type: "hello" };
+ if (m.type === "state" && typeof m.connected === "boolean") return { type: "state", connected: m.connected };
+ if (m.type !== "event" || !m.ev || typeof m.ev !== "object") return null;
+ const ev = m.ev as Record<string, unknown>;
+ if (ev.type === "deleted" && typeof ev.id === "string") return { type: "event", ev: { type: "deleted", id: ev.id } };
+ const g = ev.generation as Record<string, unknown> | undefined;
+ if (ev.type === "generation" && g && typeof g.id === "string" && typeof g.createdAt === "number") return { type: "event", ev: { type: "generation", generation: g as unknown as Generation } };
+ return null;
+}
diff --git a/src/lib/library.ts b/src/lib/library.ts
index 08c076c3..f4aec08e 100644
--- a/src/lib/library.ts
+++ b/src/lib/library.ts
@@ -2,7 +2,7 @@
* Library (Assets) logic shared by the browser and the server: feed filters, folders, the Trash,
* download names, date sections and batch stacks. Pure: no React, no database.
*/
-import type { Generation, GenerationStatus, MediaKind, OutputFile } from "./catalog/types";
+import { OPERATION_LABELS, type Generation, type GenerationStatus, type MediaKind, type OutputFile } from "./catalog/types";
// ---------------------------------------------------------------------------
// Filters (GET /api/generations query ⇄ client-side matching for live cache updates)
@@ -24,7 +24,13 @@ export interface FeedFilter {
trashed?: boolean;
}
-export function filterToSearch(f: FeedFilter, before?: number): URLSearchParams {
+/** The paging cursor for the page after `last`: its timestamp (deletedAt in the Trash) and id, so equal timestamps aren't skipped. */
+export function cursorAfter(last: Generation, trashed?: boolean): string | undefined {
+ const ts = trashed ? last.deletedAt : last.createdAt;
+ return ts ? `${ts}:${last.id}` : undefined;
+}
+
+export function filterToSearch(f: FeedFilter, before?: string | number): URLSearchParams {
const qs = new URLSearchParams();
if (f.kind) qs.set("kind", f.kind);
if (f.kinds?.length) qs.set("kinds", f.kinds.join(","));
@@ -61,9 +67,16 @@ export function matchesFilter(g: Generation, f: FeedFilter): boolean {
return true;
}
+const byIdDesc = (a: Generation, b: Generation) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+
/** Newest first, as the server orders lists (ties: id descending). */
export function byNewest(a: Generation, b: Generation): number {
- return b.createdAt - a.createdAt || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+ return b.createdAt - a.createdAt || byIdDesc(a, b);
+}
+
+/** The Trash's order: most recently deleted first (ties: id descending, like the server). */
+export function byDeleted(a: Generation, b: Generation): number {
+ return (b.deletedAt ?? 0) - (a.deletedAt ?? 0) || byIdDesc(a, b);
}
// ---------------------------------------------------------------------------
@@ -170,19 +183,28 @@ function unwrapScene(scene: string): string {
return /^[^:]{2,40}:\s*(.+?)\s+—\s+beat \d+ of \d+$/.exec(scene.trim())?.[1] ?? scene.trim();
}
-/** What the user asked for, never the internal chain prompt. */
-export function userTitle(g: Generation): string {
- const own = (g.request as { title?: string }).title?.trim();
+/**
+ * What the user asked for, never the internal chain prompt. Results made without words (transcribe,
+ * image to 3D, upscale, trim…) are named by what was done: "Transcribe · Whisper".
+ */
+export function userTitle(g: Pick<Generation, "request" | "presetName" | "prompt" | "op" | "modelName">): string {
+ const own = g.request.title?.trim();
if (own) return own;
if (g.request.frame) return unwrapScene(g.request.frame.scene);
- return g.request.prompt?.trim() || g.presetName || g.prompt || "Untitled";
+ const words = g.request.prompt?.trim() || g.presetName || g.prompt?.trim();
+ if (words && words !== g.op) return words;
+ const what = OPERATION_LABELS[g.op];
+ return what ? `${what}${g.modelName ? ` · ${g.modelName}` : ""}` : (g.modelName ?? "Untitled");
}
const order = (g: Generation) => g.request.step?.index ?? g.request.frame?.index ?? 0;
export function stackTitle(items: Generation[]): string {
- const titled = items.find((g) => (g.request as { title?: string }).title?.trim());
+ const titled = items.find((g) => g.request.title?.trim());
if (titled) return userTitle(titled);
+ // An Assist plan: its summary.
+ const plan = items.find((g) => g.request.batchTitle?.trim())?.request.batchTitle?.trim();
+ if (plan) return plan;
const frames = items.filter((g) => g.request.frame).sort((a, b) => order(a) - order(b));
if (frames.length) return unwrapScene(frames[0].request.frame!.scene);
const film = items.find((g) => g.op === "concat" && g.prompt?.trim());
@@ -197,8 +219,9 @@ export function stackLabel(items: Generation[]): string {
const shots = items.filter((g) => /^Shot \d+/.test(g.request.step?.label ?? "")).length;
if (frames) return `Storyboard · ${frames} frame${frames === 1 ? "" : "s"}${films ? " + film" : ""}`;
if (films && shots) return `Film · ${shots} shots`;
- if (items.every((g) => !g.request.step && g.request.prompt === items[0].request.prompt)) return `${items.length} takes`;
- return `${items.length} steps`;
+ if (items.some((g) => g.request.step)) return `${items.length} steps`;
+ if (items.every((g) => g.request.prompt === items[0].request.prompt && g.modelId === items[0].modelId)) return `${items.length} takes`;
+ return `${items.length} results`;
}
/** Group a newest-first list into cards: generations sharing a batch become one stack, placed where its newest member is. */
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index fd90e806..78ad761d 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -6,6 +6,7 @@
* (Download, Favorite), "menu" = the ⋯ menu. The viewer shows them all as labelled buttons.
*/
import type { Generation, OutputFile } from "./catalog/types";
+import { cueText, type Cue } from "./cues";
import { downloadHref, downloadName, extensionOf } from "./library";
export type OutputActionId =
@@ -25,6 +26,7 @@ export type OutputActionId =
| "download"
| "download-txt"
| "download-srt"
+ | "download-vtt"
| "download-all"
| "favorite"
| "finalize"
@@ -100,7 +102,10 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
case "text":
out.push({ id: "copy-text", label: "Copy", placement: "primary" }, file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
if (ext !== "txt" && o.text) out.push({ id: "download-txt", label: "Download .txt", placement: "menu" });
- if (ext !== "srt" && cuesOf(o).length) out.push({ id: "download-srt", label: "Download .srt", placement: "menu" });
+ if (cuesOf(o).length) {
+ if (ext !== "srt") out.push({ id: "download-srt", label: "Download .srt", placement: "menu" });
+ if (ext !== "vtt") out.push({ id: "download-vtt", label: "Download .vtt", placement: "menu" });
+ }
break;
case "model3d":
if (!ctx.inViewer) out.push({ id: "view-3d", label: "View in 3D", placement: "primary" });
@@ -121,39 +126,38 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
// ---------------------------------------------------------------------------
// Text, layers and 3D outputs
-export interface Cue {
- start: number;
- end: number;
- text: string;
-}
-
-/** Timed lines of a transcript (OutputFile.meta.cues, seconds). */
+/** Timed lines of a transcript (OutputFile.meta.cues, seconds; SRT / VTT writers in src/lib/cues.ts). */
export function cuesOf(o: Pick<OutputFile, "meta">): Cue[] {
const cues = o.meta?.cues;
if (!Array.isArray(cues)) return [];
return cues.filter((c): c is Cue => !!c && typeof c === "object" && typeof c.start === "number" && typeof c.end === "number" && typeof c.text === "string");
}
-/** 75.5 → "1:15.5" (viewer), or "00:01:15,500" (SRT). */
-export function cueTime(s: number, srt = false): string {
+/** 75.5 → "1:15.5": the viewer's short timing (files use the SRT / VTT stamps). */
+export function cueTime(s: number): string {
const ms = Math.max(0, Math.round(s * 1000));
const h = Math.floor(ms / 3_600_000);
const m = Math.floor((ms % 3_600_000) / 60_000);
const sec = Math.floor((ms % 60_000) / 1000);
- const frac = ms % 1000;
- const p = (n: number, w = 2) => String(n).padStart(w, "0");
- if (srt) return `${p(h)}:${p(m)}:${p(sec)},${p(frac, 3)}`;
- const tenths = Math.floor(frac / 100);
+ const p = (n: number) => String(n).padStart(2, "0");
+ const tenths = Math.floor((ms % 1000) / 100);
return `${h ? `${h}:${p(m)}` : m}:${p(sec)}${tenths ? `.${tenths}` : ""}`;
}
-export function cuesToSrt(cues: Cue[]): string {
- return cues.map((c, i) => `${i + 1}\n${cueTime(c.start, true)} --> ${cueTime(c.end, true)}\n${c.text.trim()}\n`).join("\n");
-}
-
/** The text of a text output: OutputFile.text, else the cues joined. */
export function textOf(o: Pick<OutputFile, "text" | "meta">): string {
- return o.text ?? cuesOf(o).map((c) => c.text.trim()).join("\n");
+ return o.text ?? cueText(cuesOf(o));
+}
+
+/**
+ * The outputs a result shows as tiles (and the viewer browses): a 3D model's turntable video is
+ * its preview, not a result of its own.
+ */
+export function shownOutputs(g: Pick<Generation, "kind" | "outputs">): number[] {
+ const all = g.outputs.map((_, i) => i);
+ if (g.kind !== "model3d") return all;
+ const own = all.filter((i) => g.outputs[i].kind === "model3d");
+ return own.length ? own : all;
}
/** A layer's name and stacking order (meta.name / meta.z, or meta.layer.{name,z}). */
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 3ad9ef7d..80453c83 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -1,8 +1,9 @@
import { describe, expect, it } from "vitest";
import type { Generation } from "@/lib/catalog/types";
-import { applyToList, applyToPages, applyToThread, backoff, parseSse, shareById, sharePagesById, toStreamEvent } from "@/lib/generation-stream";
-import { buildEntries, dayLabel, downloadName, matchesFilter, splitByDate, trashDaysLeft } from "@/lib/library";
-import { cuesToSrt, cueTime, layerInfo, modelPreview, outputActions, textOf } from "@/lib/output-actions";
+import { applyToList, applyToPages, applyToThread, backoff, needsCatchUp, parseSse, shareById, sharePagesById, streamResponse, toChannelMessage, toStreamEvent } from "@/lib/generation-stream";
+import { buildEntries, byDeleted, byNewest, cursorAfter, dayLabel, downloadName, filterToSearch, matchesFilter, splitByDate, trashDaysLeft, userTitle } from "@/lib/library";
+import { toSrt, toVtt } from "@/lib/cues";
+import { cueTime, layerInfo, modelPreview, outputActions, shownOutputs, textOf } from "@/lib/output-actions";
let n = 0;
function gen(p: Partial<Generation> = {}): Generation {
@@ -82,12 +83,16 @@ describe("outputActions", () => {
});
describe("text, layer and 3D outputs", () => {
- it("formats cues for the viewer and as SRT", () => {
+ it("formats cues for the viewer and as SRT / VTT (one writer, src/lib/cues.ts)", () => {
expect(cueTime(75.5)).toBe("1:15.5");
- expect(cueTime(3725.04, true)).toBe("01:02:05,040");
- expect(cuesToSrt([{ start: 0, end: 1.25, text: " Hello " }, { start: 1.25, end: 3, text: "there" }])).toBe(
- "1\n00:00:00,000 --> 00:00:01,250\nHello\n\n2\n00:00:01,250 --> 00:00:03,000\nthere\n",
- );
+ expect(cueTime(3725.04)).toBe("1:02:05");
+ const cues = [{ start: 0, end: 1.25, text: " Hello " }, { start: 1.25, end: 3, text: "there" }];
+ expect(toSrt(cues)).toBe("1\n00:00:00,000 --> 00:00:01,250\nHello\n\n2\n00:00:01,250 --> 00:00:03,000\nthere\n");
+ expect(toVtt(cues).startsWith("WEBVTT\n\n00:00:00.000 --> 00:00:01.250\nHello\n")).toBe(true);
+ // A transcript saved as .srt offers .txt and .vtt; one saved as text offers .srt and .vtt.
+ const srt = gen({ kind: "text", op: "transcribe", outputs: [{ url: "/t.srt", kind: "text", text: "Hello\nthere", meta: { cues } }] });
+ expect(outputActions(srt, 0).map((a) => a.id)).toEqual(expect.arrayContaining(["download-txt", "download-vtt"]));
+ expect(outputActions(srt, 0).map((a) => a.id)).not.toContain("download-srt");
expect(textOf({ meta: { cues: [{ start: 0, end: 1, text: "a" }, { start: 1, end: 2, text: "b" }] } })).toBe("a\nb");
});
@@ -241,3 +246,73 @@ describe("library helpers", () => {
expect(buildEntries(takes, { stacks: false })).toHaveLength(2);
});
});
+
+describe("round-3 fixes", () => {
+ it("pages with a timestamp + id cursor and orders the Trash like the server", () => {
+ const g = gen({ id: "abc123", createdAt: 500, deletedAt: 900 });
+ expect(cursorAfter(g)).toBe("500:abc123");
+ expect(cursorAfter(g, true)).toBe("900:abc123");
+ expect(cursorAfter(gen({ deletedAt: null }), true)).toBeUndefined();
+ expect(filterToSearch({ limit: 60 }, "500:abc123").get("before")).toBe("500:abc123");
+ // Same deletion time (one bulk trash): id descending, as the server's ORDER BY.
+ const a = gen({ id: "a", deletedAt: 5, createdAt: 9 });
+ const b = gen({ id: "b", deletedAt: 5, createdAt: 1 });
+ expect([a, b].sort(byDeleted).map((x) => x.id)).toEqual(["b", "a"]);
+ expect([a, b].sort(byNewest).map((x) => x.id)).toEqual(["a", "b"]);
+ });
+
+ it("decides what to do with the stream's answer and when to catch up", () => {
+ const sse = { ok: true, status: 200, contentType: "text/event-stream; charset=utf-8", hasBody: true };
+ expect(streamResponse(sse, 3)).toEqual({ open: true });
+ // No stream on this server: poll, look again in 5 minutes.
+ expect(streamResponse({ ...sse, ok: false, status: 404 }, 0)).toEqual({ open: false, retryIn: 300_000 });
+ expect(streamResponse({ ...sse, contentType: "text/html" }, 0)).toEqual({ open: false, retryIn: 300_000 });
+ // A server error backs off.
+ expect(streamResponse({ ...sse, ok: false, status: 502 }, 2)).toEqual({ open: false, retryIn: 4000 });
+ expect(needsCatchUp(false, true, false)).toBe(false); // first connection: the lists just loaded
+ expect(needsCatchUp(false, true, true)).toBe(true); // back after a drop or a hand-over
+ expect(needsCatchUp(true, true, true)).toBe(false);
+ expect(needsCatchUp(true, false, true)).toBe(false);
+ });
+
+ it("only passes on well-formed messages between tabs", () => {
+ const g = gen();
+ expect(toChannelMessage({ type: "event", ev: { type: "generation", generation: g } })).toEqual({ type: "event", ev: { type: "generation", generation: g } });
+ expect(toChannelMessage({ type: "event", ev: { type: "deleted", id: "x" } })).toEqual({ type: "event", ev: { type: "deleted", id: "x" } });
+ expect(toChannelMessage({ type: "state", connected: true })).toEqual({ type: "state", connected: true });
+ expect(toChannelMessage({ type: "hello" })).toEqual({ type: "hello" });
+ for (const bad of [null, "x", { type: "state" }, { type: "event", ev: { type: "generation", generation: { id: 1 } } }, { type: "nope" }]) expect(toChannelMessage(bad)).toBeNull();
+ });
+
+ it("lets a server event replace a local edit (no browser clock in updatedAt)", () => {
+ // A favorite applied locally keeps the server's updatedAt, so the server's next event (same or later) wins.
+ const g = gen({ updatedAt: 1000 });
+ const local = { ...g, favorite: true };
+ const server = { ...g, favorite: true, status: "succeeded" as const, updatedAt: 1000 };
+ expect(applyToList([local], {}, { type: "generation", generation: server })![0]).toBe(server);
+ });
+
+ it("names results made without words by what was done", () => {
+ expect(userTitle(gen({ op: "transcribe", modelName: "Whisper", prompt: null, request: { feature: "transcribe", modelId: "w" } }))).toBe("Transcribe · Whisper");
+ expect(userTitle(gen({ op: "image-to-3d", modelName: "Hunyuan3D", prompt: "image-to-3d", request: { feature: "3d", modelId: "h" } }))).toMatch(/ · Hunyuan3D$/);
+ expect(userTitle(gen({ request: { feature: "image", modelId: "m", prompt: "a fox", title: "Fox poster" } }))).toBe("Fox poster");
+ });
+
+ it("titles an Assist plan's stack with its summary and labels mixed results", () => {
+ const plan = [
+ gen({ batchId: "p", prompt: "a fox", request: { feature: "assist", modelId: "m", prompt: "a fox", batchTitle: "Three animal posters" } }),
+ gen({ batchId: "p", prompt: "an owl", request: { feature: "assist", modelId: "m", prompt: "an owl", batchTitle: "Three animal posters" } }),
+ ];
+ const e = buildEntries(plan)[0];
+ expect(e.type === "stack" && [e.title, e.label]).toEqual(["Three animal posters", "2 results"]);
+ // Each card keeps its own words.
+ expect(userTitle(plan[1])).toBe("an owl");
+ });
+
+ it("shows a 3D model's turntable as its preview, not as a second result", () => {
+ const glb = gen({ kind: "model3d", op: "image-to-3d", outputs: [{ url: "/m.glb", kind: "model3d" }, { url: "/t.mp4", kind: "video" }] });
+ expect(shownOutputs(glb)).toEqual([0]);
+ expect(shownOutputs(gen({ outputs: [{ url: "/1.png", kind: "image" }, { url: "/2.png", kind: "image" }] }))).toEqual([0, 1]);
+ expect(modelPreview(glb, glb.outputs[0]).video).toBe("/t.mp4");
+ });
+});