// State-machine route interception for the dashboard's backend. // // Every spec runs against the built dashboard with **zero unmocked network**: // this fixture installs a catch-all that aborts anything off-origin, then the // specific /api, /videos and /thumbnails handlers that answer with deterministic // fixtures. The only "state" is a counter per endpoint, which is enough to model // queued -> processing -> completed without a single timer or sleep in a spec — // the app's own 2s poll drives it, and Playwright's auto-wait absorbs the gap. export const BASE_ORIGIN = 'http://127.0.0.1:4173'; export const JOB_ID = '11111111-1111-4111-8111-111111111111'; // 1x1 transparent PNG, decoded by the browser at route.fulfill time. const TINY_PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC'; export function defaultClips() { return [ { video_url: `/videos/${JOB_ID}/clip_1.mp4`, video_title_for_youtube_short: 'First viral clip', video_description_for_tiktok: 'TikTok caption one #viral #shorts', video_description_for_instagram: 'Instagram caption one #reels', start: 0, end: 30, predicted_score: 91, why: 'Opens on a strong claim the rest of the clip pays off.', auto_hook: { text: 'Watch this' }, }, { video_url: `/videos/${JOB_ID}/clip_2.mp4`, video_title_for_youtube_short: 'Second viral clip', video_description_for_tiktok: 'TikTok caption two #viral', video_description_for_instagram: 'Instagram caption two #reels', start: 40, end: 70, predicted_score: 77, why: 'A clean story beat with a natural ending.', auto_hook: null, }, ]; } export function defaultResults() { return { clips: defaultClips(), cost_analysis: { input_tokens: 1200, output_tokens: 400, total_cost: 0.00123 }, }; } export function defaultEdl() { return { job_id: JOB_ID, clip_index: 0, title: 'First viral clip', segments: [{ start: 0, end: 30 }], framing: 'auto', canonical_range: { start: 0, end: 30 }, duration: 30, current_file: 'clip_1.mp4', has_captions: false, words: [ { w: 'Hello', s: 0, e: 0.6 }, { w: 'world', s: 0.6, e: 1.2 }, { w: 'this', s: 1.2, e: 1.6 }, { w: 'is', s: 1.6, e: 1.9 }, { w: 'a', s: 1.9, e: 2.1 }, { w: 'clip', s: 2.1, e: 2.7 }, ], source: { available: true, url: `/api/source/${JOB_ID}`, duration: 120, duration_estimated: false }, limits: { max_segments: 12, min_segment_seconds: 0.5, max_total_seconds: 180 }, }; } export function defaultScenes() { return { job_id: JOB_ID, clip_index: 0, crop_width_fraction: 0.5, preview_url: `/videos/${JOB_ID}/scenes_preview.mp4`, saved_overrides: {}, scenes: [ { index: 0, start: 0, end: 15, suggested_center: 0.5, suggested_center_y: 0.5, thumbnail_url: `/thumbnails/${JOB_ID}/scene_0.png`, }, { index: 1, start: 15, end: 30, suggested_center: 0.4, suggested_center_y: 0.5, thumbnail_url: `/thumbnails/${JOB_ID}/scene_1.png`, }, ], }; } export function defaultIntegrations() { return [ { id: 'int-yt', identifier: 'youtube', name: 'My YouTube', disabled: false }, { id: 'int-tt', identifier: 'tiktok', name: 'My TikTok', disabled: false }, ]; } function json(route, data, status = 200) { return route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(data), }); } function video(route) { return route.fulfill({ status: 200, contentType: 'video/mp4', body: '' }); } function png(route) { return route.fulfill({ status: 200, contentType: 'image/png', body: atob(TINY_PNG) }); } /** * Install all network handlers on `page`. Returns a mutable `state` object so a * spec can assert on call counts (e.g. the quality gate resend). */ export async function installApiMocks(page, options = {}) { const opts = { config: { youtubeUrlEnabled: true, billingEnabled: false, jobRetentionSeconds: 86400, localLlm: null, }, clips: defaultClips(), // 'queued' | 'needs_confirmation', consumed in order. processSequence: ['queued'], // 'processing' | 'completed' | 'failed', consumed in order; the last // entry repeats once exhausted. statusSequence: ['processing', 'completed'], transcript: { captions: [], durationSec: 30, language: 'en' }, edl: defaultEdl(), scenes: defaultScenes(), integrations: defaultIntegrations(), thumbnail: { analyze: { session_id: 'session-e2e', titles: ['Mock title one', 'Mock title two'], thumbnail_texts: ['Big win', 'How to'], context: '', language: 'en', recommended: [{ index: 0, reason: 'clearest promise' }], }, generate: { thumbnails: [ { url: '/thumbnails/e2e/thumb_1.png', text: 'Big win', why: 'bright and readable' }, { url: '/thumbnails/e2e/thumb_2.png', text: 'How to', why: 'strong contrast' }, ], }, describe: { description: 'A generated description with 00:00 chapters.' }, }, tools: { transcript: { title: 'Mock Video', channel: 'Mock Channel', duration: 125, kind: 'auto', language: 'en', video_id: 'dQw4w9WgXcQ', cached: false, languages: [{ code: 'en', kind: 'auto', name: 'English', request: 'en' }], segments: [ { start: 0, dur: 2, text: 'Hello world' }, { start: 2, dur: 2, text: 'Second line' }, ], }, }, ...options, }; const state = { processCalls: 0, statusCalls: 0, rerenderCalls: 0, reframeCalls: 0, subtitleCalls: 0, hookCalls: 0, postCalls: 0, thumbnailPublishCalls: 0, thumbnailPublishStatusCalls: 0, }; // Catch-all: allow same-origin and in-page schemes, abort everything else. // Registered first so the specific handlers below (registered later) win. await page.route('**/*', (route) => { const url = new URL(route.request().url()); if (url.origin === BASE_ORIGIN || url.protocol === 'data:' || url.protocol === 'blob:') { return route.continue(); } return route.abort(); }); await page.route('**/api/**', async (route) => { const req = route.request(); const method = req.method(); const path = new URL(req.url()).pathname; if (method === 'GET' && path === '/api/config') return json(route, opts.config); if (method === 'POST' && path === '/api/process') { const phase = opts.processSequence[Math.min(state.processCalls, opts.processSequence.length - 1)]; state.processCalls += 1; if (phase === 'needs_confirmation') { return json(route, { needs_confirmation: true, quality_check: { max_height: 360, min_height: 720, cookies_invalid: false }, }); } return json(route, { job_id: JOB_ID, status: 'queued', partial: null }); } if (method === 'GET' && path.startsWith('/api/status/')) { const phase = opts.statusSequence[Math.min(state.statusCalls, opts.statusSequence.length - 1)]; state.statusCalls += 1; if (phase === 'failed') { return json(route, { status: 'failed', logs: ['boom'], log_times: [Date.now() / 1000], result: null, queue: null, partial: null, error: 'The video is too short to clip.', }); } const result = phase === 'completed' ? { clips: opts.clips, cost_analysis: defaultResults().cost_analysis } : { clips: opts.clips.slice(0, 1), cost_analysis: null }; return json(route, { status: phase, logs: phase === 'completed' ? ['Done.'] : ['Rendering clip 1...'], log_times: [Date.now() / 1000], result, queue: null, partial: null, }); } if (method === 'GET' && path.startsWith('/api/source-url/')) { return json(route, { url: `/videos/${JOB_ID}/source.mp4` }); } if (method === 'GET' && path.startsWith('/api/source/')) return video(route); if (method === 'GET' && /^\/api\/jobs\/[^/]+\/download-all$/.test(path)) { return route.fulfill({ status: 200, contentType: 'application/zip', body: 'PK-e2e-zip' }); } if (method === 'GET' && /^\/api\/jobs\/[^/]+\/clip\/\d+\/download$/.test(path)) { return route.fulfill({ status: 200, contentType: 'application/zip', headers: { 'content-disposition': 'attachment; filename="Test Clip.zip"' }, body: 'PK-e2e-zip', }); } const clipMatch = path.match(/^\/api\/clip\/([^/]+)\/(\d+)\/(transcript|edl|scenes)$/); if (method === 'GET' && clipMatch) { const kind = clipMatch[3]; if (kind === 'transcript') return json(route, opts.transcript); if (kind === 'edl') return json(route, opts.edl); return json(route, opts.scenes); } if (method === 'POST' && path === '/api/clip/rerender') { state.rerenderCalls += 1; const body = req.postDataJSON(); const segments = body?.segments || [{ start: 0, end: 30 }]; return json(route, { new_video_url: `/videos/${JOB_ID}/recut_e2e_clip_1.mp4`, recipe: { v: 1, segments, canonical_range: { start: 0, end: 30 } }, framing: body?.framing || 'auto', }); } if (method === 'POST' && path === '/api/clip/reframe') { state.reframeCalls += 1; return json(route, { new_video_url: `/videos/${JOB_ID}/recut_e2e_reframe_clip_1.mp4`, recipe: { v: 1, segments: [{ start: 0, end: 30 }], canonical_range: { start: 0, end: 30 } }, framing: 'auto', framed_scenes: [0], }); } if (method === 'POST' && path === '/api/subtitle/remove') { state.subtitleCalls += 1; return json(route, { success: true, new_video_url: `/videos/${JOB_ID}/clean_clip_1.mp4` }); } if (method === 'POST' && path === '/api/subtitle') { state.subtitleCalls += 1; return json(route, { new_video_url: `/videos/${JOB_ID}/subtitled_e2e_clip_1.mp4` }); } if (method === 'POST' && path === '/api/hook') { state.hookCalls += 1; const body = req.postDataJSON(); return json(route, { new_video_url: `/videos/${JOB_ID}/hooked_e2e_clip_1.mp4`, burned_hook: body?.remove ? null : { text: body?.text || 'Hook' }, }); } if (method === 'POST' && path === '/api/effects/generate') { return json(route, { effects: { segments: [{ start: 0, end: 2, zoom: 1.2 }] } }); } if (method === 'POST' && path === '/api/edit') { return json(route, { new_video_url: `/videos/${JOB_ID}/edited_e2e_clip_1.mp4` }); } if (method === 'GET' && path === '/api/postiz/integrations') { return json(route, { integrations: opts.integrations }); } if (method === 'POST' && path === '/api/postiz/post') { state.postCalls += 1; return json(route, { success: true, results: {}, posted: [{ id: 'int-yt', name: 'My YouTube', identifier: 'youtube' }], }); } if (method === 'GET' && path === '/api/postiz/scheduled') { return json(route, { scheduled_posts: [] }); } if (method === 'POST' && path === '/api/thumbnail/upload') { return json(route, { session_id: 'session-e2e' }); } if (method === 'POST' && path === '/api/thumbnail/analyze') { return json(route, opts.thumbnail.analyze); } if (method === 'POST' && path === '/api/thumbnail/titles') { return json(route, { session_id: 'session-e2e', titles: opts.thumbnail.analyze.titles, thumbnail_texts: opts.thumbnail.analyze.thumbnail_texts, recommended: [], }); } if (method === 'POST' && path === '/api/thumbnail/generate') { return json(route, opts.thumbnail.generate); } if (method === 'GET' && path.startsWith('/api/thumbnail/frames/')) { return json(route, { frames: [] }); } if (method === 'POST' && path === '/api/thumbnail/describe') { return json(route, opts.thumbnail.describe); } if (method === 'POST' && path === '/api/thumbnail/publish') { state.thumbnailPublishCalls += 1; return json(route, { publish_id: 'pub-e2e', status: 'uploading' }); } if (method === 'GET' && path.startsWith('/api/thumbnail/publish/status/')) { state.thumbnailPublishStatusCalls += 1; return json(route, { status: 'done', result: { id: 'post-e2e' }, error: null }); } if (method === 'GET' && path === '/api/tools/youtube-transcript') { return json(route, opts.tools.transcript); } if (method === 'POST' && path === '/api/tools/youtube-metadata') { const body = req.postDataJSON() || {}; if (body.mode === 'titles') { return json(route, { mode: 'titles', titles: [{ title: 'Mock title', angle: 'how-to' }] }); } if (body.mode === 'description') { return json(route, { mode: 'description', description: 'Mock description for the video.' }); } return json(route, { mode: 'tags', tags: ['mock', 'tags', 'example'], characters: 17 }); } return json(route, { detail: `no e2e mock for ${method} ${path}` }, 404); }); await page.route('**/videos/**', (route) => video(route)); await page.route('**/thumbnails/**', (route) => png(route)); return state; }