From af6c212a91e9697b3d2a9dfb5c22230d75e3b68b Mon Sep 17 00:00:00 2001 From: benjcooley Date: Sun, 13 Sep 2026 11:14:02 -0700 Subject: [PATCH 1/2] fix(website): execute model examples through the published SDKs --- .fallowrc.jsonc | 4 +- apps/website/MODELS_INPUT_SCHEMA.md | 20 +- apps/website/package.json | 2 + .../workshop/ApiTab.execution.test.ts | 82 +++ .../src/components/workshop/ApiTab.test.ts | 147 ++--- .../src/components/workshop/ApiTab.vue | 118 ++-- .../src/config/models-snippets.test.ts | 542 ++++++++---------- apps/website/src/config/models-snippets.ts | 482 ++++++++++++---- .../src/config/workshop-upload-snippets.ts | 68 --- apps/website/src/config/workshop-url-input.ts | 19 +- knip.config.ts | 4 +- pnpm-lock.yaml | 47 ++ pnpm-workspace.yaml | 4 +- 13 files changed, 913 insertions(+), 626 deletions(-) create mode 100644 apps/website/src/components/workshop/ApiTab.execution.test.ts delete mode 100644 apps/website/src/config/workshop-upload-snippets.ts 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_INPUT_SCHEMA.md b/apps/website/MODELS_INPUT_SCHEMA.md index 62153d47df8..563d92b1b92 100644 --- a/apps/website/MODELS_INPUT_SCHEMA.md +++ b/apps/website/MODELS_INPUT_SCHEMA.md @@ -332,11 +332,21 @@ 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. +- 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 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/src/components/workshop/ApiTab.execution.test.ts b/apps/website/src/components/workshop/ApiTab.execution.test.ts new file mode 100644 index 00000000000..dc643658802 --- /dev/null +++ b/apps/website/src/components/workshop/ApiTab.execution.test.ts @@ -0,0 +1,82 @@ +// @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 ApiTab from './ApiTab.vue' + +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..182498bf7a3 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,38 @@ 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.sourceUrl) return value + const file = new File([], value.name, { type: value.type }) + sources.set(file, 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 +107,37 @@ watch( unavailable.value = false try { const files: SnippetFile[] = [] + const sources = new WeakMap() + function addReference(file: File, encoding: 'base64' | 'url') { + const reference = referenceFor(file, encoding) + if (!files.some((entry) => entry.token === reference.token)) + files.push({ + ...reference, + sourceUrl: 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 +148,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) +}) + const languageLabel: Record = { python: 'Python', typescript: 'TypeScript', @@ -184,7 +232,7 @@ const languageLabel: Record = { />

