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.

Studio feed: a run's card shows at once and stays live through site updates

Adarshaf5de7fea62e
diff --git a/src/app/motion.css b/src/app/motion.css
index d2091522..80ae5279 100644
--- a/src/app/motion.css
+++ b/src/app/motion.css
@@ -386,8 +386,9 @@ img[data-fade="wait"] { opacity: 0; }
/* ----- A result that finishes while the studio is open: the picture settles in over its tile, one soft light passes
across it, and its next steps follow. Never on a page load or a scroll back. ----- */
[data-arrive] {
- /* The tile's frame stays; only the picture settles into it (its own load fade and the skeleton hand-over skip it). */
- & > :first-child { animation: motion-settle var(--motion-slow) var(--ease-standard) backwards; animation-delay: calc(min(var(--i, 0), 6) * var(--motion-stagger)); }
+ /* The tile's frame stays; only the picture blooms into it, from soft to sharp (as its last preview looked), with its
+ own load fade and the skeleton hand-over skipped. */
+ & > :first-child { animation: motion-bloom calc(var(--motion-slow) * 1.75) var(--ease-standard) backwards; animation-delay: calc(min(var(--i, 0), 6) * var(--motion-stagger)); }
&::after {
content: "";
position: absolute;
@@ -402,8 +403,42 @@ img[data-fade="wait"] { opacity: 0; }
}
[data-follow] { animation: motion-rise var(--motion-base) var(--ease-enter) backwards; animation-delay: calc(120ms + min(var(--i, 0), 6) * var(--motion-stagger)); }
-/* A new request at the top of a feed (not the ones there when it loaded). */
-[data-enter] { animation: motion-rise var(--motion-base) var(--ease-enter) backwards; }
+/* A new request at the top of a feed (not the ones there when it loaded), and the card a press of Run shows at once. */
+[data-enter], [data-making] { animation: motion-rise var(--motion-base) var(--ease-enter) backwards; }
+
+/* ----- A run on its way: a soft light in the brand's iris and spark that drifts across its card, so a wait reads as
+ work under way. The light is a layer larger than the card that only moves (translate), so it stays on the compositor;
+ still (one resting frame) under reduced motion. ----- */
+.run-aura { overflow: hidden; isolation: isolate; }
+.run-aura::before {
+ content: "";
+ position: absolute;
+ inset: -45%;
+ z-index: -1;
+ pointer-events: none;
+ background:
+ radial-gradient(42% 44% at 38% 38%, oklch(0.52 0.21 282 / 22%), transparent 70%),
+ radial-gradient(38% 40% at 62% 62%, oklch(0.88 0.16 95 / 28%), transparent 70%),
+ radial-gradient(32% 34% at 64% 36%, oklch(0.70 0.115 195 / 15%), transparent 70%);
+ animation: run-aura 9s var(--ease-move) infinite alternate;
+}
+.dark .run-aura::before {
+ background:
+ radial-gradient(42% 44% at 38% 38%, oklch(0.57 0.20 282 / 26%), transparent 70%),
+ radial-gradient(38% 40% at 62% 62%, oklch(0.85 0.15 95 / 10%), transparent 70%),
+ radial-gradient(32% 34% at 64% 36%, oklch(0.75 0.12 195 / 12%), transparent 70%);
+}
+/* Waiting in line breathes slower and quieter than a run being made. */
+[data-stage="in-line"] > .run-aura::before, [data-stage="sending"] > .run-aura::before { animation-duration: 14s; opacity: 0.8; }
+@keyframes run-aura {
+ from { translate: -14% -10%; }
+ 50% { translate: 8% 12%; }
+ to { translate: 14% -8%; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .run-aura::before { animation: none; }
+}
+@keyframes motion-bloom { from { opacity: 0; scale: 1.04; } 55% { opacity: 1; } }
@keyframes motion-fade { from { opacity: 0; } }
@keyframes motion-fade-out { to { opacity: 0; } }
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 2e3e7604..183ff267 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -1,7 +1,7 @@
"use client";
import { OrbitPad, orbitOptions } from "@/components/studio/orbit-pad";
-import { ArrowUp, AtSign, Cloud, Cpu, GalleryHorizontalEnd, LayoutDashboard, Library, Loader2, Sparkles, X } from "lucide-react";
+import { ArrowUp, AtSign, Check, Cloud, Cpu, GalleryHorizontalEnd, LayoutDashboard, Library, Loader2, Sparkles, X } from "lucide-react";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -291,6 +291,13 @@ export function Composer({ docked }: { docked: boolean }) {
const [engine, setEngine, engineMode] = useEngine();
const visitor = useLikelyVisitor();
const create = useCreateGeneration();
+ // A run just taken: Generate shows a tick for a moment (its card is already at the top of the feed).
+ const [taken, setTaken] = useState(0);
+ useEffect(() => {
+ if (!taken) return;
+ const t = setTimeout(() => setTaken(0), 1200);
+ return () => clearTimeout(t);
+ }, [taken]);
const [enhancing, setEnhancing] = useState(false);
const [focused, setFocused] = useState(false);
const promptRef = useRef<PromptInputHandle>(null);
@@ -1157,6 +1164,7 @@ export function Composer({ docked }: { docked: boolean }) {
// Accepted: nothing to try again (a card opened later never starts this run a second time). Back from sign-up, the
// line says the run is on its way (hosted runs: its tile shows "In line" too).
onSuccess: () => {
+ setTaken(Date.now());
dropGpuRetry();
setLorasOff(false);
if (signedUp && viewerInfo?.hosted) setPriceNote(PENDING_WORDS.made);
@@ -2244,6 +2252,8 @@ export function Composer({ docked }: { docked: boolean }) {
<ArrowUp className="motion-hand-off col-start-1 row-start-1 size-4" />
<Loader2 className="motion-spinner col-start-1 row-start-1 size-4" />
</span>
+ ) : taken ? (
+ <Check key={taken} className="motion-confirm size-4" aria-label="Sent" />
) : (
<ArrowUp className="size-4" />
)}
diff --git a/src/components/studio/feed-motion.ts b/src/components/studio/feed-motion.ts
index 07b272d1..d0d73bb5 100644
--- a/src/components/studio/feed-motion.ts
+++ b/src/components/studio/feed-motion.ts
@@ -54,6 +54,16 @@ export function useArrival<T extends HTMLElement>(id: string, index: number) {
return ref;
}
+/** Presses of Run whose card already rose in (useMakingCard), with when: their run's own card takes its place still. */
+const handed: number[] = [];
+
+/** The card a press of Run shows at once: it rises in itself, so the run's own card that takes its place doesn't again. */
+export function useMakingCard(at: number) {
+ useLayoutEffect(() => {
+ handed.push(at);
+ }, [at]);
+}
+
/** A request's section: it rises in when it was just sent (in progress, made in the last moments), never on a load. */
export function useEnter<T extends HTMLElement>(id: string, active: boolean, createdAt: number) {
const ref = useRef<T>(null);
@@ -61,7 +71,12 @@ export function useEnter<T extends HTMLElement>(id: string, active: boolean, cre
useLayoutEffect(() => {
if (seen.current === id) return;
seen.current = id;
- if (active && Date.now() - createdAt < 15_000) mark(ref.current, "data-enter");
+ if (!active || Date.now() - createdAt >= 15_000) return;
+ // The card of its press was on screen: the run takes its place without moving.
+ const now = Date.now();
+ while (handed.length && now - handed[0] > 2 * 60_000) handed.shift();
+ if (handed.length) return void handed.shift();
+ mark(ref.current, "data-enter");
}, [id, active, createdAt]);
return ref;
}
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index d79c3d30..0b49e3c6 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Cloud, Copy, Cpu, Download, FolderDown, Heart, Loader2, MoreHorizontal, RotateCcw, Sparkles, Trash2, Wrench, X } from "lucide-react";
+import { Cloud, Copy, Cpu, Download, FolderDown, Heart, MoreHorizontal, PencilLine, RotateCcw, Sparkles, Trash2, Wrench, X } from "lucide-react";
import { ENGINE_WORDS } from "@/lib/engine-error";
import { useQueryClient } from "@tanstack/react-query";
import { pendingWords } from "@/lib/pending-words";
@@ -18,12 +18,15 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";
+import { OPERATION_LABELS, type Generation, type GenerationRequest } from "@/lib/catalog/types";
import { useOptionalCatalog } from "./catalog";
import { TroubleDetails } from "@/components/gpu/trouble";
import { RunTroubleActions } from "@/components/gpu/run-trouble-actions";
import { GpuFileSteps } from "@/components/gpu/file-steps";
-import { useCreateGeneration, useGenerationActions, useMakingPoolRuns, usePlaceName, useStatus } from "@/lib/api";
+import { goesToPool, useCreateGeneration, useGenerationActions, useMakingRuns, usePlaceName, useStatus } from "@/lib/api";
+import { runStage, shownMaking, STAGE_WORDS, tileBox, tileCount } from "@/lib/run-stage";
+import { RunAura, RunRing } from "./run-visuals";
+import { reducedMotion } from "@/lib/ui-motion";
import { knownPlace } from "@/lib/place-name";
import { runOnSiteAction } from "@/lib/diagnose";
import { retryRequest } from "@/lib/run-place";
@@ -44,7 +47,7 @@ import { Viewer } from "./viewer";
import { MadeNote } from "./made-note";
import { shownSettings } from "@/lib/catalog/made";
import { NextSteps } from "@/components/nav/next-steps";
-import { reservedRowHeight, useArrival, useEnter, useFollowRow, useLiveRun } from "./feed-motion";
+import { reservedRowHeight, useArrival, useEnter, useFollowRow, useLiveRun, useMakingCard } from "./feed-motion";
import { AiTag, useAiTag } from "./ai-tag";
export { MediaThumb } from "./result-media";
@@ -59,26 +62,78 @@ export function tileRatio(g: Generation): number {
return ratioValue(ar && ar !== "auto" ? ar : undefined, g.kind === "video" ? 16 / 9 : 1);
}
+/** The feed's row height, as a variable: a run card's width follows from it and its shape (tileBox). */
+const ROW_H = "h-(--tile-h) [--tile-h:14rem] sm:[--tile-h:16rem]";
+
/**
- * A run on this studio's GPUs between Run and its answer (the run is being made: a moment, or longer while the billing
- * service is tried again): "In line", as the run's own tile says once it is made. It shows only after a moment, so a
- * quick answer goes straight to the run's tile.
+ * One tile's place in a feed row, at its run's shape: its width is set from the row height, so a card that holds only
+ * an overlay (a run on its way) or a few words (a failed run) keeps its full size in the row.
*/
-export function MakingTile({ ratio }: { ratio: number }) {
+function TileSlot({ ratio, min, children }: { ratio: number; min?: number; children: React.ReactNode }) {
return (
- <div
- className="relative h-full max-w-full animate-pending-in overflow-hidden rounded-xl bg-muted"
- style={{ aspectRatio: ratio, animationDelay: "800ms" }}
- data-run-state="in-line"
- >
- <div className="skeleton-sweep absolute inset-0 animate-skeleton" />
+ <div className={cn("max-w-full shrink-0", ROW_H)} style={{ width: tileBox(ratio, min).width }}>
+ {children}
+ </div>
+ );
+}
+
+/**
+ * A run between Run and the studio's answer (a moment; on this studio's GPUs it can be longer, while the billing service
+ * is tried again): its card shows at once, at the run's shape and count, under its own words, so a press always shows
+ * that it was taken. On this studio's GPUs it says "In line", as the run's own tile does once it is made; anywhere
+ * else "Starting".
+ */
+export function MakingTile({ ratio, pool }: { ratio: number; pool?: boolean }) {
+ return (
+ <div className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }} data-run-state={pool ? "in-line" : undefined} data-stage="sending">
+ <RunAura />
<div className="absolute inset-x-0 bottom-0 p-3">
- <p className="shimmer-text animate-shimmer-text text-[13px] font-medium">{POOL_WORDS.inLine}</p>
+ <p className="flex items-start gap-2 text-[13px] font-medium">
+ <RunRing fraction={null} stage={pool ? "in-line" : "sending"} />
+ <span>{pool ? POOL_WORDS.inLine : STAGE_WORDS.sending}</span>
+ </p>
</div>
</div>
);
}
+/** A press of Run with no answer yet: the card the run will have, with the words that were sent. */
+function MakingGroup({ at, request, pool }: { at: number; request: GenerationRequest; pool: boolean }) {
+ useMakingCard(at);
+ const catalog = useOptionalCatalog();
+ const model = catalog?.getModel(request.modelId);
+ const p = request.params ?? {};
+ const ar = p.aspectRatio;
+ const ratio = ratioValue(ar && ar !== "auto" ? ar : undefined, model?.kind === "video" ? 16 / 9 : 1);
+ const count = tileCount(p.numOutputs);
+ const title = request.prompt?.trim() || model?.name || STAGE_WORDS.sending;
+ const meta = [model?.name, ar && ar !== "auto" ? ar : undefined, p.resolution].filter((x): x is string => !!x);
+ return (
+ <section data-making className="scroll-mt-20 space-y-2.5" aria-busy="true">
+ <header className="min-w-0">
+ <h2 className="line-clamp-2 font-heading text-[19px] leading-snug" title={request.prompt ?? undefined}>
+ {title}
+ </h2>
+ <p className="mt-0.5 flex flex-wrap items-center gap-x-1.5 text-[12px] text-muted-foreground">
+ {meta.map((m, i) => (
+ <span key={i} className={cn(i > 0 && "before:mr-1.5 before:content-['·']")}>
+ {m}
+ </span>
+ ))}
+ <span className={cn(meta.length > 0 && "before:mr-1.5 before:content-['·']")}>just now</span>
+ </p>
+ </header>
+ <div className="flex flex-wrap gap-2">
+ {Array.from({ length: count }, (_, i) => (
+ <TileSlot key={i} ratio={ratio}>
+ <MakingTile ratio={ratio} pool={pool} />
+ </TileSlot>
+ ))}
+ </div>
+ </section>
+ );
+}
+
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).
@@ -116,47 +171,56 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
// Waiting for its own GPU or key to come back: what helps meanwhile, and until when it waits.
const waiting = g.status === "queued" ? g.waiting : undefined;
const until = waiting?.until && waiting.until > now ? new Date(waiting.until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : null;
+ // Its stage: the card's look, its ring, and what a screen reader hears when it moves on.
+ const st = runStage(g, local ? { fraction: steps, saving: !!saving } : null) ?? { stage: "creating" as const, fraction: null };
+ const ring = st.stage === "in-line" || st.stage === "warming" || saving ? null : fraction;
return (
// max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would
// otherwise make the tile wider than its column and spill over the next card.
- <div className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }} data-run-state={pool ? (inLine ? "in-line" : "working") : undefined}>
- <div className="skeleton-sweep absolute inset-0 animate-skeleton" />
+ <div
+ className="relative h-full max-w-full overflow-hidden rounded-xl bg-muted"
+ style={{ aspectRatio: ratio }}
+ data-run-state={pool ? (inLine ? "in-line" : "working") : undefined}
+ data-stage={st.stage}
+ >
+ <RunAura />
{frame && (
// eslint-disable-next-line @next/next/no-img-element -- a live frame (a blob: address, or the run's own preview picture)
<img
src={frame}
alt=""
- // Shown once a frame decodes (a frame that doesn't keeps the shimmer).
- onLoad={(e) => (e.currentTarget.style.opacity = "0.9")}
+ data-run-preview
+ // Shown once a frame decodes (a frame that doesn't keeps the living fill).
+ onLoad={(e) => (e.currentTarget.style.opacity = "1")}
onError={(e) => (e.currentTarget.style.opacity = "0")}
- className="absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-300"
+ className="absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-(--motion-slow)"
/>
)}
- <div className={cn("absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3", frame && "bg-gradient-to-t from-background/85 to-transparent pt-8")}>
+ <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 bg-gradient-to-t from-background/85 via-background/45 to-transparent p-3 pt-10">
<div className="min-w-0">
- {/* Always a sign it is on its way (a turning ring), with the run's own words beside it. */}
- <p title={label} className="flex items-start gap-1.5 text-[13px] font-medium">
- <Loader2 aria-hidden data-run-spinner className="mt-0.5 size-3.5 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" />
- <span className="shimmer-text animate-shimmer-text line-clamp-2">{label}</span>
+ {/* Always a sign it is on its way (a ring: its progress, or turning), with the run's own words beside it. */}
+ <p title={label} className="flex items-start gap-2 text-[13px] leading-snug font-medium">
+ <RunRing fraction={ring} stage={st.stage} />
+ <span className="line-clamp-2">{label}</span>
</p>
{place && (
- <p title={place} className="line-clamp-2 text-[11px] text-muted-foreground">
+ <p title={place} className="line-clamp-2 pl-6 text-[11px] text-muted-foreground">
{place}
</p>
)}
{where && (
- <p title={where} className="line-clamp-2 text-[11px] text-muted-foreground">
+ <p title={where} className="line-clamp-2 pl-6 text-[11px] text-muted-foreground">
{where}
</p>
)}
- <p className="flex flex-wrap gap-x-1.5 font-mono text-[11px] text-muted-foreground tabular-nums">
+ <p className="mt-0.5 flex flex-wrap gap-x-1.5 pl-6 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>}
{until && <span className="before:mr-1.5 before:content-['·']">waits until {until}</span>}
</p>
{/* Run with your key moves this run (and the rest of its batch not handed over yet) to the key, in one server call. */}
- {waiting && <RunTroubleActions g={g} className="mt-1.5" actions={waiting.actions} skip={["retry"]} max={2} compact />}
+ {waiting && <RunTroubleActions g={g} className="mt-1.5 pl-6" actions={waiting.actions} skip={["retry"]} max={2} compact />}
</div>
<Tooltip>
<TooltipTrigger asChild>
@@ -165,7 +229,7 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
e.stopPropagation();
void cancel(g);
}}
- className="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground hover:text-foreground"
+ className="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground backdrop-blur transition-colors hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
aria-label="Cancel"
>
<X className="size-3.5" />
@@ -179,6 +243,10 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
<div className="h-full origin-left bg-primary transition-transform duration-(--motion-slow) ease-standard" style={{ transform: `scaleX(${bar / 100})` }} />
</div>
)}
+ {/* What a screen reader hears as it moves on: the stage, not every percent. */}
+ <span className="sr-only" role="status" aria-live="polite">
+ {STAGE_WORDS[st.stage]}
+ </span>
</div>
);
}
@@ -192,6 +260,9 @@ const SIMILAR_MODEL = { kind: "pick-model", label: "Try a similar model" } as co
/** The causes a failed tile offers no Retry for (src/lib/diagnose.ts): only a fix on the GPU helps. */
const NO_RETRY_CAUSES: readonly string[] = ["gpu-comfy-known", "gpu-model-file"];
+/** A failed run's card is never narrower than this shape (width over height): its words and buttons need the room. */
+const FAILED_MIN_SHAPE = 0.8;
+
/** A failed tile narrower than this (in px, at the feed's 224 px height) shows two trouble buttons, not three. */
const NARROW_TILE_PX = 260;
@@ -213,13 +284,13 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati
// A run on this studio's GPUs that couldn't finish: one plain sentence (the server's), nothing technical.
const poolFailed = g.place === "pool" && g.status === "failed";
const reuseFirst = poolFailed && !!onReuse && FILE_TROUBLE.includes(g.error ?? "");
- const shape = Math.max(ratio, 0.8);
+ const shape = Math.max(ratio, FAILED_MIN_SHAPE);
const narrow = shape * 224 < NARROW_TILE_PX;
const [retrying, setRetrying] = useState(false);
// Retry can't help a known ComfyUI problem or a missing model file: the same run would stop the same way.
const retryHelps = !NO_RETRY_CAUSES.includes(trouble?.cause ?? "");
return (
- <div className="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: shape }}>
+ <div className="flex h-full max-w-full flex-col justify-between overflow-hidden rounded-xl border bg-muted/40 p-3" style={{ aspectRatio: shape }} data-stage={g.status}>
<div className="flex min-h-0 flex-col gap-1 overflow-hidden">
{poolFailed ? (
<p className={cn("shrink-0 text-[13px] leading-snug font-medium break-words", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error || POOL_WORDS.failed}</p>
@@ -303,12 +374,28 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati
reuseFirst
? // After Reuse, the quiet second: the same files would only fail again.
"inline-flex h-7 w-fit items-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-70"
- : "inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-70"
+ : g.status === "failed" && g.fix
+ ? "inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-70"
+ : // The way on from here: the run again, a press away.
+ "inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground shadow-xs transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-none disabled:opacity-70"
}
>
<RotateCcw className="size-3" /> Retry
</button>
)}
+ {/* Change the words or settings first: the run comes back into the composer (as the header's Reuse). */}
+ {onReuse && !reuseFirst && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onReuse();
+ }}
+ title="Load prompt, model and settings into the composer"
+ className="inline-flex h-7 w-fit items-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <PencilLine className="size-3" /> Reuse
+ </button>
+ )}
</div>
</div>
);
@@ -439,7 +526,7 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest, first
const site = (usePlaceName() ?? knownPlace()).label;
const ratio = tileRatio(g);
const active = g.status === "queued" || g.status === "running";
- const placeholders = Math.max(1, g.request.params?.numOutputs ?? 1);
+ const placeholders = tileCount(g.request.params?.numOutputs);
const enter = useEnter<HTMLElement>(g.id, active, g.createdAt);
// The top run on its way, with one picture to come: its next-steps row will land under it, so its room is kept now.
const reserve = first && active && placeholders === 1 ? reservedRowHeight() : 0;
@@ -464,7 +551,7 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest, first
].filter((x, i, all) => x && all.indexOf(x) === i);
return (
- <section ref={enter} data-gen-id={g.id} className="group/gen space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
+ <section ref={enter} data-gen-id={g.id} className="group/gen scroll-mt-20 space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
<header className="flex items-start gap-3">
<div className="min-w-0 flex-1">
<h2 className="line-clamp-2 font-heading text-[19px] leading-snug" title={g.prompt ?? undefined}>
@@ -551,14 +638,14 @@ export const GenerationGroup = memo(function GenerationGroup({ g, newest, first
<div className="flex flex-wrap gap-2">
{active &&
Array.from({ length: placeholders }, (_, i) => (
- <div key={i} className="h-56 max-w-full sm:h-64">
+ <TileSlot key={i} ratio={ratio}>
<PendingTile g={g} ratio={ratio} />
- </div>
+ </TileSlot>
))}
{(g.status === "failed" || g.status === "canceled") && (
- <div className="h-56 max-w-full sm:h-64">
+ <TileSlot ratio={ratio} min={FAILED_MIN_SHAPE}>
<FailedTile g={g} ratio={ratio} onRetry={() => feed.retry(g)} onReuse={feed.reuse ? () => feed.reuse?.(g) : undefined} />
- </div>
+ </TileSlot>
)}
{g.status === "succeeded" &&
(layered ? (
@@ -589,14 +676,30 @@ export function Feed({
items,
onReuse,
empty,
+ features,
}: {
items: Generation[];
onReuse?: (g: Generation) => void;
empty?: React.ReactNode;
+ /** The studio features this feed lists: a press of Run elsewhere on the page shows its card only in its own feed. */
+ features?: readonly string[];
}) {
const [open, setOpen] = useState<{ id: string; index: number } | null>(null);
const create = useCreateGeneration();
- const making = useMakingPoolRuns();
+ const presses = useMakingRuns();
+ const making = shownMaking(presses, items, features);
+ // A press of Run: its card is at the top of the feed (the press's own, or its run's once made), so the feed brings it
+ // into view when it is out of sight (scrolled down into older runs).
+ const top = useRef<HTMLDivElement>(null);
+ const sent = presses.length ? presses[presses.length - 1].at : 0;
+ useEffect(() => {
+ if (!sent) return;
+ const el = top.current?.firstElementChild;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ if (r.top >= 56 && r.top <= window.innerHeight * 0.5) return;
+ el.scrollIntoView({ block: "start", behavior: reducedMotion() ? "auto" : "smooth" });
+ }, [sent]);
// Hosted runs: Retry sends a run to the place it ran (read through a ref: the feed's callbacks stay the same).
const hosted = !!useStatus().data?.viewer?.hosted;
const hostedRef = useRef(hosted);
@@ -623,24 +726,24 @@ export function Feed({
}),
[openAt, hasReuse, aiTag],
);
- // Runs on this studio's GPUs being made now: newest first, above the runs already made.
- const makingTiles = [...making].reverse().map((m, i) => {
- const ar = m.request.params?.aspectRatio;
- return (
- <div key={`making-${m.at}-${i}`} className="h-56 max-w-full sm:h-64">
- <MakingTile ratio={ratioValue(ar && ar !== "auto" ? ar : undefined, 1)} />
+ // Runs being made now (Run pressed, no answer yet): newest first, above the runs already made.
+ const makingGroups = [...making].reverse().map((m, i) => <MakingGroup key={`making-${m.at}-${i}`} at={m.at} request={m.request} pool={goesToPool(m.request)} />);
+ if (!items.length)
+ return makingGroups.length ? (
+ <div ref={top} className="space-y-9">
+ {makingGroups}
</div>
+ ) : (
+ <>{empty}</>
);
- });
- if (!items.length) return makingTiles.length ? <div className="flex flex-wrap gap-2">{makingTiles}</div> : <>{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">
- {makingTiles.length > 0 && <div className="flex flex-wrap gap-2">{makingTiles}</div>}
+ <div ref={top} className="space-y-9">
+ {makingGroups}
{items.map((g, i) => (
<GenerationGroup key={g.id} g={g} newest={g.id === newest} first={i === 0} />
))}
diff --git a/src/components/studio/run-visuals.tsx b/src/components/studio/run-visuals.tsx
new file mode 100644
index 00000000..10fd47e1
--- /dev/null
+++ b/src/components/studio/run-visuals.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import type { RunStage } from "@/lib/run-stage";
+import { cn } from "@/lib/utils";
+
+/*
+ * The look every run on its way shares, wherever it is waited on (the studios' feeds, a Library card, a Canvas node, a
+ * film's shot): a soft living light across its card, and a ring beside its words.
+ */
+
+/** The living fill under a run on its way: a soft light that drifts (still under reduced motion). */
+export function RunAura() {
+ return <div aria-hidden className="run-aura absolute inset-0" />;
+}
+
+/**
+ * The ring beside a run's words: its progress when it reports one, else a turning arc. A run in line waits calmly
+ * (muted); one being made is in the brand colour.
+ */
+export function RunRing({ fraction, stage }: { fraction: number | null; stage: RunStage }) {
+ const r = 7;
+ const c = 2 * Math.PI * r;
+ const spin = fraction == null;
+ return (
+ <svg
+ viewBox="0 0 18 18"
+ aria-hidden
+ data-run-spinner
+ className={cn("mt-px size-4 shrink-0", spin ? "animate-spin [animation-duration:1.4s] motion-reduce:animate-none" : "-rotate-90", stage === "in-line" ? "text-muted-foreground" : "text-primary")}
+ >
+ <circle cx="9" cy="9" r={r} fill="none" stroke="currentColor" strokeOpacity={0.2} strokeWidth="2" />
+ <circle
+ cx="9"
+ cy="9"
+ r={r}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeDasharray={c.toFixed(2)}
+ strokeDashoffset={(spin ? c * 0.72 : c * (1 - Math.max(0.04, fraction))).toFixed(2)}
+ className="transition-[stroke-dashoffset] duration-(--motion-slow) ease-standard"
+ />
+ </svg>
+ );
+}
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index 8606c0fa..29275539 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -580,7 +580,7 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
<div className={cn("mx-auto w-full max-w-[1240px] min-w-0 px-4 sm:px-6", hasItems && "flex-1 pb-8", live && "hidden")}>
{hasItems ? (
<div className="pt-4">
- <Feed items={items} onReuse={reuse} />
+ <Feed items={items} onReuse={reuse} features={config.feed.features} />
</div>
) : (
<div className="flex flex-col items-center pt-6 text-center sm:pt-[16vh]">
@@ -621,7 +621,9 @@ function StudioBody({ header, tabs, examples }: { header?: React.ReactNode; tabs
className={cn(
live && "hidden",
hasItems
- ? "sticky bottom-chrome z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-4 pt-8 pb-[max(1rem,env(safe-area-inset-bottom))] sm:px-6"
+ ? // Docked: a solid ground under the composer (the feed never shows through it), with a short fade above it
+ // where the feed scrolls under.
+ "sticky bottom-chrome z-20 bg-background px-4 pt-2 pb-[max(1rem,env(safe-area-inset-bottom))] before:pointer-events-none before:absolute before:inset-x-0 before:-top-8 before:h-8 before:bg-gradient-to-t before:from-background before:to-transparent sm:px-6"
: "px-4 pt-6 sm:px-6 sm:pt-10",
)}
>
diff --git a/src/lib/api.ts b/src/lib/api.ts
index f7ee5bd5..e271903a 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -15,8 +15,10 @@ import {
backoff,
needsCatchUp,
parseSse,
+ pollDelay,
shareById,
sharePagesById,
+ STREAM_IDLE_MS,
streamResponse,
toChannelMessage,
toStreamEvent,
@@ -89,8 +91,8 @@ async function json<T>(res: Response): Promise<T> {
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);
+/** Poll while something renders: fast without the live stream, a safety net with it (pollDelay). */
+const pollEvery = (items: Generation[] | undefined, live: boolean) => pollDelay(items, live) ?? false;
/** Apply one change to every cached list and thread, skipping caches it doesn't change. */
function applyEvent(qc: QueryClient, ev: StreamEvent): void {
@@ -248,6 +250,17 @@ async function connect() {
const ctrl = new AbortController();
s.abort = ctrl;
let retryIn = 0;
+ // A stream that goes quiet past the server's pings is gone (a laptop that slept, a proxy holding a stream whose
+ // server stopped): drop it and open another at once, which catches up on what changed meanwhile.
+ let stale = false;
+ let idle: ReturnType<typeof setTimeout> | null = null;
+ const awake = () => {
+ if (idle) clearTimeout(idle);
+ idle = setTimeout(() => {
+ stale = true;
+ ctrl.abort();
+ }, STREAM_IDLE_MS);
+ };
try {
const res = await fetch("/api/generations/stream", { headers: { Accept: "text/event-stream" }, signal: ctrl.signal, cache: "no-store" });
const next = streamResponse({ ok: res.ok, status: res.status, contentType: res.headers.get("content-type"), hasBody: !!res.body }, s.attempt++);
@@ -259,9 +272,11 @@ async function connect() {
setLive(true);
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
+ awake();
for (;;) {
const { value, done } = await reader.read();
if (done) break;
+ awake();
const parsed = parseSse(buf + value);
buf = parsed.rest;
for (const m of parsed.events) {
@@ -274,8 +289,10 @@ async function connect() {
retryIn = backoff(s.attempt++);
}
} catch {
- if (ctrl.signal.aborted) return;
- retryIn = backoff(s.attempt++);
+ if (ctrl.signal.aborted && !stale) return;
+ retryIn = stale ? 0 : backoff(s.attempt++);
+ } finally {
+ if (idle) clearTimeout(idle);
}
if (s.abort !== ctrl) return;
s.abort = null;
@@ -376,6 +393,23 @@ function onVisibility() {
if (s.hiddenTimer) clearTimeout(s.hiddenTimer);
s.hiddenTimer = null;
if (s.subscribers) start();
+ catchUpActive();
+}
+
+/**
+ * Back on screen, or back online: lists with a run on its way read again at once, so a run that finished meanwhile
+ * shows done straight away (a hidden tab stops polling, and its stream may have been let go).
+ */
+function catchUpActive() {
+ const qc = live().client;
+ if (!qc) return;
+ const waiting = (data: unknown): boolean =>
+ Array.isArray(data) ? data.some((g) => isActive(g as Generation)) : !!(data as Pages | undefined)?.pages?.some((p) => p.some(isActive));
+ for (const key of [["generations"], ["library"]]) {
+ for (const q of qc.getQueryCache().findAll({ queryKey: key })) {
+ if (waiting(q.state.data)) void qc.invalidateQueries({ queryKey: q.queryKey, exact: true });
+ }
+ }
}
/** Share one stream between every list on the page (and every tab, and canvas boards); returns whether it's connected. */
@@ -390,6 +424,7 @@ export function useGenerationStream(): boolean {
if (!s.hooked) {
s.hooked = true;
document.addEventListener("visibilitychange", onVisibility);
+ window.addEventListener("online", catchUpActive);
}
// A tab opened in the background waits until it's shown.
if (document.visibilityState !== "hidden") start();
@@ -550,15 +585,16 @@ export function goesToPool(req: GenerationRequest | undefined): boolean {
}
/**
- * The runs on this studio's GPUs being made now (Run pressed, no answer yet), with when Run was pressed. The feed shows
- * each one as "In line" until the run is made, so a short wait before it starts never looks like nothing happened.
+ * The runs being made now (Run pressed, no answer yet), with when Run was pressed. The feed shows each one's card at
+ * once ("In line" on this studio's GPUs, else "Starting") until the run is made, so a press never looks like nothing
+ * happened.
*/
-export function useMakingPoolRuns(): { at: number; request: GenerationRequest }[] {
+export function useMakingRuns(): { at: number; request: GenerationRequest }[] {
const pending = useMutationState({
filters: { mutationKey: CREATE_GENERATION_KEY, status: "pending" },
select: (m) => ({ at: m.state.submittedAt, request: m.state.variables as GenerationRequest | undefined }),
});
- return pending.filter((p): p is { at: number; request: GenerationRequest } => goesToPool(p.request));
+ return pending.filter((p): p is { at: number; request: GenerationRequest } => !!p.request && typeof p.request === "object");
}
/**
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
index daee3055..b46ae24f 100644
--- a/src/lib/generation-stream.ts
+++ b/src/lib/generation-stream.ts
@@ -182,6 +182,28 @@ export function sharePagesById(prev: unknown, next: unknown): unknown {
return samePages && pageParams === p.pageParams ? p : { ...n, pages, pageParams };
}
+/**
+ * How often a list with runs on their way asks for them again (null: none on its way, so it doesn't). The live stream
+ * brings every change at once; polling is the safety net that makes a missed change (a stream cut by an update of the
+ * site, a sleeping laptop, a proxy holding a stream open after its server went away) show within seconds anyway.
+ * A run just sent is asked about most often; one that has been going a long while, less.
+ */
+export function pollDelay(items: readonly Pick<Generation, "status" | "createdAt">[] | undefined, live: boolean, now = Date.now()): number | null {
+ let youngest = -Infinity;
+ for (const g of items ?? []) if ((g.status === "queued" || g.status === "running") && g.createdAt > youngest) youngest = g.createdAt;
+ if (youngest === -Infinity) return null;
+ const age = Math.max(0, now - youngest);
+ if (live) return age < 3 * 60_000 ? 4000 : 10_000;
+ return age < 60_000 ? 1500 : age < 10 * 60_000 ? 3000 : 6000;
+}
+
+/**
+ * A stream that has said nothing for this long is taken as gone (the server pings every 15 s): it is dropped and
+ * opened again, with a catch-up read of the lists. A connection can stay open while nothing comes through it (a
+ * laptop that slept, a proxy that kept it after the server behind it stopped).
+ */
+export const STREAM_IDLE_MS = 40_000;
+
/** 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/run-stage.ts b/src/lib/run-stage.ts
new file mode 100644
index 00000000..49dd9d5e
--- /dev/null
+++ b/src/lib/run-stage.ts
@@ -0,0 +1,95 @@
+import type { Generation, GenerationRequest } from "./catalog/types";
+
+/**
+ * Where a run on its way is, as one of a few stages every run card shows the same way (the studios' feeds, and the
+ * other places a run is waited on). The words on the card stay the run's own (src/lib/pending-words.ts); the stage
+ * drives the card's look, its progress ring and what a screen reader hears when it moves on.
+ *
+ * - "sending": Run was pressed and the studio hasn't answered yet (the card shows at once, before the run is made).
+ * - "in-line": made, waiting for its turn.
+ * - "warming": started, with no progress yet (its model loading).
+ * - "creating": making it, with its progress when it reports one.
+ * - "finishing": nearly there (the last steps, saving, the result's check).
+ */
+export type RunStage = "sending" | "in-line" | "warming" | "creating" | "finishing";
+
+/** A short word for each stage: the screen reader's announcement when a card moves on (never the machinery). */
+export const STAGE_WORDS: Record<RunStage, string> = {
+ sending: "Starting",
+ "in-line": "In line",
+ warming: "Warming up",
+ creating: "Creating",
+ finishing: "Finishing",
+};
+
+/** At or past this share of its progress a run reads as finishing. */
+export const FINISHING_AT = 0.97;
+
+type StageFacts = Pick<Generation, "status" | "progress"> & Partial<Pick<Generation, "stage">>;
+
+/**
+ * The stage of a run on its way (null once it is done, failed or stopped), and its progress (0–1) when it says one.
+ * `local`: its job on the ComfyUI on this computer, when it runs there (its own steps and phase come first).
+ */
+export function runStage(g: StageFacts, local?: { fraction: number | null; saving?: boolean } | null): { stage: RunStage; fraction: number | null } | null {
+ if (g.status !== "queued" && g.status !== "running") return null;
+ if (local) {
+ if (local.saving) return { stage: "finishing", fraction: null };
+ if (local.fraction == null || local.fraction <= 0) return { stage: g.status === "queued" ? "in-line" : "warming", fraction: null };
+ return { stage: local.fraction >= FINISHING_AT ? "finishing" : "creating", fraction: clamp(local.fraction) };
+ }
+ if (g.status === "queued") return { stage: "in-line", fraction: null };
+ if (g.stage === "checking") return { stage: "finishing", fraction: null };
+ const p = g.progress;
+ if (p == null || !Number.isFinite(p) || p <= 0) return { stage: "warming", fraction: null };
+ return { stage: p >= FINISHING_AT ? "finishing" : "creating", fraction: clamp(p) };
+}
+
+const clamp = (n: number) => Math.min(1, Math.max(0, n));
+
+/**
+ * A run card's box at its run's shape: `ratio` is width over height. The height is the feed's row height (a CSS
+ * variable, so phones and desktops share one rule) and the width follows from it, set outright rather than left to
+ * `aspect-ratio`: a card that holds only an overlay (a run on its way) or a few words (a failed run) then never
+ * shrinks to its content's width in a flex row, whatever the browser does with percentage heights.
+ * `min`: the narrowest shape kept (a failed run's words and buttons need some room).
+ */
+export function tileBox(ratio: number, min = 0): { width: string; aspectRatio: number } {
+ const r = Number.isFinite(ratio) && ratio > 0 ? Math.max(ratio, min) : 1;
+ const shape = Math.round(r * 10_000) / 10_000;
+ return { width: `calc(var(--tile-h) * ${shape})`, aspectRatio: shape };
+}
+
+/** A press of Run with no answer yet (useMakingRuns): when it was pressed (the browser's clock) and what it sent. */
+export interface Making {
+ at: number;
+ request: Pick<GenerationRequest, "feature" | "modelId" | "prompt">;
+}
+
+/** How far apart the browser's clock and the server's may be when a made run is matched to its press. */
+const MATCH_WINDOW_MS = 60_000;
+
+/**
+ * The presses of Run a feed shows a card for: the ones for its own features (else the features it lists already, or
+ * all when it lists none), and not one whose run has already arrived in it (the run's own card takes over in the same
+ * place, so the hand-over never shows two cards or a jump).
+ */
+export function shownMaking<T extends Making>(making: readonly T[], items: readonly Pick<Generation, "feature" | "modelId" | "createdAt" | "request" | "status">[], features?: readonly string[]): T[] {
+ const own = features?.length ? new Set(features) : items.length ? new Set(items.map((g) => g.feature)) : null;
+ return making.filter((m) => {
+ if (own && !own.has(m.request.feature)) return false;
+ return !items.some(
+ (g) =>
+ (g.status === "queued" || g.status === "running") &&
+ Math.abs(g.createdAt - m.at) <= MATCH_WINDOW_MS &&
+ g.modelId === m.request.modelId &&
+ (g.request.prompt ?? "") === (m.request.prompt ?? ""),
+ );
+ });
+}
+
+/** How many tiles a run card shows while it is on its way: the pictures or clips it was asked for (1 to 8). */
+export function tileCount(numOutputs: unknown): number {
+ const n = typeof numOutputs === "number" && Number.isFinite(numOutputs) ? Math.round(numOutputs) : 1;
+ return Math.min(8, Math.max(1, n));
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 0fec1954..9826af2e 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1302,6 +1302,13 @@ function open(): Database.Database {
} catch (e) {
console.warn(`[fuobe] Couldn't index runs by account: ${(e as Error).message}`);
}
+ // The live stream's sweep reads the runs updated in the last moments (live.ts sweepForeign): through this index, not
+ // by reading every run. Not a numbered migration either; a failure only leaves the sweep slower.
+ try {
+ db.exec("CREATE INDEX IF NOT EXISTS generations_updated ON generations(updated_at)");
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't index runs by update time: ${(e as Error).message}`);
+ }
keepPrivate(file);
return db;
}
diff --git a/src/server/live.ts b/src/server/live.ts
index db746111..1aac74aa 100644
--- a/src/server/live.ts
+++ b/src/server/live.ts
@@ -28,18 +28,85 @@ interface LiveState {
/** Turns changed ids into events: set (and re-set after hot reloads) by src/server/generations.ts. */
resolve?: (ids: string[]) => LiveEvent[];
hooked: WeakSet<object>;
+ /** The connection the change hooks are on (read by the sweep for other processes' writes). */
+ db?: Database.Database;
+ /** The last updated_at each changed row had, as this process saw it (its own writes, or the sweep). */
+ seen: Map<string, number>;
+ /** Rows updated after this (less a margin) are what the sweep reads. */
+ mark: number;
+ sweep: ReturnType<typeof setInterval> | null;
}
declare global {
var __fuobeLive: LiveState | undefined;
}
-const state = (): LiveState => (globalThis.__fuobeLive ??= { listeners: new Set(), pending: new Set(), scheduled: false, hooked: new WeakSet() });
+const state = (): LiveState => {
+ const s = (globalThis.__fuobeLive ??= { listeners: new Set(), pending: new Set(), scheduled: false, hooked: new WeakSet(), seen: new Map(), mark: Date.now(), sweep: null });
+ // A state kept across a dev hot reload may predate these.
+ s.seen ??= new Map();
+ s.mark ??= Date.now();
+ s.sweep ??= null;
+ return s;
+};
+
+/**
+ * Writes by another app process (the site's other instance while an update switches over: both run for a moment, and
+ * the runner in either may save a run's result) fire no trigger here: TEMP triggers belong to their own connection.
+ * So while anyone listens, this process also reads the rows updated lately every SWEEP_MS, and passes on the ones
+ * whose change it hasn't seen. A stream then brings every change within seconds, whichever process wrote it.
+ */
+export const SWEEP_MS = 2000;
+/** How far back each sweep reads (the processes share a clock; a write can commit a moment after its timestamp). */
+const SWEEP_MARGIN_MS = 10_000;
+
+/** Read the rows updated since the last sweep and pass on the ones another process changed (exported for tests). */
+export function sweepForeign(now = Date.now()): number {
+ const s = state();
+ if (!s.db || !s.listeners.size) return 0;
+ const since = s.mark - SWEEP_MARGIN_MS;
+ let rows: { id: string; updated_at: number }[];
+ try {
+ rows = s.db.prepare("SELECT id, updated_at FROM main.generations WHERE updated_at > ?").all(since) as { id: string; updated_at: number }[];
+ } catch {
+ return 0;
+ }
+ let n = 0;
+ for (const r of rows) {
+ if ((s.seen.get(r.id) ?? -Infinity) >= r.updated_at) continue;
+ s.seen.set(r.id, r.updated_at);
+ changed(r.id);
+ n++;
+ }
+ s.mark = Math.max(s.mark, now);
+ // Forget what is out of the sweep's reach.
+ for (const [id, at] of s.seen) if (at < since - 60_000) s.seen.delete(id);
+ return n;
+}
+
+function startSweep(): void {
+ const s = state();
+ if (s.sweep) return;
+ s.mark = Date.now();
+ s.sweep = setInterval(() => sweepForeign(), SWEEP_MS);
+ s.sweep.unref?.();
+}
+
+function stopSweep(): void {
+ const s = state();
+ if (!s.sweep) return;
+ clearInterval(s.sweep);
+ s.sweep = null;
+}
export function subscribe(listener: Listener): () => void {
const s = state();
s.listeners.add(listener);
- return () => void s.listeners.delete(listener);
+ startSweep();
+ return () => {
+ s.listeners.delete(listener);
+ if (!s.listeners.size) stopSweep();
+ };
}
export const listenerCount = () => state().listeners.size;
@@ -48,8 +115,10 @@ export function setResolver(resolve: (ids: string[]) => LiveEvent[]): void {
state().resolve = resolve;
}
-function changed(id: string): void {
+function changed(id: string, updatedAt?: number): void {
const s = state();
+ // This process's own write: the sweep needn't pass it on again.
+ if (typeof updatedAt === "number" && updatedAt > (s.seen.get(id) ?? -Infinity)) s.seen.set(id, updatedAt);
if (!s.listeners.size) return;
s.pending.add(id);
if (s.scheduled) return;
@@ -86,15 +155,16 @@ function flush(): void {
export function watchGenerations(d: Database.Database): void {
const s = state();
if (s.hooked.has(d)) return;
- d.function("fuobe_generation_changed", { deterministic: false }, (id: unknown) => {
- changed(String(id));
+ d.function("fuobe_generation_changed", { deterministic: false, varargs: true }, (id: unknown, updatedAt?: unknown) => {
+ changed(String(id), typeof updatedAt === "number" ? updatedAt : typeof updatedAt === "bigint" ? Number(updatedAt) : undefined);
return null;
});
d.exec(`
- CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_insert AFTER INSERT ON main.generations BEGIN SELECT fuobe_generation_changed(NEW.id); END;
- CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_update AFTER UPDATE ON main.generations BEGIN SELECT fuobe_generation_changed(NEW.id); END;
+ CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_insert AFTER INSERT ON main.generations BEGIN SELECT fuobe_generation_changed(NEW.id, NEW.updated_at); END;
+ CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_update AFTER UPDATE ON main.generations BEGIN SELECT fuobe_generation_changed(NEW.id, NEW.updated_at); END;
CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_delete AFTER DELETE ON main.generations BEGIN SELECT fuobe_generation_changed(OLD.id); END;
`);
+ s.db = d;
s.hooked.add(d);
}
diff --git a/tests/e2e/feed-alive.mjs b/tests/e2e/feed-alive.mjs
new file mode 100644
index 00000000..dc4bd7e6
--- /dev/null
+++ b/tests/e2e/feed-alive.mjs
@@ -0,0 +1,187 @@
+// The studio feed stays alive: a press of Run shows its card at once, a run's card keeps its shape in every state, and
+// a run that finishes while the live stream is cut (an update of the site switching over) or silent (a proxy holding a
+// stream whose server went away) still shows done within seconds, without a reload.
+//
+// The app must be running with placeholder results (`FUOBE_DEMO_MODE=on`, ComfyUI unreachable: COMFYUI_URL=http://127.0.0.1:1).
+// Usage: node tests/e2e/feed-alive.mjs [appUrl]. Exits 1 on a failure.
+//
+// 1. Send: within 300 ms the newest card is on screen, at its run's shape (a 1:1 run: as wide as it is tall).
+// 2. Every crafted state (in line, warming up, creating, failed, canceled) at 1440 and 390 px: each card's width is its
+// shape times the row height (never a blank or a thin strip), and a failed one has Retry.
+// 3. Cut: from 1 s after Send, the stream answers 503 and every list read 503 for 8 s (the run finishes meanwhile); the
+// card shows the result within 4 s of the gap's end.
+// 4. Silent: the stream connects and then says nothing; the card shows the result within 6 s of the run finishing.
+import { DESKTOP, launch, PHONE } from "./_browser.mjs";
+
+const app = (process.argv[2] ?? "http://localhost:3000").replace(/\/$/, "");
+const browser = await launch();
+const failures = [];
+const check = (ok, msg) => {
+ console.log(` ${ok ? "ok " : "FAIL"} ${msg}`);
+ if (!ok) failures.push(msg);
+};
+
+/** The newest card in the feed: its state, and its tile's size. */
+const newest = (page) =>
+ page.evaluate(() => {
+ const s = document.querySelector("[data-making],[data-gen-id]");
+ const tile = s?.querySelector("[data-stage]") ?? s?.querySelector(":scope > div.flex.flex-wrap > *");
+ const r = tile?.getBoundingClientRect();
+ const done = !!s?.querySelector("img:not([data-run-preview]),video") && !s?.querySelector("[data-stage]");
+ return { making: !!s?.hasAttribute("data-making"), stage: tile?.getAttribute("data-stage") ?? null, done, w: Math.round(r?.width ?? 0), h: Math.round(r?.height ?? 0), visible: !!r && r.bottom > 0 && r.top < innerHeight };
+ });
+
+async function send(page, words) {
+ const ta = page.locator("[data-composer] textarea").first();
+ await ta.fill(words);
+ await ta.press("Enter");
+}
+
+async function waitDone(page, ms) {
+ const end = Date.now() + ms;
+ while (Date.now() < end) {
+ if ((await newest(page)).done) return true;
+ await page.waitForTimeout(100);
+ }
+ return false;
+}
+
+/** A page whose stream and list reads this script can cut or silence (window.__mode: "live" | "cut" | "silent"). */
+async function openStudio(ctxOpts) {
+ const ctx = await browser.newContext(ctxOpts);
+ await ctx.addInitScript(() => {
+ const real = window.fetch;
+ window.__mode = sessionStorage.getItem("e2e-stream") || "live";
+ window.fetch = (input, init) => {
+ const url = typeof input === "string" ? input : input.url;
+ const down = () => Promise.resolve(new Response("<html>updating</html>", { status: 503, headers: { "Content-Type": "text/html" } }));
+ if (url.includes("/api/generations/stream")) {
+ if (window.__mode === "cut") return down();
+ if (window.__mode === "silent") return Promise.resolve(new Response(new ReadableStream({ start: (c) => c.enqueue(new TextEncoder().encode(": connected\n\n")) }), { headers: { "Content-Type": "text/event-stream" } }));
+ // A live stream that ends as soon as the gap begins (the server stopping), as an update does.
+ return real(input, init).then((res) => {
+ if (!res.body) return res;
+ const reader = res.body.getReader();
+ let timer;
+ const body = new ReadableStream({
+ start(c) {
+ timer = setInterval(() => {
+ if (window.__mode !== "live") {
+ clearInterval(timer);
+ reader.cancel().catch(() => {});
+ try {
+ c.close();
+ } catch {}
+ }
+ }, 100);
+ },
+ async pull(c) {
+ const r = await reader.read().catch(() => ({ done: true }));
+ if (r.done) {
+ clearInterval(timer);
+ try {
+ c.close();
+ } catch {}
+ } else c.enqueue(r.value);
+ },
+ cancel() {
+ clearInterval(timer);
+ reader.cancel().catch(() => {});
+ },
+ });
+ return new Response(body, { status: res.status, headers: res.headers });
+ });
+ }
+ if (window.__mode === "cut" && url.includes("/api/generations")) return down();
+ return real(input, init);
+ };
+ });
+ const page = await ctx.newPage();
+ await page.goto(app + "/image", { waitUntil: "load", timeout: 120_000 });
+ await page.locator("[data-composer] textarea").first().waitFor({ timeout: 60_000 });
+ await page.waitForTimeout(2500);
+ return { ctx, page };
+}
+
+console.log("1. a press of Run shows its card at once");
+{
+ const { ctx, page } = await openStudio(DESKTOP);
+ await send(page, "a flying cat, instant card");
+ await page.waitForTimeout(300);
+ const n = await newest(page);
+ check(n.visible && n.w > 100 && Math.abs(n.w - n.h) <= 2, `the newest card is on screen at 1:1 (${n.w}×${n.h}, ${n.making ? "being made" : n.stage})`);
+ check(await waitDone(page, 15_000), "and its result arrives");
+ await ctx.close();
+}
+
+console.log("2. every state keeps its card's shape");
+{
+ const now = Date.now();
+ const req = (prompt, ar, n = 1) => ({ feature: "image", modelId: "moss-image", op: "t2i", prompt, inputs: {}, params: { aspectRatio: ar, resolution: "1K", numOutputs: n } });
+ const run = (id, ar, o) => ({ id, batchId: null, feature: "image", presetId: null, modelId: "moss-image", engine: "open", provider: "comfyui", op: "t2i", kind: "image", status: "queued", progress: null, message: null, prompt: id, request: req(id, ar), outputs: [], error: null, costUsd: 0, favorite: false, createdAt: now - 5000, updatedAt: now - 5000, completedAt: null, modelName: "MOSS-Image", presetName: null, aspectRatio: ar, deletedAt: null, folderId: null, pinnedAt: null, review: null, place: "pool", ...o });
+ const items = [
+ run("line", "1:1", { queue: { place: 1, etaSeconds: 40 } }),
+ run("warm", "3:4", { status: "running" }),
+ run("make", "16:9", { status: "running", progress: 0.4 }),
+ run("fail", "1:1", { status: "failed", error: "That one didn't come out right — try again, or try a similar model." }),
+ run("stop", "9:16", { place: undefined, status: "canceled" }),
+ ];
+ const want = { line: 1, warm: 0.75, make: 16 / 9, fail: 1, stop: 0.8 };
+ for (const [name, opts] of [["1440", DESKTOP], ["390", PHONE]]) {
+ const ctx = await browser.newContext(opts);
+ const page = await ctx.newPage();
+ await page.route(/\/api\/generations\?/, (r) => r.fulfill({ json: { items } }));
+ await page.goto(app + "/image", { waitUntil: "load", timeout: 120_000 });
+ await page.waitForSelector('[data-gen-id="stop"] [data-stage]', { timeout: 60_000 });
+ const sizes = await page.evaluate(() =>
+ Object.fromEntries([...document.querySelectorAll("[data-gen-id]")].map((s) => {
+ const t = s.querySelector("[data-stage]");
+ const r = t.getBoundingClientRect();
+ return [s.getAttribute("data-gen-id"), { w: r.width, h: r.height, stage: t.getAttribute("data-stage"), retry: /Retry/.test(s.textContent) }];
+ })),
+ );
+ const colW = await page.evaluate(() => document.querySelector("[data-gen-id] > div.flex.flex-wrap").getBoundingClientRect().width);
+ for (const [id, ratio] of Object.entries(want)) {
+ const s = sizes[id];
+ const expectW = Math.min(s.h * ratio, colW);
+ check(s.h >= 200 && Math.abs(s.w - expectW) <= 2, `${name}: ${id} (${s.stage}) is ${Math.round(s.w)}×${Math.round(s.h)}, its shape`);
+ }
+ check(sizes.fail.retry && sizes.stop.retry, `${name}: failed and canceled cards offer Retry`);
+ await ctx.close();
+ }
+}
+
+console.log("3. a run that finishes while the stream is cut shows done soon after");
+{
+ const { ctx, page } = await openStudio(DESKTOP);
+ await send(page, "a flying cat, through an update");
+ await page.waitForTimeout(1000);
+ await page.evaluate(() => (window.__mode = "cut"));
+ await page.waitForTimeout(8000);
+ const before = await newest(page);
+ check(!before.done, "during the gap the card still shows the run on its way (nothing to read)");
+ await page.evaluate(() => (window.__mode = "live"));
+ check(await waitDone(page, 4000), "within 4 s of the gap's end, the result shows");
+ await ctx.close();
+}
+
+console.log("4. a run that finishes while the stream is silent shows done within seconds");
+{
+ const { ctx, page } = await openStudio(DESKTOP);
+ // Silent from the page's first stream on.
+ await page.evaluate(() => sessionStorage.setItem("e2e-stream", "silent"));
+ await page.reload({ waitUntil: "load" });
+ await page.locator("[data-composer] textarea").first().waitFor({ timeout: 60_000 });
+ await page.waitForTimeout(2500);
+ await send(page, "a flying cat, silent stream");
+ // The placeholder run takes about 3.5 s.
+ check(await waitDone(page, 3500 + 6000), "the result shows within 6 s of the run finishing");
+ await ctx.close();
+}
+
+await browser.close();
+if (failures.length) {
+ console.log(`\n${failures.length} failed`);
+ process.exit(1);
+}
+console.log("\nall passed");
diff --git a/tests/golden/self-host/feed-tiles.html b/tests/golden/self-host/feed-tiles.html
index 66ca6780..44c8d84c 100644
--- a/tests/golden/self-host/feed-tiles.html
+++ b/tests/golden/self-host/feed-tiles.html
@@ -1,20 +1,22 @@
-<div class="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style="aspect-ratio:1">
-<div class="skeleton-sweep absolute inset-0 animate-skeleton">
+<div class="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style="aspect-ratio:1" data-stage="in-line">
+<div aria-hidden="true" class="run-aura absolute inset-0">
</div>
-<div class="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3">
+<div class="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 bg-gradient-to-t from-background/85 via-background/45 to-transparent p-3 pt-10">
<div class="min-w-0">
-<p title="Queued" class="flex items-start gap-1.5 text-[13px] font-medium">
-<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-circle lucide-loader-2 mt-0.5 size-3.5 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-hidden="true" data-run-spinner="true">
-<path d="M21 12a9 9 0 1 1-6.219-8.56">
-</path>
+<p title="Queued" class="flex items-start gap-2 text-[13px] leading-snug font-medium">
+<svg viewBox="0 0 18 18" aria-hidden="true" data-run-spinner="true" class="mt-px size-4 shrink-0 animate-spin [animation-duration:1.4s] motion-reduce:animate-none text-muted-foreground">
+<circle cx="9" cy="9" r="7" fill="none" stroke="currentColor" stroke-opacity="0.2" stroke-width="2">
+</circle>
+<circle cx="9" cy="9" r="7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="43.98" stroke-dashoffset="31.67" class="transition-[stroke-dashoffset] duration-(--motion-slow) ease-standard">
+</circle>
</svg>
-<span class="shimmer-text animate-shimmer-text line-clamp-2">Queued</span>
+<span class="line-clamp-2">Queued</span>
</p>
-<p class="flex flex-wrap gap-x-1.5 font-mono text-[11px] text-muted-foreground tabular-nums">
+<p class="mt-0.5 flex flex-wrap gap-x-1.5 pl-6 text-[11px] text-muted-foreground tabular-nums">
<span class="">1m 30s</span>
</p>
</div>
-<button class="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground hover:text-foreground" aria-label="Cancel" data-state="closed" data-slot="tooltip-trigger">
+<button class="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground backdrop-blur transition-colors hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none" aria-label="Cancel" data-state="closed" data-slot="tooltip-trigger">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x size-3.5" aria-hidden="true">
<path d="M18 6 6 18">
</path>
@@ -23,26 +25,29 @@
</svg>
</button>
</div>
+<span class="sr-only" role="status" aria-live="polite">In line</span>
</div>
-<div class="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style="aspect-ratio:1">
-<div class="skeleton-sweep absolute inset-0 animate-skeleton">
+<div class="relative h-full max-w-full overflow-hidden rounded-xl bg-muted" style="aspect-ratio:1" data-stage="creating">
+<div aria-hidden="true" class="run-aura absolute inset-0">
</div>
-<div class="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 p-3">
+<div class="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 bg-gradient-to-t from-background/85 via-background/45 to-transparent p-3 pt-10">
<div class="min-w-0">
-<p title="Generating" class="flex items-start gap-1.5 text-[13px] font-medium">
-<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-circle lucide-loader-2 mt-0.5 size-3.5 shrink-0 animate-spin text-muted-foreground motion-reduce:animate-none" aria-hidden="true" data-run-spinner="true">
-<path d="M21 12a9 9 0 1 1-6.219-8.56">
-</path>
+<p title="Generating" class="flex items-start gap-2 text-[13px] leading-snug font-medium">
+<svg viewBox="0 0 18 18" aria-hidden="true" data-run-spinner="true" class="mt-px size-4 shrink-0 -rotate-90 text-primary">
+<circle cx="9" cy="9" r="7" fill="none" stroke="currentColor" stroke-opacity="0.2" stroke-width="2">
+</circle>
+<circle cx="9" cy="9" r="7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="43.98" stroke-dashoffset="25.51" class="transition-[stroke-dashoffset] duration-(--motion-slow) ease-standard">
+</circle>
</svg>
-<span class="shimmer-text animate-shimmer-text line-clamp-2">Generating</span>
+<span class="line-clamp-2">Generating</span>
</p>
-<p class="flex flex-wrap gap-x-1.5 font-mono text-[11px] text-muted-foreground tabular-nums">
+<p class="mt-0.5 flex flex-wrap gap-x-1.5 pl-6 text-[11px] text-muted-foreground tabular-nums">
<span>42%</span>
<span class="before:mr-1.5 before:content-[&#x27;·&#x27;]">1m 30s</span>
</p>
</div>
-<button class="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground hover:text-foreground" aria-label="Cancel" data-state="closed" data-slot="tooltip-trigger">
+<button class="grid size-7 shrink-0 place-items-center rounded-full bg-background/70 text-muted-foreground backdrop-blur transition-colors hover:bg-background hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none" aria-label="Cancel" data-state="closed" data-slot="tooltip-trigger">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x size-3.5" aria-hidden="true">
<path d="M18 6 6 18">
</path>
@@ -55,15 +60,16 @@
<div class="h-full origin-left bg-primary transition-transform duration-(--motion-slow) ease-standard" style="transform:scaleX(0.42)">
</div>
</div>
+<span class="sr-only" role="status" aria-live="polite">Creating</span>
</div>
-<div class="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style="aspect-ratio:1">
+<div class="flex h-full max-w-full flex-col justify-between overflow-hidden rounded-xl border bg-muted/40 p-3" style="aspect-ratio:1" data-stage="failed">
<div class="flex min-h-0 flex-col gap-1 overflow-hidden">
<p class="shrink-0 text-[13px] font-medium">Couldn&#x27;t generate this one</p>
<p class="shrink-0 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground line-clamp-4">Your GPU ran out of memory. Try a smaller size or a shorter clip.</p>
</div>
<div class="mt-2 flex shrink-0 flex-wrap gap-1.5">
-<button class="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-70">
+<button class="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground shadow-xs transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-none disabled:opacity-70">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-rotate-ccw size-3" aria-hidden="true">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8">
</path>
@@ -73,12 +79,12 @@
</div>
</div>
-<div class="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style="aspect-ratio:1">
+<div class="flex h-full max-w-full flex-col justify-between overflow-hidden rounded-xl border bg-muted/40 p-3" style="aspect-ratio:1" data-stage="canceled">
<div class="flex min-h-0 flex-col gap-1 overflow-hidden">
<p class="shrink-0 text-[13px] font-medium">Canceled</p>
</div>
<div class="mt-2 flex shrink-0 flex-wrap gap-1.5">
-<button class="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-70">
+<button class="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground shadow-xs transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-none disabled:opacity-70">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-rotate-ccw size-3" aria-hidden="true">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8">
</path>
diff --git a/tests/golden/self-host/feed.html b/tests/golden/self-host/feed.html
index 0c5a6be4..3d7e05da 100644
--- a/tests/golden/self-host/feed.html
+++ b/tests/golden/self-host/feed.html
@@ -1,5 +1,5 @@
<div class="space-y-9">
-<section data-gen-id="g-open" class="group/gen space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
+<section data-gen-id="g-open" class="group/gen scroll-mt-20 space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
<header class="flex items-start gap-3">
<div class="min-w-0 flex-1">
<h2 class="line-clamp-2 font-heading text-[19px] leading-snug" title="a fox in the snow">a fox in the snow</h2>
@@ -168,7 +168,7 @@
</div>
</div>
</section>
-<section data-gen-id="g-cloud" class="group/gen space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
+<section data-gen-id="g-cloud" class="group/gen scroll-mt-20 space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
<header class="flex items-start gap-3">
<div class="min-w-0 flex-1">
<h2 class="line-clamp-2 font-heading text-[19px] leading-snug" title="a fox in the snow">a fox in the snow</h2>
@@ -205,7 +205,7 @@
</div>
</div>
</section>
-<section data-gen-id="g-failed" class="group/gen space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
+<section data-gen-id="g-failed" class="group/gen scroll-mt-20 space-y-2.5 [contain-intrinsic-size:auto_330px] [content-visibility:auto]">
<header class="flex items-start gap-3">
<div class="min-w-0 flex-1">
<h2 class="line-clamp-2 font-heading text-[19px] leading-snug" title="a fox in the snow">a fox in the snow</h2>
@@ -260,14 +260,14 @@
</div>
</header>
<div class="flex flex-wrap gap-2">
-<div class="h-56 max-w-full sm:h-64">
-<div class="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style="aspect-ratio:1">
+<div class="max-w-full shrink-0 h-(--tile-h) [--tile-h:14rem] sm:[--tile-h:16rem]" style="width:calc(var(--tile-h) * 1)">
+<div class="flex h-full max-w-full flex-col justify-between overflow-hidden rounded-xl border bg-muted/40 p-3" style="aspect-ratio:1" data-stage="failed">
<div class="flex min-h-0 flex-col gap-1 overflow-hidden">
<p class="shrink-0 text-[13px] font-medium">Couldn&#x27;t generate this one</p>
<p class="shrink-0 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground line-clamp-4">ComfyUI isn&#x27;t answering. Start it again, and Fuobe goes on by itself.</p>
</div>
<div class="mt-2 flex shrink-0 flex-wrap gap-1.5">
-<button class="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-70">
+<button class="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground shadow-xs transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:outline-none disabled:opacity-70">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-rotate-ccw size-3" aria-hidden="true">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8">
</path>
diff --git a/tests/hosted-run-tiles.test.ts b/tests/hosted-run-tiles.test.ts
index 47cb4e0b..a8867149 100644
--- a/tests/hosted-run-tiles.test.ts
+++ b/tests/hosted-run-tiles.test.ts
@@ -139,16 +139,24 @@ describe("a run on this studio's GPUs between Run and its answer", () => {
expect(html).not.toMatch(/pause|error|billing|GPU/i);
});
it("a run that names no place but sends the price it showed goes there too, above the runs already made", () => {
- const html = feedWhileMaking([{ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", shown: { amount: 0, priceVersion: "" } }], [gen({ place: "pool", status: "running", message: POOL_WORDS.working })]);
+ const html = feedWhileMaking([{ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", shown: { amount: 0, priceVersion: "" } }], [gen({ place: "pool", status: "running", message: POOL_WORDS.working, prompt: "an earlier fox", request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "an earlier fox" } })]);
expect(html.indexOf('data-run-state="in-line"')).toBeGreaterThan(-1);
expect(html.indexOf('data-run-state="in-line"')).toBeLessThan(html.indexOf('data-run-state="working"'));
});
- it("every other run being made shows nothing new", () => {
+ it("every other run being made shows its card at once too, saying it is starting (never In line)", () => {
const html = feedWhileMaking([{ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" }, { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", place: "own" }]);
expect(html).not.toContain("data-run-state");
- expect(html).toContain("Nothing yet");
+ expect(html).not.toContain("Nothing yet");
+ expect(html.match(/data-stage="sending"/g)).toHaveLength(2);
+ expect(html).toContain(">Starting<");
+ expect(html).not.toContain(`>${POOL_WORDS.inLine}<`);
expect(goesToPool(undefined)).toBe(false);
});
+ it("a run made meanwhile takes its press's place: one card, never two", () => {
+ const html = feedWhileMaking([{ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", place: "pool" }], [gen({ place: "pool", status: "queued", message: POOL_WORDS.inLine })]);
+ expect(html.match(/data-run-state="in-line"/g)).toHaveLength(1);
+ expect(html).not.toContain("data-making");
+ });
});
describe("one press of Run", () => {
diff --git a/tests/live-other-process.test.ts b/tests/live-other-process.test.ts
new file mode 100644
index 00000000..073ec84c
--- /dev/null
+++ b/tests/live-other-process.test.ts
@@ -0,0 +1,84 @@
+import path from "node:path";
+import Database from "better-sqlite3";
+import { describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/*
+ * While the site updates, its two app processes run side by side for a moment, and the runner in either may save a
+ * run's result. A live stream reads its changes from the triggers on its own process's connection, so a write by the
+ * other process used to reach no open stream: a run that finished then stayed "on its way" on screen. The stream now
+ * also sweeps the rows updated lately, and passes on another process's changes within seconds.
+ */
+
+vi.setConfig({ testTimeout: 30_000 });
+const dir = tempDir("fuobe-live-other-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { db, DATA_DIR } = await import("@/server/db");
+const live = await import("@/server/live");
+
+const dec = new TextDecoder();
+
+/** Everything a stream sends, read as it comes; `until` waits for what arrives from now on. */
+function tap(body: ReadableStream<Uint8Array>) {
+ let all = "";
+ const reader = body.getReader();
+ void (async () => {
+ for (;;) {
+ const r = await reader.read().catch(() => ({ done: true as const, value: undefined }));
+ if (r.done) return;
+ all += dec.decode(r.value);
+ }
+ })();
+ return {
+ /** Wait until what arrives from now on passes `done`, or `ms` pass: that text, and how long it took. */
+ async until(done: (t: string) => boolean, ms: number): Promise<{ text: string; ms: number }> {
+ const from = all.length;
+ const start = Date.now();
+ while (!done(all.slice(from)) && Date.now() - start < ms) await new Promise((r) => setTimeout(r, 25));
+ return { text: all.slice(from), ms: Date.now() - start };
+ },
+ };
+}
+
+describe("a change written by another app process", () => {
+ it("reaches an open stream within seconds, once, and this process's own changes aren't sent twice", async () => {
+ setSetting("demoMode", "on");
+ gens.ensureRunner();
+ // A run made here and finished, so it is a row like any other.
+ const g = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt: "a flying cat" })[0];
+ for (let i = 0; i < 200 && !["succeeded", "failed"].includes(gens.getGeneration(g.id)!.status); i++) await new Promise((r) => setTimeout(r, 100));
+
+ const ac = new AbortController();
+ const stream = tap(live.generationEventStream(ac.signal, { pingMs: 60_000 }).body!);
+ await new Promise((r) => setTimeout(r, 100));
+
+ // The other process: its own connection to the same database, with no triggers of this one.
+ const other = new Database(path.join(DATA_DIR, "fuobe.db"));
+ try {
+ other.prepare("UPDATE generations SET favorite = 1, updated_at = ? WHERE id = ?").run(Date.now(), g.id);
+ const got = await stream.until((t) => t.includes(`"id":"${g.id}"`), live.SWEEP_MS * 3);
+ expect(got.text).toContain("event: generation");
+ expect(got.text).toContain(`"favorite":true`);
+ expect(got.ms).toBeLessThan(live.SWEEP_MS * 3);
+ // Seen once: the next sweeps send nothing more for it.
+ const again = await stream.until((t) => t.includes(`"id":"${g.id}"`), live.SWEEP_MS * 2 + 500);
+ expect(again.text).not.toContain(`"id":"${g.id}"`);
+
+ // A change made here comes through the triggers at once, and the sweep doesn't repeat it.
+ db().prepare("UPDATE generations SET favorite = 0, updated_at = ? WHERE id = ?").run(Date.now() + 1, g.id);
+ const own = await stream.until((t) => (t.match(new RegExp(`"id":"${g.id}"`, "g")) ?? []).length >= 2, live.SWEEP_MS * 2 + 500);
+ expect((own.text.match(new RegExp(`"id":"${g.id}"`, "g")) ?? []).length).toBe(1);
+ } finally {
+ other.close();
+ ac.abort();
+ }
+ // Nobody listening: the sweep stops.
+ expect(live.listenerCount()).toBe(0);
+ expect(live.sweepForeign()).toBe(0);
+ });
+});
diff --git a/tests/run-feed-alive.test.ts b/tests/run-feed-alive.test.ts
new file mode 100644
index 00000000..670dd5a9
--- /dev/null
+++ b/tests/run-feed-alive.test.ts
@@ -0,0 +1,183 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createElement, type ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+
+/*
+ * The studio feed's run cards: every run on its way has a stage (in line, warming up, creating, finishing) that drives
+ * its look, its ring and what a screen reader hears; every card keeps its run's shape whatever it holds; a press of Run
+ * shows its card at once; and lists with a run on their way keep asking, so a change the live stream missed still shows.
+ */
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),
+ usePathname: () => "/image",
+ useSearchParams: () => new URLSearchParams(),
+}));
+
+const { runStage, STAGE_WORDS, tileBox, tileCount, shownMaking, FINISHING_AT } = await import("@/lib/run-stage");
+const { pollDelay, STREAM_IDLE_MS, streamResponse, backoff } = await import("@/lib/generation-stream");
+const { Feed, PendingTile } = await import("@/components/studio/feed");
+const { CREATE_GENERATION_KEY } = await import("@/lib/api");
+const { TooltipProvider } = await import("@/components/ui/tooltip");
+
+const gen = (o: Partial<Generation> = {}): Generation =>
+ ({
+ id: "g1",
+ batchId: null,
+ feature: "image",
+ presetId: null,
+ modelId: "moss-image",
+ engine: "open",
+ provider: "comfyui",
+ op: "t2i",
+ kind: "image",
+ status: "queued",
+ progress: null,
+ message: null,
+ prompt: "a flying cat",
+ request: { feature: "image", modelId: "moss-image", prompt: "a flying cat", params: { aspectRatio: "1:1" } },
+ outputs: [],
+ error: null,
+ costUsd: null,
+ favorite: false,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ completedAt: null,
+ ...o,
+ }) as Generation;
+
+const render = (node: ReactNode, client = new QueryClient()) => renderToStaticMarkup(createElement(QueryClientProvider, { client }, createElement(TooltipProvider, null, node)));
+
+/** Each tile slot in a rendered feed: its inline width. */
+const slotWidths = (html: string) => [...html.matchAll(/class="max-w-full shrink-0 h-\(--tile-h\)[^"]*" style="width:([^"]+)"/g)].map((m) => m[1]);
+
+describe("a run's stage", () => {
+ it("in line, warming up, creating, finishing, and none once it is over", () => {
+ expect(runStage(gen({ status: "queued" }))).toEqual({ stage: "in-line", fraction: null });
+ // In line after a recovery: whatever an earlier attempt reached says nothing now.
+ expect(runStage(gen({ status: "queued", progress: 0.6 }))).toEqual({ stage: "in-line", fraction: null });
+ expect(runStage(gen({ status: "running", progress: null }))).toEqual({ stage: "warming", fraction: null });
+ expect(runStage(gen({ status: "running", progress: 0 }))).toEqual({ stage: "warming", fraction: null });
+ expect(runStage(gen({ status: "running", progress: 0.42 }))).toEqual({ stage: "creating", fraction: 0.42 });
+ expect(runStage(gen({ status: "running", progress: FINISHING_AT }))?.stage).toBe("finishing");
+ expect(runStage(gen({ status: "running", progress: 0.99, stage: "checking" }))).toEqual({ stage: "finishing", fraction: null });
+ for (const status of ["succeeded", "failed", "canceled"] as const) expect(runStage(gen({ status }))).toBeNull();
+ });
+
+ it("a job on this computer's ComfyUI goes by its own steps and phase", () => {
+ expect(runStage(gen({ status: "running" }), { fraction: 0.25 })).toEqual({ stage: "creating", fraction: 0.25 });
+ expect(runStage(gen({ status: "running" }), { fraction: null })).toEqual({ stage: "warming", fraction: null });
+ expect(runStage(gen({ status: "running" }), { fraction: 1, saving: true })).toEqual({ stage: "finishing", fraction: null });
+ expect(runStage(gen({ status: "running" }), { fraction: 2 })?.fraction).toBe(1);
+ });
+
+ it("each stage has a short friendly word for screen readers, with no machinery in it", () => {
+ for (const w of Object.values(STAGE_WORDS)) expect(w).not.toMatch(/gpu|worker|queue|busy|error|fail|wait/i);
+ });
+
+ it("a card on its way says its stage to screen readers in a polite live region, and shows its progress", () => {
+ const html = render(createElement(PendingTile, { g: gen({ status: "running", progress: 0.42, message: "Making your picture · step 5 of 12" }), ratio: 1 }));
+ expect(html).toContain('data-stage="creating"');
+ expect(html).toMatch(/role="status" aria-live="polite">Creating</);
+ expect(html).toContain("42%");
+ expect(html).toContain("data-run-spinner");
+ expect(html).toContain("run-aura");
+ });
+});
+
+describe("a run card's size (the collapsed card)", () => {
+ // The cause: a card on its way or a failed one sized itself by `aspect-ratio` through a percentage height inside a
+ // flex row item with no width of its own. Its width came only from that transfer: where a browser gives such a box
+ // its content's width instead (its minimum content contribution when the row is measured), a card on its way (only
+ // an overlay in it) had no width at all, a blank area under its title, and a failed one shrank to its widest word
+ // or button, a thin strip with an icon and Retry. Each card's place in the row now has its width set outright.
+ it("sets each card's width from the row height and its shape, whatever the card holds", () => {
+ expect(tileBox(1)).toEqual({ width: "calc(var(--tile-h) * 1)", aspectRatio: 1 });
+ expect(tileBox(16 / 9).width).toBe("calc(var(--tile-h) * 1.7778)");
+ expect(tileBox(9 / 16, 0.8).width).toBe("calc(var(--tile-h) * 0.8)");
+ // A shape that can't be read is square, never zero.
+ for (const bad of [NaN, 0, -1, Infinity]) expect(tileBox(bad).width).toBe("calc(var(--tile-h) * 1)");
+ });
+
+ it("in the feed, a run on its way and a failed run each keep their full width", () => {
+ const html = render(
+ createElement(Feed, {
+ items: [
+ gen({ id: "a", status: "queued", place: "pool", request: { feature: "image", modelId: "moss-image", prompt: "a", params: { aspectRatio: "3:4", numOutputs: 2 } } }),
+ gen({ id: "b", status: "failed", place: "pool", error: "That one didn't come out right." }),
+ gen({ id: "c", status: "canceled", request: { feature: "image", modelId: "moss-image", prompt: "c", params: { aspectRatio: "9:16" } } }),
+ ],
+ }),
+ );
+ // Two tiles at 3:4 for the run asked for two, one square failed card, and a 9:16 stopped run kept at its 0.8 floor.
+ expect(slotWidths(html)).toEqual(["calc(var(--tile-h) * 0.75)", "calc(var(--tile-h) * 0.75)", "calc(var(--tile-h) * 1)", "calc(var(--tile-h) * 0.8)"]);
+ // The failed card's way on is there: Retry, and Reuse to change the words first.
+ expect(html).toContain("Retry");
+ expect(tileCount(undefined)).toBe(1);
+ expect(tileCount(4)).toBe(4);
+ expect(tileCount(40)).toBe(8);
+ });
+});
+
+describe("a press of Run", () => {
+ const making = (requests: object[], items: Generation[] = [], features?: string[]) => {
+ const client = new QueryClient();
+ for (const r of requests) void client.getMutationCache().build(client, { mutationKey: CREATE_GENERATION_KEY, mutationFn: () => new Promise(() => {}) }).execute(r);
+ return render(createElement(Feed, { items, features, empty: createElement("p", null, "Nothing yet") }), client);
+ };
+
+ it("shows its card at once: its words, and a tile for each picture asked for, at its shape", () => {
+ const html = making([{ feature: "image", modelId: "moss-image", prompt: "a flying cat", params: { aspectRatio: "16:9", numOutputs: 3 } }]);
+ expect(html).toContain("data-making");
+ expect(html).toContain(">a flying cat<");
+ expect(html.match(/data-stage="sending"/g)).toHaveLength(3);
+ expect(slotWidths(html)).toEqual(Array(3).fill("calc(var(--tile-h) * 1.7778)"));
+ });
+
+ it("only in its own studio's feed", () => {
+ expect(making([{ feature: "audio", modelId: "x", prompt: "a song" }], [], ["image"])).toContain("Nothing yet");
+ expect(making([{ feature: "image", modelId: "x", prompt: "a cat" }], [], ["image"])).toContain("data-making");
+ // A feed that names none goes by the features it lists.
+ expect(making([{ feature: "audio", modelId: "x", prompt: "a song" }], [gen({ status: "succeeded" })])).not.toContain("data-making");
+ });
+
+ it("hands over to its run once the run is made (matched by its words and model, the clocks a minute apart at most)", () => {
+ const at = 1_000_000;
+ const m = { at, request: { feature: "image", modelId: "moss-image", prompt: "a flying cat" } };
+ expect(shownMaking([m], [gen({ createdAt: at + 30_000 })])).toEqual([]);
+ expect(shownMaking([m], [gen({ createdAt: at - 30_000 })])).toEqual([]);
+ // An older run, a finished one, other words or another model: the press keeps its card.
+ expect(shownMaking([m], [gen({ createdAt: at - 120_000 })])).toEqual([m]);
+ expect(shownMaking([m], [gen({ createdAt: at, status: "succeeded" })])).toEqual([m]);
+ expect(shownMaking([m], [gen({ createdAt: at, request: { feature: "image", modelId: "moss-image", prompt: "a dog" } })])).toEqual([m]);
+ expect(shownMaking([m], [gen({ createdAt: at, modelId: "other" })])).toEqual([m]);
+ });
+});
+
+describe("live updates that never stall", () => {
+ it("lists with a run on their way keep asking: often for a run just sent, less for a long one, never when none is", () => {
+ const now = 10_000_000;
+ const run = (age: number, status: Generation["status"] = "running") => ({ status, createdAt: now - age });
+ expect(pollDelay([], true, now)).toBeNull();
+ expect(pollDelay([run(5_000, "succeeded")], false, now)).toBeNull();
+ // With the live stream: a safety net every few seconds (a missed change shows within one).
+ expect(pollDelay([run(5_000)], true, now)).toBe(4000);
+ expect(pollDelay([run(10 * 60_000)], true, now)).toBe(10_000);
+ // Without it: the list is how the card learns.
+ expect(pollDelay([run(5_000, "queued")], false, now)).toBe(1500);
+ expect(pollDelay([run(5 * 60_000)], false, now)).toBe(3000);
+ expect(pollDelay([run(60 * 60_000)], false, now)).toBe(6000);
+ // The youngest run decides.
+ expect(pollDelay([run(60 * 60_000), run(2_000)], true, now)).toBe(4000);
+ });
+
+ it("a quiet stream is dropped well after the server's 15 s pings, and a server that is switching over is tried again within seconds", () => {
+ expect(STREAM_IDLE_MS).toBeGreaterThan(2 * 15_000);
+ expect(STREAM_IDLE_MS).toBeLessThanOrEqual(60_000);
+ // The site's "updating" page (502/503) while an update switches over: 1 s, 2 s, 4 s …
+ expect(streamResponse({ ok: false, status: 503, contentType: "text/html", hasBody: true }, 0)).toEqual({ open: false, retryIn: 1000 });
+ expect(backoff(2)).toBe(4000);
+ });
+});