From 63f0825b3d0f120cf61bb45d8d47d97fad774140 Mon Sep 17 00:00:00 2001 From: benjcooley Date: Fri, 25 Sep 2026 15:02:37 -0700 Subject: [PATCH 1/6] fix(website): read a Router error bucket from the body when the header is missing An insufficient_credits refusal whose bucket arrives only in the JSON body (no X-Comfy-Error-Type header, not a 402) was classified by status alone and surfaced as a provider or validation failure instead of noCredits. --- .../src/config/workshop-router-errors.ts | 18 ++++++++++- .../src/config/workshop-router.test.ts | 30 +++++++++++++++++++ apps/website/src/config/workshop-router.ts | 9 ++++-- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/apps/website/src/config/workshop-router-errors.ts b/apps/website/src/config/workshop-router-errors.ts index 593f9b916bc..912c65345d6 100644 --- a/apps/website/src/config/workshop-router-errors.ts +++ b/apps/website/src/config/workshop-router-errors.ts @@ -16,10 +16,26 @@ interface WorkshopRouterErrorOptions extends ErrorOptions { readonly requestSettlement?: WorkshopRequestSettlement } +function bodyErrorType(body: string): string | null { + if (!body.trim().startsWith('{')) return null + try { + const payload: unknown = JSON.parse(body) + const errorType = + payload !== null && typeof payload === 'object' + ? Reflect.get(payload, 'error_type') + : undefined + return typeof errorType === 'string' && errorType ? errorType : null + } catch { + return null + } +} + +/** The Router's error bucket, from its header or, failing that, the body. */ export function workshopResponseDetails(response: Response, body = '') { return { status: response.status, - errorType: response.headers.get('X-Comfy-Error-Type'), + errorType: + response.headers.get('X-Comfy-Error-Type') ?? bodyErrorType(body), retryAfter: response.headers.get('Retry-After'), concurrencyLimit: response.headers.get('X-Concurrency-Limit'), concurrencyCurrent: response.headers.get('X-Concurrency-Current'), diff --git a/apps/website/src/config/workshop-router.test.ts b/apps/website/src/config/workshop-router.test.ts index ea18f58064a..5d052d40752 100644 --- a/apps/website/src/config/workshop-router.test.ts +++ b/apps/website/src/config/workshop-router.test.ts @@ -468,6 +468,36 @@ describe('native Router requests', () => { } ) + it.for([ + { status: 400, errorType: 'insufficient_credits', reason: 'noCredits' }, + { status: 500, errorType: 'insufficient_credits', reason: 'noCredits' }, + { status: 400, errorType: 'invalid_input', reason: 'validation' } + ])( + 'classifies a $status whose body alone names $errorType', + async ({ status, errorType, reason }) => { + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + Response.json( + { detail: 'refused', error_type: errorType }, + { status } + ) + ) + ) + await expect( + runSynchronousWorkshopRouter({ + contract: contractFor('bfl/flux-2-pro'), + body: { prompt: 'Test' }, + token: 'test-token', + idempotencyKey: 'one-key', + signal: new AbortController().signal + }) + ).rejects.toMatchObject({ reason, response: { status, errorType } }) + } + ) + it.for([ { provider: 'WAN', diff --git a/apps/website/src/config/workshop-router.ts b/apps/website/src/config/workshop-router.ts index 4d061e8c681..1171152c5bb 100644 --- a/apps/website/src/config/workshop-router.ts +++ b/apps/website/src/config/workshop-router.ts @@ -89,10 +89,10 @@ async function failureDetails(response: Response) { function failureFor( response: Response, + bucket: string | null, body: string, bodyComplete: boolean ): RunFailure { - const bucket = response.headers.get('X-Comfy-Error-Type') if (bucket === 'insufficient_credits') return 'noCredits' if (bucket === 'content_policy_violation') return 'policy' if (bucket === 'not_enabled' || bucket === 'forbidden') return 'unavailable' @@ -318,7 +318,12 @@ export async function settleRouterResponse( throw new WorkshopRouterError( Object.keys(fieldErrors).length ? 'validation' - : failureFor(response, details.response.body, details.bodyComplete), + : failureFor( + response, + details.response.errorType, + details.response.body, + details.bodyComplete + ), requestId, fieldErrors, details.response, From 72e4a058d167ec380a21db8432ff1baeaad5c513 Mon Sep 17 00:00:00 2001 From: benjcooley Date: Fri, 25 Sep 2026 15:04:37 -0700 Subject: [PATCH 2/6] feat(website): price a Router run from the size and references it asks for The node-pricing helper only evaluated a rule with the node's default widgets. It now accepts the run's width, height and reference-image count, and exposes the same price as a credit range so a caller can compare it with a balance. --- .../src/config/workshop-node-pricing.test.ts | 60 ++++++++- .../src/config/workshop-node-pricing.ts | 123 +++++++++++++++--- 2 files changed, 166 insertions(+), 17 deletions(-) diff --git a/apps/website/src/config/workshop-node-pricing.test.ts b/apps/website/src/config/workshop-node-pricing.test.ts index c6e3ecf52dd..7f79a0663d4 100644 --- a/apps/website/src/config/workshop-node-pricing.test.ts +++ b/apps/website/src/config/workshop-node-pricing.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' -import { estimateWorkshopNodePrice } from './workshop-node-pricing' +import { + estimateWorkshopNodePrice, + estimateWorkshopRunCredits +} from './workshop-node-pricing' import { workshopNodePricingSchema } from './workshop-node-pricing.schema' import pricing from '../data/workshop-node-pricing.json' @@ -90,6 +93,61 @@ describe('node-based Models price estimates', () => { expect(await estimateWorkshopNodePrice(model, undefined)).toBeUndefined() }) + it('prices the size a run asks for instead of the node default', async () => { + expect( + await estimateWorkshopNodePrice( + { routerId: 'bfl/flux-2-pro' }, + 'generate-images', + { width: 2048, height: 2048 } + ) + ).toBe('15.8 credits/Run') + }) +}) + +describe('node-based Models run credits', () => { + const FLUX = { routerId: 'bfl/flux-2-pro' } + + it.for([ + ['a 1 MP Flux 2 Pro frame', FLUX, { width: 1024, height: 1024 }, 6.33], + ['a 4 MP Flux 2 Pro frame', FLUX, { width: 2048, height: 2048 }, 15.825], + [ + 'a Seedream 4.5 image at any size', + { routerId: 'byteplus/seedream-4-5-251128' }, + { width: 3136, height: 1344 }, + 8.44 + ], + ['a published flat rate', { routerId: 'bfl/flux-kontext-pro' }, {}, 8.44] + ] as const)('prices %s', async ([, model, settings, credits]) => { + const estimate = await estimateWorkshopRunCredits( + model, + 'generate-images', + settings + ) + expect(estimate?.min).toBeCloseTo(credits) + expect(estimate?.max).toBeCloseTo(credits) + }) + + it('widens to the declared range once reference images are sent', async () => { + const estimate = await estimateWorkshopRunCredits(FLUX, 'generate-images', { + width: 1024, + height: 1024, + images: 2 + }) + expect(estimate?.min).toBeCloseTo(9.495) + expect(estimate?.max).toBeCloseTo(31.65) + }) + + it('has no estimate for a model without a verified price', async () => { + expect( + await estimateWorkshopRunCredits( + { routerId: 'vertexai/gemini-3-pro-image' }, + 'generate-images' + ) + ).toBeUndefined() + }) +}) + +describe('node pricing snapshot', () => { it('rejects a snapshot missing a declared pricing dependency', () => { const row = pricing.find((entry) => entry.routerId === 'bfl/flux-2-max') if (!row) throw new Error('Missing Flux pricing fixture') diff --git a/apps/website/src/config/workshop-node-pricing.ts b/apps/website/src/config/workshop-node-pricing.ts index 53d6f7778bd..dece2b6343c 100644 --- a/apps/website/src/config/workshop-node-pricing.ts +++ b/apps/website/src/config/workshop-node-pricing.ts @@ -1,7 +1,10 @@ +import { CREDITS_PER_USD } from '@comfyorg/shared-frontend-utils/creditsUtil' import { - evaluatePricingContext, + formatPricingResult, + getCompiledRuleForNodeType, normalizeWidgetValue } from '@comfyorg/shared-frontend-utils/nodePricing' +import { z } from 'zod' import pricingJson from '../data/workshop-node-pricing.json' import publishedPricingJson from '../data/workshop-published-pricing.json' @@ -18,10 +21,41 @@ const published = new Map( ) ) -export async function estimateWorkshopNodePrice( +/** + * What one run asks for, where a node's pricing rule depends on it. Anything + * left out falls back to the node's default widget values. + */ +export interface WorkshopRunSettings { + readonly width?: number + readonly height?: number + /** Reference images sent with the run. */ + readonly images?: number +} + +export interface CreditRange { + readonly min: number + readonly max: number +} + +type RunPrice = + | { readonly kind: 'published'; readonly credits: number } + | { readonly kind: 'rule'; readonly result: unknown } + +function sizeSetting( + widget: string, + settings: WorkshopRunSettings +): number | undefined { + const name = widget.split('.').at(-1) + if (name === 'width') return settings.width + if (name === 'height') return settings.height + return undefined +} + +async function priceRun( model: Pick, - useCase: UseCase | undefined -): Promise { + useCase: UseCase | undefined, + settings: WorkshopRunSettings +): Promise { if (!useCase || !model.routerId) return const rule = rules.find( (row) => @@ -31,36 +65,93 @@ export async function estimateWorkshopNodePrice( if (!rule) { const rate = published.get(model.routerId) if (rate?.useCases.some((operation) => operation === useCase)) - return `${rate.creditsPerRun} credits/Run` + return { kind: 'published', credits: rate.creditsPerRun } return } const { priceBadge } = rule - const withImage = useCase === 'edit-images' || useCase === 'animate-images' + const images = + settings.images ?? + (useCase === 'edit-images' || useCase === 'animate-images' ? 1 : 0) const widgets = Object.fromEntries( priceBadge.depends_on.widgets.map((dep) => [ dep.name, - normalizeWidgetValue(rule.widgets[dep.name], dep.type) + normalizeWidgetValue( + sizeSetting(dep.name, settings) ?? rule.widgets[dep.name], + dep.type + ) ]) ) if (Object.values(widgets).some((value) => value === null)) return - const label = await evaluatePricingContext( + const compiled = getCompiledRuleForNodeType( `${rule.nodeType}:${rule.sourceCommit}`, - priceBadge, - { + priceBadge + )?._compiled + if (!compiled) return + try { + const result: unknown = await compiled.evaluate({ widgets, inputs: Object.fromEntries( priceBadge.depends_on.inputs.map((name) => [ name, - { connected: withImage } + { connected: images > 0 } ]) ), inputGroups: Object.fromEntries( - priceBadge.depends_on.input_groups.map((name) => [ - name, - withImage ? 1 : 0 - ]) + priceBadge.depends_on.input_groups.map((name) => [name, images]) ) + }) + return { kind: 'rule', result } + } catch { + return + } +} + +export async function estimateWorkshopNodePrice( + model: Pick, + useCase: UseCase | undefined, + settings: WorkshopRunSettings = {} +): Promise { + const price = await priceRun(model, useCase, settings) + if (price?.kind === 'published') return `${price.credits} credits/Run` + return (price && formatPricingResult(price.result)) || undefined +} + +const usdResult = z.discriminatedUnion('type', [ + z.object({ type: z.literal('usd'), usd: z.number().nonnegative() }), + z.object({ + type: z.literal('range_usd'), + min_usd: z.number().nonnegative(), + max_usd: z.number().nonnegative() + }) +]) + +function usdRange(result: unknown): CreditRange | undefined { + const parsed = usdResult.safeParse(result) + if (!parsed.success) return + const usd = parsed.data + return usd.type === 'usd' + ? { min: usd.usd, max: usd.usd } + : { min: usd.min_usd, max: usd.max_usd } +} + +/** + * Credits for one run that returns one image, from the same rule or + * published rate as {@link estimateWorkshopNodePrice}. + */ +export async function estimateWorkshopRunCredits( + model: Pick, + useCase: UseCase | undefined, + settings: WorkshopRunSettings = {} +): Promise { + const price = await priceRun(model, useCase, settings) + if (!price) return + if (price.kind === 'published') + return { min: price.credits, max: price.credits } + const usd = usdRange(price.result) + return ( + usd && { + min: usd.min * CREDITS_PER_USD, + max: usd.max * CREDITS_PER_USD } ) - return label || undefined } From d68b7a7ed982740a89dc2f5052b4f4d4dd266fc0 Mon Sep 17 00:00:00 2001 From: benjcooley Date: Fri, 25 Sep 2026 15:13:32 -0700 Subject: [PATCH 3/6] feat(website): show a Cinematic Studio shot's estimated credits and gate on them The studio priced nothing before a run and only stopped an empty balance, so a four-take batch over the balance partly failed. - Price each studio model at build time for every aspect, resolution and reference count, from the frame size the Router mapping sends. - Show ~N credits (takes x per take) beside Generate, or Cost varies for a model without a verified price. - Block a shot the balance does not cover with the need and the balance, offer the number of takes it does cover, and keep the zero-balance gate for unpriced models. The unused runGate is retired into studioGate. - Give members the switch-to-personal action instead of checkout, sharing the switch with the model page. --- .../src/components/workshop/ModelDetail.vue | 27 +- .../cinematic-studio/CinematicComposer.vue | 11 +- .../CinematicGenerateAction.vue | 234 ++++++++++++++---- .../cinematic-studio/CinematicPanel.vue | 8 + .../cinematic-studio/CinematicStudio.test.ts | 161 ++++++++++++ .../cinematic-studio/CinematicStudio.vue | 5 +- .../cinematic-studio/CinematicStudioPanel.vue | 3 + .../src/composables/useCinematicDemoRun.ts | 17 +- .../src/composables/useCinematicShot.ts | 18 +- .../src/composables/useCinematicStudioRun.ts | 47 ++-- .../composables/usePersonalWorkspaceSwitch.ts | 33 +++ apps/website/src/config/workshop-run.test.ts | 61 +---- apps/website/src/config/workshop-run.ts | 40 +-- .../src/lib/workshop/cinematic-studio/copy.ts | 40 +++ .../lib/workshop/cinematic-studio/estimate.ts | 54 ++++ .../workshop/cinematic-studio/gate.test.ts | 24 +- .../src/lib/workshop/cinematic-studio/gate.ts | 21 +- .../lib/workshop/cinematic-studio/models.ts | 3 + .../workshop/cinematic-studio/pricing.test.ts | 54 ++++ .../lib/workshop/cinematic-studio/pricing.ts | 82 ++++++ .../src/routes/models/cinematic-studio.astro | 6 +- 21 files changed, 736 insertions(+), 213 deletions(-) create mode 100644 apps/website/src/composables/usePersonalWorkspaceSwitch.ts create mode 100644 apps/website/src/lib/workshop/cinematic-studio/estimate.ts create mode 100644 apps/website/src/lib/workshop/cinematic-studio/pricing.test.ts create mode 100644 apps/website/src/lib/workshop/cinematic-studio/pricing.ts diff --git a/apps/website/src/components/workshop/ModelDetail.vue b/apps/website/src/components/workshop/ModelDetail.vue index ba990a655e2..4402efd7476 100644 --- a/apps/website/src/components/workshop/ModelDetail.vue +++ b/apps/website/src/components/workshop/ModelDetail.vue @@ -21,6 +21,7 @@ import { sameFormValues } from '../../lib/workshop/form-values' import { validateWorkshopMediaInputs } from '../../config/workshop-media-validation' import { leaveForSignIn } from '../../config/workshop-return' import { useSignInHref } from '../../composables/useSignInHref' +import { usePersonalWorkspaceSwitch } from '../../composables/usePersonalWorkspaceSwitch' import { useTablist } from '../../composables/useTablist' import type { WorkshopModelDetail } from '../../config/models-catalogue' import type { @@ -225,7 +226,7 @@ const attachments = computed(() => ) const revealed = ref(false) -const { user, session, sessionFailure, settled, ensureFresh, remint } = +const { user, session, sessionFailure, settled, ensureFresh } = useWorkshopSession() const { balance } = useWorkshopCredits() const workshopEnabled = useWorkshopEnabled() @@ -530,25 +531,11 @@ async function historyToken(): Promise { return result.session.token } -const personalSwitchPending = ref(false) -const personalSwitchError = ref(false) - -async function switchToPersonal() { - if (personalSwitchPending.value) return - personalSwitchPending.value = true - personalSwitchError.value = false - try { - const result = await remint(undefined, { - preserveCredentialOnTransientFailure: true - }) - if (result?.status === 'ok') await refreshWorkshopCredits({ force: true }) - else if (result?.status === 'error') personalSwitchError.value = true - } catch { - personalSwitchError.value = true - } finally { - personalSwitchPending.value = false - } -} +const { + pending: personalSwitchPending, + failed: personalSwitchError, + switchToPersonal +} = usePersonalWorkspaceSwitch() onUnmounted(() => { cancelRun() diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicComposer.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicComposer.vue index 986f666ab3a..92f687fcaa6 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicComposer.vue +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicComposer.vue @@ -12,6 +12,7 @@ import type { Resolution } from '../../../lib/workshop/cinematic-studio/catalog' import { directionOption } from '../../../lib/workshop/cinematic-studio/catalog' +import type { ShotEstimate } from '../../../lib/workshop/cinematic-studio/estimate' import type { StudioGate } from '../../../lib/workshop/cinematic-studio/gate' import type { CinematicModel } from '../../../lib/workshop/cinematic-studio/models' import type { Locale } from '../../../i18n/translations' @@ -28,11 +29,12 @@ const { direction, aspect, resolution, - takes, references, gate, workspaceName, rendering, + estimate, + credits, openPopover, locale = 'en' } = defineProps<{ @@ -40,11 +42,12 @@ const { direction: Direction aspect: AspectRatio resolution: Resolution - takes: number references: readonly File[] gate: StudioGate workspaceName?: string rendering: boolean + estimate?: ShotEstimate + credits?: number openPopover?: PopoverKey locale?: Locale }>() @@ -57,6 +60,7 @@ const emit = defineEmits<{ const scene = defineModel('scene', { required: true }) const modelSlug = defineModel('model', { required: true }) +const takes = defineModel('takes', { required: true }) const modelOptions = computed(() => models.map((model) => ({ @@ -227,10 +231,13 @@ const chipClass = (key: PopoverKey) => :rendering :can-generate="canGenerate" :blocked-note="blockedNote" + :estimate + :credits :locale class="ml-auto" @generate="emit('generate')" @cancel="emit('cancel')" + @reduce-takes="takes = $event" /> diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicGenerateAction.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicGenerateAction.vue index 2b034f4b88c..ffdb6588293 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicGenerateAction.vue +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicGenerateAction.vue @@ -11,9 +11,15 @@ import { computed } from 'vue' import { cn } from '@comfyorg/tailwind-utils' import Button from '@/components/ui/button/Button.vue' +import { usePersonalWorkspaceSwitch } from '../../../composables/usePersonalWorkspaceSwitch' import { useSignInHref } from '../../../composables/useSignInHref' import { requestWorkshopBuyCredits } from '../../../config/workshop-buy-credits' import { leaveForSignIn } from '../../../config/workshop-return' +import type { ShotEstimate } from '../../../lib/workshop/cinematic-studio/estimate' +import { + formatCreditRange, + takesWithin +} from '../../../lib/workshop/cinematic-studio/estimate' import type { StudioGate } from '../../../lib/workshop/cinematic-studio/gate' import type { Locale } from '../../../i18n/translations' import { t } from '../../../i18n/translations' @@ -25,6 +31,8 @@ const { rendering, canGenerate, blockedNote, + estimate, + credits, wide = false, locale = 'en' } = defineProps<{ @@ -33,16 +41,41 @@ const { rendering: boolean canGenerate: boolean blockedNote?: string + estimate?: ShotEstimate + credits?: number wide?: boolean locale?: Locale }>() -const emit = defineEmits<{ generate: []; cancel: [] }>() +const emit = defineEmits<{ + generate: [] + cancel: [] + reduceTakes: [takes: number] +}>() const signInHref = useSignInHref(locale) +const personal = usePersonalWorkspaceSwitch() +const creditGate = computed( + () => gate === 'noCredits' || gate === 'memberNoCredits' +) +const shortfall = computed(() => { + if (!creditGate.value || !estimate || credits === undefined) return undefined + const key = + estimate.takes === 1 + ? 'cinematic.credits.shortOne' + : 'cinematic.credits.short' + return { + note: tc(key, locale) + .replace('{takes}', String(estimate.takes)) + .replace('{credits}', formatCreditRange(estimate.total, locale)) + .replace('{balance}', credits.toLocaleString(locale)), + fits: Math.min(takesWithin(credits, estimate.perTake), estimate.takes - 1) + } +}) const note = computed(() => { const workspace = () => workspaceName ?? '' + if (shortfall.value) return shortfall.value.note if (gate === 'noCredits') return t('workshop.error.noCreditsCloud', locale).replace( '{workspace}', @@ -56,6 +89,28 @@ const note = computed(() => { if (gate === 'unavailable') return tc('cinematic.output.unavailable', locale) return undefined }) +const cost = computed(() => { + if (!estimate) + return { + label: tc('cinematic.credits.varies', locale), + hint: tc('cinematic.credits.variesHint', locale) + } + return { + label: tc('cinematic.credits.estimate', locale).replace( + '{credits}', + formatCreditRange(estimate.total, locale) + ), + detail: + estimate.takes > 1 + ? tc('cinematic.credits.perTake', locale) + .replace('{takes}', String(estimate.takes)) + .replace('{credits}', formatCreditRange(estimate.perTake, locale)) + : undefined + } +}) +const showCost = computed( + () => !rendering && gate !== 'unavailable' && gate !== 'pending' +) const buttonClass = computed(() => wide ? 'w-full rounded-full px-5' : 'shrink-0 rounded-full px-6' ) @@ -63,7 +118,17 @@ const buttonClass = computed(() => diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicPanel.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicPanel.vue index 9ead15825f4..123a2eefbcd 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicPanel.vue +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicPanel.vue @@ -13,6 +13,7 @@ import { cameraGroups, directionOption } from '../../../lib/workshop/cinematic-studio/catalog' +import type { ShotEstimate } from '../../../lib/workshop/cinematic-studio/estimate' import type { StudioGate } from '../../../lib/workshop/cinematic-studio/gate' import type { PromptSegment } from '../../../lib/workshop/cinematic-studio/prompt' import type { Locale } from '../../../i18n/translations' @@ -34,6 +35,8 @@ const { gate, workspaceName, rendering, + estimate, + credits, openPicker, locale = 'en' } = defineProps<{ @@ -42,6 +45,8 @@ const { gate: StudioGate workspaceName?: string rendering: boolean + estimate?: ShotEstimate + credits?: number openPicker?: PickerKey locale?: Locale }>() @@ -242,10 +247,13 @@ const cardClass = :rendering :can-generate="canGenerate" :blocked-note="blockedNote" + :estimate + :credits wide :locale @generate="emit('generate')" @cancel="emit('cancel')" + @reduce-takes="takes = $event" /> diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.test.ts b/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.test.ts index 526354ecf8a..c2a23a9fd2e 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.test.ts +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.test.ts @@ -644,6 +644,167 @@ describe('CinematicStudio', () => { expect(screen.queryByTestId('cinematic')).toBeNull() }) + describe('credits', () => { + const priced: readonly CinematicModel[] = models.map((model) => + model.slug === first.slug + ? { + ...model, + prices: { + '21:9 2K 0': { min: 6, max: 6 }, + '21:9 1K 0': { min: 3, max: 3 } + } + } + : model + ) + const estimate = () => screen.findByTestId('cinematic-estimate') + const credits = (amount: number) => + tc('cinematic.credits.estimate').replace('{credits}', String(amount)) + + async function shootTakes( + user: ReturnType, + takes: number + ) { + await user.click(screen.getByRole('button', { name: /^Format/ })) + const more = screen.getByRole('button', { name: 'More takes' }) + for (let shown = 1; shown < takes; shown++) await user.click(more) + } + + function withBalance(amount: number) { + useWorkshopCredits().balance = computed(() => ({ + status: 'ok' as const, + credits: amount + })) + } + + it('estimates a priced model and says an unpriced one varies', async () => { + const user = renderStudio(priced) + expect(await estimate()).toHaveTextContent(credits(6)) + + await user.click(screen.getByRole('button', { name: /^Model/ })) + await user.click( + await screen.findByRole('menuitemradio', { + name: new RegExp(second.name) + }) + ) + + expect(await estimate()).toHaveTextContent(tc('cinematic.credits.varies')) + expect(await estimate()).not.toHaveTextContent(/\d/) + }) + + it('scales the estimate with takes and resolution', async () => { + const user = renderStudio(priced) + + await addTake(user) + expect(await estimate()).toHaveTextContent(credits(12)) + expect(await estimate()).toHaveTextContent('2 takes × ~6 credits') + + await user.click(screen.getByRole('button', { name: 'Resolution: 2K' })) + await user.click(await screen.findByRole('menuitemradio', { name: '1K' })) + + expect(await estimate()).toHaveTextContent(credits(6)) + expect(await estimate()).toHaveTextContent('2 takes × ~3 credits') + }) + + it.for([ + { + balance: 20, + takes: 4, + note: '4 takes need ~24 credits; you have 20.', + reduce: 'Use 3 takes' + }, + { + balance: 7, + takes: 2, + note: '2 takes need ~12 credits; you have 7.', + reduce: 'Use 1 take' + }, + { + balance: 5, + takes: 1, + note: '1 take needs ~6 credits; you have 5.', + reduce: undefined + } + ])( + 'blocks $takes takes on a balance of $balance', + async ({ balance, takes, note, reduce }) => { + withBalance(balance) + const user = renderStudio(priced) + await user.type(screen.getByLabelText('Scene'), 'A diner at dawn') + await shootTakes(user, takes) + + expect(screen.getByTestId('cinematic-credit-note')).toHaveTextContent( + note + ) + expect(screen.queryByTestId('cinematic-generate')).toBeNull() + expect( + screen.getByRole('button', { name: t('workshop.run.buyCredits') }) + ).toBeInTheDocument() + expect( + screen + .queryByRole('button', { name: /^Use \d takes?$/ }) + ?.textContent.trim() + ).toBe(reduce) + } + ) + + it('generates the takes a short balance covers once reduced', async () => { + withBalance(20) + vi.mocked(router_render).mockImplementation(async (slug) => + rendered(slug) + ) + const user = renderStudio(priced) + await user.type(screen.getByLabelText('Scene'), 'A diner at dawn') + await shootTakes(user, 4) + + await user.click(screen.getByRole('button', { name: 'Use 3 takes' })) + expect(await estimate()).toHaveTextContent(credits(18)) + await user.click(generateButton()) + + expect( + await screen.findByRole('radio', { name: 'C' }) + ).toBeInTheDocument() + expect(router_render).toHaveBeenCalledTimes(3) + }) + + it('keeps the zero-balance gate for a model without an estimate', async () => { + withBalance(0) + renderStudio() + + expect(await estimate()).toHaveTextContent(tc('cinematic.credits.varies')) + expect(screen.queryByTestId('cinematic-generate')).toBeNull() + expect( + screen.getByRole('button', { name: t('workshop.run.buyCredits') }) + ).toBeInTheDocument() + }) + + it('runs an unpriced model on any balance above zero', async () => { + withBalance(1) + const user = renderStudio() + await user.type(screen.getByLabelText('Scene'), 'A diner at dawn') + + expect(generateButton()).toBeEnabled() + }) + + it('sends a member to their personal workspace instead of checkout', async () => { + withBalance(0) + signedIn.value = { ...credential, role: 'member' } + const user = renderStudio(priced) + + await user.click( + await screen.findByRole('button', { + name: t('workshop.run.switchPersonal') + }) + ) + + expect(useWorkshopSession().remint).toHaveBeenCalledWith(undefined, { + preserveCredentialOnTransientFailure: true + }) + expect( + screen.queryByRole('button', { name: t('workshop.run.buyCredits') }) + ).toBeNull() + }) + }) + describe('layout switch', () => { const panel = () => screen.queryByRole('complementary', { name: 'Shot settings' }) diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.vue index 3549e4bca8a..5f571a2ef22 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.vue +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicStudio.vue @@ -40,6 +40,7 @@ const { cast, palette, references, + estimate, choose, start: startShot, generate: generateShot @@ -194,15 +195,17 @@ function generateOn(slug: string) { { - timers.delete(timer) - settle(id, 0, null) - }, DEMO_RENDER_MS) - timers.add(timer) + ids.forEach((id) => { + dispatch({ type: 'takeRetried', id, startedAt: Date.now() }) + const timer = setTimeout(() => { + timers.delete(timer) + settle(id, 0, null) + }, DEMO_RENDER_MS) + timers.add(timer) + }) } function cancel() { @@ -133,6 +135,7 @@ export function useCinematicDemoRun() { return { reel: readonly(reel), gate, + credits: computed(() => undefined), session: shallowRef(), rendering, generate, diff --git a/apps/website/src/composables/useCinematicShot.ts b/apps/website/src/composables/useCinematicShot.ts index 15b8d999409..40133166feb 100644 --- a/apps/website/src/composables/useCinematicShot.ts +++ b/apps/website/src/composables/useCinematicShot.ts @@ -11,6 +11,7 @@ import { RESOLUTIONS, directionOption } from '../lib/workshop/cinematic-studio/catalog' +import { shotEstimate } from '../lib/workshop/cinematic-studio/estimate' import type { CinematicModel } from '../lib/workshop/cinematic-studio/models' import { cinematicPrompt, @@ -22,10 +23,6 @@ import { useCinematicStudioRun } from './useCinematicStudioRun' /** The shot being directed, shared by every Cinematic Studio layout. */ export function useCinematicShot(models: readonly CinematicModel[]) { - const studio = isCinematicDemo() - ? useCinematicDemoRun() - : useCinematicStudioRun(models.length) - const modelSlug = ref(models[0]?.slug ?? '') const scene = ref('') const enhance = ref(true) @@ -56,6 +53,18 @@ export function useCinematicShot(models: readonly CinematicModel[]) { const model = computed(() => models.find((option) => option.slug === modelSlug.value) ) + const estimate = computed(() => + shotEstimate(model.value?.prices, { + aspect: aspect.value, + resolution: resolution.value, + references: references.value.length, + takes: takes.value + }) + ) + + const studio = isCinematicDemo() + ? useCinematicDemoRun() + : useCinematicStudioRun(models.length, () => estimate.value?.total.min) function choose(part: DirectionPart, id: string) { direction.value = { ...direction.value, [part]: id } @@ -103,6 +112,7 @@ export function useCinematicShot(models: readonly CinematicModel[]) { palette, promptSegments, references, + estimate, choose, start, generate diff --git a/apps/website/src/composables/useCinematicStudioRun.ts b/apps/website/src/composables/useCinematicStudioRun.ts index 0a1a1c9addd..ce2b28ee51a 100644 --- a/apps/website/src/composables/useCinematicStudioRun.ts +++ b/apps/website/src/composables/useCinematicStudioRun.ts @@ -103,8 +103,12 @@ function mayStillSettle(error: unknown): boolean { * Runs a shot as one Router request per take, through the same render path, * credentials and credit gate as a model page. Models load lazily from their * page data, so the studio never ships the catalogue to the client. + * `shotCost` is the least the shot being directed is estimated to cost. */ -export function useCinematicStudioRun(modelCount: number) { +export function useCinematicStudioRun( + modelCount: number, + shotCost: () => number | undefined = () => undefined +) { const { user, session, sessionFailure, settled, ensureFresh } = useWorkshopSession() const { balance } = useWorkshopCredits() @@ -119,7 +123,10 @@ export function useCinematicStudioRun(modelCount: number) { } const rendering = computed(() => isRendering(reel.value)) - const gate = computed(() => + const credits = computed(() => + balance.value.status === 'ok' ? balance.value.credits : undefined + ) + const gateFor = (cost: number | undefined) => studioGate({ runEnabled: workshopEnabled.value && @@ -129,12 +136,10 @@ export function useCinematicStudioRun(modelCount: number) { authAvailable: authEnabled.value && !sessionFailure.value, sessionSettled: settled.value && !(user.value && !session.value), role: session.value?.role, - outOfCredits: - !rendering.value && - balance.value.status === 'ok' && - balance.value.credits <= 0 + credits: rendering.value ? undefined : credits.value, + cost }) - ) + const gate = computed(() => gateFor(shotCost())) const models = new Map>() function loadModel(slug: string): Promise { @@ -277,20 +282,23 @@ export function useCinematicStudioRun(modelCount: number) { await runTakes(takes, startedFor) } - async function retry(id: string) { + /** Retries settled takes; the shot being directed does not price them. */ + async function retry(...ids: string[]) { const startedFor = session.value - const plan = plans.get(id) - const take = reel.value.takes.find((candidate) => candidate.id === id) - if ( - rendering.value || - gate.value !== 'ready' || - !startedFor || - !plan || - (take?.status !== 'failed' && take?.status !== 'cancelled') + if (rendering.value || gateFor(undefined) !== 'ready' || !startedFor) return + const retried = ids.flatMap((id) => { + const plan = plans.get(id) + const take = reel.value.takes.find((candidate) => candidate.id === id) + return plan && (take?.status === 'failed' || take?.status === 'cancelled') + ? [plan] + : [] + }) + if (!retried.length) return + const startedAt = Date.now() + retried.forEach(({ id }) => + dispatch({ type: 'takeRetried', id, startedAt }) ) - return - dispatch({ type: 'takeRetried', id, startedAt: Date.now() }) - await runTakes([plan], startedFor) + await runTakes(retried, startedFor) } function cancel() { @@ -318,6 +326,7 @@ export function useCinematicStudioRun(modelCount: number) { return { reel: readonly(reel), gate, + credits, session, rendering, generate, diff --git a/apps/website/src/composables/usePersonalWorkspaceSwitch.ts b/apps/website/src/composables/usePersonalWorkspaceSwitch.ts new file mode 100644 index 00000000000..459e94289c1 --- /dev/null +++ b/apps/website/src/composables/usePersonalWorkspaceSwitch.ts @@ -0,0 +1,33 @@ +import { ref } from 'vue' + +import { refreshWorkshopCredits } from '../config/workshop-credits' +import { useWorkshopSession } from '../config/workshop-session-state' + +/** + * Moves a workspace member whose team is out of credits onto their personal + * workspace, then re-reads the balance that now pays for runs. + */ +export function usePersonalWorkspaceSwitch() { + const { remint } = useWorkshopSession() + const pending = ref(false) + const failed = ref(false) + + async function switchToPersonal() { + if (pending.value) return + pending.value = true + failed.value = false + try { + const result = await remint(undefined, { + preserveCredentialOnTransientFailure: true + }) + if (result?.status === 'ok') await refreshWorkshopCredits({ force: true }) + else if (result?.status === 'error') failed.value = true + } catch { + failed.value = true + } finally { + pending.value = false + } + } + + return { pending, failed, switchToPersonal } +} diff --git a/apps/website/src/config/workshop-run.test.ts b/apps/website/src/config/workshop-run.test.ts index f419a87c995..3d2cea3fbf8 100644 --- a/apps/website/src/config/workshop-run.test.ts +++ b/apps/website/src/config/workshop-run.test.ts @@ -6,7 +6,6 @@ import { OUTPUT_TTL_MS, formatElapsed, isExpired, - runGate, transition } from './workshop-run' @@ -68,44 +67,6 @@ describe('run transition', () => { }) }) -describe('runGate', () => { - const base = { - signedIn: true, - credits: 100, - creditsPerRun: 24, - policyDisabled: false, - unavailable: false - } - - it('is ready when signed in with enough credits', () => { - expect(runGate(base)).toBe('ready') - }) - - it('refuses to run a model whose price is unknown', () => { - expect(runGate({ ...base, creditsPerRun: undefined })).toBe('unavailable') - }) - - it('asks for sign in before anything account related', () => { - expect(runGate({ ...base, signedIn: false, credits: 0 })).toBe('signedOut') - }) - - it('prefers the policy block over buying credits', () => { - expect(runGate({ ...base, policyDisabled: true, credits: 0 })).toBe( - 'policy' - ) - }) - - it('blocks on credits below the per-run price', () => { - expect(runGate({ ...base, credits: 23 })).toBe('noCredits') - }) - - it('reports an unavailable model regardless of session', () => { - expect(runGate({ ...base, signedIn: false, unavailable: true })).toBe( - 'unavailable' - ) - }) -}) - describe('formatElapsed', () => { it('formats minutes and zero-padded seconds', () => { expect(formatElapsed(0)).toBe('0:00') @@ -113,27 +74,7 @@ describe('formatElapsed', () => { }) }) -describe('runGate for teams and model lifecycles', () => { - const base = { - signedIn: true, - credits: 100, - creditsPerRun: 24, - policyDisabled: false, - unavailable: false - } - - it('hands a member without credits to the owner instead of checkout', () => { - expect(runGate({ ...base, credits: 0, role: 'member' })).toBe( - 'memberNoCredits' - ) - expect(runGate({ ...base, credits: 0, role: 'owner' })).toBe('noCredits') - }) - - it('treats a deprecated model as unavailable', () => { - expect(runGate({ ...base, modelStatus: 'deprecated' })).toBe('unavailable') - expect(runGate({ ...base, modelStatus: 'degraded' })).toBe('ready') - }) - +describe('isExpired', () => { it('expires an output at the end of its ttl', () => { const running = transition(IDLE, { type: 'start', at: 1_000 }) const done = transition(running, { diff --git a/apps/website/src/config/workshop-run.ts b/apps/website/src/config/workshop-run.ts index f2ce2ad6bd0..9998cc2d1ba 100644 --- a/apps/website/src/config/workshop-run.ts +++ b/apps/website/src/config/workshop-run.ts @@ -1,5 +1,5 @@ import type { FieldErrors } from './workshop-playground' -import type { Modality, ModelStatus } from './models-catalogue' +import type { Modality } from './models-catalogue' export const OUTPUT_TTL_MS = 24 * 60 * 60 * 1000 @@ -112,44 +112,6 @@ export function transition(state: RunState, event: RunEvent): RunState { } } -export type RunGate = - | 'signedOut' - | 'noCredits' - | 'memberNoCredits' - | 'policy' - | 'unavailable' - | 'ready' - -export interface GateInput { - readonly signedIn: boolean - readonly credits: number - readonly creditsPerRun: number | undefined - readonly modelStatus?: ModelStatus - readonly policyDisabled: boolean - readonly unavailable: boolean - readonly role?: 'owner' | 'member' -} - -// Order matters: sign-in is asked before anything the account could fix, -// and a workspace policy block wins over credits because buying would not -// unblock the run. -export function runGate(input: GateInput): RunGate { - // No price means the cost of a run is unknown, not free. - if ( - input.unavailable || - input.modelStatus === 'deprecated' || - input.creditsPerRun === undefined - ) { - return 'unavailable' - } - if (!input.signedIn) return 'signedOut' - if (input.policyDisabled) return 'policy' - if (input.credits < input.creditsPerRun) { - return input.role === 'member' ? 'memberNoCredits' : 'noCredits' - } - return 'ready' -} - export function isExpired(state: RunState, now: number): boolean { return ( state.status === 'succeeded' && diff --git a/apps/website/src/lib/workshop/cinematic-studio/copy.ts b/apps/website/src/lib/workshop/cinematic-studio/copy.ts index b38675c54af..0eb335d4873 100644 --- a/apps/website/src/lib/workshop/cinematic-studio/copy.ts +++ b/apps/website/src/lib/workshop/cinematic-studio/copy.ts @@ -100,6 +100,46 @@ const copy = { en: 'Edit scene', 'zh-CN': '修改场景' }, + 'cinematic.credits.estimate': { + en: '~{credits} credits', + 'zh-CN': '约 {credits} 积分' + }, + 'cinematic.credits.perTake': { + en: '{takes} takes × ~{credits} credits', + 'zh-CN': '{takes} 条 × 约 {credits} 积分' + }, + 'cinematic.credits.varies': { + en: 'Cost varies', + 'zh-CN': '费用不定' + }, + 'cinematic.credits.variesHint': { + en: 'This model has no published price yet. Each take is charged what the model bills for it.', + 'zh-CN': '该模型暂无公开价格,每一条按模型实际计费扣除积分。' + }, + 'cinematic.credits.short': { + en: '{takes} takes need ~{credits} credits; you have {balance}.', + 'zh-CN': '{takes} 条需要约 {credits} 积分,你有 {balance} 积分。' + }, + 'cinematic.credits.shortOne': { + en: '1 take needs ~{credits} credits; you have {balance}.', + 'zh-CN': '1 条需要约 {credits} 积分,你有 {balance} 积分。' + }, + 'cinematic.credits.reduce': { + en: 'Use {takes} takes', + 'zh-CN': '改为 {takes} 条' + }, + 'cinematic.credits.reduceOne': { + en: 'Use 1 take', + 'zh-CN': '改为 1 条' + }, + 'cinematic.credits.skipped': { + en: '{failed} of {total} takes weren’t run: not enough credits', + 'zh-CN': '{total} 条中有 {failed} 条因积分不足未运行' + }, + 'cinematic.credits.retrySkipped': { + en: 'Run them now', + 'zh-CN': '立即运行' + }, 'cinematic.output.checking': { en: 'Checking…', 'zh-CN': '检查中…' diff --git a/apps/website/src/lib/workshop/cinematic-studio/estimate.ts b/apps/website/src/lib/workshop/cinematic-studio/estimate.ts new file mode 100644 index 00000000000..5378eb17626 --- /dev/null +++ b/apps/website/src/lib/workshop/cinematic-studio/estimate.ts @@ -0,0 +1,54 @@ +import type { CreditRange } from '../../../config/workshop-node-pricing' +import type { Locale } from '../../../i18n/translations' +import type { AspectRatio, Resolution } from './catalog' +import { MAX_TAKES } from './catalog' + +/** Credits per take, keyed by {@link priceKey}. */ +export type CinematicPrices = Readonly> + +export function priceKey( + aspect: AspectRatio, + resolution: Resolution, + references: number +): string { + return `${aspect} ${resolution} ${references}` +} + +export interface ShotEstimate { + readonly takes: number + readonly perTake: CreditRange + readonly total: CreditRange +} + +export function shotEstimate( + prices: CinematicPrices | undefined, + shot: { + readonly aspect: AspectRatio + readonly resolution: Resolution + readonly references: number + readonly takes: number + } +): ShotEstimate | undefined { + const perTake = + prices?.[priceKey(shot.aspect, shot.resolution, shot.references)] + return ( + perTake && { + takes: shot.takes, + perTake, + total: { min: perTake.min * shot.takes, max: perTake.max * shot.takes } + } + ) +} + +/** How many takes a balance covers at the low end of the estimate. */ +export function takesWithin(credits: number, perTake: CreditRange): number { + if (perTake.min <= 0) return MAX_TAKES + return Math.min(MAX_TAKES, Math.floor(credits / perTake.min)) +} + +export function formatCreditRange(range: CreditRange, locale: Locale): string { + const format = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }) + const min = format.format(range.min) + const max = format.format(range.max) + return min === max ? min : `${min}–${max}` +} diff --git a/apps/website/src/lib/workshop/cinematic-studio/gate.test.ts b/apps/website/src/lib/workshop/cinematic-studio/gate.test.ts index 6e1a74ad657..c5b0e66328b 100644 --- a/apps/website/src/lib/workshop/cinematic-studio/gate.test.ts +++ b/apps/website/src/lib/workshop/cinematic-studio/gate.test.ts @@ -11,7 +11,7 @@ const ready: StudioGateInput = { authAvailable: true, sessionSettled: true, role: 'owner', - outOfCredits: false + credits: 100 } describe('studioGate', () => { @@ -31,10 +31,28 @@ describe('studioGate', () => { ['is unavailable without auth', { authAvailable: false }, 'unavailable'], ['waits for the session to settle', { sessionSettled: false }, 'pending'], ['asks a visitor to sign in', { role: undefined }, 'signedOut'], - ['asks an owner to buy credits', { outOfCredits: true }, 'noCredits'], + [ + 'asks for sign-in before credits', + { role: undefined, credits: 0 }, + 'signedOut' + ], + ['runs before the balance is read', { credits: undefined }, 'ready'], + ['asks an owner to buy credits', { credits: 0 }, 'noCredits'], [ 'tells a member the workspace is out', - { outOfCredits: true, role: 'member' }, + { credits: 0, role: 'member' }, + 'memberNoCredits' + ], + ['runs an unpriced shot on any balance', { credits: 1 }, 'ready'], + ['runs a shot the balance covers', { credits: 24, cost: 24 }, 'ready'], + [ + 'blocks an owner below the estimate', + { credits: 23, cost: 24 }, + 'noCredits' + ], + [ + 'blocks a member below the estimate', + { credits: 23, cost: 24, role: 'member' }, 'memberNoCredits' ] ])('%s', ([, overrides, expected]) => { diff --git a/apps/website/src/lib/workshop/cinematic-studio/gate.ts b/apps/website/src/lib/workshop/cinematic-studio/gate.ts index bf05fe6b961..8a3e06f65ca 100644 --- a/apps/website/src/lib/workshop/cinematic-studio/gate.ts +++ b/apps/website/src/lib/workshop/cinematic-studio/gate.ts @@ -15,13 +15,28 @@ export interface StudioGateInput { readonly authAvailable: boolean readonly sessionSettled: boolean readonly role?: 'owner' | 'member' - readonly outOfCredits: boolean + /** The balance, once read. */ + readonly credits?: number + /** The least the shot is estimated to cost, when its model is priced. */ + readonly cost?: number +} + +/** + * Whether a balance covers a run. Without an estimate only an empty balance + * is known to be short; with one, anything below it is. + */ +function coversCost( + credits: number | undefined, + cost: number | undefined +): boolean { + if (credits === undefined) return true + return cost === undefined ? credits > 0 : credits >= cost } /** * What the Generate slot offers. `role` is present only once there is a * session; `sessionSettled` is false while a signed-in user's session is - * still being minted. + * still being minted. Sign-in is asked before anything the account could fix. */ export function studioGate(input: StudioGateInput): StudioGate { if (!input.runEnabled || !input.modelRunnable) return 'unavailable' @@ -29,7 +44,7 @@ export function studioGate(input: StudioGateInput): StudioGate { if (!input.authAvailable) return 'unavailable' if (!input.sessionSettled) return 'pending' if (!input.role) return 'signedOut' - if (!input.outOfCredits) return 'ready' + if (coversCost(input.credits, input.cost)) return 'ready' return input.role === 'member' ? 'memberNoCredits' : 'noCredits' } diff --git a/apps/website/src/lib/workshop/cinematic-studio/models.ts b/apps/website/src/lib/workshop/cinematic-studio/models.ts index 9078a4be4be..71c0067a3d5 100644 --- a/apps/website/src/lib/workshop/cinematic-studio/models.ts +++ b/apps/website/src/lib/workshop/cinematic-studio/models.ts @@ -1,4 +1,5 @@ import type { WorkshopModelDetail } from '../../../config/models-catalogue' +import type { CinematicPrices } from './estimate' import { canRunModel } from './gate' type ModelLookup = ( @@ -18,6 +19,8 @@ export interface CinematicModel { readonly degraded?: boolean /** The operation that keeps reference images, when the model has one. */ readonly referenceSlug?: string + /** Credits per take; absent when the model has no verified price. */ + readonly prices?: CinematicPrices } const CINEMATIC_MODEL_LOGOS: Readonly> = { diff --git a/apps/website/src/lib/workshop/cinematic-studio/pricing.test.ts b/apps/website/src/lib/workshop/cinematic-studio/pricing.test.ts new file mode 100644 index 00000000000..15ac2b10dc6 --- /dev/null +++ b/apps/website/src/lib/workshop/cinematic-studio/pricing.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest' + +import { getRouterWorkshopModelDetail } from '../../../config/workshop-router-content' +import { priceKey, shotEstimate } from './estimate' +import { runnableCinematicModels } from './models' +import { priceCinematicModels } from './pricing' + +const models = await priceCinematicModels( + runnableCinematicModels(getRouterWorkshopModelDetail), + getRouterWorkshopModelDetail +) +const prices = (slug: string) => + models.find((model) => model.slug === slug)?.prices + +const FLUX = 'bfl--flux-2-pro--generate-images' +const SEEDREAM = 'byteplus--seedream-4-5--generate-images' + +describe('priceCinematicModels', () => { + it.for([ + 'vertexai--gemini-3-pro-image--generate-images', + 'krea--krea-2-large--generate-images', + 'qwen--qwen-image-3.0-pro-text-to-image--generate-images' + ])('leaves %s without an estimate', (slug) => { + expect(models.some((model) => model.slug === slug)).toBe(true) + expect(prices(slug)).toBeUndefined() + }) + + it('prices Flux 2 Pro by the frame the Router is asked for', () => { + const square = (resolution: '1K' | '2K') => + prices(FLUX)?.[priceKey('1:1', resolution, 0)] + expect(square('1K')?.min).toBeCloseTo(6.33) + expect(square('2K')?.min).toBeCloseTo(15.825) + }) + + it('widens Flux 2 Pro to its reference-image range', () => { + const plain = prices(FLUX)?.[priceKey('1:1', '1K', 0)] + const referenced = prices(FLUX)?.[priceKey('1:1', '1K', 1)] + expect(referenced?.min).toBeGreaterThan(plain?.min ?? Infinity) + expect(referenced?.max).toBeGreaterThan(referenced?.min ?? Infinity) + }) + + it('prices every Seedream 4.5 format, with and without references', () => { + expect(Object.keys(prices(SEEDREAM) ?? {})).toHaveLength(30) + }) +}) + +describe('shotEstimate', () => { + it('multiplies the per-take price by the takes', () => { + const shot = { aspect: '1:1', resolution: '2K', references: 0 } as const + const one = shotEstimate(prices(FLUX), { ...shot, takes: 1 }) + const four = shotEstimate(prices(FLUX), { ...shot, takes: 4 }) + expect(four?.total.min).toBeCloseTo((one?.total.min ?? 0) * 4) + }) +}) diff --git a/apps/website/src/lib/workshop/cinematic-studio/pricing.ts b/apps/website/src/lib/workshop/cinematic-studio/pricing.ts new file mode 100644 index 00000000000..e98ada642f0 --- /dev/null +++ b/apps/website/src/lib/workshop/cinematic-studio/pricing.ts @@ -0,0 +1,82 @@ +import type { WorkshopModelDetail } from '../../../config/models-catalogue' +import { useCaseFor } from '../../../config/models-catalogue' +import { resolveModelRouterRender } from '../../../config/router-render' +import type { WorkshopRunSettings } from '../../../config/workshop-node-pricing' +import { estimateWorkshopRunCredits } from '../../../config/workshop-node-pricing' +import { ASPECT_RATIOS, RESOLUTIONS } from './catalog' +import type { AspectRatio } from './catalog' +import type { CinematicPrices } from './estimate' +import { priceKey } from './estimate' +import type { CinematicModel } from './models' + +type DetailLookup = (slug: string) => WorkshopModelDetail | undefined + +/** A shot sends no reference, the cast, the palette, or both. */ +const REFERENCE_COUNTS = [0, 1, 2] as const + +/** The frame size the Router mapping sends for this aspect and resolution. */ +function requestedSize( + model: WorkshopModelDetail, + aspect: AspectRatio, + pixels: number +): WorkshopRunSettings | undefined { + try { + const { values } = resolveModelRouterRender(model, { + aspect_ratio: aspect, + resolution: pixels + }) + const { width, height, size } = values + if (typeof width === 'number' && typeof height === 'number') + return { width, height } + const match = + typeof size === 'string' ? /^(\d+)\s*[x*]\s*(\d+)$/.exec(size) : null + return match ? { width: Number(match[1]), height: Number(match[2]) } : {} + } catch { + return undefined + } +} + +async function pricesFor( + model: CinematicModel, + lookup: DetailLookup +): Promise { + const priced = await Promise.all( + REFERENCE_COUNTS.flatMap((references) => { + const slug = references ? model.referenceSlug : model.slug + const detail = slug ? lookup(slug) : undefined + if (!detail) return [] + return ASPECT_RATIOS.flatMap(({ id: aspect }) => + RESOLUTIONS.map(async ({ id: resolution, pixels }) => { + const size = requestedSize(detail, aspect, pixels) + const credits = + size && + (await estimateWorkshopRunCredits(detail, useCaseFor(detail), { + ...size, + images: references + })) + return credits + ? [[priceKey(aspect, resolution, references), credits] as const] + : [] + }) + ) + }) + ) + const prices = Object.fromEntries(priced.flat()) + return Object.keys(prices).length ? prices : undefined +} + +/** + * Adds each model's per-take credit estimate for every format a shot can + * ask for, at build time, so the studio never ships the pricing rules. + */ +export function priceCinematicModels( + models: readonly CinematicModel[], + lookup: DetailLookup +): Promise { + return Promise.all( + models.map(async (model) => { + const prices = await pricesFor(model, lookup) + return prices ? { ...model, prices } : model + }) + ) +} diff --git a/apps/website/src/routes/models/cinematic-studio.astro b/apps/website/src/routes/models/cinematic-studio.astro index 46bb39206bd..49026325982 100644 --- a/apps/website/src/routes/models/cinematic-studio.astro +++ b/apps/website/src/routes/models/cinematic-studio.astro @@ -3,9 +3,13 @@ import BaseLayout from '../../layouts/BaseLayout.astro' import CinematicStudioPage from '../../components/workshop/cinematic-studio/CinematicStudioPage.vue' import { getRouterWorkshopModelDetail } from '../../config/workshop-router-content' import { runnableCinematicModels } from '../../lib/workshop/cinematic-studio/models' +import { priceCinematicModels } from '../../lib/workshop/cinematic-studio/pricing' import { tc } from '../../lib/workshop/cinematic-studio/copy' -const models = runnableCinematicModels(getRouterWorkshopModelDetail) +const models = await priceCinematicModels( + runnableCinematicModels(getRouterWorkshopModelDetail), + getRouterWorkshopModelDetail +) if (!models.length) throw new Error('Cinematic Studio has no runnable models') --- From d86439d2c9e07a4d59036c1c54233bcdd34d9c62 Mon Sep 17 00:00:00 2001 From: benjcooley Date: Fri, 25 Sep 2026 15:19:34 -0700 Subject: [PATCH 4/6] feat(website): give members their own credit copy and sum up unpaid takes - A take refused for credits now tells a workspace member what the model page tells them (the team is out; ask the owner or run on your personal workspace) and offers the switch to personal instead of checkout. - Takes refused for credits get a yellow warning state in the sequence, the take picker and the frame, and a shot with several takes shows how many were not run with the same top-up or switch action. - Once a top-up lands (the header's top-up watch), that action becomes a retry of the unpaid takes. --- .../CinematicCreditAction.vue | 68 ++++++++++++ .../CinematicCreditSummary.vue | 57 ++++++++++ .../cinematic-studio/CinematicSequence.vue | 20 +++- .../cinematic-studio/CinematicStage.vue | 12 +- .../cinematic-studio/CinematicStageCard.vue | 16 ++- .../cinematic-studio/CinematicStudio.test.ts | 103 +++++++++++++++++- .../cinematic-studio/CinematicStudio.vue | 2 + .../cinematic-studio/CinematicStudioPanel.vue | 2 + .../cinematic-studio/CinematicTakeBar.vue | 9 +- .../cinematic-studio/CinematicTakeFrame.vue | 7 +- .../cinematic-studio/CinematicTakeNotice.vue | 32 +++--- .../src/composables/useCinematicShot.ts | 7 ++ .../src/lib/workshop/cinematic-studio/reel.ts | 5 + 13 files changed, 320 insertions(+), 20 deletions(-) create mode 100644 apps/website/src/components/workshop/cinematic-studio/CinematicCreditAction.vue create mode 100644 apps/website/src/components/workshop/cinematic-studio/CinematicCreditSummary.vue diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicCreditAction.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicCreditAction.vue new file mode 100644 index 00000000000..9a893c71158 --- /dev/null +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicCreditAction.vue @@ -0,0 +1,68 @@ + + + diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicCreditSummary.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicCreditSummary.vue new file mode 100644 index 00000000000..f31d645a952 --- /dev/null +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicCreditSummary.vue @@ -0,0 +1,57 @@ + + + diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicSequence.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicSequence.vue index 98d97736328..4abde7f2e98 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicSequence.vue +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicSequence.vue @@ -1,9 +1,16 @@ @@ -107,6 +111,7 @@ function frameTone(take: Take): string | undefined { v-else :take="current" :other-model="otherModel" + :member-workspace="memberWorkspace" :locale @retry="emit('retry')" @switch-model="emit('switchModel', $event)" diff --git a/apps/website/src/components/workshop/cinematic-studio/CinematicTakeNotice.vue b/apps/website/src/components/workshop/cinematic-studio/CinematicTakeNotice.vue index f2073a9d5b0..d4a3cab5cc6 100644 --- a/apps/website/src/components/workshop/cinematic-studio/CinematicTakeNotice.vue +++ b/apps/website/src/components/workshop/cinematic-studio/CinematicTakeNotice.vue @@ -6,22 +6,25 @@ 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 { requestWorkshopBuyCredits } from '../../../config/workshop-buy-credits' import type { Take } from '../../../lib/workshop/cinematic-studio/reel' import { failureLabelKey } from '../../../lib/workshop/failure-label' import type { Locale } from '../../../i18n/translations' import { t } from '../../../i18n/translations' import { tc } from '../../../lib/workshop/cinematic-studio/copy' +import CinematicCreditAction from './CinematicCreditAction.vue' type Settled = Extract const { take, otherModel, + memberWorkspace, locale = 'en' } = defineProps<{ take: Settled otherModel?: { slug: string; name: string } + /** The team workspace paying for runs, when the viewer is a member. */ + memberWorkspace?: string locale?: Locale }>() @@ -53,11 +56,15 @@ const title = computed(() => { if (kind.value === 'blocked') return tc('cinematic.state.blocked', locale) return tc('cinematic.state.failed', locale) }) -const body = computed(() => - take.status === 'cancelled' - ? t('workshop.output.cancelled', locale) - : t(failureLabelKey[take.reason], locale) -) +const body = computed(() => { + if (take.status === 'cancelled') return t('workshop.output.cancelled', locale) + if (kind.value === 'noCredits' && memberWorkspace !== undefined) + return t('workshop.error.memberNoCredits', locale).replace( + '{workspace}', + () => memberWorkspace + ) + return t(failureLabelKey[take.reason], locale) +}) const requestId = computed(() => take.status === 'failed' ? take.requestId : undefined ) @@ -80,14 +87,13 @@ const requestId = computed(() => {{ body }}
- + :member="memberWorkspace !== undefined" + :retry-label="t('workshop.error.retry', locale)" + :locale + @retry="emit('retry')" + />