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.

Add tests for tab switches without blank frames

Adarsh6cf747ecbc4f
diff --git a/package.json b/package.json
index 63c8692b..4b76cd0c 100644
--- a/package.json
+++ b/package.json
@@ -17,6 +17,7 @@
"test:e2e:library": "node tests/e2e/library-flows.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",
"gen:catalog": "python3 scripts/gen-cloud-models.py && python3 scripts/gen-studio-packs.py && python3 scripts/gen-oss-loras.py && python3 scripts/gen-lora-library.py && python3 scripts/gen-influencer-options.py && python3 scripts/gen-soul-originals.py && python3 scripts/gen-trainers.py && node scripts/gen-icon-map.mjs",
"typecheck": "tsc --noEmit",
"eval:run": "node scripts/eval/eval.mjs run",
diff --git a/tests/e2e/instant-tabs.mjs b/tests/e2e/instant-tabs.mjs
new file mode 100644
index 00000000..632bab68
--- /dev/null
+++ b/tests/e2e/instant-tabs.mjs
@@ -0,0 +1,249 @@
+// Tab switches never blank the page (the app must be running, a production build: `pnpm build && pnpm start`).
+// Usage: node tests/e2e/instant-tabs.mjs [appUrl] (pnpm test:e2e:tabs). Exits 1 on the first failure.
+//
+// Every frame from the tap until the new tab's page has drawn is sampled (requestAnimationFrame), on a phone and a
+// desktop, over Chrome's "Fast 4G" preset, so a switch that waits for the server shows up as frames:
+// 1. Hub tabs (Audio, Video tools, Upscale): the title and the tab row are on screen in every frame, the tapped tab is the
+// current one within two frames, and the area under the tabs always shows a page or its skeleton, never nothing.
+// Both after the page has settled (the tabs prefetched) and straight after load (nothing prefetched yet).
+// 2. Going back to a mode shows that mode's header controls once (the hidden pages kept for Back add none), and Back marks
+// the tab of the page it returns to (Audio, the Marketing suite).
+// 2b. Marketing suite tabs: the tapped tab is current within two frames and the tab row never leaves.
+// 3. Library sections: the tapped section is selected within two frames, with no request to the server.
+// 4. Sidebar (desktop): Image → Audio never blanks the content area, and the hub's tabs are there when it lands.
+import assert from "node:assert/strict";
+import { DESKTOP, launch, openRoute, PHONE } from "./_browser.mjs";
+
+const app = (process.argv.slice(2).find((a) => !a.startsWith("--")) ?? "http://localhost:3000").replace(/\/$/, "");
+const browser = await launch();
+// --only=<text>: run the steps whose name has that text.
+const only = process.argv.find((a) => a.startsWith("--only="))?.slice(7);
+const step = (name) => {
+ if (only && !name.includes(only)) return false;
+ console.log(`- ${name}`);
+ return true;
+};
+// Chrome DevTools "Fast 4G": 9 Mbps down, 1.5 Mbps up, 165 ms latency.
+const FAST4G = { offline: false, downloadThroughput: (9e6 / 8) * 0.9, uploadThroughput: (1.5e6 / 8) * 0.9, latency: 165 };
+
+/** Injected before the page's scripts: `__frames.start(cfg)` samples every frame until `__frames.stop()`. */
+const SAMPLER = () => {
+ const w = window;
+ const vis = (el) => !!el && el.checkVisibility();
+ // innerText leaves out display:none subtrees (the previous page that React keeps hidden for Back).
+ const text = (el) => (el ? (el.innerText || "").replace(/\s+/g, "").length : 0);
+ w.__frames = {
+ list: [],
+ t0: 0,
+ on: false,
+ start(cfg) {
+ this.list = [];
+ this.on = true;
+ this.t0 = 0;
+ const tick = () => {
+ if (!this.on) return;
+ const content = document.getElementById("content");
+ // The area under the hub's bar; the whole content area where there is none (another page, or a build without it).
+ const body = (cfg.body && [...document.querySelectorAll(cfg.body)].find(vis)) || content;
+ const bar = cfg.bar ? [...document.querySelectorAll(cfg.bar)].find(vis) : null;
+ const current = cfg.current ? [...document.querySelectorAll(cfg.current)].find(vis) : null;
+ this.list.push({
+ t: performance.now(),
+ path: location.pathname + location.search,
+ content: text(content),
+ body: text(body),
+ skeleton: body ? [...body.querySelectorAll('[aria-busy="true"]')].some(vis) : false,
+ bar: !!bar,
+ title: cfg.title ? ([...document.querySelectorAll(cfg.title)].find(vis)?.textContent?.trim() ?? null) : null,
+ current: current ? (current.textContent || "").trim() : null,
+ });
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ },
+ stop() {
+ this.on = false;
+ return { t0: this.t0, list: this.list };
+ },
+ };
+ document.addEventListener("pointerdown", () => (w.__frames.t0 ||= performance.now()), true);
+ document.addEventListener("click", () => (w.__frames.t0 ||= performance.now()), true);
+};
+
+async function context(device) {
+ const ctx = await browser.newContext({ ...(device === "phone" ? PHONE : DESKTOP), colorScheme: "dark" });
+ await ctx.addInitScript(SAMPLER);
+ const page = await ctx.newPage();
+ const cdp = await ctx.newCDPSession(page);
+ await cdp.send("Network.enable");
+ await cdp.send("Network.emulateNetworkConditions", FAST4G);
+ const rsc = [];
+ page.on("request", (r) => {
+ const h = r.headers();
+ if (h.rsc || /[?&]_rsc=/.test(r.url())) rsc.push({ url: r.url(), prefetch: !!h["next-router-prefetch"] });
+ });
+ return { ctx, page, rsc };
+}
+
+/** Taps `target`, samples frames until `done(frame)` holds (or 15 s), and returns the frames from the tap on. */
+async function sampleSwitch(page, target, device, cfg, done) {
+ await page.evaluate((c) => window.__frames.start(c), cfg);
+ if (device === "phone") await target.tap();
+ else await target.click();
+ const deadline = Date.now() + 15_000;
+ let frames = [];
+ while (Date.now() < deadline) {
+ await page.waitForTimeout(100);
+ const { list } = await page.evaluate(() => ({ list: window.__frames.list }));
+ if (list.length && done(list[list.length - 1])) break;
+ }
+ await page.waitForTimeout(300);
+ const { t0, list } = await page.evaluate(() => window.__frames.stop());
+ frames = list.filter((f) => f.t >= t0).map((f) => ({ ...f, ms: Math.round(f.t - t0) }));
+ assert.ok(frames.length > 0, "no frames sampled after the tap");
+ return frames;
+}
+
+const HUB = {
+ bar: 'nav[aria-label="Modes"]',
+ body: "[data-hub-body]",
+ title: "#content header h1",
+ current: 'nav[aria-label="Modes"] [aria-current="page"]',
+};
+
+const SWITCHES = [
+ { hub: "Audio", from: "/audio", tab: "Music", to: "/audio/music" },
+ { hub: "Audio", from: "/audio/music", tab: "Translate", to: "/audio/translate" },
+ { hub: "Audio", from: "/audio/translate", tab: "Dialogue", to: "/audio/dialogue" },
+ { hub: "Audio", from: "/audio/split", tab: "Speech", to: "/audio" },
+ { hub: "Video tools", from: "/video-tools", tab: "Trim", to: "/video-tools/trim" },
+ { hub: "Upscale", from: "/upscale/fps", tab: "Export", to: "/upscale/export" },
+ { hub: "Upscale", from: "/upscale/export", tab: "SDR to HDR", to: "/upscale/hdr" },
+];
+
+let failures = 0;
+const check = (cond, msg) => {
+ if (!cond) {
+ failures++;
+ console.log(` FAIL ${msg}`);
+ }
+};
+
+try {
+ for (const device of ["phone", "desktop"]) {
+ for (const settled of [true, false]) {
+ for (const sw of SWITCHES) {
+ if (!step(`${device}${settled ? "" : ", straight after load"}: ${sw.from} → ${sw.tab}`)) continue;
+ const { ctx, page } = await context(device);
+ if (settled) await openRoute(page, app + sw.from, { settleMs: 4000 });
+ // Straight after load: the page has hydrated (a tap before that is a full page load) and the tabs' prefetches are
+ // still on their way over the throttled network.
+ else await page.goto(app + sw.from, { waitUntil: "load" }).then(() => page.waitForTimeout(150));
+ const tab = page.locator(HUB.bar).getByRole("link", { name: sw.tab, exact: true });
+ await tab.waitFor({ timeout: 30_000 });
+ await tab.scrollIntoViewIfNeeded();
+ const frames = await sampleSwitch(page, tab, device, HUB, (f) => f.path === sw.to && f.body > 0 && !f.skeleton);
+ const last = frames[frames.length - 1];
+ check(last.path === sw.to && last.body > 0 && !last.skeleton, `never reached ${sw.to} with its page drawn (last frame ${JSON.stringify(last)})`);
+ const noBar = frames.filter((f) => !f.bar);
+ check(!noBar.length, `the tab row was missing in ${noBar.length} frame(s), first ${JSON.stringify(noBar[0])}`);
+ const noTitle = frames.filter((f) => f.title !== sw.hub);
+ check(!noTitle.length, `the title “${sw.hub}” was missing in ${noTitle.length} frame(s), from ${noTitle[0]?.ms} ms`);
+ const blank = frames.filter((f) => f.body === 0 && !f.skeleton);
+ check(!blank.length, `the page under the tabs was blank in ${blank.length} frame(s), ${blank[0]?.ms}–${blank[blank.length - 1]?.ms} ms`);
+ const moved = frames.findIndex((f) => f.current === sw.tab);
+ check(moved >= 0 && moved <= 1, `the tapped tab became current only at frame ${moved} (${frames[moved]?.ms} ms)`);
+ await ctx.close();
+ }
+ }
+ }
+
+ if (step("going back to a mode shows its header controls once")) {
+ const { ctx, page } = await context("desktop");
+ await openRoute(page, `${app}/audio/music`, { settleMs: 2500 });
+ const header = page.locator("#content header").first();
+ const fresh = await header.innerText();
+ for (const [tab, to] of [
+ ["Speech", "/audio"],
+ ["Translate", "/audio/translate"],
+ ["Music", "/audio/music"],
+ ]) {
+ await page.locator(HUB.bar).getByRole("link", { name: tab, exact: true }).click();
+ await page.waitForURL((u) => u.pathname === to);
+ await page.waitForTimeout(800);
+ }
+ check((await header.innerText()) === fresh, `the header after switching back reads “${await header.innerText()}”, on a fresh load “${fresh}”`);
+ await ctx.close();
+ }
+
+ for (const device of ["phone", "desktop"]) {
+ if (!step(`${device}: Marketing suite tabs move in the next frame, and Back shows the page's own tab`)) continue;
+ const { ctx, page } = await context(device);
+ await openRoute(page, `${app}/marketing`, { settleMs: 4000 });
+ const bar = 'nav[aria-label="Marketing tools"]';
+ const cfg = { bar, current: `${bar} [aria-current="page"]` };
+ const click = page.locator(bar).getByRole("link", { name: "Click to Ad" });
+ const frames = await sampleSwitch(page, click, device, cfg, (f) => f.path === "/marketing/click-to-ad" && f.content > 0);
+ const moved = frames.findIndex((f) => f.current === "Click to Ad");
+ check(moved >= 0 && moved <= 1, `Click to Ad became current only at frame ${moved} (${frames[moved]?.ms} ms)`);
+ const noBar = frames.filter((f) => !f.bar);
+ check(!noBar.length, `the Marketing tabs were missing in ${noBar.length} frame(s), first ${JSON.stringify(noBar[0])}`);
+ await page.goBack();
+ await page.waitForURL((u) => u.pathname === "/marketing");
+ await page.waitForTimeout(500);
+ const back = await page.locator(`${bar} [aria-current="page"]`).filter({ visible: true }).allInnerTexts();
+ check(back.length === 1 && back[0].trim() === "Marketing Studio", `after Back the current Marketing tab reads ${JSON.stringify(back)}`);
+ await ctx.close();
+ }
+
+ if (step("Back after a hub tab switch shows the mode it returns to")) {
+ const { ctx, page } = await context("phone");
+ await openRoute(page, `${app}/audio/music`, { settleMs: 2500 });
+ await page.locator(HUB.bar).getByRole("link", { name: "Dialogue", exact: true }).tap();
+ await page.waitForURL((u) => u.pathname === "/audio/dialogue");
+ await page.waitForTimeout(500);
+ await page.goBack();
+ await page.waitForURL((u) => u.pathname === "/audio/music");
+ await page.waitForTimeout(500);
+ const back = await page.locator(HUB.current).filter({ visible: true }).allInnerTexts();
+ check(back.length === 1 && back[0].trim() === "Music", `after Back the current tab reads ${JSON.stringify(back)}`);
+ await ctx.close();
+ }
+
+ for (const device of ["phone", "desktop"]) {
+ if (!step(`${device}: Library sections switch in the same frame, with no request`)) continue;
+ const { ctx, page, rsc } = await context(device);
+ await openRoute(page, `${app}/library`, { settleMs: 2500 });
+ const list = page.locator('[role="tablist"][aria-label="Library sections"]');
+ const videos = list.getByRole("tab", { name: /^Videos/ });
+ await videos.waitFor({ timeout: 20_000 });
+ const before = rsc.length;
+ const frames = await sampleSwitch(page, videos, device, { current: '[aria-label="Library sections"] [aria-selected="true"]' }, (f) => /^Videos/.test(f.current ?? ""));
+ const moved = frames.findIndex((f) => /^Videos/.test(f.current ?? ""));
+ check(moved >= 0 && moved <= 1, `the Videos section became selected only at frame ${moved} (${frames[moved]?.ms} ms)`);
+ check(new URL(page.url()).searchParams.get("tab") === "videos", `the address did not follow (${page.url()})`);
+ const asked = rsc.slice(before).filter((r) => !r.prefetch);
+ check(!asked.length, `switching asked the server: ${asked.map((r) => r.url).join(", ")}`);
+ await ctx.close();
+ }
+
+ if (step("desktop: sidebar Image → Audio never blanks the content area")) {
+ const { ctx, page } = await context("desktop");
+ await openRoute(page, `${app}/image`, { settleMs: 4000 });
+ const audio = page.locator('[data-sidebar="sidebar"]').getByRole("link", { name: /^Audio$/ }).first();
+ const frames = await sampleSwitch(page, audio, "desktop", { bar: HUB.bar, body: HUB.body }, (f) => f.path === "/audio" && f.bar && f.body > 0 && !f.skeleton);
+ const blank = frames.filter((f) => f.content === 0);
+ check(!blank.length, `the content area was blank in ${blank.length} frame(s), from ${blank[0]?.ms} ms`);
+ const last = frames[frames.length - 1];
+ check(last.path === "/audio" && last.bar, `Audio did not land with its tabs (last frame ${JSON.stringify(last)})`);
+ await ctx.close();
+ }
+} finally {
+ await browser.close();
+}
+
+if (failures) {
+ console.log(`${failures} failure(s)`);
+ process.exit(1);
+}
+console.log("ok");
diff --git a/tests/instant-tabs.test.ts b/tests/instant-tabs.test.ts
new file mode 100644
index 00000000..d7b2c174
--- /dev/null
+++ b/tests/instant-tabs.test.ts
@@ -0,0 +1,126 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { HUB_MODES, hubOfPath, modeHref, modeOfPath, type HubKind } from "@/lib/hubs";
+
+const src = (p: string) => fs.readFileSync(path.join(__dirname, "..", p), "utf8");
+const HUBS = Object.keys(HUB_MODES) as HubKind[];
+
+describe("hub paths", () => {
+ it("reads the hub and the mode of a path", () => {
+ expect(hubOfPath("/audio")).toBe("audio");
+ expect(hubOfPath("/audio/music?x=1")).toBe("audio");
+ expect(hubOfPath("/video-tools/trim")).toBe("video-tools");
+ expect(hubOfPath("/audiobook")).toBeUndefined();
+ expect(hubOfPath("/image")).toBeUndefined();
+ expect(modeOfPath("audio", "/audio")).toBe("speech");
+ expect(modeOfPath("audio", "/audio/music")).toBe("music");
+ expect(modeOfPath("audio", "/audio/nope")).toBeUndefined();
+ expect(modeOfPath("audio", "/audio/music/more")).toBeUndefined();
+ expect(modeOfPath("upscale", "/audio/music")).toBeUndefined();
+ });
+
+ it("round-trips every mode's URL", () => {
+ for (const kind of HUBS) for (const m of HUB_MODES[kind]) expect(modeOfPath(kind, modeHref(kind, m.id))).toBe(m.id);
+ });
+});
+
+describe("hub tabs never leave the screen during a switch", () => {
+ it("each hub's layout draws the title bar and the tabs, shared by every mode", () => {
+ for (const kind of HUBS) {
+ const layout = src(`src/app/(studio)/${kind}/layout.tsx`);
+ expect(layout).toContain(`<HubFrame kind="${kind}">`);
+ }
+ });
+
+ it("no mode page draws its own tabs, and the per-mode boundary has a skeleton, never an empty fallback", () => {
+ const hub = src("src/components/studio/mode-switch-studio.tsx");
+ expect(hub).not.toMatch(/fallback=\{null\}/);
+ expect(hub).toMatch(/fallback=\{<HubBodySkeleton \/>\}/);
+ expect(hub).not.toMatch(/ModeTabs|tabs=\{/);
+ });
+
+ it("the tabs prefetch whole mode pages, also the ones scrolled out of a phone's row", () => {
+ const chrome = src("src/components/studio/hub-chrome.tsx");
+ // The tab's <Link> has a bare `prefetch` (prefetch={true}: the whole mode page, not only the route's shared shell).
+ const link = chrome.slice(chrome.indexOf("<Link"), chrome.indexOf("</Link>"));
+ expect(link).toMatch(/^ +prefetch\r?$/m);
+ expect(chrome).toMatch(/whenIdle\(/);
+ // The tapped tab is marked at once, before the route commits.
+ expect(chrome).toMatch(/useTappedTab<string>\(pathname\)/);
+ expect(chrome).toMatch(/onClick=\{\(e\) => isPlainClick\(e\) && tap\(m\.id\)\}/);
+ });
+
+ it("the hub's engine badge says self-hosted for the same modes as their tools", () => {
+ const files: Record<string, string> = {
+ "audio/translate": "src/components/dub/dub-studio.tsx",
+ "audio/split": "src/components/audio-tools/split-tool.tsx",
+ "audio/clean": "src/components/audio-tools/clean-voice-tool.tsx",
+ "video-tools/remove-object": "src/components/remove-object/remove-object-tool.tsx",
+ "video-tools/remove-dialogue": "src/components/audio-tools/remove-dialogue-tool.tsx",
+ "video-tools/evolution": "src/components/evolution/evolution-tool.tsx",
+ "video-tools/restore": "src/components/restore/restore-tool.tsx",
+ "video-tools/captions": "src/components/captions/captions-studio.tsx",
+ "video-tools/trim": "src/components/av/trim-tool.tsx",
+ };
+ for (const [key, file] of Object.entries(files)) {
+ const [kind, id] = key.split("/") as [HubKind, string];
+ const mode = HUB_MODES[kind].find((m) => m.id === id);
+ const shell = src(file).match(/<ToolShell[^>]*>/)?.[0] ?? "";
+ expect(!!mode?.selfHostedOnly, key).toBe(/\bselfHostedOnly\b/.test(shell));
+ }
+ });
+});
+
+describe("other tab bars switch without a round trip", () => {
+ it("Library sections update the address with the History API, not a router navigation", () => {
+ const lib = src("src/components/library-view.tsx");
+ expect(lib).toMatch(/window\.history\.replaceState\(null, "", /);
+ expect(lib).not.toMatch(/router\.replace\(/);
+ });
+
+ it("sidebar rows prefetch once the page is idle, not only on hover or touch", () => {
+ expect(src("src/components/app-sidebar.tsx")).toMatch(/<IntentLink href=\{item\.href\} eager=\{item\.eager\} settled /);
+ const link = src("src/components/intent-link.tsx");
+ expect(link).toMatch(/const now = eager \|\| \(settled && idle\);/);
+ // Also the rows scrolled out of view: prefetched on idle, not when a scroll brings them in front of the tap.
+ expect(link).toMatch(/if \(settled && idle && href\) router\.prefetch\(href\);/);
+ });
+
+ it("a tapped tab is marked before the route commits, and dropped once the route moves or the page is hidden", () => {
+ const hook = src("src/lib/use-tapped-tab.ts");
+ expect(hook).toMatch(/if \(tapped && tapped\.at !== pathname\) setTapped\(null\);/);
+ expect(hook).toMatch(/useLayoutEffect\(\(\) => \(\) => setTapped\(null\), \[\]\);/);
+ const marketing = src("src/components/marketing/shell.tsx");
+ expect(marketing).toMatch(/useTappedTab<SuiteTab>\(active\)/);
+ expect(marketing).toMatch(/aria-current=\{t\.id === current \? "page" : undefined\}/);
+ });
+
+ it("the marketing suite's route skeletons draw its real header and tabs, the page's own tab current", () => {
+ expect(src("src/components/marketing/skeletons.tsx")).toMatch(/<MarketingHeader title=\{title\} active=\{active\}/);
+ expect(src("src/app/(studio)/marketing/loading.tsx")).toMatch(/<MarketingSkeleton \/>/);
+ for (const [file, title, active] of [
+ ["marketing/click-to-ad", "Click to Ad", "click"],
+ ["ads", "Ads Studio", "ads"],
+ ["ads/multiplier", "Ad Multiplier", "multiplier"],
+ ])
+ expect(src(`src/app/(studio)/${file}/loading.tsx`)).toContain(`<MarketingToolSkeleton title="${title}" active="${active}" />`);
+ });
+
+ it("Library sections show the tapped section before useSearchParams follows", () => {
+ const lib = src("src/components/library-view.tsx");
+ expect(lib).toMatch(/setSet\(\{ from: routed\.toString\(\), to: next \}\);/);
+ expect(lib).toMatch(/if \(set && set\.from !== routed\.toString\(\)\) setSet\(null\);/);
+ });
+
+ it("gallery categories mark the chip in an urgent render and filter the grid in a deferred one", () => {
+ const gallery = src("src/components/preset-gallery.tsx");
+ expect(gallery).toMatch(/const listCat = useDeferredValue\(cat\);/);
+ expect(gallery).toMatch(/aria-pressed=\{cat === c\}/);
+ expect(gallery).not.toMatch(/p\.category === cat\)/);
+ });
+
+ 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 /);
+ });
+});