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.

Home: the first screen is in the first HTML, and first-screen reads give up in time

Adarshfe7dc1919e1a
diff --git a/package.json b/package.json
index 0fa87311..95f08d4f 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"test:e2e:comfyui": "node tests/e2e/comfyui-selftest.mjs",
"test:e2e:library": "node tests/e2e/library-flows.mjs",
"test:e2e:home": "node tests/e2e/home-bento.mjs",
+ "test:e2e:first-paint": "node tests/e2e/home-first-paint.mjs",
"test:e2e:mobile": "node tests/e2e/no-horizontal-scroll.mjs",
"test:e2e:shell": "node tests/e2e/shell.mjs",
"test:e2e:tabs": "node tests/e2e/instant-tabs.mjs",
diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjs
index d6f9a429..436b9b64 100644
--- a/scripts/build-worker.mjs
+++ b/scripts/build-worker.mjs
@@ -12,7 +12,7 @@ import ts from "typescript";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const out = path.join(root, "bin/lib/worker/dist");
-const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "local-comfy", "relay", "lanes", "worker-hours"];
+const SOURCES = ["computer-runner", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours"];
fs.mkdirSync(out, { recursive: true });
for (const name of SOURCES) {
diff --git a/src/app/(studio)/assist/loading.tsx b/src/app/(studio)/assist/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/assist/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/canvas/loading.tsx b/src/app/(studio)/canvas/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/canvas/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/character-sheet/loading.tsx b/src/app/(studio)/character-sheet/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/character-sheet/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/character-swap/loading.tsx b/src/app/(studio)/character-swap/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/character-swap/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/cinema/loading.tsx b/src/app/(studio)/cinema/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/cinema/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/color-grade/loading.tsx b/src/app/(studio)/color-grade/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/color-grade/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/connect/loading.tsx b/src/app/(studio)/connect/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/connect/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/content-factory/loading.tsx b/src/app/(studio)/content-factory/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/content-factory/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/edit/loading.tsx b/src/app/(studio)/edit/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/edit/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/explainer/loading.tsx b/src/app/(studio)/explainer/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/explainer/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/extend/loading.tsx b/src/app/(studio)/extend/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/extend/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/faceless/loading.tsx b/src/app/(studio)/faceless/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/faceless/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/fashion-factory/loading.tsx b/src/app/(studio)/fashion-factory/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/fashion-factory/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/genjutsu/loading.tsx b/src/app/(studio)/genjutsu/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/genjutsu/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/image-to-3d/loading.tsx b/src/app/(studio)/image-to-3d/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/image-to-3d/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/image/loading.tsx b/src/app/(studio)/image/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/image/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/influencer/loading.tsx b/src/app/(studio)/influencer/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/influencer/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/inpaint/loading.tsx b/src/app/(studio)/inpaint/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/inpaint/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/katana/loading.tsx b/src/app/(studio)/katana/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/katana/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/layers/loading.tsx b/src/app/(studio)/layers/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/layers/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/lipsync/loading.tsx b/src/app/(studio)/lipsync/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/lipsync/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/live-edit/loading.tsx b/src/app/(studio)/live-edit/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/live-edit/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/loading.tsx b/src/app/(studio)/loading.tsx
deleted file mode 100644
index ba2bdbd3..00000000
--- a/src/app/(studio)/loading.tsx
+++ /dev/null
@@ -1,6 +0,0 @@
-import { HubBodySkeleton, StudioSkeleton } from "@/components/skeletons";
-import { StudioRouteSkeleton } from "@/components/studio/hub-chrome";
-
-export default function Loading() {
- return <StudioRouteSkeleton generic={<StudioSkeleton />} hubBody={<HubBodySkeleton />} />;
-}
diff --git a/src/app/(studio)/mixed-media/loading.tsx b/src/app/(studio)/mixed-media/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/mixed-media/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/moodboards/loading.tsx b/src/app/(studio)/moodboards/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/moodboards/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/motion-control/loading.tsx b/src/app/(studio)/motion-control/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/motion-control/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/photodump/loading.tsx b/src/app/(studio)/photodump/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/photodump/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/privacy/loading.tsx b/src/app/(studio)/privacy/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/privacy/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/reframe/loading.tsx b/src/app/(studio)/reframe/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/reframe/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/shorts/loading.tsx b/src/app/(studio)/shorts/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/shorts/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/storyboard/loading.tsx b/src/app/(studio)/storyboard/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/storyboard/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/terms/loading.tsx b/src/app/(studio)/terms/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/terms/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/video-edit/loading.tsx b/src/app/(studio)/video-edit/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/video-edit/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/video/loading.tsx b/src/app/(studio)/video/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/video/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/app/(studio)/virality/loading.tsx b/src/app/(studio)/virality/loading.tsx
new file mode 100644
index 00000000..cec96360
--- /dev/null
+++ b/src/app/(studio)/virality/loading.tsx
@@ -0,0 +1 @@
+export { default } from "@/components/studio/route-loading";
diff --git a/src/components/home-view.tsx b/src/components/home-view.tsx
index 4f7ddd9e..656c66b3 100644
--- a/src/components/home-view.tsx
+++ b/src/components/home-view.tsx
@@ -172,8 +172,8 @@ export function HomeView({
const recent = useGenerations({ limit: 6 });
// How many (up to 6): a phone's grid holds 3 a row, so 1 to 3 results are one row of skeletons, 4 to 6 two.
useHadItems("home-recent", recent.data?.length, 6);
- // The page hydrates inside the route's Suspense boundary, possibly after the sidebar already fetched
- // the status: render the server's (status-less) view until hydrated, as useEngineMode does.
+ // The page may hydrate after the top bar already fetched the status: render the server's (status-less) view
+ // until hydrated, as useEngineMode does.
const hydrated = useHydrated();
const statusData = useStatus().data;
const status = hydrated ? statusData : undefined;
@@ -449,7 +449,8 @@ export function HomeView({
</Row>
) : (
// Loading, in a browser that saw results here last time: the row keeps its place from the first paint, so the rows below don't move down when it arrives.
- !recent.data && (
+ // A read that failed or ran out of time (a busy or restarting server) takes the placeholder away: no row, rather than one that never fills.
+ !recent.data && recent.failureCount === 0 && (
<>
<HadItemsScript name="home-recent" />
<Row title="Recent" href="/library" className="mt-12 hidden sm:mt-16 [html[data-had-home-recent]_&]:block">
diff --git a/src/components/studio/route-loading.tsx b/src/components/studio/route-loading.tsx
new file mode 100644
index 00000000..3e12ca07
--- /dev/null
+++ b/src/components/studio/route-loading.tsx
@@ -0,0 +1,17 @@
+import { HubBodySkeleton, StudioSkeleton } from "@/components/skeletons";
+import { StudioRouteSkeleton } from "@/components/studio/hub-chrome";
+
+/**
+ * The route skeleton of a studio page with no skeleton of its own: each top-level folder under src/app/(studio) has a
+ * loading.tsx, most of them this one re-exported. On the way into a hub it is the hub's real title bar and tabs over
+ * the body's skeleton; elsewhere the generic one.
+ *
+ * There is deliberately no loading.tsx in src/app/(studio) itself. A loading.tsx wraps its folder's page in a Suspense
+ * boundary, and React sends a boundary that big as the skeleton first and the page last, hidden, at the end of the
+ * HTML. Home would then show this skeleton on every full load until the whole document has been read and drawn in one
+ * frame, which takes many seconds on a busy computer. Without the boundary, Home's first screen is drawn as its HTML
+ * arrives.
+ */
+export default function StudioRouteLoading() {
+ return <StudioRouteSkeleton generic={<StudioSkeleton />} hubBody={<HubBodySkeleton />} />;
+}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index bc6d8c16..ef684445 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -25,6 +25,7 @@ import {
type Pages,
type StreamEvent,
} from "./generation-stream";
+import { fetchWithin, READ_LIMIT_MS } from "./fetch-within";
import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";
import { markRefusalShown, responseError } from "./refusals";
import { postFile } from "./upload";
@@ -447,7 +448,7 @@ export function useGenerations(filter: FeedFilter, opts: { keepPrevious?: boolea
const connected = useGenerationStream();
return useQuery({
queryKey: feedKey(filter),
- queryFn: async () => (await json<{ items: Generation[] }>(await fetch(`/api/generations?${filterToSearch(filter)}`))).items,
+ queryFn: async () => (await json<{ items: Generation[] }>(await fetchWithin(`/api/generations?${filterToSearch(filter)}`, READ_LIMIT_MS.list))).items,
placeholderData: opts.keepPrevious ? keepPreviousData : undefined,
structuralSharing: shareById,
refetchInterval: (q) => pollEvery(q.state.data, connected),
@@ -464,7 +465,7 @@ export function useRunningGenerations() {
const connected = useGenerationStream();
return useQuery({
queryKey: feedKey(RUNNING),
- queryFn: async () => (await json<{ items: Generation[] }>(await fetch(`/api/generations?${filterToSearch(RUNNING)}`))).items,
+ queryFn: async () => (await json<{ items: Generation[] }>(await fetchWithin(`/api/generations?${filterToSearch(RUNNING)}`, READ_LIMIT_MS.list))).items,
structuralSharing: shareById,
refetchInterval: (q) => (q.state.data?.length ? (connected ? 30_000 : 5000) : false),
});
@@ -931,7 +932,7 @@ export async function saveSettings(patch: Record<string, string>): Promise<void>
export function useStatus() {
return useQuery({
queryKey: ["status"],
- queryFn: async () => json<StatusInfo>(await fetch("/api/status")),
+ queryFn: async () => json<StatusInfo>(await fetchWithin("/api/status", READ_LIMIT_MS.status)),
staleTime: 15_000,
refetchInterval: 30_000,
});
@@ -1168,7 +1169,7 @@ export interface ViewerInfo {
export function useViewer() {
return useQuery({
queryKey: ["viewer"],
- queryFn: async () => json<ViewerInfo>(await fetch("/api/auth/me")),
+ queryFn: async () => json<ViewerInfo>(await fetchWithin("/api/auth/me", READ_LIMIT_MS.viewer)),
staleTime: 60_000,
});
}
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.ts
index 7b74855a..2ffe01fc 100644
--- a/src/lib/computer-runner.ts
+++ b/src/lib/computer-runner.ts
@@ -8,6 +8,7 @@
* a socket and a clock, and the tests drive it from Node against a stand-in ComfyUI.
*/
import { isGuard } from "./comfy-guard";
+import { fetchWithin } from "./fetch-within";
import { parseComfyBinary, parseComfyText } from "./comfy-ws";
import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";
import { DONE_SHOWN_MS, RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type TabFailure, type WantedFile } from "./relay";
@@ -99,6 +100,13 @@ const POLL_MS = 1000;
const FIND_EVERY_MS = 20_000;
/** Ended jobs the view keeps (a tile shows the last preview until its run moves on). */
const KEEP_ENDED = 6;
+/**
+ * How long a look at ComfyUI here (its facts, a job's state) and a beat to the studio wait for an answer. A ComfyUI busy
+ * at full load, or a studio that is restarting, can take a request and not answer: the beat then counts it as not
+ * answering and the next one tries again, instead of waiting for good and never beating again.
+ */
+const LOOK_MS = 15_000;
+const BEAT_MS = 20_000;
/** How long a result may wait for a busy studio before the run gives up. */
const SAVE_WAIT_MS = 60 * 60_000;
@@ -179,7 +187,7 @@ export class ComputerRunner {
// The ComfyUI here
private async read<T>(path: string): Promise<T> {
- const res = await this.deps.local(`${this.base}${readPath(path)}`, { credentials: "omit", cache: "no-store" });
+ const res = await fetchWithin(`${this.base}${readPath(path)}`, LOOK_MS, { credentials: "omit", cache: "no-store" }, this.deps.local);
if (!res.ok) throw Object.assign(new Error(`ComfyUI ${path.split("?")[0]} answered HTTP ${res.status}`), { status: res.status });
return (await res.json()) as T;
}
@@ -198,7 +206,7 @@ export class ComputerRunner {
try {
l = { comfy: "ok", stats: await this.read<SystemStats>("/system_stats") };
} catch (e) {
- const answers = (e as { status?: number }).status === 403 || (await this.deps.local(`${this.base}/system_stats`, { mode: "no-cors", credentials: "omit", cache: "no-store" }).then(() => true, () => false));
+ const answers = (e as { status?: number }).status === 403 || (await fetchWithin(`${this.base}/system_stats`, LOOK_MS, { mode: "no-cors", credentials: "omit", cache: "no-store" }, this.deps.local).then(() => true, () => false));
l = { comfy: answers ? "no-setting" : "down" };
if (!answers && (await this.findElsewhere())) return this.look();
}
@@ -374,7 +382,7 @@ export class ComputerRunner {
}
private async beatWith(body: Record<string, unknown>, stopped: string[] = []): Promise<BeatAnswer | null> {
- const res = await this.deps.api("/api/gpu/computer/beat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const res = await fetchWithin("/api/gpu/computer/beat", BEAT_MS, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }, this.deps.api);
if (res.ok) for (const s of stopped) this.stoppedDone.delete(s);
if (res.status === 401) {
this.stop("signed-out");
diff --git a/src/lib/fetch-within.ts b/src/lib/fetch-within.ts
new file mode 100644
index 00000000..3c000736
--- /dev/null
+++ b/src/lib/fetch-within.ts
@@ -0,0 +1,50 @@
+/**
+ * A read that gives up after a time limit. A busy or restarting server can then never hold a placeholder on screen
+ * for good: the read fails like any other, React Query retries it once, and the page shows what it shows without it.
+ */
+
+/** The error a read that ran out of time throws (`name` is "TimeoutError", like AbortSignal.timeout's). */
+export class FetchTimeoutError extends Error {
+ readonly name = "TimeoutError";
+ constructor(readonly url: string, readonly ms: number) {
+ super("The server took too long to answer. Please try again.");
+ }
+}
+
+/**
+ * fetch(), aborted when the server hasn't answered (its status and headers) within `ms`. The body is read after that
+ * without a limit: these routes send a small JSON body at once. An abort of `init.signal` still ends it early.
+ */
+export function fetchWithin(url: string, ms: number, init: RequestInit = {}, fetchImpl: (url: string, init?: RequestInit) => Promise<Response> = fetch): Promise<Response> {
+ const ctl = new AbortController();
+ const timeout = new FetchTimeoutError(url, ms);
+ const timer = setTimeout(() => ctl.abort(timeout), ms);
+ const outer = init.signal;
+ const onOuter = () => ctl.abort(outer?.reason);
+ if (outer?.aborted) onOuter();
+ else outer?.addEventListener("abort", onOuter, { once: true });
+ const done = () => {
+ clearTimeout(timer);
+ outer?.removeEventListener("abort", onOuter);
+ };
+ return fetchImpl(url, { ...init, signal: ctl.signal }).then(
+ (res) => {
+ done();
+ return res;
+ },
+ (err: unknown) => {
+ done();
+ throw ctl.signal.reason === timeout ? timeout : err;
+ },
+ );
+}
+
+/** How long the first screen's own reads may take, by what they are. */
+export const READ_LIMIT_MS = {
+ /** GET /api/status: the server already bounds its own ComfyUI and model checks to about 2 s. */
+ status: 12_000,
+ /** GET /api/auth/me: a cookie check. */
+ viewer: 10_000,
+ /** GET /api/generations: a short list (Home's Recent, the running jobs). */
+ list: 20_000,
+} as const;
diff --git a/tests/e2e/home-first-paint.mjs b/tests/e2e/home-first-paint.mjs
new file mode 100644
index 00000000..656612a1
--- /dev/null
+++ b/tests/e2e/home-first-paint.mjs
@@ -0,0 +1,335 @@
+// Home's first screen on a full load, in Chromium, when what it depends on hangs and while the studio restarts.
+// Run it on a production build (`pnpm build`): it starts two `next start` servers from it (a blue and a green, on one
+// throwaway data folder) behind a small proxy, as a deploy switches between them.
+//
+// pnpm build && node tests/e2e/home-first-paint.mjs (pnpm test:e2e:first-paint)
+//
+// Every load is a new browser context (nothing cached), at 1x and at 4x CPU slowdown, as a guest, an account, the owner,
+// and the owner whose runs go to the ComfyUI on their own computer (the Open source engine): that ComfyUI takes every
+// request and never answers, as one busy at full load can. The studio's own ComfyUI never answers either.
+//
+// Checks, for each of them:
+// 1. The headline is drawn within 3 s, and Home's route skeleton is never on screen (no skeleton in front of Home).
+// 2. The same while every /api request hangs (a busy or restarting server): the page never waits for one.
+// 3. The owner's own engine was really asked (the busy ComfyUI saw the tab's look), and the page didn't wait for it.
+// 4. A restart, as a deploy does it: the proxy sends new requests to the other server and the old one is stopped
+// (SIGTERM; on Windows, which can't send one, a kill). Home loads in a loop through two switches, each within 3 s,
+// and a tab opened before the switch still opens Home within 3 s afterwards. Off Windows: the old server stops within
+// 10 s although an owner tab holds its live-updates stream open.
+// 5. A click to Home from another page shows it within 3 s.
+//
+// Ports (all on 127.0.0.1): E2E_PORT_BASE (3810): the proxy, +1 and +2 the two servers, +3 the studio's ComfyUI,
+// +7 the owner's ComfyUI. The browser reaches no other port on this computer, so a real ComfyUI is never touched.
+import { spawn } from "node:child_process";
+import http from "node:http";
+import net from "node:net";
+import path from "node:path";
+import { launch, root } from "./_browser.mjs";
+import { removeDir, stopProcess, tempDir } from "./_temp.mjs";
+
+const BASE = Number(process.env.E2E_PORT_BASE ?? 3810);
+const PROXY = BASE;
+const SERVERS = [BASE + 1, BASE + 2];
+const STUDIO_COMFY = BASE + 3;
+const OWN_COMFY = BASE + 7;
+const SITE = `http://127.0.0.1:${PROXY}`;
+const LIMIT_MS = 3000;
+const PASSWORD = `e2e-${Math.random().toString(36).slice(2)}`;
+const data = tempDir("fuobe-first-paint-e2e-");
+
+const results = [];
+const check = (name, ok, detail = "") => {
+ results.push({ name, ok: !!ok, detail });
+ console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);
+};
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+async function until(fn, ms = 30_000, every = 250) {
+ const end = Date.now() + ms;
+ for (;;) {
+ try {
+ const v = await fn();
+ if (v) return v;
+ } catch {}
+ if (Date.now() > end) return null;
+ await sleep(every);
+ }
+}
+
+// --- ComfyUI stand-ins that take every request and never answer (a ComfyUI busy at full load can do that).
+const hung = { studio: 0, own: 0 };
+const held = new Set();
+function hangingServer(port, name) {
+ const s = http.createServer((req, res) => {
+ hung[name]++;
+ held.add(res);
+ // The page's look at its own ComfyUI asks first whether it may (CORS): the answer lets it through, and the look itself then hangs.
+ if (req.method === "OPTIONS") {
+ res.writeHead(204, { "Access-Control-Allow-Origin": req.headers.origin ?? "*", "Access-Control-Allow-Headers": "content-type", "Access-Control-Allow-Private-Network": "true" });
+ res.end();
+ }
+ });
+ s.on("upgrade", (_req, socket) => held.add(socket)); // its socket too
+ return new Promise((r) => s.listen(port, "127.0.0.1", () => r(s)));
+}
+
+// --- The proxy, as Apache in front of the two servers: requests in flight stay where they started, new ones go to the
+// live server. `hangApi`: every /api request is held without an answer (a busy or restarting server).
+let live = SERVERS[0];
+let hangApi = false;
+const proxy = http.createServer((req, res) => {
+ if (hangApi && req.url.startsWith("/api/")) return void held.add(res);
+ const up = http.request({ host: "127.0.0.1", port: live, path: req.url, method: req.method, headers: req.headers }, (r) => {
+ res.writeHead(r.statusCode ?? 502, r.headers);
+ r.pipe(res);
+ });
+ up.on("error", () => {
+ if (!res.headersSent) res.writeHead(502);
+ res.end();
+ });
+ req.pipe(up);
+ res.on("close", () => up.destroy());
+});
+
+// --- The two servers.
+const procs = new Map();
+function startServer(port) {
+ const p = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "start", "-p", String(port), "-H", "127.0.0.1"], {
+ cwd: root,
+ env: {
+ ...process.env,
+ FUOBE_DATA_DIR: data,
+ FUOBE_PASSWORD: PASSWORD,
+ FUOBE_PUBLIC_SIGNUP: "1",
+ FUOBE_ACCOUNT_DISK_FREE_GB: "0.5",
+ COMFYUI_URL: `http://127.0.0.1:${STUDIO_COMFY}`,
+ NODE_ENV: "production",
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ p.log = "";
+ p.stdout.on("data", (d) => (p.log += d));
+ p.stderr.on("data", (d) => (p.log += d));
+ procs.set(port, p);
+ return until(() => fetch(`http://127.0.0.1:${port}/login`).then((r) => r.ok), 120_000, 500);
+}
+/** Stop a server as the service manager does: SIGTERM (Windows can't send one: a kill). Resolves with the ms it took. */
+async function stopServer(port) {
+ const p = procs.get(port);
+ procs.delete(port);
+ const t = Date.now();
+ if (process.platform === "win32") await stopProcess(p);
+ else {
+ const exited = new Promise((r) => p.once("exit", r));
+ p.kill("SIGTERM");
+ await Promise.race([exited, sleep(30_000)]);
+ if (p.exitCode === null && p.signalCode === null) p.kill("SIGKILL");
+ }
+ return Date.now() - t;
+}
+
+// --- Signing in: once for the owner and once for an account (sign-in is rate limited), straight to a server (the
+// proxy may be holding /api requests); every context then carries that session's cookie (one for every port).
+const direct = () => `http://127.0.0.1:${live}`;
+const sessions = {};
+async function session(who) {
+ if (sessions[who]) return sessions[who];
+ const [route, body] = who === "account" ? ["/api/auth/signup", { email: `e2e-${Math.random().toString(36).slice(2, 8)}@example.com`, password: "long enough password" }] : ["/api/auth/login", { password: PASSWORD }];
+ const r = await fetch(direct() + route, { method: "POST", headers: { "content-type": "application/json", origin: direct() }, body: JSON.stringify(body) });
+ const cookies = (r.headers.getSetCookie?.() ?? []).map((c) => c.split(";")[0].split("=")).map(([name, ...v]) => ({ name, value: v.join("=") }));
+ if (!r.ok || !cookies.length) throw new Error(`${who}'s sign-in answered ${r.status}`);
+ return (sessions[who] = cookies);
+}
+/** Where the owner's runs go: "server" (the studio's ComfyUI) or "computer" (the ComfyUI on the owner's own computer). */
+let comfyWhere = "server";
+async function setWhere(v) {
+ if (comfyWhere === v) return;
+ const cookie = (await session("owner")).map((c) => `${c.name}=${c.value}`).join("; ");
+ const r = await fetch(`${direct()}/api/settings`, { method: "PUT", headers: { "content-type": "application/json", origin: direct(), cookie }, body: JSON.stringify({ comfyWhere: v }) });
+ if (!r.ok) throw new Error(`Settings answered ${r.status}: ${await r.text()}`);
+ comfyWhere = v;
+}
+
+// --- One full load of Home in a new context: when the skeleton and the headline were first on screen.
+let browser;
+async function context(who) {
+ if (who === "owner") await setWhere("server");
+ if (who === "owner-computer") await setWhere("computer");
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+ // This computer's other apps: only the proxy, the servers and the owner's stand-in ComfyUI are reachable.
+ await ctx.route(/^(https?|wss?):\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+/, (route) => {
+ const port = Number(new URL(route.request().url()).port);
+ return port === PROXY || port === OWN_COMFY ? route.continue() : route.abort("connectionrefused");
+ });
+ if (who !== "guest") await ctx.addCookies((await session(who === "account" ? "account" : "owner")).map((c) => ({ ...c, domain: "127.0.0.1", path: "/", httpOnly: true, sameSite: "Lax" })));
+ if (who === "owner-computer") {
+ // The Open source engine, on the ComfyUI this browser reached before (on the stand-in's port).
+ await ctx.addInitScript((port) => {
+ try {
+ localStorage.setItem("fuobe.engine", "open");
+ localStorage.setItem("fuobe.comfy.port", String(port));
+ localStorage.setItem("fuobe.computer.reached", "1");
+ } catch {}
+ }, OWN_COMFY);
+ }
+ await ctx.addInitScript(() => {
+ const W = (window.__W = {});
+ let seen;
+ const tick = () => {
+ const now = performance.now();
+ const skeleton = document.querySelector('main [aria-label="Loading"]');
+ if (W.skeleton === undefined && skeleton) W.skeleton = now;
+ if (seen !== undefined) return void (W.headline = now); // the frame after it entered the page: drawn
+ if (document.querySelector("main h1") && !skeleton) seen = now;
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ });
+ return ctx;
+}
+async function measure(page, timeout = 20_000) {
+ await page.waitForFunction(() => window.__W?.headline !== undefined, null, { timeout, polling: 100 }).catch(() => {});
+ return page.evaluate(() => ({ ...window.__W, title: document.querySelector("main h1")?.textContent?.trim() ?? "" }));
+}
+async function loadHome(who, { cpu = 1 } = {}) {
+ const ctx = await context(who);
+ try {
+ const page = await ctx.newPage();
+ const cdp = await ctx.newCDPSession(page);
+ if (cpu > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: cpu });
+ await page.goto(`${SITE}/`, { waitUntil: "commit", timeout: 30_000 });
+ return await measure(page);
+ } finally {
+ await ctx.close();
+ }
+}
+const fmt = (w) => `headline ${w.headline === undefined ? "never" : `${Math.round(w.headline)} ms`}, skeleton ${w.skeleton === undefined ? "never" : `at ${Math.round(w.skeleton)} ms`}`;
+const inTime = (w) => w.headline !== undefined && w.headline <= LIMIT_MS && w.skeleton === undefined;
+
+const AUDIENCES = ["guest", "account", "owner", "owner-computer"];
+
+async function finish(code) {
+ await browser?.close().catch(() => {});
+ for (const port of [...procs.keys()]) await stopServer(port).catch(() => {});
+ for (const h of held) h.destroy?.();
+ proxy.close();
+ removeDir(data);
+ const failed = results.filter((r) => !r.ok);
+ console.log(`\n${results.length - failed.length}/${results.length} passed.`);
+ if (failed.length) for (const p of procs.values()) console.log(p.log.split("\n").slice(-30).join("\n"));
+ process.exit(code ?? (failed.length ? 1 : 0));
+}
+
+try {
+ for (const port of [PROXY, ...SERVERS, STUDIO_COMFY, OWN_COMFY]) {
+ const free = await new Promise((r) => {
+ const s = net.createServer().once("error", () => r(false)).listen(port, "127.0.0.1", () => s.close(() => r(true)));
+ });
+ if (!free) throw new Error(`port ${port} is in use`);
+ }
+ await hangingServer(STUDIO_COMFY, "studio");
+ await hangingServer(OWN_COMFY, "own");
+ await new Promise((r) => proxy.listen(PROXY, "127.0.0.1", r));
+ if (!(await startServer(SERVERS[0]))) throw new Error(`the studio didn't start:\n${procs.get(SERVERS[0])?.log}`);
+ if (!(await startServer(SERVERS[1]))) throw new Error(`the second server didn't start:\n${procs.get(SERVERS[1])?.log}`);
+ browser = await launch(process.platform === "win32" && !process.env.CHROMIUM_PATH ? { channel: "chrome" } : {});
+
+ // A first load warms the server (a deploy's health check does it too).
+ await loadHome("guest");
+
+ // 1. Every audience, with both ComfyUIs hanging, at 1x and 4x.
+ for (const cpu of [1, 4])
+ for (const who of AUDIENCES) {
+ const runs = [];
+ for (let i = 0; i < 2; i++) runs.push(await loadHome(who, { cpu }));
+ check(`${who}, ${cpu}x CPU: the headline within 3 s, no skeleton in front of Home`, runs.every(inTime), runs.map(fmt).join(" | "));
+ }
+
+ // 3. The owner's engine was asked: the page looked at the busy ComfyUI, and still didn't wait for it.
+ {
+ const before = hung.own;
+ const ctx = await context("owner-computer");
+ const page = await ctx.newPage();
+ await page.goto(`${SITE}/`, { waitUntil: "commit" });
+ const w = await measure(page);
+ const asked = await until(() => hung.own > before, 15_000);
+ check("the owner's own engine: the tab looked at the busy ComfyUI on this computer", !!asked, `${hung.own - before} requests`);
+ check("…and Home's headline didn't wait for it", inTime(w), fmt(w));
+ await ctx.close();
+ }
+
+ // 2. Every /api request hangs.
+ hangApi = true;
+ for (const who of AUDIENCES) {
+ const w = await loadHome(who);
+ check(`${who}, every /api request hanging: the headline within 3 s`, inTime(w), fmt(w));
+ }
+ hangApi = false;
+
+ // 5. A click to Home from another page.
+ for (const who of ["guest", "owner-computer"]) {
+ const ctx = await context(who);
+ const page = await ctx.newPage();
+ await page.goto(`${SITE}/library`, { waitUntil: "load" });
+ await page.locator("main h1").first().waitFor({ timeout: 20_000 }).catch(() => {});
+ await page.waitForTimeout(500);
+ const t = Date.now();
+ await page.locator('a[href="/"]').first().click();
+ const ok = await until(() => page.evaluate(() => location.pathname === "/" && !!document.querySelector("main h1") && /Make anything/i.test(document.querySelector("main h1")?.textContent ?? "")), LIMIT_MS, 50);
+ check(`${who}: a click to Home shows it within 3 s`, !!ok, `${Date.now() - t} ms`);
+ await ctx.close();
+ }
+
+ // 4. Restarts, as a deploy does them: switch, then stop the old server; twice (blue to green, then back).
+ {
+ // Tabs opened before the switch: the owner's (with its live-updates stream open) and an account's.
+ const before = [];
+ for (const who of ["owner-computer", "account"]) {
+ const ctx = await context(who);
+ const page = await ctx.newPage();
+ await page.goto(`${SITE}/library`, { waitUntil: "load" });
+ await page.locator("main h1").first().waitFor({ timeout: 20_000 }).catch(() => {});
+ before.push({ who, ctx, page });
+ }
+ const loads = [];
+ let looping = true;
+ let loopError = null;
+ const loop = (async () => {
+ for (let i = 0; looping; i++) {
+ const who = AUDIENCES[i % AUDIENCES.length];
+ // A sign-in that met the stopping server is tried again: what is measured is Home.
+ const w = await loadHome(who).catch(() => sleep(500).then(() => loadHome(who)));
+ loads.push({ who, w });
+ }
+ })().catch((e) => (loopError = e));
+ for (const step of [0, 1]) {
+ await sleep(3000);
+ const old = live;
+ const next = SERVERS[(SERVERS.indexOf(old) + 1) % 2];
+ if (!procs.has(next) && !(await startServer(next))) throw new Error("the new server didn't start");
+ live = next;
+ await sleep(1500);
+ const ms = await stopServer(old);
+ if (process.platform !== "win32") check(`restart ${step + 1}: the old server stops within 10 s with an owner tab's stream open`, ms <= 10_000, `${ms} ms`);
+ await sleep(3000);
+ if (step === 0) {
+ // The old tabs, after the switch: to Home.
+ for (const b of before) {
+ const t = Date.now();
+ await b.page.locator('a[href="/"]').first().click();
+ const ok = await until(() => b.page.evaluate(() => location.pathname === "/" && /Make anything/i.test(document.querySelector("main h1")?.textContent ?? "")), LIMIT_MS, 50);
+ check(`${b.who}: a tab opened before the restart opens Home within 3 s after it`, !!ok, `${Date.now() - t} ms`);
+ await b.ctx.close();
+ }
+ }
+ }
+ looping = false;
+ await loop;
+ if (loopError) check("restarts: the loop of Home loads ran", false, loopError.stack ?? String(loopError));
+ const slow = loads.filter((l) => !inTime(l.w));
+ check(`restarts: ${loads.length} Home loads through two switches, each within 3 s with no skeleton`, loads.length >= 8 && slow.length === 0, slow.map((l) => `${l.who}: ${fmt(l.w)}`).join(" | ") || `slowest ${Math.round(Math.max(...loads.map((l) => l.w.headline ?? Infinity)))} ms`);
+ }
+ check("the studio's own ComfyUI was asked and never answered (the hanging dependency was in play)", hung.studio > 0, `${hung.studio} requests`);
+} catch (e) {
+ check("the run", false, e.stack ?? String(e));
+}
+await finish();
diff --git a/tests/fetch-within.test.ts b/tests/fetch-within.test.ts
new file mode 100644
index 00000000..b347fca1
--- /dev/null
+++ b/tests/fetch-within.test.ts
@@ -0,0 +1,64 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { FetchTimeoutError, fetchWithin, READ_LIMIT_MS } from "@/lib/fetch-within";
+
+// The first screen's reads (status, who is looking, Recent) give up after a time limit, so a busy or restarting server
+// never holds a placeholder on screen for good.
+
+/** A fetch that never answers, but ends when its signal aborts, as the browser's does. */
+function hangingFetch() {
+ const calls: RequestInit[] = [];
+ const impl = ((_url: string, init: RequestInit = {}) => {
+ calls.push(init);
+ return new Promise<Response>((_ok, fail) => {
+ init.signal?.addEventListener("abort", () => fail(init.signal?.reason ?? new Error("aborted")), { once: true });
+ });
+ }) as unknown as typeof fetch;
+ return { impl, calls };
+}
+
+afterEach(() => vi.useRealTimers());
+
+describe("fetchWithin", () => {
+ it("gives up with a TimeoutError when the server doesn't answer in time", async () => {
+ vi.useFakeTimers();
+ const { impl, calls } = hangingFetch();
+ const read = fetchWithin("/api/status", 1000, {}, impl);
+ const caught = read.catch((e: unknown) => e);
+ await vi.advanceTimersByTimeAsync(999);
+ expect(calls[0].signal?.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ const err = await caught;
+ expect(err).toBeInstanceOf(FetchTimeoutError);
+ expect((err as Error).name).toBe("TimeoutError");
+ expect((err as FetchTimeoutError).url).toBe("/api/status");
+ });
+
+ it("passes an answer through and stops its timer", async () => {
+ vi.useFakeTimers();
+ const res = new Response("{}", { status: 200 });
+ let signal: AbortSignal | undefined;
+ const impl = ((_u: string, init: RequestInit = {}) => ((signal = init.signal ?? undefined), Promise.resolve(res))) as unknown as typeof fetch;
+ await expect(fetchWithin("/api/auth/me", 1000, {}, impl)).resolves.toBe(res);
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(signal?.aborted).toBe(false);
+ });
+
+ it("keeps a caller's own abort, with its reason", async () => {
+ const { impl } = hangingFetch();
+ const outer = new AbortController();
+ const read = fetchWithin("/api/generations", 60_000, { signal: outer.signal }, impl);
+ outer.abort(new Error("left the page"));
+ await expect(read).rejects.toThrow("left the page");
+ });
+
+ it("passes a network error through as it is", async () => {
+ const impl = (() => Promise.reject(new TypeError("Failed to fetch"))) as unknown as typeof fetch;
+ await expect(fetchWithin("/api/status", 1000, {}, impl)).rejects.toThrow(TypeError);
+ });
+
+ it("bounds every first-screen read to a few seconds", () => {
+ for (const ms of Object.values(READ_LIMIT_MS)) expect(ms).toBeGreaterThan(2_000);
+ for (const ms of Object.values(READ_LIMIT_MS)) expect(ms).toBeLessThanOrEqual(20_000);
+ });
+});
diff --git a/tests/home-first-paint.test.ts b/tests/home-first-paint.test.ts
new file mode 100644
index 00000000..cd0850ac
--- /dev/null
+++ b/tests/home-first-paint.test.ts
@@ -0,0 +1,42 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+// Home's first screen is in its first HTML: no route skeleton stands in front of it on a full load (see
+// src/components/studio/route-loading.tsx for why), and every other studio page keeps its own skeleton for a click
+// in the menus.
+
+const root = path.join(__dirname, "..");
+const studio = path.join(root, "src/app/(studio)");
+const read = (p: string) => fs.readFileSync(path.join(root, p), "utf8");
+
+describe("Home's first paint", () => {
+ it("has no loading.tsx around Home: a Suspense boundary that big is sent last, behind its skeleton", () => {
+ expect(fs.existsSync(path.join(studio, "loading.tsx"))).toBe(false);
+ expect(fs.existsSync(path.join(studio, "page.tsx"))).toBe(true);
+ });
+
+ it("keeps a route skeleton for every other studio page, in its own folder", () => {
+ const missing = fs
+ .readdirSync(studio, { withFileTypes: true })
+ .filter((e) => e.isDirectory() && !e.name.startsWith("(") && fs.existsSync(path.join(studio, e.name, "page.tsx")))
+ .map((e) => e.name)
+ .filter((name) => !fs.existsSync(path.join(studio, name, "loading.tsx")));
+ // A new studio folder: add `export { default } from "@/components/studio/route-loading";` as its loading.tsx.
+ expect(missing).toEqual([]);
+ });
+
+ it("the shared skeleton is the studio's", () => {
+ expect(read("src/components/studio/route-loading.tsx")).toMatch(/<StudioRouteSkeleton generic=\{<StudioSkeleton \/>\}/);
+ });
+
+ it("Home's page needs no request data, so it stays prerendered for everyone", () => {
+ const page = read("src/app/(studio)/page.tsx");
+ expect(page).not.toMatch(/\b(cookies|headers|connection)\(/);
+ expect(read("src/app/(studio)/layout.tsx")).not.toMatch(/\b(cookies|headers|connection)\(|async function/);
+ });
+
+ it("Home's Recent placeholder goes once its read has failed", () => {
+ expect(read("src/components/home-view.tsx")).toMatch(/!recent\.data && recent\.failureCount === 0 && \(/);
+ });
+});
diff --git a/tests/instant-tabs.test.ts b/tests/instant-tabs.test.ts
index 46d7f568..9eb19765 100644
--- a/tests/instant-tabs.test.ts
+++ b/tests/instant-tabs.test.ts
@@ -157,7 +157,9 @@ describe("other tab bars switch without a round trip", () => {
});
it("the studio's route skeleton keeps a hub's bar and tabs on the way in", () => {
- expect(src("src/app/(studio)/loading.tsx")).toMatch(/<StudioRouteSkeleton /);
+ // Each studio folder's loading.tsx (none around Home: tests/home-first-paint.test.ts).
+ expect(src("src/components/studio/route-loading.tsx")).toMatch(/<StudioRouteSkeleton /);
+ expect(src("src/app/(studio)/image/loading.tsx")).toMatch(/@\/components\/studio\/route-loading/);
});
it("example cards (a lazy chunk) load under their own placeholder, so a tapped page never waits for them", () => {
diff --git a/tests/runner-timeouts.test.ts b/tests/runner-timeouts.test.ts
new file mode 100644
index 00000000..7f7780d0
--- /dev/null
+++ b/tests/runner-timeouts.test.ts
@@ -0,0 +1,47 @@
+/**
+ * The Fuobe tab's runner (src/lib/computer-runner.ts) when something takes its request and never answers: a ComfyUI
+ * busy at full load, or a studio that is restarting. A beat still ends, so the next one can try again.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ComputerRunner } from "@/lib/computer-runner";
+
+/** A request that never answers, but ends when its signal aborts, as the browser's does. */
+const hang = (_url: string, init: RequestInit = {}) =>
+ new Promise<Response>((_ok, fail) => init.signal?.addEventListener("abort", () => fail(init.signal?.reason ?? new Error("aborted")), { once: true }));
+
+function runner(o: { api?: typeof hang; local?: typeof hang }) {
+ const beats: Record<string, unknown>[] = [];
+ const api =
+ o.api ??
+ (async (p: string, init: RequestInit = {}) => {
+ if (p === "/api/gpu/computer/beat") beats.push(JSON.parse(String(init.body)));
+ return Response.json({ runner: true, heldElsewhere: false, waiting: 0, stops: [] });
+ });
+ const local = o.local ?? (async () => Response.json({ system: { ram_total: 1 }, devices: [] }));
+ const r = new ComputerRunner({ api, local, sha256: async () => "", origin: "http://x", sleep: async () => {} }, { device: "device-0001", port: 8188, clientId: "client-0001" });
+ return { r, beats };
+}
+
+afterEach(() => vi.useRealTimers());
+
+describe("a beat when nothing answers", () => {
+ it("a ComfyUI that takes the request and never answers: the beat still goes out, saying it isn't ready", async () => {
+ vi.useFakeTimers();
+ const { r, beats } = runner({ local: hang });
+ const beat = r.beat();
+ await vi.advanceTimersByTimeAsync(31_000);
+ await expect(beat).resolves.toMatchObject({ runner: true });
+ expect(beats).toHaveLength(1);
+ expect(beats[0]).toMatchObject({ ready: false });
+ expect(r.view.comfy).toBe("down");
+ });
+
+ it("a studio that takes the beat and never answers: the beat gives up, and the next one can go", async () => {
+ vi.useFakeTimers();
+ const { r } = runner({ api: hang });
+ const beat = r.beat().catch((e: unknown) => e);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect((await beat) as Error).toHaveProperty("name", "TimeoutError");
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});