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
Feed and Library: the reuse loop (live clock, next steps, select all)
Claudeb6c589c77900
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex 6525f875..58e04bbc 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -1,6 +1,6 @@"use client";-import { ArchiveRestore, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Heart, Loader2, Pin, PinOff, Search, Trash2, X } from "lucide-react";+import { ArchiveRestore, CheckCheck, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Heart, Loader2, Pin, PinOff, Search, Trash2, X } from "lucide-react";import Link from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";@@ -30,7 +30,8 @@ import { Kbd } from "@/components/ui/kbd";import { Skeleton } from "@/components/ui/skeleton";import { BULK_MAX, useCreateGeneration, useFolders, useGenerationActions, useLibrary, useLibraryFacets, useUploads, type Asset, type FeedFilter } from "@/lib/api";import type { Generation, MediaKind } from "@/lib/catalog/types";-import { buildEntries, folderAndDescendants, reviewInfo, splitByDate, TRASH_DAYS, type LibraryEntry } from "@/lib/library";+import { modKey } from "@/lib/keys";+import { buildEntries, folderAndDescendants, reviewInfo, splitByDate, toggleAll, TRASH_DAYS, type LibraryEntry } from "@/lib/library";import { isLayered, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";@@ -349,7 +350,8 @@ function Inner() {if (e.key === "Escape" && (selecting || latest.current.selected.size)) {e.preventDefault();clear();- } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "a" && selecting) {+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "a" && (selecting || latest.current.selected.size)) {+ // In selection mode ⌘/Ctrl+A takes every result loaded under the filters (elsewhere it selects text as usual).e.preventDefault();setSelected(new Set(latest.current.items.map((g) => g.id)));}@@ -625,12 +627,27 @@ function Inner() {) : (<div className={cn("space-y-7 transition-opacity", refreshing && "opacity-70")}>{sections.map((s) => (- <section key={s.key} aria-label={s.label || "Results"}>+ <section key={s.key} aria-label={s.label || "Results"} className="group/section">{s.label && (- <h2 className="mb-2.5 flex items-center gap-1.5 text-[13px] font-medium">- {s.key === -1 && <Pin className="size-3.5 text-muted-foreground" />}- {s.label} <span className="font-mono text-[11px] font-normal text-muted-foreground">{s.items.reduce((n, e) => n + members(e).length, 0)}</span>- </h2>+ <div className="mb-2.5 flex items-center gap-3">+ <h2 className="flex items-center gap-1.5 text-[13px] font-medium">+ {s.key === -1 && <Pin className="size-3.5 text-muted-foreground" />}+ {s.label} <span className="font-mono text-[11px] font-normal text-muted-foreground">{s.items.reduce((n, e) => n + members(e).length, 0)}</span>+ </h2>+ {/* Select a whole day (or the pinned ones) at once; again to unselect them. */}+ {!uploadsTab && (+ <SectionSelect+ label={s.label}+ ids={s.items.flatMap(ids)}+ selected={selected}+ quiet={!selecting}+ onToggle={(list) => {+ setSelecting(true);+ setSelected((cur) => toggleAll(cur, list));+ }}+ />+ )}+ </div>)}<Cardsentries={s.items}@@ -702,6 +719,16 @@ function Inner() {</>)}</span>+ {items.length > 0 && selected.size < items.length && (+ <button+ onClick={() => setSelected(new Set(items.map((g) => g.id)))}+ className={cn(BAR, "text-brand-text")}+ aria-label={`Select all ${items.length}`}+ title={`Select all ${items.length} shown here (${modKey()}+A)`}+ >+ <CheckCheck className="size-4" /> <span className="hidden sm:inline">Select all</span> <span className="font-mono text-[11px] tabular-nums">{items.length}</span>+ </button>+ )}{trash ? (<><BarButton icon={ArchiveRestore} label="Restore" disabled={!selected.size} onClick={() => void actions.restore(selectedGens).then((n) => (n && toast(`Restored ${n}`), clear()))} />@@ -812,6 +839,24 @@ function Inner() {);}+/** A date header's "Select" / "Unselect": shown on hover from a mouse, always while selecting or on touch. */+function SectionSelect({ label, ids, selected, quiet, onToggle }: { label: string; ids: string[]; selected: ReadonlySet<string>; quiet: boolean; onToggle: (ids: string[]) => void }) {+ const all = ids.length > 0 && ids.every((id) => selected.has(id));+ return (+ <button+ type="button"+ onClick={() => onToggle(ids)}+ aria-label={`${all ? "Unselect" : "Select"} ${label}, ${ids.length}`}+ className={cn(+ "inline-flex h-6 items-center gap-1 rounded-full px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none",+ quiet && "[@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/section:opacity-100 [@media(hover:hover)]:focus-visible:opacity-100",+ )}+ >+ {all ? "Unselect" : "Select"}+ </button>+ );+}+const BAR = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[13px] font-medium whitespace-nowrap transition-colors hover:bg-accent disabled:pointer-events-none disabled:opacity-40";function BarButton({ icon: Icon, label, onClick, disabled, destructive }: { icon: typeof Download; label: string; onClick: () => void; disabled?: boolean; destructive?: boolean }) {diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 8fff5161..b8ad8c90 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -1,6 +1,7 @@"use client";import { Cloud, Copy, Cpu, Download, FolderDown, Heart, MoreHorizontal, RotateCcw, Sparkles, Trash2, X } from "lucide-react";+import Link from "next/link";import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import {@@ -13,13 +14,14 @@ import {import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";import { useCreateGeneration, useGenerationActions } from "@/lib/api";-import { elapsed, formatCost, ratioValue, timeAgo } from "@/lib/format";+import { elapsed, formatCost, leftLabel, ratioValue, timeAgo, timeLeft } from "@/lib/format";import { downloadHref, downloadName, userTitle } from "@/lib/library";-import { isLayered, shownOutputs } from "@/lib/output-actions";+import { isLayered, nextSteps, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";import { copyWithToast } from "@/lib/clipboard";-import { TileActions, useCanHover, type RunnerOptions } from "./result-actions";+import { ACTION_ICONS, TileActions, useCanHover, type RunnerOptions } from "./result-actions";import { LayersStack, MediaThumb } from "./result-media";+import { useNow } from "./use-now";import { Viewer } from "./viewer";export { MediaThumb } from "./result-media";@@ -35,17 +37,24 @@ export function tileRatio(g: Generation): number {export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {const { cancel } = useGenerationActions();+ // The clock runs between the job's reports (a fal queue or Higgsfield may report rarely).+ const now = useNow(1000);const pct = g.progress != null ? Math.round(g.progress * 100) : null;const label = g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…");+ // The first progress this tile saw: with the latest one it gives the pace, so the time left.+ const [first, setFirst] = useState<{ at: number; progress: number } | null>(null);+ if (!first && g.progress != null && g.status === "running") setFirst({ at: g.updatedAt, progress: g.progress });+ const left = first && g.progress != null ? timeLeft(first, { at: g.updatedAt, progress: g.progress }, now) : null;return (<div className="relative h-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}><div className="skeleton-sweep absolute inset-0 animate-skeleton" /><div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3"><div className="min-w-0"><p className="shimmer-text animate-shimmer-text truncate text-[13px] font-medium">{label}</p>- <p className="font-mono text-[11px] text-muted-foreground">- {pct != null ? `${pct}% · ` : ""}- {elapsed(g.createdAt)}+ <p className="flex flex-wrap gap-x-1.5 font-mono text-[11px] text-muted-foreground tabular-nums">+ {pct != null && <span>{pct}%</span>}+ <span className={cn(pct != null && "before:mr-1.5 before:content-['·']")}>{elapsed(g.createdAt, Math.max(now, g.createdAt))}</span>+ {left != null && <span className="before:mr-1.5 before:content-['·']">{leftLabel(left)}</span>}</p></div><Tooltip>@@ -198,8 +207,34 @@ const OutputTile = memo(function OutputTile({ g, index, ratio, layered, count }:);});+/**+ * Under the newest result: three next steps as chips (Animate, Upscale, Edit for a picture). A+ * group with several takes has none: which one to animate is picked on its tile.+ */+function NextSteps({ g, index }: { g: Generation; index: number }) {+ const steps = nextSteps(g, index);+ if (!steps.length) return null;+ return (+ <nav aria-label="Next steps" className="flex flex-wrap gap-1.5">+ {steps.map((a) => {+ const Icon = ACTION_ICONS[a.id];+ return (+ <Link+ key={a.id}+ href={a.href!}+ prefetch={false}+ className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ <Icon className="size-3.5" /> {a.label}+ </Link>+ );+ })}+ </nav>+ );+}+/** One request: the user's words in serif, a meta line, then its outputs (or progress / failure). */-export const GenerationGroup = memo(function GenerationGroup({ g }: { g: Generation }) {+export const GenerationGroup = memo(function GenerationGroup({ g, newest }: { g: Generation; newest?: boolean }) {const feed = useFeed();const { favorite, trash } = useGenerationActions();const ratio = tileRatio(g);@@ -310,6 +345,7 @@ export const GenerationGroup = memo(function GenerationGroup({ g }: { g: Generatshown.map((i) => <OutputTile key={g.outputs[i].url} g={g} index={i} ratio={ratio} count={shown.length} />)))}</div>+ {newest && !layered && shown.length === 1 && <NextSteps g={g} index={shown[0]} />}</section>);});@@ -344,13 +380,15 @@ export function Feed({[openAt, hasReuse],);if (!items.length) return <>{empty}</>;+ // The feed is newest first: the next steps go under the first finished result.+ const newest = items.find((g) => g.status === "succeeded")?.id;const flat = items.flatMap((g) => (g.status === "succeeded" ? (isLayered(g) ? [{ g, i: 0 }] : shownOutputs(g).map((i) => ({ g, i }))) : []));const pos = open ? flat.findIndex((f) => f.g.id === open.id && (f.i === open.index || isLayered(f.g))) : -1;return (<FeedCtx.Provider value={api}><div className="space-y-9">{items.map((g) => (- <GenerationGroup key={g.id} g={g} />+ <GenerationGroup key={g.id} g={g} newest={g.id === newest} />))}</div>{open && pos >= 0 && (diff --git a/src/components/studio/use-now.ts b/src/components/studio/use-now.tsnew file mode 100644index 00000000..49422f27--- /dev/null+++ b/src/components/studio/use-now.ts@@ -0,0 +1,53 @@+"use client";++import { useSyncExternalStore } from "react";++/*+ * A shared clock: one setInterval per interval while anything listens (every running tile on the+ * page ticks from the same timer), stopped when the last listener goes.+ */+interface Clock {+ now: number;+ subscribe: (cb: () => void) => () => void;+ read: () => number;+}++const clocks = new Map<number, Clock>();++function clock(ms: number): Clock {+ const known = clocks.get(ms);+ if (known) return known;+ const listeners = new Set<() => void>();+ let timer: ReturnType<typeof setInterval> | null = null;+ const c: Clock = {+ now: Date.now(),+ // One function per clock: a new one each render would make React subscribe again every render.+ subscribe: (cb) => {+ listeners.add(cb);+ if (!timer) {+ // Fresh once subscribed (React reads the time again after subscribing).+ c.now = Date.now();+ timer = setInterval(() => {+ c.now = Date.now();+ listeners.forEach((l) => l());+ }, ms);+ }+ return () => {+ listeners.delete(cb);+ if (!listeners.size && timer) {+ clearInterval(timer);+ timer = null;+ }+ };+ },+ read: () => c.now,+ };+ clocks.set(ms, c);+ return c;+}++/** The time now, re-rendering every `ms` while mounted. */+export function useNow(ms = 1000): number {+ const c = clock(ms);+ return useSyncExternalStore(c.subscribe, c.read, c.read);+}diff --git a/src/lib/format.ts b/src/lib/format.tsindex e5c940dd..94936f0d 100644--- a/src/lib/format.ts+++ b/src/lib/format.ts@@ -33,3 +33,23 @@ export function untitledName(taken: readonly string[], base = "Untitled project"if (!used.has(base.toLowerCase())) return base;for (let i = 2; ; i++) if (!used.has(`${base} ${i}`.toLowerCase())) return `${base} ${i}`;}++/**+ * Seconds left on a running job, from how fast its progress moved: between the first report the+ * page saw (`first`) and the latest one (`last`, at the generation's updatedAt), counted down to+ * `now`. Null until there's a rate to go on (two reports a second or more apart, 5 % done), and at 0+ * it stays 0 ("almost done") rather than going negative.+ */+export function timeLeft(first: { at: number; progress: number }, last: { at: number; progress: number }, now = Date.now()): number | null {+ const dp = last.progress - first.progress;+ const dt = last.at - first.at;+ if (last.progress < 0.05 || last.progress >= 1 || dp <= 0 || dt < 1000) return null;+ const total = ((1 - last.progress) * dt) / dp;+ return Math.max(0, Math.round((total - (now - last.at)) / 1000));+}++/** 75 → "1m 15s left", 12 → "12s left", 0 → "almost done". */+export function leftLabel(s: number): string {+ if (s <= 0) return "almost done";+ return s < 60 ? `${s}s left` : `${Math.floor(s / 60)}m ${s % 60}s left`;+}diff --git a/src/lib/library.ts b/src/lib/library.tsindex 0e06bcc6..5e637bc0 100644--- a/src/lib/library.ts+++ b/src/lib/library.ts@@ -475,3 +475,17 @@ export function coverOf(items: Generation[]): { g: Generation; o: OutputFile; inconst g = film ?? done[0];return g ? { g, o: g.outputs[0], index: 0 } : null;}++/**+ * Select a group of results (a date's, or everything loaded): every one of `ids` when any is+ * missing, else none of them. Returns a new set; other selected ids stay as they are.+ */+export function toggleAll(selected: ReadonlySet<string>, ids: readonly string[]): Set<string> {+ const next = new Set(selected);+ const all = ids.length > 0 && ids.every((id) => next.has(id));+ for (const id of ids) {+ if (all) next.delete(id);+ else next.add(id);+ }+ return next;+}diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 60235407..22e83296 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -136,6 +136,27 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =return out;}+/** The hand-offs offered as next steps under a fresh result, best first (UX-18). */+const NEXT_STEPS: Partial<Record<OutputFile["kind"], OutputActionId[]>> = {+ image: ["animate", "upscale", "edit"],+ video: ["extend", "upscale", "add-sound"],+ audio: ["lipsync", "voice-change"],+};++/**+ * Up to `max` next steps for output `index` (Animate, Upscale, Edit for a picture), taken from+ * outputActions so they go where the tile's own actions go. Only hand-offs to another studio.+ */+export function nextSteps(g: Generation, index: number, max = 3): OutputAction[] {+ const o = g.outputs[index];+ if (!o || g.status !== "succeeded") return [];+ const all = outputActions(g, index);+ return (NEXT_STEPS[o.kind] ?? [])+ .map((id) => all.find((a) => a.id === id && a.href))+ .filter((a): a is OutputAction => !!a)+ .slice(0, max);+}+/*** A vector result (an SVG: Vectorize, Recraft's vector styles, an uploaded .svg). Demo pictures are* SVG placeholders standing in for raster results, so they keep the raster hand-offs (except Vectorize's).diff --git a/tests/ux-flows.test.ts b/tests/ux-flows.test.tsindex f90e5500..c7607e8a 100644--- a/tests/ux-flows.test.ts+++ b/tests/ux-flows.test.ts@@ -1,6 +1,36 @@import { describe, expect, it } from "vitest";import { directorPicks } from "@/components/cinema/draft";-import { untitledName } from "@/lib/format";+import type { Generation, OutputFile } from "@/lib/catalog/types";+import { leftLabel, timeLeft, untitledName } from "@/lib/format";+import { toggleAll } from "@/lib/library";+import { nextSteps } from "@/lib/output-actions";++function gen(outputs: Partial<OutputFile>[], over: Partial<Generation> = {}): Generation {+ return {+ id: "g1",+ batchId: null,+ feature: "image",+ presetId: null,+ modelId: "nano-banana-pro",+ engine: "cloud",+ provider: "fal",+ op: "t2i",+ kind: (outputs[0]?.kind ?? "image") as Generation["kind"],+ status: "succeeded",+ progress: 1,+ message: null,+ prompt: "a fox",+ request: { feature: "image", modelId: "nano-banana-pro", prompt: "a fox" },+ outputs: outputs.map((o, i) => ({ url: `/api/files/out-${i}.png`, kind: "image", ...o }) as OutputFile),+ error: null,+ costUsd: null,+ favorite: false,+ createdAt: 0,+ updatedAt: 0,+ completedAt: 0,+ ...over,+ };+}describe("a new Cinema project starts with a name", () => {it("takes the first free Untitled project", () => {@@ -21,3 +51,54 @@ describe("the phone's folded Director chip", () => {expect(directorPicks({ tempo: "fast" }, "video")).toBe(1);});});++describe("next steps under a fresh result", () => {+ it("offers three hand-offs from the tile's own actions", () => {+ const img = nextSteps(gen([{ kind: "image" }]), 0);+ expect(img.map((a) => a.id)).toEqual(["animate", "upscale", "edit"]);+ expect(img[0].href).toBe(`/video?image=${encodeURIComponent("/api/files/out-0.png")}`);+ const vid = nextSteps(gen([{ kind: "video", url: "/api/files/clip.mp4" }], { kind: "video", op: "t2v" }), 0);+ expect(vid.map((a) => a.label)).toEqual(["Extend", "Upscale", "Add sound"]);+ expect(nextSteps(gen([{ kind: "audio", url: "/api/files/a.mp3" }], { kind: "audio", op: "tts" }), 0).map((a) => a.id)).toEqual(["lipsync", "voice-change"]);+ });++ it("has none for what doesn't hand off (text, vectors) or isn't done", () => {+ expect(nextSteps(gen([{ kind: "text", url: "/api/files/t.txt", text: "hi" }], { kind: "text", op: "transcribe" }), 0)).toEqual([]);+ expect(nextSteps(gen([{ kind: "image", url: "/api/files/logo.svg", contentType: "image/svg+xml" }], { op: "vectorize" }), 0)).toEqual([]);+ expect(nextSteps(gen([{ kind: "image" }], { status: "running" }), 0)).toEqual([]);+ expect(nextSteps(gen([{ kind: "image" }]), 3)).toEqual([]);+ });+});++describe("time left on a running tile", () => {+ it("comes from the pace between the first report seen and the latest, counted down", () => {+ // 10 % → 30 % in 2 s: 0.7 to go at 0.1/s is 7 s; one second after that report, 6 s.+ expect(timeLeft({ at: 1000, progress: 0.1 }, { at: 3000, progress: 0.3 }, 3000)).toBe(7);+ expect(timeLeft({ at: 1000, progress: 0.1 }, { at: 3000, progress: 0.3 }, 4000)).toBe(6);+ // Past the estimate it stays at 0 ("almost done").+ expect(timeLeft({ at: 1000, progress: 0.1 }, { at: 3000, progress: 0.3 }, 60_000)).toBe(0);+ });++ it("waits for a pace to go on", () => {+ expect(timeLeft({ at: 1000, progress: 0.1 }, { at: 1000, progress: 0.1 }, 2000)).toBeNull();+ expect(timeLeft({ at: 1000, progress: 0.01 }, { at: 1500, progress: 0.03 }, 2000)).toBeNull();+ expect(timeLeft({ at: 1000, progress: 0.5 }, { at: 3000, progress: 0.4 }, 3000)).toBeNull();+ expect(timeLeft({ at: 1000, progress: 0.2 }, { at: 3000, progress: 1 }, 3000)).toBeNull();+ });++ it("reads as minutes and seconds", () => {+ expect(leftLabel(12)).toBe("12s left");+ expect(leftLabel(75)).toBe("1m 15s left");+ expect(leftLabel(0)).toBe("almost done");+ });+});++describe("Library: select a whole day, or everything", () => {+ it("adds the group when any is missing, removes it when all are in, and keeps the rest", () => {+ const day = ["a", "b", "c"];+ expect([...toggleAll(new Set(), day)]).toEqual(day);+ expect([...toggleAll(new Set(["a", "x"]), day)].sort()).toEqual(["a", "b", "c", "x"]);+ expect([...toggleAll(new Set(["a", "b", "c", "x"]), day)]).toEqual(["x"]);+ expect([...toggleAll(new Set(["x"]), [])]).toEqual(["x"]);+ });+});