diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index 2204f907406..f138ebc4694 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -8,6 +8,8 @@ "index.html", "scripts/**/*.{js,ts}", "apps/website/src/scripts/**/*.ts", + // Astro injects these routes when WORKSHOP_IN_BUILD is enabled. + "apps/website/src/routes/models/*.{astro,ts}", "**/.storybook/{main,preview}.ts", "packages/ingest-types/openapi-ts.config.ts" ], @@ -29,7 +31,9 @@ // Loaded by config, not imported: oxlint jsPlugin (.oxlintrc.json) and // stylelint customSyntax (.stylelintrc.json) respectively. "eslint-plugin-playwright", - "postcss-html" + "postcss-html", + // Executed by models-snippets.test.ts inside the generated Node examples. + "mime-types" ], "ignoreUnresolvedImports": [ diff --git a/apps/website/MODELS_CONTENT_FORMAT.md b/apps/website/MODELS_CONTENT_FORMAT.md index 6153e90d172..8c0433ddae5 100644 --- a/apps/website/MODELS_CONTENT_FORMAT.md +++ b/apps/website/MODELS_CONTENT_FORMAT.md @@ -25,6 +25,13 @@ preserved in the packed file, not added to the UI. Old model-only URLs redirect to a deterministic current record. Detail lookup, sample ownership and saved drafts use the content slug, not only the Router ID. +Corrections to a published page's catalogue category live in +`src/data/workshop-use-case-overrides.json`, keyed by verified Router ID. They +change its search/category/task labels while preserving the published URL, +example ownership and production-test ledger. The OpenAI GPT Image routes +accept text-to-image generation, so their imported `edit-images` categorization +is corrected to `generate-images`. The build rejects unknown IDs or categories. + ## Media policy A thumbnail or output sample URL may not be published in two different use diff --git a/apps/website/MODELS_INPUT_SANITY_REVIEW.md b/apps/website/MODELS_INPUT_SANITY_REVIEW.md index 4538af59398..1d261010ee5 100644 --- a/apps/website/MODELS_INPUT_SANITY_REVIEW.md +++ b/apps/website/MODELS_INPUT_SANITY_REVIEW.md @@ -30,7 +30,7 @@ Prefer a small, obvious form over complete exposure of the provider schema. ## Evidence and false-positive rules - Review the current worktree, not the older PR preview or previous conversation. - Start with `routerWorkshopModels`, `getRouterWorkshopModelDetail`, + Start with `workshopModels`, `getRouterWorkshopModelDetail`, `schemaForModel`, `defaultValues`, `validateForm` and `prepareWorkshopRouterInput`. Inspect actual per-use-case slugs. - Check both the curated contract and the pinned native OpenAPI snapshot. diff --git a/apps/website/MODELS_INPUT_SCHEMA.md b/apps/website/MODELS_INPUT_SCHEMA.md index 62153d47df8..1e95f6ee003 100644 --- a/apps/website/MODELS_INPUT_SCHEMA.md +++ b/apps/website/MODELS_INPUT_SCHEMA.md @@ -53,7 +53,8 @@ HeyGen's curated language choices correspond to languages in the Language and locale remain unset for automatic detection; a selected locale overrides language, as described in the [HeyGen speech contract](https://developers.heygen.com/docs/voices/speech). -Voice ID stays editable in Advanced with the existing tested voice. +Voice ID is hidden and fixed to the existing tested account voice in the +input-presentation data; creators cannot choose an unavailable account voice. Model price estimates prefer the generated node pricing rules. Models whose nodes have no price badge can use verified flat rates from @@ -332,11 +333,24 @@ with `pnpm --filter @comfyorg/website generate:workshop-router-contracts`. - Multiple Qwen reference inputs become ordered native image entries; Base64 arrays and first/last-frame mappings remain unchanged. This does not add every optional provider media mode or override provider-specific limits. -- Python/TypeScript examples use the same storage handshake for URL files and - local Base64 encoding for Base64 files. cURL continues to omit local files and - marks the request incomplete. For script retries, reuse the prepared URLs and - key; rerunning upload setup creates different request URLs. Signed URLs and - keys must not be logged, checked in, or put into the content pack. +- Python/TypeScript examples use `comfy-sdk==0.2.0` / `@comfyorg/sdk@0.2.0`. + URL-capable local inputs use SDK assets; native inline-only inputs retain + Base64 with MIME inferred from the supplied file or HTTP response. Default + source URLs remain runnable without inventing local filenames. Preparing the + API tab does not read private file bytes or download example media. + Embedded default media retains its original data URI: inline requests use + those known bytes, and URL inputs use the SDK's `assets.from_bytes` / + `assets.fromBytes`. User-selected files still refer to local paths. +- JSON endpoints use the SDK's `models.run`, which owns request identity and + retries. SDK 0.2.0 cannot decode binary responses, so binary/unknown-output + endpoints retain HTTP examples that check errors and save non-JSON bytes. + cURL generates a fresh key on execution, preserves usable source URLs, and + warns when it omits file inputs. Retrying a request requires its original + prepared body and key. Credentials are checked before accessing inputs. +- SDK examples use the same environment family as the page, with separate + `COMFY_ROUTER_BASE_URL` and `COMFY_BASE_URL` overrides. SDK dependencies are + development-only: tests execute generated code; they add no browser imports. + Signed URLs and keys must not be checked in or put into the content pack. **Live verification is blocked, not certified.** On September 10, both `api-nodes-prod` and `api-nodes-staging` returned HTTP 200 without any @@ -442,6 +456,23 @@ Content identity and unfinished per-use-case widget customization are documented in [Models content format](MODELS_CONTENT_FORMAT.md). Live render tests remain paused while these input definitions are tuned. +## Sign-in drafts + +Signed-out visitors can select local media before signing in. The same +pre-navigation hook serves the header and Playground: scalar edits flush to +session storage, while media is saved to IndexedDB before same-tab navigation. +No file is uploaded until the authenticated Run path prepares the request. + +Each tab stores an opaque draft key in session storage. Media drafts are consumed +on return, validated against the current input schema, and usable for one hour. +Writes prune expired entries and retain at most four drafts, each capped at +100 MiB. Entries left behind by an abandoned login are pruned on a later write; +there is no background deletion timer. Document-owned Blob URLs are never stored. +The storage operation has a five-second deadline and aborts with its component. +Repeated sign-in clicks share one save; completion cannot redirect a departed +page. If storage fails, sign-in proceeds and the return page asks the visitor to +reselect missing files instead of silently submitting default media. + ## Verification boundaries During input tuning, use a short change → focused test/browser check → fix loop. diff --git a/apps/website/e2e/models-catalogue-corrections.spec.ts b/apps/website/e2e/models-catalogue-corrections.spec.ts new file mode 100644 index 00000000000..36d7757b6c3 --- /dev/null +++ b/apps/website/e2e/models-catalogue-corrections.spec.ts @@ -0,0 +1,38 @@ +import { expect } from '@playwright/test' + +import { test } from './fixtures/modelsAccount' + +test('GPT Image generation pages are discoverable as text-to-image while published URLs remain valid', async ({ + page +}) => { + const hydrated = Promise.withResolvers() + const moduleRequested = page.waitForRequest( + '**/_website/ModelsCatalogue.*.js' + ) + await page.route('**/_website/ModelsCatalogue.*.js', async (route) => { + await hydrated.promise + await route.continue() + }) + try { + await page.goto('/models/?useCase=generate-images', { waitUntil: 'commit' }) + await moduleRequested + await expect(page.getByTestId('workshop-search')).toBeDisabled() + } finally { + hydrated.resolve() + } + await page.getByTestId('workshop-search').fill('gpt image') + const cards = page + .getByTestId('workshop-models-grid') + .getByTestId('workshop-model-card') + await expect(cards).toHaveCount(3) + await page.getByRole('link', { name: /GPT Image 1\.5/ }).click() + await expect(page).toHaveURL( + /\/models\/openai--gpt-image-1\.5--edit-images\/$/ + ) + await expect( + page.getByRole('textbox', { name: 'Prompt', exact: true }) + ).toBeVisible() + await page.goto('/models/?useCase=edit-images') + await page.getByTestId('workshop-search').fill('gpt image') + await expect(cards).toHaveCount(0) +}) diff --git a/apps/website/e2e/models-performance.spec.ts b/apps/website/e2e/models-performance.spec.ts new file mode 100644 index 00000000000..ac168959c7f --- /dev/null +++ b/apps/website/e2e/models-performance.spec.ts @@ -0,0 +1,101 @@ +import type { Page } from '@playwright/test' +import { expect } from '@playwright/test' + +import { test } from './fixtures/modelsAccount' + +/** Same-origin script resources the page has requested so far, by URL. */ +function requestedScripts(page: Page) { + return page.evaluate(() => + performance + .getEntriesByType('resource') + .filter( + (entry): entry is PerformanceResourceTiming => + entry instanceof PerformanceResourceTiming + ) + .flatMap((entry) => { + const url = new URL(entry.name) + return url.origin === location.origin && url.pathname.endsWith('.js') + ? [[entry.name, entry.decodedBodySize] as const] + : [] + }) + ) +} + +test('catalogue browsing stays within its JavaScript budget', async ({ + page +}) => { + // Every page pays for the layout islands (header, footer, translations, + // analytics). Charge the catalogue only for what it adds on top of those, + // so a header change cannot fail this test and a catalogue regression + // cannot hide behind a shrink elsewhere. + // The default resource-timing buffer holds 250 entries and drops the rest + // silently; a late catalogue chunk must not fall off the end. + await page.addInitScript(() => performance.setResourceTimingBufferSize(2000)) + await page.goto('/') + const shared = new Set((await requestedScripts(page)).map(([name]) => name)) + + await page.goto('/models/') + await page.getByTestId('workshop-search').fill('kling') + await page.getByRole('heading', { level: 1 }).click() + await expect( + page + .getByTestId('workshop-models-grid') + .getByTestId('workshop-model-card') + .first() + ).toContainText('Kling') + const scripts = await requestedScripts(page) + const catalogueBytes = scripts + .filter(([name]) => !shared.has(name)) + .reduce((total, [, bytes]) => total + bytes, 0) + expect(catalogueBytes).toBeGreaterThan(0) + expect(catalogueBytes).toBeLessThan(900_000) + // The whole-route ceiling stays as well: catalogue code that migrated into + // a chunk the homepage also loads would pass the delta and still be paid + // for by every visitor to /models/. + const totalBytes = scripts.reduce((total, [, bytes]) => total + bytes, 0) + expect(totalBytes).toBeLessThan(1_800_000) +}) + +test('video cards load on screen and stop playing when scrolled away', async ({ + page +}) => { + await page.goto('/models/') + await page.getByTestId('workshop-filter').click() + const videos = page.getByTestId('section-generate-videos').locator('video') + await expect.poll(() => videos.count()).toBeGreaterThan(0) + await expect + .poll(() => + videos.evaluateAll((elements: HTMLVideoElement[]) => + elements.every((video) => video.currentSrc === '' && video.paused) + ) + ) + .toBe(true) + + const first = videos.first() + await first.scrollIntoViewIfNeeded() + await expect + .poll(() => + first.evaluate( + (video: HTMLVideoElement) => video.readyState >= 2 && !video.paused + ) + ) + .toBe(true) + await page.getByRole('heading', { level: 1 }).scrollIntoViewIfNeeded() + await expect + .poll(() => + videos.evaluateAll((elements: HTMLVideoElement[]) => + elements.every((video) => video.paused) + ) + ) + .toBe(true) + await page.emulateMedia({ reducedMotion: 'reduce' }) + await first.scrollIntoViewIfNeeded() + // The source is attached (so the frame can show) before playback would have + // started; asserting `paused` earlier than that proves nothing. + await expect + .poll(() => first.evaluate((video: HTMLVideoElement) => video.readyState)) + .toBeGreaterThanOrEqual(1) + await expect + .poll(() => first.evaluate((video: HTMLVideoElement) => video.paused)) + .toBe(true) +}) diff --git a/apps/website/e2e/models-sign-in-draft.spec.ts b/apps/website/e2e/models-sign-in-draft.spec.ts new file mode 100644 index 00000000000..19ae82f5e71 --- /dev/null +++ b/apps/website/e2e/models-sign-in-draft.spec.ts @@ -0,0 +1,172 @@ +import { readFileSync } from 'node:fs' +import { expect } from '@playwright/test' + +import { test } from './fixtures/modelsAccount' + +const path = '/models/byteplus--seedream-4-5--edit-images/' + +for (const { entry, randomUUID, failRead } of [ + { entry: 'playground', randomUUID: true, failRead: false }, + { entry: 'header', randomUUID: true, failRead: false }, + { entry: 'header', randomUUID: false, failRead: false }, + { entry: 'header', randomUUID: true, failRead: true } +]) { + test(`selected reference bytes survive ${entry} sign-in and reach Router${randomUUID ? '' : ' without crypto.randomUUID'}${failRead ? ' after a transient read failure' : ''}`, async ({ + page, + modelsAccount + }) => { + if (!randomUUID) + await page.addInitScript(() => { + Object.defineProperty(crypto, 'randomUUID', { value: undefined }) + }) + if (failRead) + await page.addInitScript(() => { + const get = IDBObjectStore.prototype.get + IDBObjectStore.prototype.get = function (query) { + if ( + this.transaction.db.name === 'comfy-workshop-drafts' && + !sessionStorage.getItem('test:draft-read-failed') + ) { + sessionStorage.setItem('test:draft-read-failed', '1') + throw new DOMException('Read interrupted', 'UnknownError') + } + return get.call(this, query) + } + }) + await page.goto(path) + const chooser = page.waitForEvent('filechooser') + await page + .getByText('Choose images or drop them here', { exact: true }) + .click() + await (await chooser).setFiles('e2e/assets/placeholder-1x1.webp') + const replacement = page.getByRole('button', { + name: 'Replace placeholder-1x1.webp' + }) + await expect(replacement).toBeVisible() + await page + .getByRole('textbox', { name: 'Prompt', exact: true }) + .fill('Keep the reference character, watercolor style') + const signIn = + entry === 'playground' + ? page.getByRole('link', { name: 'Sign in to run', exact: true }) + : page.getByRole('link', { name: 'Sign in', exact: true }) + await signIn.click() + await expect(page).toHaveURL(/\/login\/\?returnTo=/) + await page.getByRole('button', { name: 'Use email instead' }).click() + await page.getByLabel('Email').fill(modelsAccount.email) + await page + .getByLabel('Password', { exact: true }) + .fill(modelsAccount.password) + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page).toHaveURL(new RegExp(`${path}$`)) + if (failRead) { + await expect( + page.getByText( + 'Some saved inputs could not be restored. Check your inputs and select your files again.' + ) + ).toBeVisible() + await page.reload() + } + await expect(replacement).toBeVisible() + await expect( + page.getByRole('textbox', { name: 'Prompt', exact: true }) + ).toHaveValue('Keep the reference character, watercolor style') + const request = page.waitForRequest( + '**/v2/models/byteplus/seedream-4-5-251128' + ) + let calls = 0 + await page.route('**/v2/models/**', (route) => { + if (++calls === 2) + return route.fulfill({ + status: 503, + headers: { 'X-Comfy-Error-Type': 'provider_error' }, + contentType: 'application/json', + body: JSON.stringify({ detail: 'Temporary provider error' }) + }) + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + images: [{ url: 'https://media.comfy.org/tests/result.webp' }] + }) + }) + }) + await page.getByRole('button', { name: 'Run', exact: true }).click() + const first = await request + expect(first.postDataJSON()).toMatchObject({ + prompt: 'Keep the reference character, watercolor style', + image: + 'data:image/webp;base64,' + + readFileSync('e2e/assets/placeholder-1x1.webp').toString('base64') + }) + await expect(page.getByTestId('playground-output')).toHaveAttribute( + 'data-state', + 'succeeded' + ) + const changedBytes = readFileSync('public/hero/input.webp') + const replaceChooser = page.waitForEvent('filechooser') + await replacement.click() + await ( + await replaceChooser + ).setFiles({ + name: 'placeholder-1x1.webp', + mimeType: 'image/webp', + buffer: changedBytes + }) + const changedRequest = page.waitForRequest( + '**/v2/models/byteplus/seedream-4-5-251128' + ) + await page.getByRole('button', { name: 'Run', exact: true }).click() + const changed = await changedRequest + expect(changed.postDataJSON()).toMatchObject({ + image: 'data:image/webp;base64,' + changedBytes.toString('base64') + }) + expect(changed.headers()['idempotency-key']).not.toBe( + first.headers()['idempotency-key'] + ) + await expect(page.getByTestId('playground-output')).toHaveAttribute( + 'data-state', + 'failed' + ) + const retryRequest = page.waitForRequest( + '**/v2/models/byteplus/seedream-4-5-251128' + ) + await page.getByRole('button', { name: 'Run', exact: true }).click() + const retried = await retryRequest + expect(retried.postDataJSON()).toEqual(changed.postDataJSON()) + expect(retried.headers()['idempotency-key']).toBe( + changed.headers()['idempotency-key'] + ) + await expect(page.getByTestId('playground-output')).toHaveAttribute( + 'data-state', + 'succeeded' + ) + }) +} + +test('unavailable draft storage does not trap sign-in and reports missing files on return', async ({ + page +}) => { + await page.addInitScript(() => { + window.indexedDB.open = () => { + throw new DOMException('Storage disabled', 'SecurityError') + } + }) + await page.goto(path) + const chooser = page.waitForEvent('filechooser') + await page + .getByText('Choose images or drop them here', { exact: true }) + .click() + await (await chooser).setFiles('e2e/assets/placeholder-1x1.webp') + await page.getByRole('link', { name: 'Sign in to run', exact: true }).click() + await expect(page).toHaveURL(/\/login\/\?returnTo=/) + await page.goto(path) + await expect( + page.getByText( + 'Some saved inputs could not be restored. Check your inputs and select your files again.' + ) + ).toBeVisible() + await expect( + page.getByRole('button', { name: 'Replace placeholder-1x1.webp' }) + ).toHaveCount(0) +}) diff --git a/apps/website/e2e/workshop-input-feedback.spec.ts b/apps/website/e2e/workshop-input-feedback.spec.ts index 2856c6d1b85..8bdb5353f50 100644 --- a/apps/website/e2e/workshop-input-feedback.spec.ts +++ b/apps/website/e2e/workshop-input-feedback.spec.ts @@ -63,7 +63,7 @@ test('Beeble displays readable options while the API keeps its native values', a await expect(page.getByTestId('snippet')).toContainText('fill') }) -test('HeyGen offers named language and locale choices and keeps Voice ID in Advanced', async ({ +test('HeyGen offers named language and locale choices and uses the supported voice without exposing its account-specific ID', async ({ page }) => { await page.goto('/models/heygen--starfish-tts--audio/') @@ -83,9 +83,12 @@ test('HeyGen offers named language and locale choices and keeps Voice ID in Adva await page.getByTestId('playground-advanced').locator('summary').click() await expect( page.getByRole('textbox', { name: 'Voice ID', exact: true }) - ).toBeVisible() + ).toHaveCount(0) await page.getByRole('tab', { name: 'API', exact: true }).click() await expect(page.getByTestId('snippet')).toContainText('fr-FR') + await expect(page.getByTestId('snippet')).toContainText( + 'd2f4f24783d04e22ab49ee8fdc3715e0' + ) await expect(page.getByTestId('snippet')).not.toContainText('French (France)') }) diff --git a/apps/website/package.json b/apps/website/package.json index 7cf0d28ff41..0664403d729 100644 --- a/apps/website/package.json +++ b/apps/website/package.json @@ -68,6 +68,7 @@ "@astrojs/check": "catalog:", "@astrojs/mdx": "catalog:", "@astrojs/vue": "catalog:", + "@comfyorg/sdk": "catalog:", "@playwright/test": "catalog:", "@storybook/vue3-vite": "catalog:", "@tailwindcss/vite": "catalog:", @@ -78,7 +79,9 @@ "@types/leaflet": "catalog:", "@vitejs/plugin-vue": "catalog:", "astro": "catalog:", + "fake-indexeddb": "catalog:", "happy-dom": "catalog:", + "mime-types": "catalog:", "tailwindcss": "catalog:", "tsx": "catalog:", "tw-animate-css": "catalog:", diff --git a/apps/website/reviews/2026-09-13-models-performance.md b/apps/website/reviews/2026-09-13-models-performance.md new file mode 100644 index 00000000000..b2e04429ae0 --- /dev/null +++ b/apps/website/reviews/2026-09-13-models-performance.md @@ -0,0 +1,45 @@ +# Models performance follow-up + +Christian's report prompted an audit of data loading, video previews, and background animation on the live Models routes. The related SDK examples and sign-in recovery are separate changes. + +## Findings and changes + +- The catalogue imported the same module that joins and validates the source catalogues at build time. Importing its filter helpers caused that work and its source data to ship to the browser, even though Astro already supplies the prepared cards. Data ownership now stays in `workshop-browse-content`; filtering helpers have no catalogue-data dependency. Model pages and aliases still resolve from the same approved manifest. +- Model-card videos loaded metadata and started playback throughout the page, including horizontal overflow and rows below the viewport. Preview videos now attach their source only while visible in a visible tab, pause and release the source when hidden, and respect reduced motion. Unmount releases the media resource. The same lifecycle covers the featured video. +- The featured carousel's animation loop continued while offscreen. Rotation now stops offscreen and in hidden tabs, retaining hover, keyboard-focus and reduced-motion behavior. + +## Controlled browser measurements + +Baseline: `fab94df2fb` with the same production build configuration as the TEST preview. Chrome 149.0.7827.55, macOS 25.5.0, Apple M5 Pro, 48 GiB RAM, 1440×900 at 1×. Each sample used a fresh browser context, fixed local media fixtures, blocked external APIs, and an uncompressed local static server. No paid generations ran. + +Two warmups per arm, then ABBA/BAAB (four recorded samples per arm). Build processes were stopped before sampling. Times and heap below are medians at hydration; bytes are decoded JavaScript actually requested through the catalogue search or detail API-tab interaction. + +| Catalogue measurement | Before | After | Change | +| --------------------- | -----------: | -----------: | -----: | +| Requested JavaScript | 2,450,151 B | 1,395,168 B | −43% | +| Script duration | 36.4 ms | 20.9 ms | −43% | +| Used JS heap | 19,088,326 B | 12,851,676 B | −33% | +| Hydration reached | 176.5 ms | 154.2 ms | −13% | + +The Seedream 4.5 detail page was effectively unchanged: 1.67 MB JavaScript and approximately 111 ms to hydration. Its emitted 3.8 MB complete-contract chunk was **not requested**; emitted bundle size alone was not treated as a page-load regression. No long tasks occurred on this fast machine. These results do not measure provider latency, real media decoding costs, mobile performance, or Core Web Vitals in production. The final featured-carousel lifecycle change followed the table's measurement run; it is covered by behavior tests. + +## Regression checks + +`e2e/models-performance.spec.ts` exercises working catalogue search with a 1.8 MB decoded-JavaScript budget and actual browser video readiness/playback before and after scrolling, including reduced motion. Both tests fail against the baseline (2.66 MB with the full account fixture, and offscreen videos already loaded), and pass with the fixes. `FeaturedBanner.test.ts` checks that rotation freezes offscreen and in a hidden tab, then resumes. + +Run against a TEST-enabled build: + +```sh +NODE_ENV=production WORKSHOP_IN_BUILD=1 PUBLIC_WORKSHOP_ROUTER_RUN=1 PUBLIC_WORKSHOP_CLOUD_ENV=test WEBSITE_GITHUB_STARS_OVERRIDE=110000 PUBLIC_CUSTOMERIO_WRITE_KEY=test-e2e-write-key pnpm --filter @comfyorg/website build +pnpm --filter @comfyorg/website exec playwright test e2e/models-performance.spec.ts --project desktop --workers 1 +``` + +These are website checks. The canvas-specific performance CI does not establish a website timing baseline. The byte budget is deterministic; timings are supporting local evidence, not a CI performance guarantee. + +## Reviewer criteria and remaining boundaries + +[Alex's review of the account integration](https://github.com/Comfy-Org/ComfyUI_frontend/pull/17283#pullrequestreview-5172958399) emphasizes single ownership and explicit lifecycle boundaries. [Christian's follow-up](https://github.com/Comfy-Org/ComfyUI_frontend/pull/17283#issuecomment-5627167630) accepts a narrow unblock when architectural follow-ups have explicit owners. This change keeps catalogue data with its existing owner and uses one shared preview lifecycle rather than independent playback rules. + +The existing all-locale translation payload (~546 KB) and shared analytics remain material page costs. They span the website and need their own measured optimization and localization/consent validation. No production RUM percentiles were available for this work; the numbers above are local measurements only. + +The featured slide keeps its source in the server-rendered markup, so the browser requests its first frame during parse rather than after hydration and the first observer callback. Cards request theirs 20% of a viewport before they scroll in. A hidden tab and reduced motion only pause; scrolling away is what releases a card's buffer, and a banner slide releases its outgoing video when the next one takes over. diff --git a/apps/website/scripts/generate-template-model-join.test.ts b/apps/website/scripts/generate-template-model-join.test.ts index 55355f4c2fb..1859c893632 100644 --- a/apps/website/scripts/generate-template-model-join.test.ts +++ b/apps/website/scripts/generate-template-model-join.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { WorkshopModel } from '../src/config/models-catalogue' -import { workshopModels } from '../src/config/models-catalogue' +import { workshopModels } from '../src/config/workshop-browse-content' import hubTemplates from '../src/data/hubTemplates.json' import templateModelJoin from '../src/data/templateModelJoin.json' import { diff --git a/apps/website/scripts/generate-template-model-join.ts b/apps/website/scripts/generate-template-model-join.ts index 7777666c699..7ac2c462a1f 100644 --- a/apps/website/scripts/generate-template-model-join.ts +++ b/apps/website/scripts/generate-template-model-join.ts @@ -13,9 +13,11 @@ import { readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { workshopModels } from '../src/config/models-catalogue' +import { + workshopModels, + routerModelSlugAliases +} from '../src/config/workshop-browse-content' import type { WorkshopModel } from '../src/config/models-catalogue' -import { routerModelSlugAliases } from '../src/config/workshop-browse-content' import { hubTemplatesSchema } from '../src/lib/hub/types' import { modelNamedBy, partnerModelFor } from '../src/lib/hub/template-use-case' import { API_PROVIDER_MAP } from './generate-models' diff --git a/apps/website/scripts/generate-workshop-versions.ts b/apps/website/scripts/generate-workshop-versions.ts index 9bfc970a5cc..7678a48f631 100644 --- a/apps/website/scripts/generate-workshop-versions.ts +++ b/apps/website/scripts/generate-workshop-versions.ts @@ -10,7 +10,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { workshopModels } from '../src/config/models-catalogue' +import { workshopModels } from '../src/config/workshop-browse-content' import type { WorkshopModel } from '../src/config/models-catalogue' import type { HubTemplate } from '../src/lib/hub/types' import { API_PROVIDER_MAP } from './generate-models' diff --git a/apps/website/scripts/test-router-models.ts b/apps/website/scripts/test-router-models.ts index f2602615e72..d0ec17b1477 100644 --- a/apps/website/scripts/test-router-models.ts +++ b/apps/website/scripts/test-router-models.ts @@ -6,7 +6,7 @@ import { join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { parseArgs } from 'node:util' -import { routerWorkshopModels } from '../src/config/workshop-browse-content' +import { workshopModels } from '../src/config/workshop-browse-content' import { resolveWorkshopCloudEnv } from '../src/config/workshop-cloud-env' import { WORKSHOP_ROUTER_BASE_URL } from '../src/config/workshop-env' import { releaseRouterOutputs } from '../src/config/workshop-response' @@ -123,7 +123,7 @@ async function main() { : fileURLToPath( new URL(`../../../temp/router-model-tests/${runId}/`, import.meta.url) ) - const models = routerWorkshopModels.filter( + const models = workshopModels.filter( (model) => isMediaKind(model.modality) && (!values.modality || model.modality === values.modality) @@ -163,7 +163,7 @@ async function main() { } const report = openRouterModelReport({ jsonPath, markdownPath }) try { - for (const model of routerWorkshopModels) { + for (const model of workshopModels) { report.update({ slug: model.slug, routerId: model.routerId, diff --git a/apps/website/scripts/workshop-input-presentation.test.ts b/apps/website/scripts/workshop-input-presentation.test.ts index 84779ceca91..dec4424afde 100644 --- a/apps/website/scripts/workshop-input-presentation.test.ts +++ b/apps/website/scripts/workshop-input-presentation.test.ts @@ -541,8 +541,11 @@ describe('curated model inputs', () => { }, { id: 'heygen/starfish', - values: { text: 'Hello', voice_id: 'creator-voice' }, - expected: { input_type: 'text', voice_id: 'creator-voice' }, + values: { text: 'Hello' }, + expected: { + input_type: 'text', + voice_id: 'd2f4f24783d04e22ab49ee8fdc3715e0' + }, absent: ['language', 'locale'] }, { diff --git a/apps/website/src/components/hub/HubBrowse.vue b/apps/website/src/components/hub/HubBrowse.vue index c18ddde2fe2..65829d89556 100644 --- a/apps/website/src/components/hub/HubBrowse.vue +++ b/apps/website/src/components/hub/HubBrowse.vue @@ -9,9 +9,9 @@ import type { UseCase, WorkshopModel } from '../../config/models-catalogue' import { USE_CASES, sortWorkshopModels, - useCaseFor, - workshopModels + useCaseFor } from '../../config/models-catalogue' +import { workshopModels } from '../../config/workshop-browse-content' import { groupModels } from '../../config/model-family' import hubTemplates from '../../data/hubTemplates.json' import { hubWorkflowPath } from '../../lib/hub/workflow-detail' diff --git a/apps/website/src/components/workshop/ApiTab.execution.test.ts b/apps/website/src/components/workshop/ApiTab.execution.test.ts new file mode 100644 index 00000000000..08a45c8cafc --- /dev/null +++ b/apps/website/src/components/workshop/ApiTab.execution.test.ts @@ -0,0 +1,113 @@ +// @vitest-environment happy-dom +import { execFileSync } from 'node:child_process' +import userEvent from '@testing-library/user-event' +import { render, screen } from '@testing-library/vue' +import { expect, it } from 'vitest' + +import { workshopExampleFile } from '../../config/workshop-example-file' +import { initialWorkshopPageState } from '../../config/workshop-page-state' +import { getRouterWorkshopModelDetail } from '../../config/workshop-router-content' +import { workshopContract } from '../../config/workshop-contract-catalog' +import defaultMedia from '../../data/router-default-media.json' +import ApiTab from './ApiTab.vue' + +it('copies the embedded default image and mask into a runnable BFL request', async () => { + const model = getRouterWorkshopModelDetail('bfl--flux-pro-fill--edit-images') + if (!model) throw new Error('Missing FLUX Fill page') + render(ApiTab, { + props: { + contract: model.execution, + values: initialWorkshopPageState(model).values + } + }) + await screen.findByTestId('snippet') + await userEvent.setup().click(screen.getByRole('tab', { name: 'cURL' })) + const args = execFileSync( + 'bash', + [ + '-c', + 'curl() { printf \'%s\\0\' "$@"; }\n' + + screen.getByTestId('snippet').textContent + ], + { + encoding: 'utf8', + env: { PATH: process.env.PATH, COMFY_API_KEY: 'test-key' } + } + ).split('\0') + expect(JSON.parse(args[args.indexOf('--data') + 1])).toMatchObject({ + image: defaultMedia.image, + mask: defaultMedia.mask + }) + expect(screen.queryByRole('note')).toBeNull() +}) + +it('a copied cURL example starts distinct executions with fresh idempotency keys', async () => { + const visitor = userEvent.setup() + render(ApiTab, { + props: { + contract: workshopContract('bfl/flux-2-pro'), + values: { prompt: 'A watercolor sunflower', seed: 42 } + } + }) + const snippet = await screen.findByTestId('snippet') + await visitor.click(screen.getByTestId('snippet-curl')) + const run = () => + execFileSync( + 'bash', + ['-c', 'curl() { printf \'%s\\0\' "$@"; }\n' + snippet.textContent], + { + encoding: 'utf8', + env: { PATH: process.env.PATH, COMFY_API_KEY: 'test-key' } + } + ).split('\0') + const first = run() + const second = run() + const key = (args: string[]) => + args.find((argument) => argument.startsWith('Idempotency-Key: ')) + expect(key(first)).toMatch(/^Idempotency-Key: [\da-f-]{36}$/i) + expect(key(second)).toMatch(/^Idempotency-Key: [\da-f-]{36}$/i) + expect(key(second)).not.toBe(key(first)) + expect(JSON.parse(first[first.indexOf('--data') + 1])).toEqual({ + prompt: 'A watercolor sunflower', + seed: 42 + }) +}) + +it('copies all selected Seedream reference URLs into an executable cURL request', async () => { + const visitor = userEvent.setup() + const model = getRouterWorkshopModelDetail( + 'byteplus--seedream-4-5--edit-images' + ) + if (!model) throw new Error('Missing Seedream edit page') + const urls = ['first', 'second', 'third'].map( + (name) => `https://source.example/${name}.webp` + ) + const images = urls.map((url) => { + const file = workshopExampleFile(url) + if (!file) throw new Error('Invalid fixture URL') + return file + }) + render(ApiTab, { + props: { + contract: model.execution, + values: { ...initialWorkshopPageState(model).values, images } + } + }) + await screen.findByTestId('snippet') + await visitor.click(screen.getByRole('tab', { name: 'cURL' })) + const args = execFileSync( + 'bash', + [ + '-c', + 'curl() { printf \'%s\\0\' "$@"; }\n' + + screen.getByTestId('snippet').textContent + ], + { + encoding: 'utf8', + env: { PATH: process.env.PATH, COMFY_API_KEY: 'test-key' } + } + ).split('\0') + const parameters = JSON.parse(args[args.indexOf('--data') + 1]) + expect(parameters.image).toEqual(urls) + expect(screen.queryByRole('note')).toBeNull() +}) diff --git a/apps/website/src/components/workshop/ApiTab.test.ts b/apps/website/src/components/workshop/ApiTab.test.ts index cba9ed12f6b..5e185d564f7 100644 --- a/apps/website/src/components/workshop/ApiTab.test.ts +++ b/apps/website/src/components/workshop/ApiTab.test.ts @@ -5,21 +5,46 @@ import { describe, expect, it, vi } from 'vitest' import { buildSnippet } from '../../config/models-snippets' import { workshopContract } from '../../config/workshop-contract-catalog' +import { getRouterWorkshopModelDetail } from '../../config/workshop-router-content' +import { initialWorkshopPageState } from '../../config/workshop-page-state' import ApiTab from './ApiTab.vue' const routerId = 'bfl/flux-2-pro' const contract = workshopContract(routerId) const values = { prompt: 'a capybara', seed: 5 } -function pythonKey(text: string): string { - const key = /"Idempotency-Key": "([^"]+)"/.exec(text)?.[1] - if (!key) throw new Error('Missing key') - return key -} - describe('ApiTab', () => { - it('generates URL-upload examples without uploading or reading private files while browsing tabs', async () => { - const user = userEvent.setup() + it('reuses one file setup for repeated positions in a multi-file input', async () => { + const visitor = userEvent.setup() + const model = getRouterWorkshopModelDetail( + 'byteplus--seedream-4-5--edit-images' + ) + if (!model) throw new Error('Missing model') + const file = new File(['private'], 'reference.webp', { type: 'image/webp' }) + const value = { file, name: file.name, type: file.type, size: file.size } + render(ApiTab, { + props: { + contract: model.execution, + values: { + ...initialWorkshopPageState(model).values, + images: [value, value] + } + } + }) + const snippet = await screen.findByTestId('snippet') + expect( + snippet.textContent.match(/from_file\("reference.webp"\)/g) + ).toHaveLength(1) + expect(snippet.textContent).toMatch(/"image":\s*\[\s*url_1,\s*url_1\s*\]/) + await visitor.click(screen.getByTestId('snippet-typescript')) + expect( + snippet.textContent.match(/fromFile\("reference.webp"\)/g) + ).toHaveLength(1) + expect(snippet.textContent).toMatch(/"image":\s*\[\s*url_1,\s*url_1\s*\]/) + }) + + it('prepares SDK asset examples without uploading or reading private files while browsing tabs', async () => { + const visitor = userEvent.setup() const file = new File(['private'], 'photo.png', { type: 'image/png' }) const network = vi.fn() const read = vi.spyOn(file, 'arrayBuffer') @@ -34,59 +59,43 @@ describe('ApiTab', () => { }) const snippet = await screen.findByTestId('snippet') expect(snippet.textContent).toContain( - 'upload_file("photo.png", "image/png")' + 'client.assets.from_file("photo.png").get_download_url()' ) - expect(snippet.textContent).toContain('/customers/storage') - expect(snippet.textContent).toContain('"image": input_1') + expect(snippet.textContent).toContain('"image": url_1') expect(snippet.textContent).not.toContain('https://upload.invalid/') - await user.click(screen.getByTestId('snippet-typescript')) + await visitor.click(screen.getByTestId('snippet-typescript')) expect(snippet.textContent).toContain( - 'await uploadFile("photo.png", "image/png")' + 'client.assets.fromFile("photo.png").getDownloadUrl()' ) - await user.click(screen.getByTestId('snippet-curl')) + await visitor.click(screen.getByTestId('snippet-curl')) expect(snippet.textContent).not.toContain('"image":') - expect(snippet.textContent).not.toContain('/customers/storage') expect(snippet.textContent).toContain('This request may be incomplete') expect(network).not.toHaveBeenCalled() expect(read).not.toHaveBeenCalled() }) - it('uses one validated request and retry key across language tabs', async () => { - const user = userEvent.setup() - const network = vi.fn() - vi.stubGlobal('fetch', network) - render(ApiTab, { props: { contract, values } }) - const snippet = await screen.findByTestId('snippet') - const key = pythonKey(snippet.textContent) - expect(snippet.textContent).toBe( - buildSnippet('python', routerId, values, key) - ) - await user.click(screen.getByTestId('snippet-typescript')) - expect(snippet.textContent).toBe( - buildSnippet('typescript', routerId, values, key) - ) - await user.click(screen.getByTestId('snippet-curl')) - expect(snippet.textContent).toBe( - buildSnippet('curl', routerId, values, key) - ) - expect(network).not.toHaveBeenCalled() - }) - it('rotates the key for an edited body but not a semantically unchanged body', async () => { + it('uses the validated native parameters across language tabs and updates when the form changes', async () => { + const visitor = userEvent.setup() const { rerender } = render(ApiTab, { props: { contract, values } }) - const first = pythonKey((await screen.findByTestId('snippet')).textContent) - await rerender({ values: { ...values, unused: undefined } }) - await waitFor(() => - expect(pythonKey(screen.getByTestId('snippet').textContent)).toBe(first) + const snippet = await screen.findByTestId('snippet') + expect(snippet.textContent).toBe(buildSnippet('python', routerId, values)) + await visitor.click(screen.getByTestId('snippet-typescript')) + expect(snippet.textContent).toBe( + buildSnippet('typescript', routerId, values) ) await rerender({ values: { ...values, prompt: 'a different capybara' } }) await waitFor(() => - expect(pythonKey(screen.getByTestId('snippet').textContent)).not.toBe( - first + expect(screen.getByTestId('snippet').textContent).toContain( + 'a different capybara' ) ) + await visitor.click(screen.getByTestId('snippet-curl')) + expect(screen.getByTestId('snippet').textContent).toContain( + 'a different capybara' + ) }) - it('does not publish a request for invalid input or an unverified model mapping', async () => { + it('does not publish invalid input or an unverified model mapping', async () => { const { rerender } = render(ApiTab, { props: { contract, values: { prompt: '', width: 0 } } }) @@ -103,9 +112,11 @@ describe('ApiTab', () => { expect(screen.queryByRole('button', { name: 'Copy snippet' })).toBeNull() }) - it('loads local files in Python and TypeScript but omits them from cURL without reading upload bytes', async () => { - const user = userEvent.setup() - const file = new File(['real image'], 'image.png', { type: 'image/png' }) + it('preserves native Base64 inputs without reading local bytes into the page', async () => { + const visitor = userEvent.setup() + const file = new File(['private pixels'], 'image.png', { + type: 'image/png' + }) const read = vi.spyOn(file, 'arrayBuffer') render(ApiTab, { props: { @@ -122,58 +133,39 @@ describe('ApiTab', () => { } }) const snippet = await screen.findByTestId('snippet') - const key = pythonKey(snippet.textContent) - expect(snippet.textContent).not.toContain(btoa('real image')) expect(snippet.textContent).toContain('Path("image.png").read_bytes()') - expect(snippet.textContent).toContain('base64.b64encode') expect(snippet.textContent).toContain('input_image') - expect(snippet.textContent).not.toContain('media_image') - expect(screen.getByRole('note').textContent).toContain('local files') - await user.click(screen.getByTestId('snippet-typescript')) + expect(snippet.textContent).not.toContain(btoa('private pixels')) + await visitor.click(screen.getByTestId('snippet-typescript')) expect(snippet.textContent).toContain('readFile("image.png")') expect(snippet.textContent).toContain('.toString("base64")') - expect(snippet.textContent).toContain(key) - await user.click(screen.getByTestId('snippet-curl')) - expect(snippet.textContent).not.toContain('input_image') - expect(snippet.textContent).not.toContain('image.png') - expect(snippet.textContent).toContain('"prompt": "a capybara"') - expect(snippet.textContent).toContain('This request may be incomplete') - expect(snippet.textContent).not.toContain(key) - expect(screen.getByRole('note').textContent).toContain('omitted from cURL') - const curl = snippet.textContent - await user.click(screen.getByTestId('snippet-python')) - expect(pythonKey(snippet.textContent)).toBe(key) - await user.click(screen.getByTestId('snippet-curl')) - expect(snippet.textContent).toBe(curl) expect(read).not.toHaveBeenCalled() }) - it('keeps file references stable and rotates the key for a replacement file with identical metadata', async () => { - const first = new File(['first'], 'image.png', { - type: 'image/png', - lastModified: 123 - }) - const second = new File(['other'], first.name, { - type: first.type, - lastModified: first.lastModified - }) - function form(file: File) { - return { - ...values, - media_image: { file, name: file.name, size: file.size, type: file.type } - } + it.for([ + 'vertexai--gemini-3-pro-image--edit-images', + 'bfl--flux-2-max--generate-images' + ])( + 'uses default source URLs without fetching media to show the API example: %s', + async (slug) => { + const model = getRouterWorkshopModelDetail(slug) + if (!model) throw new Error('Missing model') + const network = vi.fn(() => + Promise.reject(new Error('API browsing must not fetch media')) + ) + vi.stubGlobal('fetch', network) + render(ApiTab, { + props: { + contract: model.execution, + values: initialWorkshopPageState(model).values + } + }) + const snippet = await screen.findByTestId('snippet') + expect(snippet.textContent).toContain( + 'https://cdn.jsdelivr.net/gh/Comfy-Org/workflow_templates@' + ) + expect(snippet.textContent).not.toContain('Path(') + expect(network).not.toHaveBeenCalled() } - const { rerender } = render(ApiTab, { - props: { contract, values: form(first) } - }) - const key = pythonKey((await screen.findByTestId('snippet')).textContent) - await rerender({ values: form(first) }) - expect(pythonKey((await screen.findByTestId('snippet')).textContent)).toBe( - key - ) - await rerender({ values: form(second) }) - expect( - pythonKey((await screen.findByTestId('snippet')).textContent) - ).not.toBe(key) - }) + ) }) diff --git a/apps/website/src/components/workshop/ApiTab.vue b/apps/website/src/components/workshop/ApiTab.vue index c95801ab487..b6d38fa9ae7 100644 --- a/apps/website/src/components/workshop/ApiTab.vue +++ b/apps/website/src/components/workshop/ApiTab.vue @@ -6,9 +6,17 @@ import { cn } from '@comfyorg/tailwind-utils' import Button from '@/components/ui/button/Button.vue' import CopyTextButton from '@/components/ui/copy-text-button/CopyTextButton.vue' import { externalLinks } from '../../config/routes' -import type { FormValues } from '../../config/workshop-playground' +import type { FileValue, FormValues } from '../../config/workshop-playground' +import { schemaForModel } from '../../config/workshop-playground' +import { formForContract } from '../../config/workshop-contract' +import { workshopExampleFile } from '../../config/workshop-example-file' +import { shouldRehostWorkshopUrl } from '../../config/workshop-url-input' import type { SnippetFile, SnippetLanguage } from '../../config/models-snippets' -import { SNIPPET_LANGUAGES, buildSnippet } from '../../config/models-snippets' +import { + SNIPPET_LANGUAGES, + buildSnippet, + hasOmittedCurlFiles +} from '../../config/models-snippets' import type { WorkshopContract } from '../../config/workshop-contract' import { prepareWorkshopRouterInput } from '../../config/workshop-request' import { WorkshopRouterError } from '../../config/workshop-router-errors' @@ -35,8 +43,6 @@ const { onKeydown: onLanguageKeydown } = useTablist( const request = ref<{ body: Readonly> files: readonly SnippetFile[] - key: string - curlKey: string }>() const fileReferences = new WeakMap< File, @@ -60,7 +66,40 @@ function referenceFor(file: File, encoding: 'base64' | 'url'): SnippetFile { return reference } const unavailable = ref(false) -let previous: { fingerprint: string; key: string; curlKey: string } | undefined + +function previewValues( + values: FormValues, + sources: WeakMap> +): FormValues { + function preview(value: FileValue): FileValue { + if (value.file && value.sourceDataUrl) + sources.set(value.file, { sourceDataUrl: value.sourceDataUrl }) + if (value.file || !value.sourceUrl) return value + const file = new File([], value.name, { type: value.type }) + sources.set(file, { sourceUrl: value.sourceUrl }) + return { ...value, file } + } + const fields = contract?.rehostUrlInputs + ? schemaForModel({ fields: [], form: formForContract(contract) }) + : [] + return Object.fromEntries( + Object.entries(values).map(([name, value]) => { + const field = fields.find((field) => field.name === name) + if (field && shouldRehostWorkshopUrl(field, value)) { + const example = workshopExampleFile(value) + if (example) return [name, preview(example)] + } + return [ + name, + Array.isArray(value) + ? value.map(preview) + : value && typeof value === 'object' + ? preview(value) + : value + ] + }) + ) +} watch( [() => contract, () => values], async (_, __, onCleanup) => { @@ -70,39 +109,40 @@ watch( unavailable.value = false try { const files: SnippetFile[] = [] + const sources = new WeakMap< + File, + Pick + >() + function addReference(file: File, encoding: 'base64' | 'url') { + const reference = referenceFor(file, encoding) + if (!files.some((entry) => entry.token === reference.token)) + files.push({ + ...reference, + ...sources.get(file), + rehost: contract?.rehostUrlInputs, + urlAlternative: + contract?.creator?.request.kind === 'callback' && + ['seedream', 'seedance', 'runway-image'].includes( + contract.creator.request.callback + ) + }) + return reference.token + } const body = await prepareWorkshopRouterInput( contract, - values, + previewValues(values, sources), controller.signal, (file, signal) => { signal.throwIfAborted() - const reference = referenceFor(file, 'base64') - if (!files.includes(reference)) files.push(reference) - return Promise.resolve(reference.token) + return Promise.resolve(addReference(file, 'base64')) }, (file, signal) => { signal.throwIfAborted() - const reference = referenceFor(file, 'url') - if (!files.includes(reference)) files.push(reference) - return Promise.resolve(reference.token) + return Promise.resolve(addReference(file, 'url')) } ) controller.signal.throwIfAborted() - const fingerprint = JSON.stringify([contract?.id, body]) - if (previous?.fingerprint !== fingerprint) { - const key = workshopIdempotencyKey() - previous = { - fingerprint, - key, - curlKey: files.length ? workshopIdempotencyKey() : key - } - } - request.value = { - body, - files, - key: previous.key, - curlKey: previous.curlKey - } + request.value = { body, files } } catch (error) { if (controller.signal.aborted) return unavailable.value = @@ -113,16 +153,29 @@ watch( ) const snippet = computed(() => request.value && contract - ? buildSnippet( - language.value, - contract.id, - request.value.body, - language.value === 'curl' ? request.value.curlKey : request.value.key, - request.value.files - ) + ? buildSnippet(language.value, contract.id, request.value.body, { + files: request.value.files, + output: + contract.output.format === 'json' || + (contract.output.format === 'auto' && + contract.output.contentTypes.includes('application/json') && + contract.output.contentTypes.every( + (type) => type.includes('json') || type === 'text/event-stream' + )) + ? 'json' + : 'binary' + }) : '' ) +const showFileNotice = computed(() => { + if (!request.value) return false + const { body, files } = request.value + return language.value === 'curl' + ? hasOmittedCurlFiles(body, files) + : files.some((file) => !file.sourceUrl && !file.sourceDataUrl) +}) + const languageLabel: Record = { python: 'Python', typescript: 'TypeScript', @@ -184,7 +237,7 @@ const languageLabel: Record = { />