diff --git a/apps/website/src/config/models-snippets.test.ts b/apps/website/src/config/models-snippets.test.ts index 8b8e6e5013e..f0996502847 100644 --- a/apps/website/src/config/models-snippets.test.ts +++ b/apps/website/src/config/models-snippets.test.ts @@ -1,351 +1,281 @@ import { execFileSync, spawnSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Asset } from '@comfyorg/sdk/low' import { afterEach, describe, expect, it } from 'vitest' import { buildSnippet } from './models-snippets' import type { SnippetFile } from './models-snippets' -import { workshopContract } from './workshop-contract-catalog' const id = 'bfl/flux-2-pro' -const key = 'one-intent-one-key' const body = { - prompt: - "It's a 🌻; $(exit 1) " + - String.fromCharCode(96) + - 'exit 1' + - String.fromCharCode(96), - prompt_upsampling: false, + prompt: 'A 🌻; $(exit 1) `exit 1`', nested: [true, null, { quote: '\\n' }] } +const directories: string[] = [] +const image = readFileSync( + fileURLToPath( + new URL('../../e2e/assets/placeholder-1x1.webp', import.meta.url) + ) +) -describe('buildSnippet', () => { - it('round-trips the exact Python request body without confusing JSON and Python literals', () => { - const snippet = buildSnippet('python', id, body, key) - const result = execFileSync( - 'python3', - [ - '-c', - 'import ast,json,sys\nm=ast.parse(sys.stdin.read())\nc=next(n for n in ast.walk(m) if isinstance(n,ast.Call) and isinstance(n.func,ast.Attribute) and n.func.attr=="loads")\nprint(json.dumps(json.loads(ast.literal_eval(c.args[0]))))' - ], - { input: snippet, encoding: 'utf8' } - ) - expect(JSON.parse(result)).toEqual(body) - expect(snippet).toContain(key) - expect(snippet).toContain('timeout=660') - }) - - it('sends the exact cURL payload and a stable nonempty key on repeated execution', () => { - const snippet = buildSnippet('curl', id, body, key) - const capture = 'curl() { printf \'%s\\0\' "$@"; }\n' - for (let attempt = 0; attempt < 2; attempt++) { - const args = execFileSync('bash', ['-c', capture + snippet], { - encoding: 'utf8' - }).split('\0') - expect(JSON.parse(args[args.indexOf('--data') + 1])).toEqual(body) - expect(args).toContain('Idempotency-Key: ' + key) - expect(args).toContain('https://stagingapi.comfy.org/v2/models/' + id) - } - }) - - it('prints responses and error bodies for an actual JSON contract', () => { - const contract = workshopContract('bfl/flux-2-pro') - if (!contract) throw new Error('Missing JSON contract') - expect(contract.output.format).toBe('json') - - const snippet = buildSnippet('curl', contract.id, body, key) - const args = execFileSync( - 'bash', - ['-c', 'curl() { printf \'%s\\0\' "$@"; }\n' + snippet], - { encoding: 'utf8' } - ).split('\0') +function directory() { + const path = mkdtempSync(join(tmpdir(), 'models-sdk-snippets-')) + directories.push(path) + symlinkSync( + fileURLToPath(new URL('../../node_modules', import.meta.url)), + join(path, 'node_modules'), + 'dir' + ) + return path +} - expect(args).not.toContain('--output') - expect(snippet).toContain('save a binary response') - }) +afterEach(() => { + for (const path of directories.splice(0)) + rmSync(path, { recursive: true, force: true }) +}) - it('keeps a binary-capable contract visible and explains how to save it', () => { - const contract = workshopContract('elevenlabs/eleven_sfx_v2') - if (!contract) throw new Error('Missing binary-capable contract') - expect(contract.output).toMatchObject({ - format: 'auto', - contentTypes: ['*/*'] - }) +const asset: Asset = { + id: 'asset-1', + hash: null, + size_bytes: 0, + content_type: 'image/webp', + created_at: '2026-09-13T00:00:00Z', + url: 'https://storage.example/unused', + url_expires_at: '2026-09-14T00:00:00Z' +} - const snippet = buildSnippet('curl', contract.id, body, key) - const args = execFileSync( - 'bash', - ['-c', 'curl() { printf \'%s\\0\' "$@"; }\n' + snippet], - { encoding: 'utf8' } - ).split('\0') +const transport = ` +const runs = [], uploads = [] +globalThis.fetch = async (target, init = {}) => { + const url = new URL(target) + const headers = new Headers(init.headers) + if (url.pathname.startsWith('/v2/models/')) { + runs.push({ body: JSON.parse(init.body), key: headers.get('Idempotency-Key'), url: url.href }) + if (process.env.RETRY && runs.length === 1) return Response.json({ detail: 'Provider temporarily unavailable', error_type: 'provider_error' }, { status: 503, headers: { 'X-Comfy-Error-Type': 'provider_error' } }) + if (process.env.BINARY) return new Response(new Uint8Array([0, 255, 1]), { headers: { 'Content-Type': 'audio/mpeg' } }) + return Response.json({ images: [{ url: 'https://result.example/output.webp' }] }, { headers: { 'X-Comfy-Request-Id': 'request-1' } }) + } + if (url.pathname.startsWith('/api/v2/assets/by-hash/')) return new Response(null, { status: 404 }) + if (url.pathname === '/api/v2/assets' && init.method === 'POST') { + if (process.env.FAIL_UPLOAD) return Response.json({ error: 'forbidden' }, { status: 403 }) + const file = init.body.get('file') + if (!(file instanceof Blob)) throw new Error('Missing SDK multipart file') + uploads.push({ bytes: [...new Uint8Array(await file.arrayBuffer())], type: init.body.get('content_type'), path: init.body.get('file_path') }) + return Response.json({ ...${JSON.stringify(asset)}, id: 'asset-' + uploads.length, hash: init.body.get('expected_hash'), size_bytes: file.size, content_type: file.type }, { status: 201 }) + } + if (url.pathname.endsWith('/content')) return new Response(null, { status: 302, headers: { Location: 'https://storage.example/' + url.pathname.split('/').at(-2) } }) + if (url.href === 'https://source.example/input.png') { + if (headers.has('Authorization') || headers.has('X-API-Key')) throw new Error('Credential leaked to input host') + return new Response(new Uint8Array([0, 42, 255]), { headers: { 'Content-Type': 'image/webp' } }) + } + throw new Error('Unexpected network request: ' + url.href) +} +console.log = () => process.stdout.write(JSON.stringify({ runs, uploads })) +` - expect(args).not.toContain('--output') - expect(snippet).toContain('save a binary response') +function execute( + snippet: string, + cwd = directory(), + env: Record = {} +) { + return execFileSync(process.execPath, ['--input-type=module', '-'], { + cwd, + input: transport + snippet, + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + timeout: 8000, + env: { PATH: process.env.PATH, COMFY_API_KEY: 'test-key', ...env } }) +} - it('executes TypeScript with the same body and no invented model or output envelope', () => { - const snippet = buildSnippet('typescript', id, body, key) - const capture = - 'globalThis.fetch = async (url, init) => { process.stdout.write(init.body); return Response.json({}) }; console.log=()=>{};\n' - const result = execFileSync( - process.execPath, - ['--input-type=module', '-'], - { - input: capture + snippet, - encoding: 'utf8', - env: { COMFY_API_KEY: 'test-key', PATH: process.env.PATH } - } +describe('SDK snippets', () => { + it('executes through the released SDK, preserving native JSON and minting a fresh key per execution', () => { + const snippet = buildSnippet('typescript', id, body) + const first = JSON.parse(execute(snippet)) + const second = JSON.parse(execute(snippet)) + expect(first.runs[0].body).toEqual(body) + expect(first.runs[0].url).toBe( + 'https://stagingapi.comfy.org/v2/models/' + id ) - expect(JSON.parse(result)).toEqual(body) - expect(snippet).toContain(key) + expect(first.runs[0].key).toMatch(/^[\da-f-]{36}$/i) + expect(second.runs[0].key).not.toBe(first.runs[0].key) + const retry = JSON.parse(execute(snippet, directory(), { RETRY: '1' })) + expect(retry.runs).toHaveLength(2) + expect(retry.runs[1]).toEqual(retry.runs[0]) }) -}) -describe('local files in snippets', () => { - const temporaryDirectories: string[] = [] - afterEach(() => { - for (const directory of temporaryDirectories.splice(0)) - rmSync(directory, { recursive: true, force: true }) - }) - const files: SnippetFile[] = [ - { token: 'file-token-1', name: 'input.png', mimeType: 'image/png' }, - { token: 'file-token-2', name: 'input.png', mimeType: 'image/jpeg' } - ] - const bytes = [Buffer.from([0, 255, 34, 92]), Buffer.from([255, 0, 13, 10])] - const payload = { - ...body, - unchanged: bytes[0].toString('base64'), - input_image: files[0].token, - contents: [ + it('uploads URL-capable inputs through SDK assets, retaining bytes and deriving inline MIME from the supplied path', () => { + const cwd = directory() + const files: SnippetFile[] = [ { - role: 'user', - parts: [ - { text: body.prompt }, - { inlineData: { data: files[0].token, mimeType: 'image/png' } } - ] - } - ], - content: [ - { type: 'text', text: body.prompt }, + token: 'first', + name: 'first.webp', + mimeType: 'image/webp', + encoding: 'base64', + urlAlternative: true + }, { - type: 'image_url', - role: 'first_frame', - image_url: { url: `data:image/jpeg;base64,${files[1].token}` } - } - ], - instances: [ + token: 'https://upload.invalid/second', + name: 'second.webp', + mimeType: 'image/webp', + encoding: 'url' + }, { - prompt: body.prompt, - image: { bytesBase64Encoded: files[0].token, mimeType: 'image/png' } + token: 'third', + name: 'third.webp', + mimeType: 'image/png', + encoding: 'base64' } ] - } - - it.for(['python', 'typescript'] as const)( - '%s reads distinct local files and reproduces the native body, including raw Base64 and data URLs', - (language) => { - const directory = mkdtempSync(join(tmpdir(), 'models-snippets-')) - temporaryDirectories.push(directory) - writeFileSync(join(directory, 'input_1-input.png'), bytes[0]) - writeFileSync(join(directory, 'input_2-input.png'), bytes[1]) - const snippet = buildSnippet(language, id, payload, key, files) - const capture = - language === 'python' - ? 'import json,sys,types\ndef post(url, **kwargs):\n print(json.dumps(kwargs["json"]))\n raise SystemExit(0)\nsys.modules["requests"]=types.SimpleNamespace(post=post)\n' - : 'globalThis.fetch = async (url, init) => { process.stdout.write(init.body); return Response.json({}) }; console.log=()=>{};\n' - const result = execFileSync( - language === 'python' ? 'python3' : process.execPath, - language === 'python' ? ['-'] : ['--input-type=module', '-'], - { - cwd: directory, - input: capture + snippet, - encoding: 'utf8', - env: { COMFY_API_KEY: 'test-key', PATH: process.env.PATH } - } - ) - const expected = JSON.parse( - JSON.stringify(payload) - .replaceAll(files[0].token, bytes[0].toString('base64')) - .replaceAll(files[1].token, bytes[1].toString('base64')) - ) - expect(JSON.parse(result)).toEqual(expected) - expect(snippet).not.toContain(files[0].token) - expect(snippet).not.toContain(files[1].token) - expect(snippet).toContain(key) + for (const file of files) writeFileSync(join(cwd, file.name), image) + const payload = { + image: ['data:image/webp;base64,first', files[1].token], + nested: { data: 'third', mimeType: 'image/png' }, + prompt: body.prompt } - ) + const snippet = buildSnippet('typescript', id, payload, { files }) + const result = JSON.parse(execute(snippet, cwd)) + expect(result.runs[0].body).toEqual({ + image: [ + 'https://storage.example/asset-1', + 'https://storage.example/asset-2' + ], + nested: { data: image.toString('base64'), mimeType: 'image/webp' }, + prompt: body.prompt + }) + expect(result.uploads).toEqual([ + { path: 'first.webp', bytes: [...image], type: 'image/webp' }, + { path: 'second.webp', bytes: [...image], type: 'image/webp' } + ]) + const failed = spawnSync(process.execPath, ['--input-type=module', '-'], { + cwd, + input: transport + snippet, + encoding: 'utf8', + timeout: 8000, + env: { + PATH: process.env.PATH, + COMFY_API_KEY: 'test-key', + FAIL_UPLOAD: '1' + } + }) + expect(failed.status).not.toBe(0) + expect(failed.stdout).toBe('') + expect(failed.stderr).not.toContain('test-key') + }) - it('removes whole nested image parts from cURL, preserves ordinary fields and URLs, and copies the warning', () => { - const snippet = buildSnippet( - 'curl', - id, + it('keeps default reference URLs runnable without local files and downloads only native inline inputs', () => { + const files: SnippetFile[] = [ { - ...payload, - source_url: 'https://example.com/image.png', - images: [files[0].token, files[1].token], - empty: [] + token: 'reference', + name: 'absent.webp', + mimeType: 'image/webp', + sourceUrl: 'https://source.example/reference.webp', + urlAlternative: true }, - key, - files - ) - const args = execFileSync( - 'bash', - ['-c', 'curl() { printf \'%s\\0\' "$@"; }\n' + snippet], { - encoding: 'utf8' + token: 'inline', + name: 'input.png', + mimeType: 'image/png', + sourceUrl: 'https://source.example/input.png' } - ).split('\0') - expect(JSON.parse(args[args.indexOf('--data') + 1])).toEqual({ - ...body, - unchanged: bytes[0].toString('base64'), - contents: [{ role: 'user', parts: [{ text: body.prompt }] }], - content: [{ type: 'text', text: body.prompt }], - instances: [{ prompt: body.prompt }], - source_url: 'https://example.com/image.png', - empty: [] - }) - expect(snippet).not.toContain(files[0].token) - expect(snippet).not.toContain('base64,') - expect(snippet).toContain('This request may be incomplete') - }) - - it('keeps a root-level model type when the uploaded image is its only other input', () => { + ] const snippet = buildSnippet( - 'curl', + 'typescript', id, { - type: 'image-edit', - input_image: files[0].token + image: 'data:image/webp;base64,reference', + inline: { data: 'inline', mimeType: 'image/png' } }, - key, - files + { files } ) - const args = execFileSync( - 'bash', - ['-c', 'curl() { printf \'%s\\0\' "$@"; }\n' + snippet], - { - encoding: 'utf8' + const result = JSON.parse(execute(snippet)) + expect(result.runs[0].body).toEqual({ + image: 'https://source.example/reference.webp', + inline: { + data: Buffer.from([0, 42, 255]).toString('base64'), + mimeType: 'image/webp' } - ).split('\0') - expect(JSON.parse(args[args.indexOf('--data') + 1])).toEqual({ - type: 'image-edit' }) + expect(result.uploads).toEqual([]) }) - it.for(['python', 'typescript'] as const)( - '%s uploads distinct URL files, keeps Base64 separate and stops before generation on a failed upload', - (language) => { - const directory = mkdtempSync(join(tmpdir(), 'models-url-snippets-')) - temporaryDirectories.push(directory) - const references: SnippetFile[] = [ - { - token: 'https://upload.invalid/first', - name: 'first.png', - mimeType: 'image/png', - encoding: 'url' - }, - { - token: 'https://upload.invalid/second', - name: 'second.jpg', - mimeType: 'image/jpeg', - encoding: 'url' - }, - { - token: 'BASE64_TOKEN', - name: 'third.png', - mimeType: 'image/png', - encoding: 'base64' - } - ] - writeFileSync(join(directory, 'first.png'), bytes[0]) - writeFileSync(join(directory, 'second.jpg'), bytes[1]) - writeFileSync(join(directory, 'third.png'), bytes[0]) - const request = { - images: [references[0].token, references[1].token], - nested: { data: references[2].token }, - prompt: body.prompt + it('rehosts a default URL through SDK assets when the native mapping requires a new URL', () => { + const files: SnippetFile[] = [ + { + token: 'url', + name: 'input.png', + mimeType: 'image/png', + encoding: 'url', + sourceUrl: 'https://source.example/input.png', + rehost: true } - const snippet = buildSnippet(language, id, request, key, references) - const capture = - language === 'python' - ? [ - 'import json, sys, types, os', - 'grants, uploads = [], []', - 'def post(url, **kwargs):', - ' if url.endswith("/customers/storage"):', - ' assert kwargs["headers"]["Authorization"] == "Bearer test-key"', - ' assert kwargs["allow_redirects"] is False', - ' grants.append(kwargs["json"])', - ' i = len(grants)', - ' return types.SimpleNamespace(status_code=200, json=lambda: {"upload_url": "https://storage.example/upload/"+str(i), "download_url": "https://storage.example/download/"+str(i)})', - ' print(json.dumps({"body": kwargs["json"], "key": kwargs["headers"]["Idempotency-Key"], "grants": grants, "uploads": uploads}))', - ' raise SystemExit(0)', - 'def put(url, **kwargs):', - ' assert "Authorization" not in kwargs["headers"]', - ' assert kwargs["allow_redirects"] is False', - ' uploads.append({"url": url, "bytes": list(kwargs["data"].read()), "type": kwargs["headers"]["Content-Type"]})', - ' return types.SimpleNamespace(status_code=403 if os.environ.get("FAIL_UPLOAD") else 200)', - 'sys.modules["requests"] = types.SimpleNamespace(post=post, put=put)', - '' - ].join('\n') - : [ - 'const grants = [], uploads = []; console.log = () => {}', - 'globalThis.fetch = async (url, init) => {', - ' if (url.endsWith("/customers/storage")) {', - ' if (init.headers.Authorization !== "Bearer test-key" || init.redirect !== "error") throw new Error("Invalid grant headers")', - ' grants.push(JSON.parse(init.body))', - ' return Response.json({ upload_url: `https://storage.example/upload/${grants.length}`, download_url: `https://storage.example/download/${grants.length}` })', - ' }', - ' if (init.method === "PUT") {', - ' if (init.headers.Authorization || init.credentials !== "omit" || init.redirect !== "error") throw new Error("Leaked credential")', - ' uploads.push({url, bytes: [...init.body], type: init.headers["Content-Type"]})', - ' return new Response(null, {status: process.env.FAIL_UPLOAD ? 403 : 200})', - ' }', - ' process.stdout.write(JSON.stringify({body: JSON.parse(init.body), key: init.headers["Idempotency-Key"], grants, uploads}))', - ' return Response.json({})', - '}', - '' - ].join('\n') - const program = language === 'python' ? 'python3' : process.execPath - const args = - language === 'python' ? ['-'] : ['--input-type=module-typescript', '-'] - const options = { - cwd: directory, - input: capture + snippet, - encoding: 'utf8' as const, - env: { COMFY_API_KEY: 'test-key', PATH: process.env.PATH } + ] + const result = JSON.parse( + execute(buildSnippet('typescript', id, { image: 'url' }, { files })) + ) + expect(result.runs[0].body).toEqual({ + image: 'https://storage.example/asset-1' + }) + expect(result.uploads[0]).toMatchObject({ + bytes: [0, 42, 255], + type: 'image/webp' + }) + }) + + it('fails on a missing key before accessing local inputs or sending requests', () => { + const files: SnippetFile[] = [ + { + token: 'image', + name: 'missing.png', + mimeType: 'image/png', + encoding: 'url' } - const result = JSON.parse(execFileSync(program, args, options)) - expect(result.body).toEqual({ - ...request, - images: [ - 'https://storage.example/download/1', - 'https://storage.example/download/2' - ], - nested: { data: bytes[0].toString('base64') } - }) - expect(result.key).toBe(key) - expect(result.uploads).toEqual([ - { - url: 'https://storage.example/upload/1', - bytes: [...bytes[0]], - type: 'image/png' - }, - { - url: 'https://storage.example/upload/2', - bytes: [...bytes[1]], - type: 'image/jpeg' - } - ]) - expect(result.grants[0].file_name).not.toBe(result.grants[1].file_name) - const failed = spawnSync(program, args, { - ...options, - env: { ...options.env, FAIL_UPLOAD: '1' } - }) - expect(failed.status).not.toBe(0) - expect(failed.stdout).toBe('') - expect(failed.stderr).toContain('Upload failed') - } - ) + ] + expect(() => + execute( + buildSnippet('typescript', id, { image: 'image' }, { files }), + directory(), + { COMFY_API_KEY: ' ' } + ) + ).toThrow('Set COMFY_API_KEY') + }) + + it('preserves binary output for endpoints unsupported by models.run', () => { + const cwd = directory() + execute( + buildSnippet( + 'typescript', + 'elevenlabs/eleven_v3', + { text: 'Hello' }, + { output: 'binary' } + ), + cwd, + { BINARY: '1' } + ) + expect(readFileSync(join(cwd, 'output.bin'))).toEqual( + Buffer.from([0, 255, 1]) + ) + }) + + it('renders valid Python literals and passes the exact native arguments to the asynchronous SDK call', () => { + const snippet = buildSnippet('python', id, body) + const parsed = execFileSync( + 'python3', + [ + '-c', + 'import ast,json,sys\nm=ast.parse(sys.stdin.read())\na=next(n for n in ast.walk(m) if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=="parameters" for t in n.targets))\nc=next(n for n in ast.walk(m) if isinstance(n,ast.Await) and isinstance(n.value,ast.Call) and isinstance(n.value.func,ast.Attribute) and n.value.func.attr=="run")\nprint(json.dumps([ast.literal_eval(a.value),ast.literal_eval(c.value.args[0]),c.value.args[1].id]))' + ], + { input: snippet, encoding: 'utf8' } + ) + expect(JSON.parse(parsed)).toEqual([body, id, 'parameters']) + }) }) diff --git a/apps/website/src/config/models-snippets.ts b/apps/website/src/config/models-snippets.ts index 26a83a49868..e35019a6f5e 100644 --- a/apps/website/src/config/models-snippets.ts +++ b/apps/website/src/config/models-snippets.ts @@ -1,5 +1,7 @@ -import { WORKSHOP_ROUTER_BASE_URL } from './workshop-env' -import { uploadSnippet } from './workshop-upload-snippets' +import { + WORKSHOP_CLOUD_BASE_URL, + WORKSHOP_ROUTER_BASE_URL +} from './workshop-env' export type SnippetLanguage = 'python' | 'typescript' | 'curl' @@ -14,13 +16,18 @@ export interface SnippetFile { readonly name: string readonly mimeType: string readonly encoding?: 'base64' | 'url' + readonly sourceUrl?: string + readonly rehost?: boolean + readonly urlAlternative?: boolean } function fileReference(value: unknown, files: readonly SnippetFile[]) { for (const [index, file] of files.entries()) { - if (value === file.token) return { index, prefix: '' } + if (value === file.token) + return { index, kind: file.encoding === 'url' ? 'url' : 'base64' } const prefix = `data:${file.mimeType};base64,` - if (value === prefix + file.token) return { index, prefix } + if (value === prefix + file.token) + return { index, kind: file.urlAlternative ? 'url' : 'data-url' } } return undefined } @@ -32,8 +39,9 @@ function renderInput( depth = 0 ): string { const file = fileReference(value, files) - if (file) - return `${file.prefix ? JSON.stringify(file.prefix) + ' + ' : ''}input_${file.index + 1}` + if (file?.kind === 'data-url') + return `"data:" + mime_${file.index + 1} + ";base64," + input_${file.index + 1}` + if (file) return `${file.kind === 'url' ? 'url' : 'input'}_${file.index + 1}` if (value === null) return language === 'python' ? 'None' : 'null' if (typeof value === 'boolean' && language === 'python') return value ? 'True' : 'False' @@ -49,7 +57,12 @@ function renderInput( language === 'typescript' && key === '__proto__' ? `[${quoted}]` : quoted - return `${property}: ${renderInput(child, language, files, depth + 1)}` + const mime = mimeFile(value, files) + const rendered = + mime !== undefined && (key === 'mimeType' || key === 'mime_type') + ? `mime_${mime + 1}` + : renderInput(child, language, files, depth + 1) + return `${property}: ${rendered}` }) const [open, close] = array ? ['[', ']'] : ['{', '}'] return entries.length @@ -70,7 +83,11 @@ function omitFiles( files: readonly SnippetFile[], root = false ): unknown { - if (fileReference(value, files)) return undefined + const reference = fileReference(value, files) + if (reference) { + const file = files[reference.index] + return reference.kind === 'url' && !file.rehost ? file.sourceUrl : undefined + } if (value === null || typeof value !== 'object') return value if (Array.isArray(value)) { const kept = value @@ -100,122 +117,365 @@ function filePaths(files: readonly SnippetFile[]): string[] { ) } -export function buildSnippet( - language: SnippetLanguage, - routerId: string, +function mimeFile(value: object, files: readonly SnippetFile[]) { + const entries = Object.entries(value) + const index = files.findIndex( + (file) => + file.encoding !== 'url' && + entries.some(([, child]) => child === file.token) && + entries.some( + ([key, child]) => + (key === 'mimeType' || key === 'mime_type') && child === file.mimeType + ) + ) + return index < 0 ? undefined : index +} + +function fileUses(body: unknown, files: readonly SnippetFile[]) { + const uses = files.map(() => ({ base64: false, url: false, mime: false })) + function visit(value: unknown) { + const file = fileReference(value, files) + if (file) { + if (file.kind === 'url') uses[file.index].url = true + else uses[file.index].base64 = true + if (file.kind === 'data-url') uses[file.index].mime = true + } + if (!value || typeof value !== 'object') return + const mime = mimeFile(value, files) + if (mime !== undefined) uses[mime].mime = true + Object.values(value).forEach(visit) + } + visit(body) + return uses +} + +export function hasOmittedCurlFiles( body: Readonly>, - idempotencyKey: string, - files: readonly SnippetFile[] = [] -): string { - const endpoint = `${WORKSHOP_ROUTER_BASE_URL}/v2/models/${routerId.split('/').map(encodeURIComponent).join('/')}` - const json = JSON.stringify(body, null, 2) - const key = JSON.stringify(idempotencyKey) - if (!idempotencyKey) throw new Error('Missing idempotency key') + files: readonly SnippetFile[] +): boolean { + return fileUses(body, files).some( + (use, index) => + use.base64 || + (use.url && (!files[index].sourceUrl || files[index].rehost)) + ) +} + +interface SnippetOptions { + readonly files?: readonly SnippetFile[] + readonly output?: 'json' | 'binary' +} + +type FileUse = ReturnType[number] +interface InputFile extends SnippetFile, FileUse { + readonly path: string + readonly index: number +} + +function inputFiles(body: unknown, files: readonly SnippetFile[]): InputFile[] { + const uses = fileUses(body, files) const paths = filePaths(files) - const hasUploads = files.some((file) => file.encoding === 'url') - if (language === 'python') { + return files.map((file, index) => ({ + ...file, + ...uses[index], + path: paths[index], + index: index + 1 + })) +} + +function pythonFileUrl(file: InputFile): string[] { + const { index: n, sourceUrl, path, rehost } = file + if (!sourceUrl) return [ - ...(files.length ? ['import base64', 'from pathlib import Path'] : []), - ...(!files.length ? ['import json'] : []), - 'import os', - 'import requests', - '', - ...(hasUploads ? uploadSnippet('python') : []), - ...(files.length - ? [ - '# Set these paths to your local input files.', - ...paths.map( - (path, index) => - `input_${index + 1} = ${ - files[index].encoding === 'url' - ? `upload_file(${JSON.stringify(path)}, ${JSON.stringify(files[index].mimeType || 'application/octet-stream')})` - : `base64.b64encode(Path(${JSON.stringify(path)}).read_bytes()).decode("ascii")` - }` - ), - '' - ] - : []), - ...(hasUploads - ? [ - '# For retries, reuse these prepared inputs and the same key; do not rerun uploads.' - ] - : []), - `response = requests.post(${JSON.stringify(endpoint)},`, - ' headers={', - ' "X-API-Key": os.environ["COMFY_API_KEY"],', - ` "Idempotency-Key": ${key},`, - ' },', - ` json=${files.length ? renderInput(body, 'python', files, 2) : `json.loads(${JSON.stringify(json)})`},`, - ' timeout=660,', - ')', - 'response.raise_for_status()', - 'if "json" in response.headers.get("Content-Type", ""):', - ' print(response.json())', - 'else:', - ' with open("output.bin", "wb") as output:', - ' output.write(response.content)' - ].join('\n') - } - if (language === 'typescript') { + `url_${n} = (await client.assets.from_file(${JSON.stringify(path)}).get_download_url()).url` + ] + if (!rehost) return [`url_${n} = ${JSON.stringify(sourceUrl)}`] + return [ + `asset_${n} = await client.assets.from_url(${JSON.stringify(sourceUrl)})`, + `url_${n} = (await asset_${n}.get_download_url()).url` + ] +} + +function pythonFileBytes(file: InputFile): string[] { + const { index: n, sourceUrl, path } = file + if (!sourceUrl) return [ - ...(files.length - ? ['import { readFile } from "node:fs/promises"', ''] - : []), - 'const apiKey = process.env.COMFY_API_KEY', - 'if (!apiKey) throw new Error("Set COMFY_API_KEY")', - ...(hasUploads ? uploadSnippet('typescript') : []), - ...(files.length - ? [ - '// Set these paths to your local input files.', - ...paths.map( - (path, index) => - `const input_${index + 1} = ${ - files[index].encoding === 'url' - ? `await uploadFile(${JSON.stringify(path)}, ${JSON.stringify(files[index].mimeType || 'application/octet-stream')})` - : `(await readFile(${JSON.stringify(path)})).toString("base64")` - }` - ), - '' - ] - : []), - ...(hasUploads - ? [ - '// For retries, reuse these prepared inputs and the same key; do not rerun uploads.' - ] - : []), - `const response = await fetch(${JSON.stringify(endpoint)}, {`, - ' method: "POST",', - ' headers: {', - ' "X-API-Key": apiKey,', - ' "Content-Type": "application/json",', - ` "Idempotency-Key": ${key},`, - ' },', - ` body: JSON.stringify(${renderInput(body, 'typescript', files, 1)}),`, - ' signal: AbortSignal.timeout(660_000)', - '})', - 'if (!response.ok) throw new Error(await response.text())', - 'if (response.headers.get("Content-Type")?.includes("json")) {', - ' console.log(await response.json())', - '} else {', - ' const { writeFile } = await import("node:fs/promises")', - ' await writeFile("output.bin", new Uint8Array(await response.arrayBuffer()))', - '}' - ].join('\n') - } + `input_${n} = base64.b64encode(Path(${JSON.stringify(path)}).read_bytes()).decode("ascii")` + ] + return [ + `download_${n} = await http.get(${JSON.stringify(sourceUrl)})`, + `download_${n}.raise_for_status()`, + `input_${n} = base64.b64encode(download_${n}.content).decode("ascii")` + ] +} + +function pythonFileMime(file: InputFile): string[] { + const { index: n, sourceUrl, path } = file + if (sourceUrl) + return [`mime_${n} = download_${n}.headers["content-type"].split(";")[0]`] + return [ + `mime_${n} = mimetypes.guess_type(${JSON.stringify(path)})[0]`, + `if not mime_${n}: raise ValueError("Cannot determine the input file's MIME type")` + ] +} + +function pythonFile(file: InputFile): string[] { + return [ + ...(file.url ? pythonFileUrl(file) : []), + ...(file.base64 ? pythonFileBytes(file) : []), + ...(file.mime ? pythonFileMime(file) : []) + ] +} + +function pythonImports(needs: { + sdk: boolean + base64: boolean + mime: boolean + http: boolean + binary: boolean +}): string[] { + return [ + '# Python 3.10+: pip install comfy-sdk==0.2.0', + 'import asyncio', + 'import os', + ...(needs.sdk ? ['from comfy_sdk import AsyncComfy'] : []), + ...(needs.base64 ? ['import base64'] : []), + ...(needs.binary || needs.base64 ? ['from pathlib import Path'] : []), + ...(needs.mime ? ['import mimetypes'] : []), + ...(needs.http ? ['import httpx'] : []), + ...(needs.binary ? ['from uuid import uuid4'] : []) + ] +} + +function pythonContexts( + sdk: boolean, + binary: boolean, + downloads: boolean +): string[] { + return [ + ...(sdk ? ['AsyncComfy(api_key=api_key) as client'] : []), + ...(binary || downloads + ? [`httpx.AsyncClient(timeout=${binary ? 660 : 120}) as http`] + : []) + ] +} + +function pythonSnippet( + routerId: string, + body: Readonly>, + options: SnippetOptions +) { + const files = options.files ?? [] + const uses = fileUses(body, files) + const binary = options.output === 'binary' + const uploads = uses.some( + (use, index) => use.url && (!files[index].sourceUrl || files[index].rehost) + ) + const downloads = uses.some( + (use, index) => use.base64 && files[index].sourceUrl + ) + const hasSdk = !binary || uploads + const operation = binary + ? [ + '# This endpoint can return binary data, which SDK 0.2 cannot decode.', + 'idempotency_key = str(uuid4())', + `response = await http.post(os.environ["COMFY_ROUTER_BASE_URL"] + ${JSON.stringify('/v2/models/' + routerId.split('/').map(encodeURIComponent).join('/'))},`, + ' headers={"X-API-Key": api_key, "Idempotency-Key": idempotency_key}, json=parameters)', + 'response.raise_for_status()', + 'if "json" in response.headers.get("content-type", ""):', + ' print(response.json())', + 'else:', + ' Path("output.bin").write_bytes(response.content)' + ] + : [ + `result = await client.models.run(${JSON.stringify(routerId)}, parameters)`, + 'print(result)' + ] + return [ + ...pythonImports({ + sdk: hasSdk, + base64: uses.some((use) => use.base64), + mime: uses.some((use) => use.mime), + http: binary || downloads, + binary + }), + '', + 'api_key = os.environ.get("COMFY_API_KEY", "").strip()', + 'if not api_key: raise RuntimeError("Set COMFY_API_KEY")', + `os.environ.setdefault("COMFY_ROUTER_BASE_URL", ${JSON.stringify(WORKSHOP_ROUTER_BASE_URL)})`, + ...(uploads + ? [ + `os.environ.setdefault("COMFY_BASE_URL", ${JSON.stringify(WORKSHOP_CLOUD_BASE_URL)})` + ] + : []), + '', + 'async def main():', + ` async with ${pythonContexts(hasSdk, binary, downloads).join(', ')}:`, + ...[ + ...inputFiles(body, files).flatMap(pythonFile), + `parameters = ${renderInput(body, 'python', files)}`, + ...operation + ].flatMap((line) => line.split('\n').map((part) => ' ' + part)), + '', + 'asyncio.run(main())' + ].join('\n') +} + +function typescriptFileUrl(file: InputFile): string[] { + const { index: n, sourceUrl, path, rehost } = file + if (!sourceUrl) + return [ + `const { url: url_${n} } = await client.assets.fromFile(${JSON.stringify(path)}).getDownloadUrl()` + ] + if (!rehost) return [`const url_${n} = ${JSON.stringify(sourceUrl)}`] + return [ + `const asset_${n} = await client.assets.fromUrl(${JSON.stringify(sourceUrl)})`, + `const { url: url_${n} } = await asset_${n}.getDownloadUrl()` + ] +} + +function typescriptFileBytes(file: InputFile): string[] { + const { index: n, sourceUrl, path } = file + if (!sourceUrl) + return [ + `const input_${n} = (await readFile(${JSON.stringify(path)})).toString("base64")` + ] + return [ + `const download_${n} = await fetch(${JSON.stringify(sourceUrl)}, { signal: AbortSignal.timeout(120_000) })`, + `if (!download_${n}.ok) throw new Error("Input download failed")`, + `const input_${n} = Buffer.from(await download_${n}.arrayBuffer()).toString("base64")` + ] +} + +function typescriptFileMime(file: InputFile): string[] { + const { index: n, sourceUrl, path } = file + const value = sourceUrl + ? `download_${n}.headers.get("content-type")?.split(";")[0]` + : `lookup(${JSON.stringify(path)})` + return [ + `const mime_${n} = ${value}`, + `if (!mime_${n}) throw new Error("Cannot determine the input file's MIME type")` + ] +} + +function typescriptFile(file: InputFile): string[] { + return [ + ...(file.url ? typescriptFileUrl(file) : []), + ...(file.base64 ? typescriptFileBytes(file) : []), + ...(file.mime ? typescriptFileMime(file) : []) + ] +} + +function typescriptImports( + sdkImports: readonly string[], + fsImports: readonly string[], + mime: boolean, + binary: boolean +): string[] { + return [ + `// Node 22+: npm install @comfyorg/sdk@0.2.0${mime ? ' mime-types' : ''}`, + ...(sdkImports.length + ? [`import { ${sdkImports.join(', ')} } from "@comfyorg/sdk"`] + : []), + ...(fsImports.length + ? [`import { ${fsImports.join(', ')} } from "node:fs/promises"`] + : []), + ...(mime ? ['import { lookup } from "mime-types"'] : []), + ...(binary ? ['import { randomUUID } from "node:crypto"'] : []) + ] +} + +function typescriptSnippet( + routerId: string, + body: Readonly>, + options: SnippetOptions +) { + const files = options.files ?? [] + const uses = fileUses(body, files) + const binary = options.output === 'binary' + const uploads = uses.some( + (use, index) => use.url && (!files[index].sourceUrl || files[index].rehost) + ) + const mime = uses.some((use, index) => use.mime && !files[index].sourceUrl) + const sdkImports = [ + ...(uploads ? ['Comfy'] : []), + ...(!binary ? ['comfy'] : []) + ] + const operation = binary + ? [ + '// This endpoint can return binary data, which SDK 0.2 cannot decode.', + 'const idempotencyKey = randomUUID()', + `const response = await fetch(routerBaseUrl + ${JSON.stringify('/v2/models/' + routerId.split('/').map(encodeURIComponent).join('/'))}, {`, + ' method: "POST",', + ' headers: {"X-API-Key": apiKey, "Content-Type": "application/json", "Idempotency-Key": idempotencyKey},', + ' body: JSON.stringify(parameters), signal: AbortSignal.timeout(660_000)', + '})', + 'if (!response.ok) throw new Error(await response.text())', + 'if (response.headers.get("Content-Type")?.includes("json")) {', + ' console.log(await response.json())', + '} else {', + ' await writeFile("output.bin", new Uint8Array(await response.arrayBuffer()))', + '}' + ] + : [ + 'comfy.config({ credentials: apiKey, baseUrl: routerBaseUrl })', + `const { data, requestId } = await comfy.models.run(${JSON.stringify(routerId)}, parameters)`, + 'console.log({ requestId, data })' + ] + const fsImports = [ + ...(uses.some((use) => use.base64) ? ['readFile'] : []), + ...(binary ? ['writeFile'] : []) + ] + return [ + ...typescriptImports(sdkImports, fsImports, mime, binary), + '', + 'const apiKey = process.env.COMFY_API_KEY?.trim()', + 'if (!apiKey) throw new Error("Set COMFY_API_KEY")', + `const routerBaseUrl = process.env.COMFY_ROUTER_BASE_URL ?? ${JSON.stringify(WORKSHOP_ROUTER_BASE_URL)}`, + ...(uploads + ? [ + `process.env.COMFY_BASE_URL ??= ${JSON.stringify(WORKSHOP_CLOUD_BASE_URL)}`, + 'const client = new Comfy({ apiKey })' + ] + : []), + ...inputFiles(body, files).flatMap(typescriptFile), + `const parameters = ${renderInput(body, 'typescript', files)}`, + ...operation + ].join('\n') +} + +function curlSnippet( + routerId: string, + body: Readonly>, + files: readonly SnippetFile[] +) { const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'` return [ - ...(files.length + ': "${COMFY_API_KEY:?Set COMFY_API_KEY}"', + "IDEMPOTENCY_KEY=$(python3 -c 'import uuid; print(uuid.uuid4())') || exit", + '# A fresh key starts a new generation. For a retry, reuse the prepared body and key.', + ...(hasOmittedCurlFiles(body, files) ? [ '# Uploaded files are omitted. This request may be incomplete.', - '# Use Python or TypeScript to include local files.', - '' + '# Use Python or TypeScript to include local files.' ] : []), '# To save a binary response, add --output output.bin to the command.', - `curl --fail-with-body --max-time 660 --request POST ${quote(endpoint)} \\`, + `curl --fail-with-body --max-time 660 --request POST ${quote(WORKSHOP_ROUTER_BASE_URL + '/v2/models/' + routerId.split('/').map(encodeURIComponent).join('/'))} \\`, ' --header "X-API-Key: $COMFY_API_KEY" \\', ' --header "Content-Type: application/json" \\', - ` --header ${quote(`Idempotency-Key: ${idempotencyKey}`)} \\`, + ' --header "Idempotency-Key: $IDEMPOTENCY_KEY" \\', ` --data ${quote(JSON.stringify(omitFiles(body, files, true) ?? {}, null, 2))}` ].join('\n') } + +export function buildSnippet( + language: SnippetLanguage, + routerId: string, + body: Readonly>, + options: SnippetOptions = {} +): string { + if (language === 'python') return pythonSnippet(routerId, body, options) + if (language === 'typescript') + return typescriptSnippet(routerId, body, options) + return curlSnippet(routerId, body, options.files ?? []) +} diff --git a/apps/website/src/config/workshop-upload-snippets.ts b/apps/website/src/config/workshop-upload-snippets.ts deleted file mode 100644 index e68637b4620..00000000000 --- a/apps/website/src/config/workshop-upload-snippets.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { WORKSHOP_ROUTER_BASE_URL } from './workshop-env' - -export function uploadSnippet(language: 'python' | 'typescript'): string[] { - const endpoint = JSON.stringify( - `${WORKSHOP_ROUTER_BASE_URL}/customers/storage` - ) - if (language === 'python') - return [ - 'from uuid import uuid4', - 'from urllib.parse import urlsplit', - '', - 'def storage_url(value):', - ' url = urlsplit(value)', - ' if url.scheme != "https" or not url.hostname or url.username or url.password:', - ' raise ValueError("Invalid storage URL")', - ' return value', - '', - 'def upload_file(path, content_type):', - ' source = Path(path)', - ` grant = requests.post(${endpoint},`, - ' headers={"Authorization": "Bearer " + os.environ["COMFY_API_KEY"]},', - ' json={"file_name": str(uuid4()) + "-" + source.name, "content_type": content_type},', - ' timeout=120, allow_redirects=False)', - ' if not 200 <= grant.status_code < 300:', - ' raise RuntimeError("Upload authorization failed")', - ' urls = grant.json()', - ' upload_url = storage_url(urls["upload_url"])', - ' download_url = storage_url(urls["download_url"])', - ' with source.open("rb") as data:', - ' uploaded = requests.put(upload_url, data=data,', - ' headers={"Content-Type": content_type}, timeout=120, allow_redirects=False)', - ' if not 200 <= uploaded.status_code < 300:', - ' raise RuntimeError("Upload failed")', - ' return download_url', - '' - ] - return [ - 'function storageUrl(value: unknown): string {', - ' if (typeof value !== "string") throw new Error("Invalid storage URL")', - ' const url = new URL(value)', - ' if (url.protocol !== "https:" || url.username || url.password) throw new Error("Invalid storage URL")', - ' return value', - '}', - '', - 'async function uploadFile(path: string, contentType: string): Promise {', - ' const data = await readFile(path)', - ` const grant = await fetch(${endpoint}, {`, - ' method: "POST", redirect: "error", credentials: "omit",', - ' headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json" },', - ' body: JSON.stringify({ file_name: `${crypto.randomUUID()}-${path.split(/[\\\\/]/).at(-1)}`, content_type: contentType }),', - ' signal: AbortSignal.timeout(120_000)', - ' })', - ' if (!grant.ok) throw new Error("Upload authorization failed")', - ' const urls: unknown = await grant.json()', - ' if (!urls || typeof urls !== "object" || !("upload_url" in urls) || !("download_url" in urls)) throw new Error("Invalid upload response")', - ' const uploadUrl = storageUrl(urls.upload_url)', - ' const downloadUrl = storageUrl(urls.download_url)', - ' const uploaded = await fetch(uploadUrl, {', - ' method: "PUT", redirect: "error", credentials: "omit",', - ' headers: { "Content-Type": contentType }, body: data,', - ' signal: AbortSignal.timeout(120_000)', - ' })', - ' if (!uploaded.ok) throw new Error("Upload failed")', - ' return downloadUrl', - '}', - '' - ] -} diff --git a/apps/website/src/config/workshop-url-input.ts b/apps/website/src/config/workshop-url-input.ts index bf56050e2db..5df01cd8332 100644 --- a/apps/website/src/config/workshop-url-input.ts +++ b/apps/website/src/config/workshop-url-input.ts @@ -10,6 +10,18 @@ const formSources = new WeakMap>() const REHOST_SOURCE = /^https:\/\/cdn\.jsdelivr\.net\/gh\/Comfy-Org\/workflow_templates@[^/]+\// +export function shouldRehostWorkshopUrl( + field: FieldSchema, + source: unknown +): source is string { + return ( + !!urlUploadField(field) && + typeof source === 'string' && + isHttpImageSource(source) && + REHOST_SOURCE.test(source) + ) +} + async function rehostUrlInputs( fields: readonly FieldSchema[], values: FormValues, @@ -17,12 +29,7 @@ async function rehostUrlInputs( ): Promise { const pending = fields.flatMap((field) => { const source = values[field.name] - return urlUploadField(field) && - typeof source === 'string' && - isHttpImageSource(source) && - REHOST_SOURCE.test(source) - ? [{ field, source }] - : [] + return shouldRehostWorkshopUrl(field, source) ? [{ field, source }] : [] }) if (!pending.length) return values const errors = validateForm(fields, values) diff --git a/knip.config.ts b/knip.config.ts index a696bb7a973..4084df18962 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -44,7 +44,9 @@ const config: KnipConfig = { }, 'apps/website': { // Models pages are registered by the release-gate integration. - entry: ['src/scripts/**/*.ts', 'src/routes/models/*.astro'] + entry: ['src/scripts/**/*.ts', 'src/routes/models/*.astro'], + // Executed by models-snippets.test.ts inside the generated Node examples. + ignoreDependencies: ['mime-types'] }, 'tools/test-recorder': { project: ['src/**/*.ts'] diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fa9667af0e4..526bab76130 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,6 +27,9 @@ catalogs: '@comfyorg/comfyui-electron-types': specifier: 0.6.2 version: 0.6.2 + '@comfyorg/sdk': + specifier: 0.2.0 + version: 0.2.0 '@customerio/cdp-analytics-browser': specifier: ^0.5.3 version: 0.5.6 @@ -294,6 +297,9 @@ catalogs: mediabunny: specifier: ^1.53.1 version: 1.53.1 + mime-types: + specifier: 3.0.2 + version: 3.0.2 minisearch: specifier: ^7.2.0 version: 7.2.0 @@ -1026,6 +1032,9 @@ importers: '@astrojs/vue': specifier: 'catalog:' version: 7.0.2(@types/node@25.9.5)(astro@7.2.1(@astrojs/markdown-remark@7.2.2)(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(terser@5.49.0)(tsx@4.23.1)(yaml@2.9.0))(esbuild@0.28.1)(jiti@2.7.0)(terser@5.49.0)(tsx@4.23.1)(vue@3.5.42(typescript@6.0.3))(yaml@2.9.0) + '@comfyorg/sdk': + specifier: 'catalog:' + version: 0.2.0 '@playwright/test': specifier: 'catalog:' version: 1.61.1 @@ -1059,6 +1068,9 @@ importers: happy-dom: specifier: 'catalog:' version: 20.9.0 + mime-types: + specifier: 'catalog:' + version: 3.0.2 tailwindcss: specifier: 'catalog:' version: 4.3.2 @@ -1706,6 +1718,10 @@ packages: '@types/three': optional: true + '@comfyorg/sdk@0.2.0': + resolution: {integrity: sha512-x2a9mat9+s6xOACYFnlsAri7ovNaFD2VjwKohsNWJ65RodnLU5Rviq2fd7feQyfQS2C6XKZRjXj81AfypHonTQ==} + engines: {node: '>=22'} + '@csstools/color-helpers@6.1.0': resolution: {integrity: sha512-064IFJdjTfUqnjpCVpMOdbr8FLQBhinbZj6yRv2An2E41O/pLEXqfFRWqGq/SxlE5PEUYTlvWsG2r8MswAVvkg==} engines: {node: '>=20.19.0'} @@ -6080,6 +6096,10 @@ packages: eventemitter3@5.0.4: resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} + eventsource-parser@4.1.0: + resolution: {integrity: sha512-+DHvQ1wLO//MK+1OZgcuXCbZFKgu3YjKPJt7n98rxX8vezL0ni+7s3ZQiM8bJkUEOk7MsuCycrPLj0FzUNf7Og==} + engines: {node: '>=22.12'} + execa@5.1.1: resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} engines: {node: '>=10'} @@ -6398,6 +6418,9 @@ packages: hash-sum@2.0.0: resolution: {integrity: sha512-WdZTbAByD+pHfl/g9QSsBIIwy8IT+EsPiKDs0KNX+zSHhdDLFKdZu0BQHljvO+0QI/BasbMSUa8wYNCZTvhslg==} + hash-wasm@4.12.0: + resolution: {integrity: sha512-+/2B2rYLb48I/evdOIhP+K/DD2ca2fgBjp6O+GBEnCDk2e4rpeXIK8GvIyRPjTezgmWn9gmKwkQjjx6BtqDHVQ==} + hashery@1.5.1: resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} engines: {node: '>=20'} @@ -7376,10 +7399,18 @@ packages: resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} engines: {node: '>= 0.6'} + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + mime-types@2.1.35: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} + mimic-fn@2.1.0: resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} engines: {node: '>=6'} @@ -10249,6 +10280,12 @@ snapshots: optionalDependencies: '@types/three': 0.184.1 + '@comfyorg/sdk@0.2.0': + dependencies: + eventsource-parser: 4.1.0 + hash-wasm: 4.12.0 + zod: 4.4.3 + '@csstools/color-helpers@6.1.0': {} '@csstools/css-calc@3.2.1(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': @@ -14561,6 +14598,8 @@ snapshots: eventemitter3@5.0.4: {} + eventsource-parser@4.1.0: {} + execa@5.1.1: dependencies: cross-spawn: 7.0.6 @@ -14956,6 +14995,8 @@ snapshots: hash-sum@2.0.0: {} + hash-wasm@4.12.0: {} + hashery@1.5.1: dependencies: hookified: 1.15.1 @@ -16231,10 +16272,16 @@ snapshots: mime-db@1.52.0: {} + mime-db@1.54.0: {} + mime-types@2.1.35: dependencies: mime-db: 1.52.0 + mime-types@3.0.2: + dependencies: + mime-db: 1.54.0 + mimic-fn@2.1.0: {} mimic-function@5.0.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a63e85f35ad..ced260a79d1 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -18,6 +18,7 @@ catalog: '@astrojs/vue': ^7.0.2 '@comfyorg/comfyui-desktop-bridge-types': 0.2.0 '@comfyorg/comfyui-electron-types': 0.6.2 + '@comfyorg/sdk': 0.2.0 '@customerio/cdp-analytics-browser': ^0.5.3 '@datadog/browser-rum': ^6.33.0 '@eslint/js': ^10.0.1 @@ -109,6 +110,7 @@ catalog: markdown-table: ^3.0.4 mediabunny: ^1.53.1 minisearch: ^7.2.0 + mime-types: 3.0.2 mixpanel-browser: ^2.71.0 monocart-coverage-reports: ^2.12.9 openai: ^7.4.0 @@ -138,6 +140,7 @@ catalog: typegpu: ^0.8.2 typescript: ^6.0.3 typescript-eslint: ^8.69.0 + undici: ^7.29.0 unplugin-icons: ^23.0.1 unplugin-typegpu: 0.8.0 unplugin-vue-components: ^32.1.0 @@ -160,7 +163,6 @@ catalog: zod: ^3.23.8 zod-to-json-schema: ^3.24.1 zod-validation-error: ^3.3.0 - undici: ^7.29.0 cleanupUnusedCatalogs: true From 1162e24b8fbe8fb43c5011276f5729a6af7864f9 Mon Sep 17 00:00:00 2001 From: benjcooley Date: Sun, 13 Sep 2026 11:57:28 -0700 Subject: [PATCH 2/2] fix(website): retain model inputs through sign-in and copied examples --- apps/website/MODELS_CONTENT_FORMAT.md | 7 + apps/website/MODELS_INPUT_SCHEMA.md | 23 ++- .../e2e/models-catalogue-corrections.spec.ts | 24 +++ apps/website/e2e/models-sign-in-draft.spec.ts | 141 ++++++++++++++++++ .../e2e/workshop-input-feedback.spec.ts | 7 +- .../workshop-input-presentation.test.ts | 7 +- .../workshop/ApiTab.execution.test.ts | 31 ++++ .../src/components/workshop/ApiTab.vue | 15 +- .../components/workshop/HeaderAccount.test.ts | 32 ++++ .../src/components/workshop/HeaderAccount.vue | 10 +- .../components/workshop/ModelDetail.test.ts | 12 +- .../src/components/workshop/ModelDetail.vue | 70 +++------ .../workshop/WorkshopPlayground.test.ts | 6 +- .../src/composables/useWorkshopFormDraft.ts | 122 +++++++++++++++ .../src/config/models-snippets.test.ts | 39 +++++ apps/website/src/config/models-snippets.ts | 62 ++++++-- .../src/config/router-default-inputs.ts | 3 - apps/website/src/config/router-media.ts | 5 +- .../src/config/workshop-browse-content.ts | 12 +- .../src/config/workshop-draft-files.test.ts | 112 ++++++++++++++ .../src/config/workshop-draft-files.ts | 118 +++++++++++++++ .../src/config/workshop-draft-storage.ts | 124 +++++++++++++++ .../website/src/config/workshop-playground.ts | 1 + apps/website/src/config/workshop-return.ts | 56 ++++++- .../content/workshop-router-contracts.json | 2 +- .../src/data/workshop-input-presentation.json | 3 +- .../src/data/workshop-use-case-overrides.json | 5 + apps/website/src/i18n/translations.ts | 6 +- 28 files changed, 951 insertions(+), 104 deletions(-) create mode 100644 apps/website/e2e/models-catalogue-corrections.spec.ts create mode 100644 apps/website/e2e/models-sign-in-draft.spec.ts create mode 100644 apps/website/src/composables/useWorkshopFormDraft.ts create mode 100644 apps/website/src/config/workshop-draft-files.test.ts create mode 100644 apps/website/src/config/workshop-draft-files.ts create mode 100644 apps/website/src/config/workshop-draft-storage.ts create mode 100644 apps/website/src/data/workshop-use-case-overrides.json 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 563d92b1b92..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 @@ -337,6 +338,9 @@ with `pnpm --filter @comfyorg/website generate:workshop-router-contracts`. 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. @@ -452,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/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 index dc643658802..08a45c8cafc 100644 --- a/apps/website/src/components/workshop/ApiTab.execution.test.ts +++ b/apps/website/src/components/workshop/ApiTab.execution.test.ts @@ -8,8 +8,39 @@ 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, { diff --git a/apps/website/src/components/workshop/ApiTab.vue b/apps/website/src/components/workshop/ApiTab.vue index 182498bf7a3..b6d38fa9ae7 100644 --- a/apps/website/src/components/workshop/ApiTab.vue +++ b/apps/website/src/components/workshop/ApiTab.vue @@ -69,12 +69,14 @@ const unavailable = ref(false) function previewValues( values: FormValues, - sources: WeakMap + 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, value.sourceUrl) + sources.set(file, { sourceUrl: value.sourceUrl }) return { ...value, file } } const fields = contract?.rehostUrlInputs @@ -107,13 +109,16 @@ watch( unavailable.value = false try { const files: SnippetFile[] = [] - const sources = new WeakMap() + 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, - sourceUrl: sources.get(file), + ...sources.get(file), rehost: contract?.rehostUrlInputs, urlAlternative: contract?.creator?.request.kind === 'callback' && @@ -168,7 +173,7 @@ const showFileNotice = computed(() => { const { body, files } = request.value return language.value === 'curl' ? hasOmittedCurlFiles(body, files) - : files.some((file) => !file.sourceUrl) + : files.some((file) => !file.sourceUrl && !file.sourceDataUrl) }) 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 @@