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.

Result hooks: live stream reducer, Trash with Undo, folders, paged Library, shared outputActions

Claude9cec0baff387
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 3f826f93..356d9dc4 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -1,10 +1,13 @@
"use client";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useCallback, useEffect, useSyncExternalStore } from "react";
+import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useMemo, 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, toStreamEvent, type Pages, type StreamEvent } from "./generation-stream";
+import { filterToSearch, type FeedFilter, type Folder } from "./library";
export interface Asset {
id: string;
@@ -25,32 +28,192 @@ async function json<T>(res: Response): Promise<T> {
// ---------------------------------------------------------------------------
// Generations
+//
+// Lists live under ["generations", filter] (studio feeds, home) and ["library", filter] (the
+// Library's paged lists); Assist threads hold theirs in ["assist", id]. Every change (the live
+// stream, the user's own actions) goes through applyEvent(), which patches all of them by id.
+
+export type { FeedFilter } from "./library";
+
+const isActive = (g: Generation) => g.status === "queued" || g.status === "running";
+/** Poll while something renders: fast without the live stream, a slow safety net with it. */
+const pollEvery = (items: Generation[] | undefined, live: boolean) => (items?.some(isActive) ? (live ? 10_000 : 1500) : false);
+
+/** Apply one change to every cached list and thread, skipping caches it doesn't change. */
+function applyEvent(qc: QueryClient, ev: StreamEvent): void {
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["generations"] })) {
+ const data = q.state.data as Generation[] | undefined;
+ const next = applyToList(data, (q.queryKey[1] ?? {}) as FeedFilter, ev);
+ if (next !== data) qc.setQueryData(q.queryKey, next);
+ }
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["library"] })) {
+ if (q.queryKey.length !== 2 || typeof q.queryKey[1] !== "object") continue;
+ const data = q.state.data as Pages | undefined;
+ const next = applyToPages(data, q.queryKey[1] as FeedFilter, ev);
+ if (next !== data) qc.setQueryData(q.queryKey, next);
+ }
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["assist"] })) {
+ if (typeof q.queryKey[1] !== "string") continue;
+ const data = q.state.data as AssistThreadView | undefined;
+ const next = applyToThread(data, ev);
+ if (next !== data) qc.setQueryData(q.queryKey, next);
+ }
+}
+
+/** The freshest copy of a generation in any cache (a viewer may hold an older object). */
+function cached(qc: QueryClient, id: string): Generation | undefined {
+ let best: Generation | undefined;
+ const consider = (g: Generation | undefined) => {
+ if (g?.id === id && (!best || g.updatedAt >= best.updatedAt)) best = g;
+ };
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["generations"] })) (q.state.data as Generation[] | undefined)?.forEach(consider);
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["library"] })) (q.state.data as Pages | undefined)?.pages?.forEach((p) => p.forEach(consider));
+ for (const q of qc.getQueryCache().findAll({ queryKey: ["assist"] })) (q.state.data as AssistThreadView | undefined)?.generations?.forEach(consider);
+ return best;
+}
+
+const patched = (g: Generation, patch: Partial<Generation>): Generation => ({ ...g, ...patch, updatedAt: Math.max(Date.now(), g.updatedAt + 1) });
-export interface FeedFilter {
- kind?: MediaKind;
- features?: string[];
- favorites?: boolean;
- q?: string;
- limit?: number;
+// --- Live updates (GET /api/generations/stream, built by the runtime) -------------------------
+
+const live = {
+ connected: 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,
+};
+
+function setLive(v: boolean) {
+ if (live.connected === v) return;
+ live.connected = v;
+ live.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));
}
+async function connect() {
+ live.timer = null;
+ if (live.abort || !live.subscribers || !live.client) return;
+ const ctrl = new AbortController();
+ live.abort = ctrl;
+ 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);
+ // Catch up on whatever changed while we were away.
+ void live.client.invalidateQueries({ queryKey: ["generations"] });
+ 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);
+ }
+ }
+ } catch {
+ if (ctrl.signal.aborted) return;
+ }
+ if (live.abort === ctrl) scheduleReconnect(false);
+}
+
+/** Share one stream between every list on the page; returns whether it's connected. */
+function useGenerationStream(): boolean {
+ const qc = useQueryClient();
+ useEffect(() => {
+ live.client = qc;
+ live.subscribers++;
+ if (!live.abort && !live.timer) void connect();
+ return () => {
+ live.subscribers--;
+ if (live.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);
+ }, 5000);
+ };
+ }, [qc]);
+ return useSyncExternalStore(
+ (cb) => {
+ live.listeners.add(cb);
+ return () => live.listeners.delete(cb);
+ },
+ () => live.connected,
+ () => false,
+ );
+}
+
+// --- Lists ----------------------------------------------------------------------------------
+
function feedKey(f: FeedFilter) {
return ["generations", f] as const;
}
-export function useGenerations(filter: FeedFilter) {
+export function useGenerations(filter: FeedFilter, opts: { keepPrevious?: boolean } = {}) {
+ const connected = useGenerationStream();
return useQuery({
queryKey: feedKey(filter),
- queryFn: async () => {
- const qs = new URLSearchParams();
- if (filter.kind) qs.set("kind", filter.kind);
- if (filter.features?.length) qs.set("features", filter.features.join(","));
- if (filter.favorites) qs.set("favorites", "1");
- if (filter.q) qs.set("q", filter.q);
- qs.set("limit", String(filter.limit ?? 80));
- return (await json<{ items: Generation[] }>(await fetch(`/api/generations?${qs}`))).items;
+ queryFn: async () => (await json<{ items: Generation[] }>(await fetch(`/api/generations?${filterToSearch(filter)}`))).items,
+ placeholderData: opts.keepPrevious ? keepPreviousData : undefined,
+ refetchInterval: (q) => pollEvery(q.state.data, connected),
+ });
+}
+
+export const LIBRARY_PAGE = 60;
+
+/** The Library's paged list ("Load more" pages back with the before cursor). */
+export function useLibrary(filter: FeedFilter) {
+ const connected = useGenerationStream();
+ const f = { ...filter, limit: filter.limit ?? LIBRARY_PAGE };
+ return useInfiniteQuery({
+ queryKey: ["library", f] as const,
+ initialPageParam: undefined as number | 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;
},
- refetchInterval: (q) => (q.state.data?.some((g) => g.status === "queued" || g.status === "running") ? 1500 : false),
+ placeholderData: keepPreviousData,
+ refetchInterval: (q) => pollEvery(q.state.data?.pages.flat(), connected),
+ });
+}
+
+export interface LibraryFacets {
+ models: { id: string; name: string; count: number }[];
+ kinds: Partial<Record<MediaKind, number>>;
+ total: number;
+ favorites: number;
+ failed: number;
+ trash: number;
+}
+
+export function useLibraryFacets() {
+ return useQuery({
+ queryKey: ["library-facets"],
+ queryFn: async () => json<LibraryFacets>(await fetch("/api/generations/facets")),
+ staleTime: 15_000,
});
}
@@ -68,38 +231,123 @@ export function useCreateGeneration() {
)
).items,
onSuccess: (items) => {
- // Show new cards instantly in every matching feed, then let polling take over.
- qc.setQueriesData<Generation[]>({ queryKey: ["generations"] }, (old) => (old ? [...items, ...old] : old));
+ // Show new cards instantly in the feeds they belong to (newest first, like the server), then let polling take over.
+ for (const g of items) applyEvent(qc, { type: "generation", generation: { ...g, deletedAt: null } });
void qc.invalidateQueries({ queryKey: ["generations"] });
+ void qc.invalidateQueries({ queryKey: ["library-facets"] });
},
});
}
+export type BulkAction = "trash" | "restore" | "delete" | "favorite" | "unfavorite" | "move";
+
+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;
+}
+
+/** Stable result actions (one object per QueryClient), so memoized tiles don't re-render. */
export function useGenerationActions() {
const qc = useQueryClient();
- const patchLocal = (id: string, fn: (g: Generation) => Generation | null) =>
- qc.setQueriesData<Generation[]>({ queryKey: ["generations"] }, (old) =>
- old?.map((g) => (g.id === id ? fn(g) : g)).filter((g): g is Generation => !!g),
- );
- return {
- favorite: async (g: Generation) => {
- patchLocal(g.id, (x) => ({ ...x, favorite: !x.favorite }));
- await fetch(`/api/generations/${g.id}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ favorite: !g.favorite }),
- });
- },
- remove: async (g: Generation) => {
- patchLocal(g.id, () => null);
- await fetch(`/api/generations/${g.id}`, { method: "DELETE" });
- },
- cancel: async (g: Generation) => {
- patchLocal(g.id, (x) => ({ ...x, status: "canceled" }));
- await fetch(`/api/generations/${g.id}/cancel`, { method: "POST" });
+ return useMemo(() => {
+ const refresh = () => {
void qc.invalidateQueries({ queryKey: ["generations"] });
- },
- };
+ void qc.invalidateQueries({ queryKey: ["library"] });
+ void qc.invalidateQueries({ queryKey: ["library-facets"] });
+ void qc.invalidateQueries({ queryKey: ["folders"] });
+ };
+ const local = (gs: Generation[], patch: Partial<Generation> | null) => {
+ for (const g of gs) {
+ const cur = cached(qc, g.id) ?? g;
+ applyEvent(qc, patch ? { type: "generation", generation: patched(cur, patch) } : { type: "deleted", id: g.id });
+ }
+ };
+ /** Optimistic, then the server; on failure the caches are refetched and the error shown. */
+ const run = async (gs: Generation[], patch: Partial<Generation> | null, action: BulkAction, folderId?: string | null) => {
+ if (!gs.length) return 0;
+ local(gs, patch);
+ try {
+ return await bulkRequest(action, gs.map((g) => g.id), folderId);
+ } catch (e) {
+ toast.error((e as Error).message);
+ return 0;
+ } finally {
+ refresh();
+ }
+ };
+ const restore = (gs: Generation[]) => run(gs, { deletedAt: null }, "restore");
+ const trash = (gs: Generation[], what?: string) => {
+ const p = run(gs, { deletedAt: Date.now() }, "trash");
+ toast(what ?? (gs.length === 1 ? "Moved to Trash" : `${gs.length} moved to Trash`), {
+ id: "trash-undo",
+ duration: 6000,
+ action: { label: "Undo", onClick: () => void p.then(() => restore(gs)) },
+ });
+ return p;
+ };
+ return {
+ /** Toggle (or set) a favorite from the freshest cached copy, so a stale viewer object can't send the wrong value. */
+ favorite: async (g: Generation, value?: boolean) => {
+ const cur = cached(qc, g.id) ?? g;
+ const next = value ?? !cur.favorite;
+ local([cur], { favorite: next });
+ const res = await fetch(`/api/generations/${g.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ favorite: next }) });
+ if (!res.ok) refresh();
+ },
+ favoriteMany: (gs: Generation[], value: boolean) => run(gs, { favorite: value }, value ? "favorite" : "unfavorite"),
+ /** Move to the Trash quietly (callers that announce it themselves). */
+ remove: (g: Generation) => run([g], { deletedAt: Date.now() }, "trash"),
+ /** Move to the Trash with an Undo toast. */
+ trash,
+ restore,
+ deleteForever: (gs: Generation[]) => run(gs, null, "delete"),
+ emptyTrash: async () => {
+ await fetch("/api/generations/trash", { method: "DELETE" });
+ refresh();
+ },
+ move: (gs: Generation[], folderId: string | null) => run(gs, { folderId }, "move", folderId),
+ cancel: async (g: Generation) => {
+ local([g], { status: "canceled" });
+ await fetch(`/api/generations/${g.id}/cancel`, { method: "POST" });
+ refresh();
+ },
+ };
+ }, [qc]);
+}
+
+// ---------------------------------------------------------------------------
+// Library folders
+
+export function useFolders() {
+ return useQuery({
+ queryKey: ["folders"],
+ queryFn: async () => (await json<{ items: Folder[] }>(await fetch("/api/folders"))).items,
+ staleTime: 10_000,
+ });
+}
+
+export function useFolderActions() {
+ const qc = useQueryClient();
+ return useMemo(() => {
+ const send = async <T,>(url: string, method: string, body?: unknown) => {
+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ const out = res.status === 204 ? (undefined as T) : await json<T>(res);
+ void qc.invalidateQueries({ queryKey: ["folders"] });
+ return out;
+ };
+ return {
+ create: (body: { name: string; color?: string }) => send<Folder>("/api/folders", "POST", body),
+ update: (id: string, body: { name?: string; color?: string }) => send<Folder>(`/api/folders/${id}`, "PATCH", body),
+ remove: async (id: string) => {
+ await send<void>(`/api/folders/${id}`, "DELETE");
+ void qc.invalidateQueries({ queryKey: ["library"] });
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ };
+ }, [qc]);
}
// ---------------------------------------------------------------------------
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
new file mode 100644
index 00000000..6e4b1baf
--- /dev/null
+++ b/src/lib/generation-stream.ts
@@ -0,0 +1,129 @@
+/**
+ * Live generation updates from GET /api/generations/stream (server-sent events), applied to the
+ * React Query caches by id. Pure: the parser and the cache reducers are tested without a browser.
+ *
+ * event: generation data: <Generation JSON, as GET /api/generations returns it>
+ * event: deleted data: {"id": "..."}
+ * : ping (every 15 s)
+ */
+import type { Generation } from "./catalog/types";
+import { 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 };
+
+/** Split an SSE byte stream (decoded) into events; returns what's left of an unfinished event. */
+export function parseSse(buffer: string): { events: { event: string; data: string; id?: string }[]; rest: string } {
+ const events: { event: string; data: string; id?: string }[] = [];
+ const blocks = buffer.replace(/\r\n?/g, "\n").split("\n\n");
+ const rest = blocks.pop() ?? "";
+ for (const block of blocks) {
+ let event = "message";
+ let id: string | undefined;
+ const data: string[] = [];
+ for (const line of block.split("\n")) {
+ if (!line || line.startsWith(":")) continue;
+ const i = line.indexOf(":");
+ const field = i < 0 ? line : line.slice(0, i);
+ const value = i < 0 ? "" : line.slice(i + 1).replace(/^ /, "");
+ if (field === "event") event = value;
+ else if (field === "data") data.push(value);
+ else if (field === "id") id = value;
+ }
+ if (data.length) events.push({ event, data: data.join("\n"), ...(id !== undefined && { id }) });
+ }
+ return { events, rest };
+}
+
+/** An SSE message → a cache event (null for unknown or malformed ones). */
+export function toStreamEvent(m: { event: string; data: string }): StreamEvent | null {
+ try {
+ const v = JSON.parse(m.data) as Record<string, unknown>;
+ if (m.event === "deleted" && typeof v.id === "string") return { type: "deleted", id: v.id };
+ if (m.event === "generation" && typeof v.id === "string" && typeof v.createdAt === "number" && v.request) return { type: "generation", generation: v as unknown as Generation };
+ } catch {}
+ return null;
+}
+
+/**
+ * Apply one event to a cached list for `filter` (newest first, at most `limit` long). Unknown
+ * generations are inserted when they match and fall inside the loaded window; ones that stop
+ * matching (unfavorited on the Favorites tab, moved to the Trash) are removed. Returns the same
+ * array when nothing changed, so React Query keeps every unchanged object (and memoized tile) as is.
+ */
+export function applyToList(list: Generation[] | undefined, filter: FeedFilter, ev: StreamEvent, opts: { window?: boolean } = {}): Generation[] | undefined {
+ if (!list) return list;
+ const id = ev.type === "deleted" ? ev.id : ev.generation.id;
+ const at = list.findIndex((g) => g.id === id);
+ if (ev.type === "deleted") return at < 0 ? list : list.filter((g) => g.id !== id);
+ const g = ev.generation;
+ const fits = matchesFilter(g, filter);
+ if (at >= 0) {
+ if (!fits) return list.filter((x) => x.id !== id);
+ const old = list[at];
+ if (old.updatedAt > g.updatedAt) return list; // a late event
+ const next = list.slice();
+ next[at] = g;
+ return next;
+ }
+ if (!fits) return list;
+ // Inside the loaded window only: an older item belongs to a page that isn't loaded yet.
+ const oldest = list.at(-1);
+ const full = list.length >= (filter.limit ?? 80);
+ if ((opts.window ?? true) && full && oldest && orderFor(filter)(g, oldest) > 0) return list;
+ const next = [...list, g].sort(orderFor(filter));
+ return full ? next.slice(0, list.length) : next;
+}
+
+export interface Pages {
+ pages: Generation[][];
+ pageParams: unknown[];
+}
+
+/** Same for infinite (paged) lists: patch any page, insert into the page whose range holds it. */
+export function applyToPages(data: Pages | undefined, filter: FeedFilter, ev: StreamEvent): Pages | undefined {
+ if (!data?.pages.length) return data;
+ const id = ev.type === "deleted" ? ev.id : ev.generation.id;
+ const p = data.pages.findIndex((page) => page.some((g) => g.id === id));
+ if (p >= 0) {
+ const page = applyToList(data.pages[p], filter, ev, { window: false });
+ if (page === data.pages[p]) return data;
+ const pages = data.pages.slice();
+ pages[p] = page!;
+ return { ...data, pages };
+ }
+ if (ev.type === "deleted" || !matchesFilter(ev.generation, filter)) return data;
+ const g = ev.generation;
+ // A new one goes into the first page whose last item it sorts before (the first page, nearly always)…
+ let target = data.pages.findIndex((page) => page.length > 0 && orderFor(filter)(g, page.at(-1)!) < 0);
+ if (target < 0) {
+ // …or after everything loaded, when the last page isn't full (there's nothing further to load).
+ const last = data.pages.length - 1;
+ if (data.pages[last].length >= (filter.limit ?? 60)) return data;
+ target = last;
+ }
+ const pages = data.pages.slice();
+ pages[target] = [...pages[target], g].sort(orderFor(filter));
+ return { ...data, pages };
+}
+
+/** Assist threads hold their own generations: patch them by id (a thread never gains one from the stream). */
+export function applyToThread<T extends { generations: Generation[] }>(view: T | undefined, ev: StreamEvent): T | undefined {
+ if (!view) return view;
+ const id = ev.type === "deleted" ? ev.id : ev.generation.id;
+ const at = view.generations.findIndex((g) => g.id === id);
+ if (at < 0) return view;
+ if (ev.type === "deleted" || ev.generation.deletedAt) return { ...view, generations: view.generations.filter((g) => g.id !== id) };
+ if (view.generations[at].updatedAt > ev.generation.updatedAt) return view;
+ const generations = view.generations.slice();
+ generations[at] = ev.generation;
+ return { ...view, generations };
+}
+
+/** Reconnect delays: 1 s, 2 s, 4 s … capped at 30 s (5 min once the endpoint said it doesn't exist). */
+export function backoff(attempt: number, missing = false): number {
+ return missing ? 300_000 : Math.min(30_000, 1000 * 2 ** Math.max(0, attempt));
+}
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
new file mode 100644
index 00000000..72395c42
--- /dev/null
+++ b/src/lib/output-actions.ts
@@ -0,0 +1,179 @@
+/**
+ * What you can do with one result, shared by feed tiles, the viewer and the Library, so the same
+ * action is in the same place everywhere (U15). Pure: the UI maps ids to icons and handlers.
+ *
+ * placement: "primary" = the labelled pill (Animate / Extend …), "bar" = icon buttons on tiles
+ * (Download, Favorite), "menu" = the ⋯ menu. The viewer shows them all as labelled buttons.
+ */
+import type { Generation, OutputFile } from "./catalog/types";
+import { downloadHref, downloadName, extensionOf } from "./library";
+
+export type OutputActionId =
+ | "animate"
+ | "edit"
+ | "upscale"
+ | "reference"
+ | "grade"
+ | "save-character"
+ | "extend"
+ | "reframe"
+ | "lipsync"
+ | "add-sound"
+ | "voice-change"
+ | "copy-text"
+ | "view-3d"
+ | "download"
+ | "download-txt"
+ | "download-srt"
+ | "download-all"
+ | "favorite"
+ | "finalize"
+ | "compare"
+ | "reuse"
+ | "copy-prompt"
+ | "delete"
+ | "restore"
+ | "delete-forever";
+
+export interface OutputAction {
+ id: OutputActionId;
+ label: string;
+ placement: "primary" | "bar" | "menu";
+ /** A page to hand the output to (open with prefetch off) or a file to download. */
+ href?: string;
+ /** Set on file links: the browser downloads instead of navigating. */
+ download?: string;
+ destructive?: boolean;
+}
+
+export interface ActionContext {
+ /** The view can load the request back into a composer. */
+ reuse?: boolean;
+ /** The output has a source image to compare with (viewer only). */
+ compare?: boolean;
+ /** Shown in the viewer: actions that only open the viewer are left out. */
+ inViewer?: boolean;
+}
+
+const q = (url: string) => encodeURIComponent(url);
+
+/** Every action for output `index` of `g`, in display order. */
+export function outputActions(g: Generation, index: number, ctx: ActionContext = {}): OutputAction[] {
+ const o = g.outputs[index];
+ if (!o) return [];
+ const name = downloadName(g, o, index);
+ const ext = extensionOf(o);
+ const file: OutputAction = { id: "download", label: o.kind === "text" ? `Download .${ext}` : "Download", placement: "bar", href: downloadHref(o.url, name), download: name };
+ if (g.deletedAt) {
+ return [
+ { id: "restore", label: "Restore", placement: "primary" },
+ file,
+ { id: "delete-forever", label: "Delete forever", placement: "menu", destructive: true },
+ ];
+ }
+ const out: OutputAction[] = [];
+ const link = (id: OutputActionId, label: string, href: string, placement: OutputAction["placement"] = "menu") => out.push({ id, label, href, placement });
+ switch (o.kind) {
+ case "image":
+ link("animate", "Animate", `/video?image=${q(o.url)}`, "primary");
+ out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
+ link("edit", "Edit", `/edit?image=${q(o.url)}`);
+ link("upscale", "Upscale", `/upscale?image=${q(o.url)}`);
+ link("reference", "Use as reference", `/image?ref=${q(o.url)}`);
+ link("grade", "Color grade", `/color-grade?image=${q(o.url)}`);
+ out.push({ id: "save-character", label: "Save as character", placement: "menu" });
+ break;
+ case "video":
+ link("extend", "Extend", `/extend?video=${q(o.url)}`, "primary");
+ out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
+ link("reframe", "Reframe", `/reframe?video=${q(o.url)}`);
+ link("lipsync", "Lipsync", `/lipsync?video=${q(o.url)}`);
+ link("upscale", "Upscale", `/upscale?video=${q(o.url)}`);
+ link("add-sound", "Add sound", `/audio?video=${q(o.url)}`);
+ link("grade", "Color grade", `/color-grade?video=${q(o.url)}`);
+ break;
+ case "audio":
+ link("lipsync", "Lipsync", `/lipsync?audio=${q(o.url)}`, "primary");
+ out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
+ link("voice-change", "Change voice", `/audio?mode=voice-change&audio=${q(o.url)}`);
+ break;
+ 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" });
+ break;
+ case "model3d":
+ if (!ctx.inViewer) out.push({ id: "view-3d", label: "View in 3D", placement: "primary" });
+ out.push({ ...file, label: `Download .${ext}` }, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
+ break;
+ }
+ if (g.outputs.length > 1) out.push({ id: "download-all", label: `Download all ${g.outputs.length} (.zip)`, placement: "menu", href: `/api/generations/zip?ids=${g.id}`, download: "" });
+ if (o.draftId) out.push({ id: "finalize", label: "Render this draft in 1080p", placement: "menu" });
+ if (ctx.compare) out.push({ id: "compare", label: "Compare with original", placement: "menu" });
+ if (ctx.reuse) out.push({ id: "reuse", label: "Reuse settings", placement: "menu" });
+ if (g.prompt) out.push({ id: "copy-prompt", label: "Copy prompt", placement: "menu" });
+ out.push({ id: "delete", label: "Delete", placement: "menu", destructive: true });
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Text, layers and 3D outputs
+
+export interface Cue {
+ start: number;
+ end: number;
+ text: string;
+}
+
+/** Timed lines of a transcript (OutputFile.meta.cues, seconds). */
+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 {
+ 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);
+ 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");
+}
+
+/** A layer's name and stacking order (meta.name / meta.z, or meta.layer.{name,z}). */
+export function layerInfo(o: Pick<OutputFile, "meta">, index: number): { name: string; z: number } {
+ const m = (o.meta ?? {}) as Record<string, unknown>;
+ const layer = (m.layer && typeof m.layer === "object" ? m.layer : {}) as Record<string, unknown>;
+ const name = typeof m.name === "string" ? m.name : typeof layer.name === "string" ? layer.name : index === 0 ? "Background" : `Layer ${index + 1}`;
+ const z = typeof m.z === "number" ? m.z : typeof layer.z === "number" ? layer.z : index;
+ return { name, z };
+}
+
+/** A generation whose outputs are the layers of one picture (Layers, text layers). */
+export function isLayered(g: Pick<Generation, "op" | "outputs">): boolean {
+ return (g.op === "layers" || g.op === "text-layers" || g.outputs.some((o) => !!(o.meta && ("layer" in o.meta || "z" in o.meta)))) && g.outputs.length > 1;
+}
+
+/** A 3D model's still and turntable: meta.poster / meta.preview, meta.video / meta.turntable, or a sibling output. */
+export function modelPreview(g: Pick<Generation, "outputs">, o: OutputFile): { poster?: string; video?: string } {
+ const m = (o.meta ?? {}) as Record<string, unknown>;
+ const str = (...keys: string[]) => keys.map((k) => m[k]).find((v): v is string => typeof v === "string" && v.length > 0);
+ return {
+ poster: str("poster", "preview", "thumbnail", "image") ?? g.outputs.find((x) => x.kind === "image")?.url,
+ video: str("video", "turntable") ?? g.outputs.find((x) => x.kind === "video")?.url,
+ };
+}
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
new file mode 100644
index 00000000..0bdc7abb
--- /dev/null
+++ b/tests/library-pure.test.ts
@@ -0,0 +1,221 @@
+import { describe, expect, it } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+import { applyToList, applyToPages, applyToThread, backoff, parseSse, 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";
+
+let n = 0;
+function gen(p: Partial<Generation> = {}): Generation {
+ n++;
+ return {
+ id: p.id ?? `g${String(n).padStart(3, "0")}`,
+ batchId: null,
+ feature: "image",
+ presetId: null,
+ modelId: "nano-banana-pro",
+ engine: "cloud",
+ provider: "mock",
+ op: "t2i",
+ kind: "image",
+ status: "succeeded",
+ progress: 1,
+ message: null,
+ prompt: "a fox",
+ request: { feature: "image", modelId: "nano-banana-pro", prompt: "a fox" },
+ outputs: [{ url: `/api/files/outputs/d/${p.id ?? n}.png`, kind: "image" }],
+ error: null,
+ costUsd: 0,
+ favorite: false,
+ createdAt: 1000 + n,
+ updatedAt: 1000 + n,
+ completedAt: null,
+ deletedAt: null,
+ folderId: null,
+ ...p,
+ };
+}
+
+describe("outputActions", () => {
+ const ids = (g: Generation, ctx = {}) => outputActions(g, 0, ctx).map((a) => `${a.placement}:${a.id}`);
+
+ it("gives images Animate first, Download and Favorite on the bar, the rest in the menu", () => {
+ expect(ids(gen(), { reuse: true })).toEqual([
+ "primary:animate",
+ "bar:download",
+ "bar:favorite",
+ "menu:edit",
+ "menu:upscale",
+ "menu:reference",
+ "menu:grade",
+ "menu:save-character",
+ "menu:reuse",
+ "menu:copy-prompt",
+ "menu:delete",
+ ]);
+ const [animate, download] = outputActions(gen({ id: "abcdef123456" }), 0);
+ expect(animate.href).toBe("/video?image=%2Fapi%2Ffiles%2Foutputs%2Fd%2Fabcdef123456.png");
+ expect(download.download).toBe("a-fox-abcdef.png");
+ expect(download.href).toBe("/api/files/outputs/d/abcdef123456.png?download=a-fox-abcdef.png");
+ });
+
+ it("gives videos Extend first and the video hand-offs", () => {
+ const g = gen({ kind: "video", op: "t2v", outputs: [{ url: "/api/files/o/v.mp4", kind: "video", draftId: "d1" }] });
+ expect(ids(g)).toEqual(["primary:extend", "bar:download", "bar:favorite", "menu:reframe", "menu:lipsync", "menu:upscale", "menu:add-sound", "menu:grade", "menu:finalize", "menu:copy-prompt", "menu:delete"]);
+ });
+
+ it("handles audio, text, 3D, layers, favorites and the Trash", () => {
+ expect(ids(gen({ kind: "audio", outputs: [{ url: "/a.wav", kind: "audio" }] }))[0]).toBe("primary:lipsync");
+ const text = gen({ kind: "text", op: "transcribe", outputs: [{ url: "/t.txt", kind: "text", text: "Hi", meta: { cues: [{ start: 0, end: 1.5, text: "Hi" }] } }] });
+ expect(ids(text).slice(0, 4)).toEqual(["primary:copy-text", "bar:download", "bar:favorite", "menu:download-srt"]);
+ expect(outputActions(text, 0)[1].label).toBe("Download .txt");
+ const glb = gen({ kind: "model3d", op: "image-to-3d", outputs: [{ url: "/m.glb", kind: "model3d" }] });
+ expect(ids(glb).slice(0, 2)).toEqual(["primary:view-3d", "bar:download"]);
+ expect(ids(glb, { inViewer: true })[0]).toBe("bar:download");
+ const layers = gen({ op: "layers", outputs: [{ url: "/l0.png", kind: "image" }, { url: "/l1.png", kind: "image" }] });
+ expect(outputActions(layers, 1).find((a) => a.id === "download-all")?.href).toBe(`/api/generations/zip?ids=${layers.id}`);
+ expect(outputActions(gen({ favorite: true }), 0)[2].label).toBe("Unfavorite");
+ expect(ids(gen({ deletedAt: 5 }))).toEqual(["primary:restore", "bar:download", "menu:delete-forever"]);
+ expect(outputActions(gen(), 3)).toEqual([]);
+ });
+});
+
+describe("text, layer and 3D outputs", () => {
+ it("formats cues for the viewer and as SRT", () => {
+ 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(textOf({ meta: { cues: [{ start: 0, end: 1, text: "a" }, { start: 1, end: 2, text: "b" }] } })).toBe("a\nb");
+ });
+
+ it("reads layer names and 3D previews from meta", () => {
+ expect(layerInfo({ meta: { name: "Logo", z: 3 } }, 1)).toEqual({ name: "Logo", z: 3 });
+ expect(layerInfo({ meta: { layer: { name: "Sky", z: 0 } } }, 0)).toEqual({ name: "Sky", z: 0 });
+ expect(layerInfo({}, 2)).toEqual({ name: "Layer 3", z: 2 });
+ const o = { url: "/m.glb", kind: "model3d" as const, meta: { poster: "/p.png" } };
+ expect(modelPreview({ outputs: [o, { url: "/t.mp4", kind: "video" }] }, o)).toEqual({ poster: "/p.png", video: "/t.mp4" });
+ });
+});
+
+describe("stream reducer", () => {
+ const ev = (g: Generation) => ({ type: "generation" as const, generation: g });
+
+ it("parses server-sent events across chunk boundaries", () => {
+ const a = parseSse(': ping\n\nevent: generation\ndata: {"id":"a"}\n\nevent: deleted\ndata: {"id"');
+ expect(a.events).toEqual([{ event: "generation", data: '{"id":"a"}' }]);
+ const b = parseSse(`${a.rest}:"b"}\n\n`);
+ expect(b.events).toEqual([{ event: "deleted", data: '{"id":"b"}' }]);
+ expect(toStreamEvent(b.events[0])).toEqual({ type: "deleted", id: "b" });
+ expect(toStreamEvent({ event: "generation", data: "nope" })).toBeNull();
+ expect(toStreamEvent({ event: "generation", data: JSON.stringify(gen({ id: "x" })) })?.type).toBe("generation");
+ });
+
+ it("patches by id and keeps unchanged lists identical", () => {
+ const a = gen({ status: "running" });
+ const b = gen();
+ const list = [b, a];
+ const done = { ...a, status: "succeeded" as const, updatedAt: a.updatedAt + 5 };
+ const next = applyToList(list, {}, ev(done))!;
+ expect(next).not.toBe(list);
+ expect(next[1]).toBe(done);
+ expect(next[0]).toBe(b); // structural sharing: untouched items keep their identity
+ expect(applyToList(next, {}, ev({ ...a, updatedAt: a.updatedAt - 1 }))).toBe(next); // late event
+ expect(applyToList(list, {}, { type: "deleted", id: "missing" })).toBe(list);
+ expect(applyToList(list, {}, { type: "deleted", id: a.id })).toEqual([b]);
+ expect(applyToList(undefined, {}, ev(a))).toBeUndefined();
+ });
+
+ it("inserts new matching ones in order and drops ones that stop matching", () => {
+ const old = gen();
+ const list = [old];
+ const fresh = gen();
+ expect(applyToList(list, {}, ev(fresh))).toEqual([fresh, old]);
+ expect(applyToList(list, { kind: "video" }, ev(fresh))).toBe(list);
+ expect(applyToList(list, { features: ["vid*"] }, ev(gen({ feature: "video" })))?.length).toBe(2);
+ const fav = gen({ favorite: true });
+ expect(applyToList([fav], { favorites: true }, ev({ ...fav, favorite: false, updatedAt: fav.updatedAt + 1 }))).toEqual([]);
+ expect(applyToList([fav], {}, ev({ ...fav, deletedAt: 9, updatedAt: fav.updatedAt + 1 }))).toEqual([]);
+ // A full list doesn't take items older than what it shows (they're on an unloaded page).
+ const full = [gen(), gen()].reverse();
+ const older = gen({ createdAt: 1 });
+ expect(applyToList(full, { limit: 2 }, ev(older))).toBe(full);
+ });
+
+ it("patches paged lists and Assist threads", () => {
+ const p1 = [gen(), gen()].reverse();
+ const p2 = [gen({ createdAt: 10 }), gen({ createdAt: 5 })];
+ const data = { pages: [p1, p2], pageParams: [undefined, p1[1].createdAt] };
+ const moved = { ...p2[1], favorite: true, updatedAt: 99_999 };
+ const next = applyToPages(data, {}, ev(moved))!;
+ expect(next.pages[0]).toBe(p1);
+ expect(next.pages[1][1].favorite).toBe(true);
+ const fresh = gen();
+ expect(applyToPages(data, {}, ev(fresh))!.pages[0][0]).toBe(fresh);
+ expect(applyToPages(data, {}, { type: "deleted", id: p2[0].id })!.pages[1]).toHaveLength(1);
+ expect(applyToPages({ pages: [[]], pageParams: [undefined] }, {}, ev(fresh))!.pages[0]).toEqual([fresh]);
+
+ const view = { thread: { id: "t" }, generations: [p1[0]] };
+ expect(applyToThread(view, ev(fresh))).toBe(view);
+ expect(applyToThread(view, ev({ ...p1[0], favorite: true, updatedAt: 99_999 }))!.generations[0].favorite).toBe(true);
+ expect(applyToThread(view, { type: "deleted", id: p1[0].id })!.generations).toEqual([]);
+ });
+
+ it("backs off between reconnects", () => {
+ expect([0, 1, 2, 10].map((a) => backoff(a))).toEqual([1000, 2000, 4000, 30_000]);
+ expect(backoff(0, true)).toBe(300_000);
+ });
+});
+
+describe("library helpers", () => {
+ it("matches filters like the server", () => {
+ const g = gen({ prompt: "Neon KOI pond", request: { feature: "image", modelId: "m1", prompt: "neon koi" }, folderId: "f1", modelId: "m1", status: "failed" });
+ expect(matchesFilter(g, { q: "koi" })).toBe(true);
+ expect(matchesFilter(g, { q: "fox" })).toBe(false);
+ expect(matchesFilter(g, { folderId: "f1", models: ["m1"], statuses: ["failed"] })).toBe(true);
+ expect(matchesFilter(g, { since: g.createdAt + 1 })).toBe(false);
+ expect(matchesFilter(g, { trashed: true })).toBe(false);
+ });
+
+ it("names downloads and counts Trash days", () => {
+ expect(downloadName(gen({ id: "zzzzzz999" }), { url: "/x/out.webm", kind: "video" }, 1)).toBe("a-fox-zzzzzz-2.webm");
+ const now = Date.UTC(2026, 9, 17);
+ expect(trashDaysLeft(now - 29.5 * 86_400_000, now)).toBe(1);
+ expect(trashDaysLeft(now - 40 * 86_400_000, now)).toBe(0);
+ });
+
+ it("splits by date", () => {
+ const now = new Date(2026, 9, 17, 15).getTime();
+ expect(dayLabel(now, now)).toBe("Today");
+ expect(dayLabel(new Date(2026, 9, 16, 23).getTime(), now)).toBe("Yesterday");
+ expect(dayLabel(new Date(2026, 9, 12, 9).getTime(), now)).toBe("Mon, Oct 12");
+ expect(dayLabel(new Date(2025, 0, 2).getTime(), now)).toBe("Jan 2, 2025");
+ const items = [now, now - 1000, new Date(2026, 9, 16, 8).getTime()].map((t) => ({ t }));
+ expect(splitByDate(items, (x) => x.t, now).map((s) => [s.label, s.items.length])).toEqual([
+ ["Today", 2],
+ ["Yesterday", 1],
+ ]);
+ });
+
+ it("stacks a batch into one card titled with the user's idea", () => {
+ const frame = (i: number) =>
+ gen({
+ batchId: "b1",
+ feature: "storyboard",
+ prompt: `Frame ${i + 1} of a storyboard: …`,
+ request: { feature: "storyboard", modelId: "m", prompt: "internal", frame: { scene: `establishing wide shot: A lighthouse keeper finds a bottle — beat ${i + 1} of 2`, index: i, of: 2 } },
+ });
+ const film = gen({ batchId: "b1-film", op: "concat", prompt: "x", request: { feature: "storyboard-film", modelId: "join-clips", step: { label: "Film · 2 shots", index: 2, of: 3 } } });
+ const solo = gen();
+ const entries = buildEntries([solo, film, frame(1), frame(0)]);
+ expect(entries.map((e) => e.type)).toEqual(["single", "stack"]);
+ const stack = entries[1];
+ expect(stack.type === "stack" && stack.title).toBe("A lighthouse keeper finds a bottle");
+ expect(stack.type === "stack" && stack.label).toBe("Storyboard · 2 frames + film");
+ expect(stack.type === "stack" && stack.items[0].request.frame?.index).toBe(0);
+ const takes = [gen({ batchId: "t" }), gen({ batchId: "t" })];
+ const t = buildEntries(takes)[0];
+ expect(t.type === "stack" && [t.title, t.label]).toEqual(["a fox", "2 takes"]);
+ expect(buildEntries(takes, { stacks: false })).toHaveLength(2);
+ });
+});