diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index 38cc97a14d7..8b673d838db 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -31,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_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..278078432b0 --- /dev/null +++ b/apps/website/e2e/models-catalogue-corrections.spec.ts @@ -0,0 +1,24 @@ +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 +}) => { + await page.goto('/models/?useCase=generate-images') + 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-sign-in-draft.spec.ts b/apps/website/e2e/models-sign-in-draft.spec.ts new file mode 100644 index 00000000000..b26f9f09150 --- /dev/null +++ b/apps/website/e2e/models-sign-in-draft.spec.ts @@ -0,0 +1,141 @@ +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 of ['playground', 'header']) { + test(`selected reference bytes survive ${entry} sign-in and reach Router`, async ({ + page, + modelsAccount + }) => { + 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}$`)) + 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..0e57d2a6fb4 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:", @@ -79,6 +80,7 @@ "@vitejs/plugin-vue": "catalog:", "astro": "catalog:", "happy-dom": "catalog:", + "mime-types": "catalog:", "tailwindcss": "catalog:", "tsx": "catalog:", "tw-animate-css": "catalog:", 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/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..9d5545760b2 100644 --- a/apps/website/src/components/workshop/ApiTab.test.ts +++ b/apps/website/src/components/workshop/ApiTab.test.ts @@ -5,21 +5,17 @@ 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('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 +30,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 +83,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 +104,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/HeaderAccount.test.ts b/apps/website/src/components/workshop/HeaderAccount.test.ts index e7738f89455..ae759500bca 100644 --- a/apps/website/src/components/workshop/HeaderAccount.test.ts +++ b/apps/website/src/components/workshop/HeaderAccount.test.ts @@ -217,6 +217,38 @@ describe('HeaderAccount sign-in link', () => { ) }) + it('waits for an asynchronous file stash before navigating', async () => { + const assign = vi.fn() + vi.spyOn(window.location, 'assign').mockImplementation(assign) + const saved = Promise.withResolvers() + const stop = onBeforeSignInLeave(() => saved.promise) + onTestFinished(stop) + render(HeaderAccount) + await userEvent + .setup() + .click(screen.getByRole('link', { name: /sign in/i })) + expect(assign).not.toHaveBeenCalled() + saved.resolve() + await vi.waitFor(() => expect(assign).toHaveBeenCalledOnce()) + }) + + it('does not redirect a departed page after its file stash settles', async () => { + const assign = vi.fn() + vi.spyOn(window.location, 'assign').mockImplementation(assign) + const saved = Promise.withResolvers() + const stop = onBeforeSignInLeave(() => saved.promise) + onTestFinished(stop) + render(HeaderAccount) + await userEvent + .setup() + .click(screen.getByRole('link', { name: /sign in/i })) + window.dispatchEvent(new Event('pagehide')) + saved.resolve() + await saved.promise + await Promise.resolve() + expect(assign).not.toHaveBeenCalled() + }) + it('sends the visitor to sign in with the current page as the return destination', async () => { const assign = vi.fn() vi.spyOn(window.location, 'assign').mockImplementation(assign) diff --git a/apps/website/src/components/workshop/HeaderAccount.vue b/apps/website/src/components/workshop/HeaderAccount.vue index 291c5000dd8..bdcb4383fd4 100644 --- a/apps/website/src/components/workshop/HeaderAccount.vue +++ b/apps/website/src/components/workshop/HeaderAccount.vue @@ -4,7 +4,7 @@ import { computed, ref, useTemplateRef } from 'vue' import { useWorkshopCredits } from '../../config/workshop-credits' import { WORKSHOP_CREDITS_URL } from '../../config/workshop-env' -import { runBeforeSignInLeave } from '../../config/workshop-return' +import { leaveForSignIn } from '../../config/workshop-return' import { useWorkshopSession } from '../../config/workshop-session-state' import type { Locale } from '../../i18n/translations' import { t } from '../../i18n/translations' @@ -38,12 +38,8 @@ function prepareSignInHref(): void { signInHref.value = signInDestination() } -function goToSignIn(event: MouseEvent): void { - runBeforeSignInLeave() - if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) - return - event.preventDefault() - window.location.assign(signInDestination()) +async function goToSignIn(event: MouseEvent): Promise { + await leaveForSignIn(event, signInDestination()) } const menuOpen = ref(false) diff --git a/apps/website/src/components/workshop/ModelDetail.test.ts b/apps/website/src/components/workshop/ModelDetail.test.ts index 4760e851f44..1e53654fd28 100644 --- a/apps/website/src/components/workshop/ModelDetail.test.ts +++ b/apps/website/src/components/workshop/ModelDetail.test.ts @@ -821,7 +821,7 @@ describe('ModelDetail', () => { } } ])( - 'requires sign-in before selecting a local $kind upload while retaining the example and text draft', + 'allows a signed-out visitor to select a local $kind upload while keeping Run gated', async (field) => { const mediaModel: WorkshopModelDetail = { ...runnable, @@ -835,17 +835,18 @@ describe('ModelDetail', () => { const input = screen.getByLabelText('Image', { selector: 'input[type="file"]' }) - expect(input).toHaveProperty('disabled', true) + expect(input).toHaveProperty('disabled', false) expect(screen.getByRole('img', { name: 'example.png' })).toBeTruthy() - expect(screen.getByText(/Sign in before uploading files/)).toBeTruthy() await visitor.type( screen.getByRole('textbox', { name: /Prompt/ }), 'My image idea' ) await visitor.upload(input, file) expect( - screen.queryByRole('button', { name: 'Replace local.png' }) - ).toBeNull() + screen.getByRole('button', { name: 'Replace local.png' }) + ).toBeTruthy() + expect(screen.getByRole('link', { name: 'Sign in to run' })).toBeTruthy() + expect(runWorkshopRouter).not.toHaveBeenCalled() unmount() auth.session.value = credential @@ -864,7 +865,6 @@ describe('ModelDetail', () => { expect( screen.getByRole('button', { name: 'Replace local.png' }) ).toBeTruthy() - expect(screen.queryByText(/Sign in before uploading files/)).toBeNull() expect(runWorkshopRouter).not.toHaveBeenCalled() } ) diff --git a/apps/website/src/components/workshop/ModelDetail.vue b/apps/website/src/components/workshop/ModelDetail.vue index 9ad82502aa6..03c71792bb2 100644 --- a/apps/website/src/components/workshop/ModelDetail.vue +++ b/apps/website/src/components/workshop/ModelDetail.vue @@ -1,11 +1,13 @@