diff --git a/apps/website/src/components/workshop/FeaturedBanner.test.ts b/apps/website/src/components/workshop/FeaturedBanner.test.ts index 089fd6f00ae..0db4d667d73 100644 --- a/apps/website/src/components/workshop/FeaturedBanner.test.ts +++ b/apps/website/src/components/workshop/FeaturedBanner.test.ts @@ -6,6 +6,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { WorkshopModel } from '../../config/models-catalogue' import FeaturedBanner from './FeaturedBanner.vue' +import { + setAllIntersecting, + stubIntersectionObserver +} from '../../test/fakeIntersectionObserver' const motion = vi.hoisted(() => ({ reduced: false })) @@ -40,6 +44,7 @@ const kling: WorkshopModel = { } async function advanceAutoplay(ms = AUTOPLAY_MS + RAF_MARGIN_MS) { + await setAllIntersecting(true) await vi.advanceTimersByTimeAsync(ms) await nextTick() } @@ -53,6 +58,7 @@ function setupAutoplayUser() { describe('FeaturedBanner', () => { beforeEach(() => { motion.reduced = false + stubIntersectionObserver() }) it('leads with the first model and links the whole slide to its page', () => { @@ -100,6 +106,7 @@ describe('FeaturedBanner', () => { ] } }) + await setAllIntersecting(true) expect(screen.getByTestId('featured-video').getAttribute('src')).toBe( '/video.mp4' ) @@ -153,4 +160,22 @@ describe('FeaturedBanner', () => { expect(screen.getByRole('heading', { level: 2 }).textContent).toBe('Flux') }) + + it('freezes rotation offscreen and in a hidden tab, then resumes where it stopped', async () => { + vi.useFakeTimers({ shouldAdvanceTime: false }) + render(FeaturedBanner, { props: { models: [base, kling] } }) + await setAllIntersecting(false) + await vi.advanceTimersByTimeAsync(AUTOPLAY_MS) + expect(screen.getByRole('heading', { level: 2 }).textContent).toBe('Flux') + await setAllIntersecting(true) + vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden') + document.dispatchEvent(new Event('visibilitychange')) + await nextTick() + await vi.advanceTimersByTimeAsync(AUTOPLAY_MS) + expect(screen.getByRole('heading', { level: 2 }).textContent).toBe('Flux') + vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') + document.dispatchEvent(new Event('visibilitychange')) + await advanceAutoplay() + expect(screen.getByRole('heading', { level: 2 }).textContent).toBe('Kling') + }) }) diff --git a/apps/website/src/components/workshop/FeaturedBanner.vue b/apps/website/src/components/workshop/FeaturedBanner.vue index 5fe5adfa8b5..ff9dffb82a3 100644 --- a/apps/website/src/components/workshop/FeaturedBanner.vue +++ b/apps/website/src/components/workshop/FeaturedBanner.vue @@ -1,9 +1,16 @@