diff --git a/apps/website/e2e/fixtures/modelsAccount.ts b/apps/website/e2e/fixtures/modelsAccount.ts index 5faef2d2099..3df81fc951f 100644 --- a/apps/website/e2e/fixtures/modelsAccount.ts +++ b/apps/website/e2e/fixtures/modelsAccount.ts @@ -10,7 +10,7 @@ export const MODEL_PATH = '/models/bfl--flux-2-max--generate-images/' /** The identity this fixture signs in as, and the workspace its token mints. */ export const MODELS_ACCOUNT_UID = 'e2e-models-user' export const MODELS_WORKSPACE_ID = 'ws-personal' -const MODELS_WORKSPACE_TOKEN = 'mock-workspace-jwt' +export const MODELS_WORKSPACE_TOKEN = 'mock-workspace-jwt' function jsonRoute(body: unknown, status = 200) { return { status, contentType: 'application/json', body: JSON.stringify(body) } diff --git a/apps/website/e2e/fixtures/reshootProxy.ts b/apps/website/e2e/fixtures/reshootProxy.ts new file mode 100644 index 00000000000..5a1cfbca67a --- /dev/null +++ b/apps/website/e2e/fixtures/reshootProxy.ts @@ -0,0 +1,124 @@ +import { deflateSync } from 'node:zlib' + +import type { Page, Request, Route } from '@playwright/test' +import { expect } from '@playwright/test' + +/** + * comfy-api's app proxy for Re-shoot, answering as a warm deployment: the + * analyze job succeeds as soon as it is submitted and its output is a small + * but well-formed `.cvgeo`, so the page reads a real scene end to end. + */ + +/** An 8x8 baseline JPEG, the frame image a `.cvgeo` carries per frame. */ +const FRAME_JPEG = Buffer.from( + '/9j/4AAQSkZJRgABAgAAAQABAAD//gAPTGF2YzYzLjEuMTAxAP/bAEMACBQUFxQXGxsbGxsbIB4gISEhICAgICEhISQkJCoqKiQkJCEhJCQoKCoqLi8uKysqKy8vMjIyPDw5OUZGSFZWZ//EAEwAAQEAAAAAAAAAAAAAAAAAAAAGAQEBAAAAAAAAAAAAAAAAAAAFBhABAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/AABEIAAgACAMBIgACEQADEQD/2gAMAwEAAhEDEQA/AJsBRAX/2Q==', + 'base64' +) + +/** 2.0 as an IEEE half float: the depth, in metres, of every pixel. */ +const TWO_METRES_HALF = 0x4000 + +/** + * The file CrossViewGeometryExport writes (see reshoot-engine/cvgeo.ts): the + * magic, a little-endian header length, a JSON header, then the frame JPEGs + * and the zlib-deflated depth planes with each half's low bytes before its + * high bytes. + */ +function reshootGeometry({ frames = 2, width = 8, height = 8 } = {}): Buffer { + const count = frames * width * height + const planes = Buffer.alloc(2 * count) + planes.fill(TWO_METRES_HALF & 0xff, 0, count) + planes.fill(TWO_METRES_HALF >> 8, count) + const depth = deflateSync(planes) + const jpegs = Buffer.concat(Array.from({ length: frames }, () => FRAME_JPEG)) + const header = Buffer.from( + JSON.stringify({ + version: 1, + frames, + width, + height, + fps: 24, + source_width: 864, + source_height: 480, + fx_norm: null, + jpegs: Array.from({ length: frames }, (_, i) => ({ + offset: i * FRAME_JPEG.length, + length: FRAME_JPEG.length + })), + depth: { + offset: jpegs.length, + length: depth.length, + dtype: 'float16', + shape: [frames, height, width], + encoding: 'shuffle2+zlib' + } + }) + ) + const length = Buffer.alloc(4) + length.writeUInt32LE(header.length) + return Buffer.concat([ + Buffer.from('CVGEO1\0\0', 'latin1'), + length, + header, + jpegs, + depth + ]) +} + +type Answer = Parameters[0] + +const QUOTE = { + free_runs_allowance: { runs: 5, period: 'P7D', period_seconds: 604_800 }, + free_runs_remaining: 3, + resets_at: null, + price_credits: 40, + next_run: 'free' +} + +const ANALYZE_JOB = { + id: 'e2e-reshoot-analyze', + status: 'succeeded', + outputs: [{ id: 'geo', filename: 'crossview/geometry.cvgeo' }] +} + +/** + * Answers the Re-shoot app proxy on any Router origin and proxy id. Every + * request must carry the workspace token the signed-in session minted. + * Returns the `METHOD path` of each call, in order, below the proxy id. + */ +export async function mockReshootProxy(page: Page, workspaceToken: string) { + const calls: string[] = [] + const geometry = reshootGeometry() + const answers = new Map Answer>( + Object.entries({ + 'GET /quote': () => ({ json: QUOTE }), + 'POST /assets': () => ({ json: { file_path: 'crossview-e2e.mp4' } }), + 'POST /jobs': (request: Request) => { + expect(request.postData()).toContain('CrossViewGeometryExport') + return { json: ANALYZE_JOB } + }, + [`GET /jobs/${ANALYZE_JOB.id}`]: () => ({ json: ANALYZE_JOB }), + [`GET /jobs/${ANALYZE_JOB.id}/outputs/geo/content`]: () => ({ + contentType: 'application/octet-stream', + body: geometry + }) + }) + ) + await page.route(/\/app-proxy\/[^/]+\//, async (route: Route) => { + const request = route.request() + const path = new URL(request.url()).pathname.replace( + /^.*\/app-proxy\/[^/]+/, + '' + ) + const call = `${request.method()} ${path}` + calls.push(call) + expect(request.headers()['authorization']).toBe(`Bearer ${workspaceToken}`) + const answer = answers.get(call) + return route.fulfill( + answer + ? answer(request) + : { status: 404, json: { error_type: 'not_found' } } + ) + }) + return calls +} diff --git a/apps/website/e2e/workshop-apps.spec.ts b/apps/website/e2e/workshop-apps.spec.ts index b7b2f1f7a20..a3bccab40f4 100644 --- a/apps/website/e2e/workshop-apps.spec.ts +++ b/apps/website/e2e/workshop-apps.spec.ts @@ -1,11 +1,16 @@ -import type { BrowserContext } from '@playwright/test' +import type { BrowserContext, Page } from '@playwright/test' import { expect } from '@playwright/test' import { test } from './fixtures/blockExternalMedia' +import { + MODELS_WORKSPACE_TOKEN, + test as signedInTest +} from './fixtures/modelsAccount' +import { mockReshootProxy } from './fixtures/reshootProxy' async function mockFlags( context: BrowserContext, - flags: { apps: boolean; workflows: boolean } + flags: { apps: boolean; workflows: boolean; auth?: boolean } ) { await context.route('**/t.comfy.org/**', (route) => /\/(flags|decide)\//.test(route.request().url()) @@ -15,7 +20,8 @@ async function mockFlags( featureFlags: { 'workshop-enabled': true, 'workshop-apps-enabled': flags.apps, - 'workshop-workflows-enabled': flags.workflows + 'workshop-workflows-enabled': flags.workflows, + ...(flags.auth ? { 'workshop-auth': true } : {}) }, featureFlagPayloads: {} } @@ -24,6 +30,40 @@ async function mockFlags( ) } +/** + * Signs in with a workspace, opens Re-shoot on the example clip and waits + * for the app proxy (mocked) to read its scene, so the viewport is aimable. + */ +async function openReadReshootScene( + page: Page, + context: BrowserContext, + account: { email: string; password: string } +) { + await mockFlags(context, { apps: true, workflows: false, auth: true }) + // Firebase waits for gapi's onload, which the empty stub never calls. + await context.route('https://apis.google.com/js/api.js*', (route) => + route.abort('blockedbyclient') + ) + const proxy = await mockReshootProxy(page, MODELS_WORKSPACE_TOKEN) + await page.goto('/login/') + await page.getByRole('button', { name: 'Use email instead' }).click() + await page.getByLabel('Email').fill(account.email) + await page.getByLabel('Password', { exact: true }).fill(account.password) + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page).toHaveURL('/') + + await page.goto('/models/apps/reshoot/') + await page.getByText('Sci-fi pilot').first().click() + await expect(page.getByTestId('reshoot-drag-hint')).toBeVisible() + expect(proxy).toEqual( + expect.arrayContaining([ + 'POST /assets', + 'POST /jobs', + 'GET /jobs/e2e-reshoot-analyze/outputs/geo/content' + ]) + ) +} + test('opens Cinematic Studio on the apps flag alone', async ({ page, context @@ -104,50 +144,46 @@ test('asks Safari for a first frame on the Re-shoot example video tile', async ( ) }) -test('@mobile keeps the Re-shoot aim badges to one line on a phone', async ({ - page, - context -}) => { - await mockFlags(context, { apps: true, workflows: false }) - await page.goto('/models/apps/reshoot/') - await page.getByText('Sci-fi pilot').first().click() - - const viewport = page.getByTestId('reshoot-viewport').first() - await expect( - viewport.getByText('Drag to orbit', { exact: true }) - ).toBeVisible() - await expect(viewport.getByText(/Scroll to move closer/)).toBeHidden() +signedInTest( + '@mobile keeps the Re-shoot aim badges to one line on a phone', + async ({ page, context, modelsAccount }) => { + await openReadReshootScene(page, context, modelsAccount) - for (const badge of [ - viewport.getByTestId('reshoot-drag-hint'), - viewport.getByTestId('reshoot-angle-readout') - ]) { - const box = await badge.boundingBox() - expect(box?.height).toBeLessThan(40) + const viewport = page.getByTestId('reshoot-viewport').first() + await expect( + viewport.getByText('Drag to orbit', { exact: true }) + ).toBeVisible() + await expect(viewport.getByText(/Scroll to move closer/)).toBeHidden() + + for (const badge of [ + viewport.getByTestId('reshoot-drag-hint'), + viewport.getByTestId('reshoot-angle-readout') + ]) { + const box = await badge.boundingBox() + expect(box?.height).toBeLessThan(40) + } } -}) - -test('@mobile pins the Re-shoot preview while the camera controls scroll under it', async ({ - page, - context -}) => { - await mockFlags(context, { apps: true, workflows: false }) - await page.goto('/models/apps/reshoot/') - await page.getByText('Sci-fi pilot').first().click() - - const frame = page.getByTestId('reshoot-frame') - const distance = page.getByRole('slider', { name: /Distance/ }) - await page.getByTestId('reshoot-action').scrollIntoViewIfNeeded() - const pinned = await frame.boundingBox() - expect(pinned?.y).toBeGreaterThanOrEqual(0) - expect(pinned?.y).toBeLessThan(120) - - const before = Number(await distance.inputValue()) - await page.getByRole('button', { name: 'Move the camera closer' }).tap() - await expect - .poll(async () => Number(await distance.inputValue())) - .toBeLessThan(before) -}) +) + +signedInTest( + '@mobile pins the Re-shoot preview while the camera controls scroll under it', + async ({ page, context, modelsAccount }) => { + await openReadReshootScene(page, context, modelsAccount) + + const frame = page.getByTestId('reshoot-frame') + const distance = page.getByRole('slider', { name: /Distance/ }) + await page.getByTestId('reshoot-action').scrollIntoViewIfNeeded() + const pinned = await frame.boundingBox() + expect(pinned?.y).toBeGreaterThanOrEqual(0) + expect(pinned?.y).toBeLessThan(120) + + const before = Number(await distance.inputValue()) + await page.getByRole('button', { name: 'Move the camera closer' }).tap() + await expect + .poll(async () => Number(await distance.inputValue())) + .toBeLessThan(before) + } +) test('shows a preview frame for every Cinematic Studio shot option', async ({ page, diff --git a/apps/website/package.json b/apps/website/package.json index 2c67717ac86..499c56a56f3 100644 --- a/apps/website/package.json +++ b/apps/website/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "astro dev", "dev:no-toolbar": "cross-env NO_TOOLBAR=1 astro dev", + "dev:crossview-proxy": "tsx scripts/crossview-dev-proxy.ts", "build": "astro build", "format": "prettier --write \"src/**/*.astro\"", "format:check": "prettier --check \"src/**/*.astro\"", diff --git a/apps/website/scripts/crossview-dev-proxy.test.ts b/apps/website/scripts/crossview-dev-proxy.test.ts new file mode 100644 index 00000000000..5c1dfea3e90 --- /dev/null +++ b/apps/website/scripts/crossview-dev-proxy.test.ts @@ -0,0 +1,138 @@ +import { once } from 'node:events' +import { createServer, request } from 'node:http' +import { describe, expect, it, vi } from 'vitest' + +import { + corsHeaders, + handler, + parseEnvFile, + proxyConfig, + route, + upstreamHeaders +} from './crossview-dev-proxy' + +describe('crossview dev proxy', () => { + it('reads plain and exported assignments, unquoting values', () => { + expect( + parseEnvFile( + [ + '# comment', + 'export CROSSVIEW_DEPLOYMENT_URL="https://dep.run.comfy.app/"', + " COMFY_API_KEY='k' ", + 'not an assignment' + ].join('\n') + ) + ).toEqual({ + CROSSVIEW_DEPLOYMENT_URL: 'https://dep.run.comfy.app/', + COMFY_API_KEY: 'k' + }) + }) + + it.for<{ + env: Record + files: Record + config?: { target: string; key: string } + }>([ + { + env: { CROSSVIEW_DEPLOYMENT_URL: 'https://a/', COMFY_API_KEY: 'env' }, + files: { COMFY_API_KEY: 'file' }, + config: { target: 'https://a', key: 'env' } + }, + { + env: {}, + files: { CROSSVIEW_DEPLOYMENT_URL: 'https://b', COMFY_API_KEY: 'file' }, + config: { target: 'https://b', key: 'file' } + }, + { env: { CROSSVIEW_DEPLOYMENT_URL: 'https://a' }, files: {} }, + { env: { COMFY_API_KEY: 'k' }, files: {} } + ])('configures $config.target', ({ env, files, config }) => { + expect(proxyConfig(env, files)).toEqual(config) + }) + + it.for<[string | undefined, boolean]>([ + ['http://localhost:4321', true], + ['http://127.0.0.1:4321', true], + ['https://comfy.org', false], + [undefined, false] + ])('allows %s from the browser: %s', ([origin, allowed]) => { + const headers = corsHeaders(origin) + expect(headers['Access-Control-Allow-Origin']).toBe( + allowed ? origin : undefined + ) + }) + + it('adds the key and passes on only the headers a job needs', () => { + expect( + upstreamHeaders( + { + 'content-type': 'application/json', + 'idempotency-key': 'k-1', + cookie: 'session=1' + }, + 'secret' + ) + ).toEqual({ + authorization: 'Bearer secret', + 'content-type': 'application/json', + 'idempotency-key': 'k-1' + }) + }) + + it.for<[string, string, string]>([ + ['OPTIONS', '/api/v2/jobs', 'preflight'], + ['POST', '/api/v2/jobs', 'forward'], + ['GET', '/api/v2/jobs/1', 'forward'], + ['GET', '/admin', 'notFound'] + ])('routes %s %s to %s', ([method, url, next]) => { + expect(route(method, url)).toBe(next) + }) + + it('handles an upstream response-stream failure after sending headers', async () => { + const failure = new Error('upstream failed') + vi.stubGlobal( + 'fetch', + vi.fn(async () => + Promise.resolve( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('partial')) + queueMicrotask(() => controller.error(failure)) + } + }) + ) + ) + ) + ) + const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) + const server = createServer( + handler({ target: 'https://deployment.example', key: 'key' }) + ) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (!address || typeof address === 'string') throw new Error('no port') + + try { + await new Promise((resolve) => { + const outgoing = request( + { host: '127.0.0.1', port: address.port, path: '/api/v2/jobs' }, + (response) => { + const finish = () => resolve() + response.resume() + response.once('aborted', finish) + response.once('end', finish) + response.once('error', finish) + } + ) + outgoing.once('error', () => resolve()) + outgoing.end() + }) + expect(logged).toHaveBeenCalledWith(failure) + } finally { + server.closeAllConnections() + server.close() + await once(server, 'close') + } + }) +}) diff --git a/apps/website/scripts/crossview-dev-proxy.ts b/apps/website/scripts/crossview-dev-proxy.ts new file mode 100644 index 00000000000..bbddbec2a8f --- /dev/null +++ b/apps/website/scripts/crossview-dev-proxy.ts @@ -0,0 +1,165 @@ +/** + * Local stand-in for the app proxy, for developing Re-shoot only. + * + * A Comfy API deployment takes an API key, and a static site has nowhere to + * keep one, so this forwards /api/v2/* to the deployment and adds the key on + * the way. It runs on the developer's machine and nowhere else; the site + * reaches it only under `astro dev` (PUBLIC_CROSSVIEW_PROXY). + * + * CROSSVIEW_DEPLOYMENT_URL=https://dep-….run.comfy.app \ + * COMFY_API_KEY=… pnpm --filter @comfyorg/website dev:crossview-proxy + * + * Both values may instead live as `export NAME=value` lines in + * ~/.config/comfy-workshop/crossview.env or deployment.env. + */ +import { readFileSync } from 'node:fs' +import type { + IncomingHttpHeaders, + IncomingMessage, + ServerResponse +} from 'node:http' +import { createServer } from 'node:http' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { Readable } from 'node:stream' +import { pipeline } from 'node:stream/promises' +import type { ReadableStream as NodeReadableStream } from 'node:stream/web' + +import { isDirectExecution } from './script-entry-point' + +const ENV_FILES = ['deployment.env', 'crossview.env'] +const FORWARDED = ['content-type', 'idempotency-key'] +const LOCAL = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/ + +/** `NAME=value` and `export NAME="value"` lines; anything else is ignored. */ +export function parseEnvFile(text: string): Record { + const entries = text + .split('\n') + .map((line) => line.trim().match(/^(?:export\s+)?(\w+)=(.*)$/)) + .flatMap((m) => (m ? [[m[1], m[2].replace(/^["']|["']$/g, '')]] : [])) + return Object.fromEntries(entries) +} + +function readEnvFile(name: string): string { + try { + return readFileSync(join(homedir(), '.config/comfy-workshop', name), 'utf8') + } catch { + return '' + } +} + +export interface ProxyConfig { + readonly target: string + readonly key: string +} + +/** The process environment wins over the files; undefined if either is missing. */ +export function proxyConfig( + env: Partial>, + files: Partial> +): ProxyConfig | undefined { + const target = ( + env.CROSSVIEW_DEPLOYMENT_URL ?? + files.CROSSVIEW_DEPLOYMENT_URL ?? + '' + ).replace(/\/$/, '') + const key = env.COMFY_API_KEY ?? files.COMFY_API_KEY + return target && key ? { target, key } : undefined +} + +export function corsHeaders( + origin: string | undefined +): Record { + if (!origin || !LOCAL.test(origin)) return {} + return { + 'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers': FORWARDED.join(', ') + } +} + +export function upstreamHeaders( + incoming: IncomingHttpHeaders, + key: string +): Record { + const passed = FORWARDED.flatMap((name) => { + const value = incoming[name] + return typeof value === 'string' ? [[name, value]] : [] + }) + return { authorization: `Bearer ${key}`, ...Object.fromEntries(passed) } +} + +/** What to do with a request before it reaches the deployment. */ +export function route( + method: string | undefined, + url: string +): 'preflight' | 'forward' | 'notFound' { + if (method === 'OPTIONS') return 'preflight' + return url.startsWith('/api/v2/') ? 'forward' : 'notFound' +} + +async function forward( + req: IncomingMessage, + res: ServerResponse, + { target, key }: ProxyConfig +) { + const hasBody = req.method !== 'GET' && req.method !== 'HEAD' + // Redirects to signed storage are followed here; fetch drops the key on + // the way to another origin. + const upstream = await fetch(target + String(req.url), { + method: req.method, + headers: upstreamHeaders(req.headers, key), + body: hasBody ? (Readable.toWeb(req) as ReadableStream) : undefined, + // required by Node for a streamed request body + ...(hasBody ? { duplex: 'half' } : {}) + }) + const type = upstream.headers.get('content-type') + res.writeHead(upstream.status, type ? { 'content-type': type } : {}) + if (upstream.body) + await pipeline(Readable.fromWeb(upstream.body as NodeReadableStream), res) + else res.end() + process.stdout.write(`${req.method} ${req.url} -> ${upstream.status}\n`) +} + +export function handler(config: ProxyConfig) { + return async (req: IncomingMessage, res: ServerResponse) => { + for (const [name, value] of Object.entries(corsHeaders(req.headers.origin))) + res.setHeader(name, value) + const next = route(req.method, String(req.url)) + if (next !== 'forward') { + res.writeHead(next === 'preflight' ? 204 : 404).end() + return + } + try { + await forward(req, res, config) + } catch (error) { + console.error(error) + if (!res.headersSent) { + res.writeHead(502, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ error: String(error) })) + } + } + } +} + +function main() { + const files = Object.assign( + {}, + ...ENV_FILES.map((name) => parseEnvFile(readEnvFile(name))) + ) + const config = proxyConfig(process.env, files) + if (!config) { + console.error( + 'crossview-dev-proxy: set CROSSVIEW_DEPLOYMENT_URL and COMFY_API_KEY' + ) + process.exit(1) + } + const port = Number(process.env.CROSSVIEW_PROXY_PORT ?? 4329) + createServer(handler(config)).listen(port, '127.0.0.1', () => + process.stdout.write( + `crossview-dev-proxy: http://127.0.0.1:${port} -> ${config.target}\n` + ) + ) +} + +if (isDirectExecution(process.argv[1], import.meta.filename)) main() diff --git a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootMoveControls.vue b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootMoveControls.vue index 8292dd74084..360e6ae7e3c 100644 --- a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootMoveControls.vue +++ b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootMoveControls.vue @@ -18,10 +18,12 @@ import ReshootSlider from './ReshootSlider.vue' const { keys, + frames = RESHOOT_FRAMES, disabled = false, locale = 'en' } = defineProps<{ keys: readonly CameraKey[] + frames?: number disabled?: boolean locale?: Locale }>() @@ -62,7 +64,7 @@ const motionValue = computed({ :label="rc('reshoot.move.frame', locale)" :display="frameTime(frame)" :min="0" - :max="RESHOOT_FRAMES - 1" + :max="frames - 1" :step="1" :disabled class="flex-1" diff --git a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootSide.vue b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootSide.vue index 93dbc10e2d0..b925ba6958a 100644 --- a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootSide.vue +++ b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootSide.vue @@ -2,8 +2,8 @@ import { computed } from 'vue' import Button from '@/components/ui/button/Button.vue' -import type { DepthState } from '../../../../composables/useReshootDemo' -import { RESHOOT_FRAMES } from '../../../../lib/workshop/cinematic-studio/reshoot' +import type { DepthState } from '../../../../composables/useReshoot' +import type { StudioGate } from '../../../../lib/workshop/cinematic-studio/gate' import type { CameraKey, ReshootAspect, @@ -13,6 +13,7 @@ import type { } from '../../../../lib/workshop/cinematic-studio/reshoot' import { rc } from '../../../../lib/workshop/cinematic-studio/reshoot-copy' import type { Locale } from '../../../../i18n/translations' +import CinematicGenerateAction from '../CinematicGenerateAction.vue' import ReshootAimRig from './ReshootAimRig.vue' import ReshootDisclosure from './ReshootDisclosure.vue' import ReshootFormat from './ReshootFormat.vue' @@ -25,6 +26,11 @@ const { camera, keys, depth, + frames, + gate, + canGenerate, + priceNote, + workspaceName, locale = 'en' } = defineProps<{ clip: string @@ -33,6 +39,11 @@ const { camera: Readonly keys: readonly CameraKey[] depth: DepthState + frames: number + gate: StudioGate + canGenerate: boolean + priceNote?: string + workspaceName?: string locale?: Locale }>() @@ -54,10 +65,12 @@ const motion = defineModel('motion', { required: true }) const prompt = defineModel('prompt', { required: true }) const ready = computed(() => depth === 'ready') -const frames = rc('reshoot.frames', locale, { - frames: RESHOOT_FRAMES, - seconds: (RESHOOT_FRAMES / 24).toFixed(1) -}) +const framesLabel = computed(() => + rc('reshoot.frames', locale, { + frames, + seconds: (frames / 24).toFixed(1) + }) +) function choose(event: Event) { const input = event.target @@ -90,7 +103,7 @@ function choose(event: Event) { {{ ready - ? `${rc('reshoot.clip.ready', locale)} · ${frames}` + ? `${rc('reshoot.clip.ready', locale)} · ${framesLabel}` : rc('reshoot.aim.reading', locale) }} @@ -120,6 +133,7 @@ function choose(event: Event) { v-model:frame="frame" v-model:motion="motion" :keys + :frames :disabled="!ready" :locale @key="emit('key')" @@ -181,15 +195,32 @@ function choose(event: Event) { rc(ready ? 'reshoot.generate.note' : 'reshoot.generate.wait', locale) }}

+

+ {{ priceNote }} +

+ diff --git a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStage.vue b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStage.vue index 28362909441..f361e181a46 100644 --- a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStage.vue +++ b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStage.vue @@ -6,8 +6,9 @@ import { computed, ref, useTemplateRef } from 'vue' import type { DepthState, ReshootTake -} from '../../../../composables/useReshootDemo' +} from '../../../../composables/useReshoot' import type { ReshootCamera } from '../../../../lib/workshop/cinematic-studio/reshoot' +import type { ReshootRunPhase } from '../../../../lib/workshop/cinematic-studio/reshoot-engine/run' import { rc } from '../../../../lib/workshop/cinematic-studio/reshoot-copy' import type { Locale } from '../../../../i18n/translations' import type { ReshootSound, ReshootView } from './output' @@ -21,6 +22,8 @@ const { clip, camera, depth, + stage, + notice, step, takes, selected, @@ -31,6 +34,8 @@ const { clip: string camera: Readonly depth: DepthState + stage?: ReshootRunPhase + notice?: string step: 1 | 2 takes: readonly ReshootTake[] selected: string @@ -54,6 +59,11 @@ const sound = ref('generated') const finished = computed(() => current?.status === 'done' && current.url ? current : undefined ) +const href = computed(() => + sound.value === 'original' + ? (finished.value?.originalUrl ?? finished.value?.url) + : finished.value?.url +) const fileName = computed( () => `crossview-take-${current?.n ?? 0}${sound.value === 'original' ? '-original-audio' : ''}.mp4` @@ -69,11 +79,11 @@ const fileName = computed( class="flex w-[min(100%,calc(52svh*16/9))] flex-col gap-3 max-lg:contents" > ({ reshootTransport: vi.fn() }) +) +vi.mock( + import('../../../../lib/workshop/cinematic-studio/reshoot-engine/cvgeo'), + () => ({ readGeometry: vi.fn() }) +) + function setup() { render(ReshootStudio) return userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) @@ -11,6 +30,13 @@ function setup() { beforeEach(() => { vi.useFakeTimers({ shouldAdvanceTime: true }) + vi.mocked(reshootTransport).mockReturnValue(fakeTransport()) + vi.mocked(readGeometry).mockResolvedValue(fakeGeometry()) + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(new Blob(['clip'], { type: 'video/mp4' }))) + ) + signIn() }) describe('Re-shoot on one screen', () => { @@ -38,17 +64,26 @@ describe('Re-shoot on one screen', () => { expect(screen.getByTestId('reshoot-action')).toBeEnabled() }) + it('shows what the next take costs above Generate', async () => { + const user = setup() + await pickExample(user) + + expect(screen.getByTestId('reshoot-price')).toHaveTextContent( + 'Free · 3 of 5 left this week' + ) + }) + it('lets only the latest scene reading finish', async () => { const user = setup() const example = () => screen.getByRole('button', { name: /Sci-fi pilot/ }) - await user.click(example()) - await vi.advanceTimersByTimeAsync(2000) await user.click(example()) await vi.advanceTimersByTimeAsync(1000) + await user.click(example()) + await vi.advanceTimersByTimeAsync(1500) expect(screen.getByTestId('reshoot-action')).toBeDisabled() - await vi.advanceTimersByTimeAsync(1500) + await vi.advanceTimersByTimeAsync(1000) expect(screen.getByTestId('reshoot-action')).toBeEnabled() }) @@ -96,6 +131,23 @@ describe('Re-shoot on one screen', () => { expect(screen.getByRole('status')).toHaveTextContent('Cancelled') }) + it('asks before the page is left while a take renders', async () => { + const user = setup() + await pickExample(user) + const leave = () => { + const event = new Event('beforeunload', { cancelable: true }) + window.dispatchEvent(event) + return event.defaultPrevented + } + expect(leave()).toBe(false) + + await user.click(screen.getByTestId('reshoot-action')) + + expect(leave()).toBe(true) + await user.click(screen.getByRole('button', { name: 'Cancel' })) + expect(leave()).toBe(false) + }) + it("aims again from a finished take's angle", async () => { const user = setup() await pickExample(user) diff --git a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStudio.vue b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStudio.vue index 9987ec3c0c4..6c5b53c4bf0 100644 --- a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStudio.vue +++ b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootStudio.vue @@ -1,9 +1,12 @@ diff --git a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootTakeView.vue b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootTakeView.vue index 8d69cbfb36c..f3f93e6798e 100644 --- a/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootTakeView.vue +++ b/apps/website/src/components/workshop/cinematic-studio/reshoot/ReshootTakeView.vue @@ -3,7 +3,7 @@ import { CircleStop, LoaderCircle } from '@lucide/vue' import { useTimestamp } from '@vueuse/core' import { computed } from 'vue' -import type { ReshootTake } from '../../../../composables/useReshootDemo' +import type { ReshootTake } from '../../../../composables/useReshoot' import { formatElapsed } from '../../../../config/workshop-run' import { rc } from '../../../../lib/workshop/cinematic-studio/reshoot-copy' import type { Locale } from '../../../../i18n/translations' @@ -29,7 +29,11 @@ const emit = defineEmits<{ cancel: [] }>() const now = useTimestamp({ interval: 1000 }) const elapsed = computed(() => Math.max(0, now.value - take.startedAt)) -const shown = computed(() => (view === 'result' ? take.url : clip)) +const shown = computed(() => { + if (view === 'source') return clip + if (view === 'warp') return take.warpUrl ?? clip + return sound === 'original' ? (take.originalUrl ?? take.url) : take.url +})