diff --git a/.gitignore b/.gitignore index ac685b64..e90c148f 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,9 @@ frontend/.pnpm-debug.log* # Testing frontend/coverage/ +frontend/test-results/ +frontend/playwright-report/ +frontend/playwright/.cache/ # TypeScript frontend/*.tsbuildinfo diff --git a/frontend/components/audio-search/AudioSearchDialog.tsx b/frontend/components/audio-search/AudioSearchDialog.tsx index 600c8a1e..093d3d13 100644 --- a/frontend/components/audio-search/AudioSearchDialog.tsx +++ b/frontend/components/audio-search/AudioSearchDialog.tsx @@ -1,6 +1,6 @@ "use client" -import { useState } from "react" +import { useState, useEffect } from "react" import { api, AudioSearchResult } from "@/lib/api" import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog" @@ -19,11 +19,12 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect }: AudioSearc const [isSelecting, setIsSelecting] = useState(false) const [error, setError] = useState("") - useState(() => { + // Load results when dialog opens + useEffect(() => { if (open) { loadResults() } - }) + }, [open, jobId]) async function loadResults() { setIsLoading(true) diff --git a/frontend/e2e/karaoke-generation.spec.ts b/frontend/e2e/karaoke-generation.spec.ts new file mode 100644 index 00000000..81e8c8d8 --- /dev/null +++ b/frontend/e2e/karaoke-generation.spec.ts @@ -0,0 +1,393 @@ +import { test, expect, Page, ConsoleMessage, Request, Response } from '@playwright/test'; + +/** + * E2E tests for karaoke generation flow using real cloud backend. + * + * These tests run against localhost:3000 which proxies to api.nomadkaraoke.com + * + * IMPORTANT: Set KARAOKE_ACCESS_TOKEN environment variable for authenticated tests: + * KARAOKE_ACCESS_TOKEN=your-token npm run test:e2e + */ + +const ACCESS_TOKEN = process.env.KARAOKE_ACCESS_TOKEN; + +// Helper to authenticate the page by setting localStorage token +async function authenticatePage(page: Page) { + if (!ACCESS_TOKEN) { + console.warn('No KARAOKE_ACCESS_TOKEN set - tests requiring auth will fail'); + return false; + } + + // Set the token in localStorage before navigating + await page.addInitScript((token) => { + localStorage.setItem('karaoke_access_token', token); + }, ACCESS_TOKEN); + + return true; +} + +// Helper to log network requests and responses +function setupNetworkLogging(page: Page, testInfo: any) { + const networkLogs: { type: string; url: string; status?: number; body?: any }[] = []; + + page.on('request', (request: Request) => { + if (request.url().includes('/api/')) { + networkLogs.push({ + type: 'REQUEST', + url: request.url(), + body: request.postData() ? tryParseJson(request.postData()!) : undefined, + }); + console.log(`>> ${request.method()} ${request.url()}`); + } + }); + + page.on('response', async (response: Response) => { + if (response.url().includes('/api/')) { + let body; + try { + body = await response.json(); + } catch { + body = 'non-JSON response'; + } + networkLogs.push({ + type: 'RESPONSE', + url: response.url(), + status: response.status(), + body, + }); + console.log(`<< ${response.status()} ${response.url()}`); + if (response.status() >= 400) { + console.log(' Error body:', JSON.stringify(body, null, 2)); + } + } + }); + + return networkLogs; +} + +// Helper to log console messages +function setupConsoleLogging(page: Page) { + const consoleLogs: { type: string; text: string }[] = []; + + page.on('console', (msg: ConsoleMessage) => { + const type = msg.type(); + const text = msg.text(); + consoleLogs.push({ type, text }); + if (type === 'error') { + console.log(`[CONSOLE ERROR] ${text}`); + } else if (type === 'warning') { + console.log(`[CONSOLE WARN] ${text}`); + } + }); + + return consoleLogs; +} + +function tryParseJson(str: string): any { + try { + return JSON.parse(str); + } catch { + return str; + } +} + +// Wait for job to reach a specific status or set of statuses +async function waitForJobStatus( + page: Page, + targetStatuses: string[], + timeoutMs: number = 300000 // 5 minutes default +): Promise { + const startTime = Date.now(); + + while (Date.now() - startTime < timeoutMs) { + // Look for status badges in the job cards + const badges = await page.locator('[class*="Badge"]').allTextContents(); + + for (const status of targetStatuses) { + if (badges.some(badge => badge.toLowerCase().includes(status.toLowerCase()))) { + console.log(`Found target status: ${status}`); + return status; + } + } + + // Also check if failed or cancelled + if (badges.some(badge => badge.toLowerCase().includes('failed'))) { + throw new Error('Job failed'); + } + if (badges.some(badge => badge.toLowerCase().includes('cancelled'))) { + throw new Error('Job was cancelled'); + } + + // Wait and refresh + await page.waitForTimeout(3000); + await page.click('button:has-text("Refresh")'); + await page.waitForTimeout(1000); + } + + throw new Error(`Timed out waiting for status: ${targetStatuses.join(' or ')}`); +} + +test.describe('Karaoke Generation', () => { + test.beforeEach(async ({ page }, testInfo) => { + // Set up auth if token available + await authenticatePage(page); + + // Set up logging + setupNetworkLogging(page, testInfo); + setupConsoleLogging(page); + }); + + test('homepage loads and shows job submission form', async ({ page }) => { + await page.goto('/'); + + // Check header + await expect(page.locator('h1')).toContainText('Karaoke Generator'); + + // Check tabs exist + await expect(page.getByRole('tab', { name: /upload/i })).toBeVisible(); + await expect(page.getByRole('tab', { name: /url/i })).toBeVisible(); + await expect(page.getByRole('tab', { name: /search/i })).toBeVisible(); + + // Check Recent Jobs section + await expect(page.locator('text=Recent Jobs')).toBeVisible(); + }); + + test('search tab shows artist and title inputs', async ({ page }) => { + await page.goto('/'); + + // Click Search tab + await page.getByRole('tab', { name: /search/i }).click(); + + // Verify inputs exist + await expect(page.getByLabel('Artist')).toBeVisible(); + await expect(page.getByLabel('Title')).toBeVisible(); + await expect(page.getByRole('button', { name: /search.*create/i })).toBeVisible(); + }); + + test('can submit audio search request', async ({ page }) => { + await page.goto('/'); + + // Click Search tab + await page.getByRole('tab', { name: /search/i }).click(); + + // Fill in artist and title + await page.getByLabel('Artist').fill('ABBA'); + await page.getByLabel('Title').fill('Waterloo'); + + // Submit + await page.getByRole('button', { name: /search.*create/i }).click(); + + // Wait for the button to show loading or for a new job to appear + await page.waitForTimeout(2000); + + // Check for either success (job appears) or error message + const hasError = await page.locator('.text-red-400').isVisible(); + if (hasError) { + const errorText = await page.locator('.text-red-400').textContent(); + console.log('Search error:', errorText); + } + + // Should see either a new job or an error - both are valid test results + // that tell us about the system state + }); + + test('full song search and selection flow', async ({ page }) => { + test.setTimeout(300000); // 5 minutes for this test (backend can be slow) + + // Skip if no auth token + if (!ACCESS_TOKEN) { + test.skip(true, 'KARAOKE_ACCESS_TOKEN not set'); + return; + } + + await page.goto('/'); + + // Wait for jobs to load + await page.waitForTimeout(2000); + + // First check if there's already a job awaiting audio selection we can use + let jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({ + hasText: /select audio/i + }).first(); + + if (await jobCard.isVisible()) { + console.log('Found existing job awaiting audio selection, using it...'); + } else { + // Create a new job via search + console.log('No existing job found, creating new one...'); + + // Click Search tab + await page.getByRole('tab', { name: /search/i }).click(); + + // Fill in artist and title - use a test song + await page.getByLabel('Artist').fill('LCMDF'); + await page.getByLabel('Title').fill('Take Me To The Mountains'); + + console.log('Submitting search for LCMDF - Take Me To The Mountains...'); + + // Submit and wait for response (backend search can take 30+ seconds) + await page.getByRole('button', { name: /search.*create/i }).click(); + + // Wait longer for backend response (audio search takes time) + await page.waitForTimeout(10000); + + // Check for error + const errorLocator = page.locator('.text-red-400'); + if (await errorLocator.isVisible()) { + const errorText = await errorLocator.textContent(); + console.log('Error:', errorText); + + // Network errors or timeouts - retry by looking for existing jobs + if (errorText?.includes('Internal Server Error') || errorText?.includes('Failed to fetch')) { + console.log('Search request failed, checking for existing jobs...'); + } else { + throw new Error(`Search failed: ${errorText}`); + } + } + + // Refresh to see jobs + await page.click('button:has-text("Refresh")'); + await page.waitForTimeout(3000); + + // Look for any job awaiting audio selection + jobCard = page.locator('[class*="rounded-lg"][class*="border"]').filter({ + hasText: /select audio/i + }).first(); + } + + // Now work with the job that needs audio selection + if (await jobCard.isVisible()) { + console.log('Found job awaiting audio selection'); + + // Click to expand + await jobCard.click(); + await page.waitForTimeout(1000); + + // Take a screenshot of current state + await page.screenshot({ path: 'test-results/job-expanded.png' }); + + // Look for the Select Audio Source button + const selectAudioBtn = page.getByRole('button', { name: /select audio source/i }); + + if (await selectAudioBtn.isVisible()) { + console.log('Opening audio selection dialog...'); + await selectAudioBtn.click(); + await page.waitForTimeout(2000); + + // Look for dialog + const dialog = page.locator('[role="dialog"]'); + if (await dialog.isVisible()) { + console.log('Audio selection dialog opened'); + await page.screenshot({ path: 'test-results/audio-selection-dialog.png' }); + + // Select the first audio result + const selectButtons = dialog.getByRole('button', { name: /^select$/i }); + const selectCount = await selectButtons.count(); + console.log(`Found ${selectCount} audio options`); + + if (selectCount > 0) { + console.log('Selecting first audio option...'); + // Use JavaScript click to bypass Playwright's viewport restrictions + // This is needed because the dialog is in a portal with nested scrolling + const firstButton = selectButtons.first(); + await firstButton.evaluate((btn: HTMLButtonElement) => btn.click()); + + // Wait for dialog to close - selection can take a while (audio download) + // The backend may timeout, so we handle that gracefully + const dialogClosed = await dialog.waitFor({ state: 'hidden', timeout: 120000 }).then(() => true).catch(() => false); + + if (!dialogClosed) { + console.log('Dialog still open - selection may have failed or is still processing'); + // Close dialog manually by clicking outside or pressing escape + await page.keyboard.press('Escape'); + await page.waitForTimeout(1000); + } + + await page.screenshot({ path: 'test-results/after-audio-selection.png' }); + + // Verify the job status changed + await page.click('button:has-text("Refresh")'); + await page.waitForTimeout(2000); + + console.log('Audio selection flow completed!'); + } else { + console.log('No audio options found in dialog'); + await page.screenshot({ path: 'test-results/empty-audio-dialog.png' }); + } + } else { + console.log('Dialog did not open'); + } + } else { + console.log('Select Audio Source button not visible'); + await page.screenshot({ path: 'test-results/no-select-button.png' }); + } + } else { + console.log('No job awaiting audio selection found'); + await page.screenshot({ path: 'test-results/no-awaiting-job.png' }); + } + + console.log('Audio search/selection test completed'); + }); + + test.skip('complete karaoke generation with auto mode', async ({ page }) => { + // This test uses auto mode to go through the full flow + // Skip for now - enable once basic flow works + test.setTimeout(600000); // 10 minutes + + await page.goto('/?auto=true'); + + // Verify auto mode is enabled + await expect(page.locator('text=Non-Interactive Mode Active')).toBeVisible(); + + // Submit a search + await page.getByRole('tab', { name: /search/i }).click(); + await page.getByLabel('Artist').fill('Rick Astley'); + await page.getByLabel('Title').fill('Never Gonna Give You Up'); + await page.getByRole('button', { name: /search.*create/i }).click(); + + // With auto mode, the job should progress automatically through: + // 1. Audio search -> auto-selects first result + // 2. Lyrics review -> auto-accepts + // 3. Instrumental selection -> auto-selects clean + + // Wait for completion (or timeout) + try { + await waitForJobStatus(page, ['Complete'], 540000); // 9 minutes + console.log('Job completed successfully!'); + } catch (error) { + console.log('Job did not complete:', error); + await page.screenshot({ path: 'test-results/auto-mode-final-state.png' }); + throw error; + } + }); +}); + +test.describe('API Health', () => { + test('backend health check', async ({ page }) => { + // Direct API call through proxy + const response = await page.request.get('/api/health'); + expect(response.ok()).toBeTruthy(); + + const data = await response.json(); + console.log('Health check response:', data); + expect(data.status).toBe('healthy'); + }); + + test('jobs list endpoint (authenticated)', async ({ page }) => { + // Skip if no auth token + if (!ACCESS_TOKEN) { + test.skip(true, 'KARAOKE_ACCESS_TOKEN not set'); + return; + } + + const response = await page.request.get('/api/jobs?limit=5', { + headers: { + 'Authorization': `Bearer ${ACCESS_TOKEN}`, + }, + }); + expect(response.ok()).toBeTruthy(); + + const jobs = await response.json(); + console.log(`Found ${jobs.length} jobs`); + }); +}); diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index 9c56e81f..3e57e48a 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -2,7 +2,11 @@ * API client for karaoke-gen backend */ -const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com'; +// In development, use relative URLs to go through Next.js proxy (avoids CORS) +// In production (static export), use the full backend URL +const API_BASE_URL = typeof window !== 'undefined' && window.location.hostname === 'localhost' + ? '' // Relative URL - goes through Next.js proxy + : (process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com'); // Token management - stored in localStorage (client-side only) let accessToken: string | null = null; @@ -259,7 +263,9 @@ export const api = { artist?: string; title?: string; }> { - const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/review-data`); + const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/review-data`, { + headers: getAuthHeaders() + }); return handleResponse(response); }, @@ -269,6 +275,7 @@ export const api = { async completeReview(jobId: string): Promise<{ status: string; job_status: string; message: string }> { const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/complete-review`, { method: 'POST', + headers: getAuthHeaders() }); return handleResponse(response); }, @@ -277,7 +284,9 @@ export const api = { * Get instrumental options */ async getInstrumentalOptions(jobId: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/instrumental-options`); + const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/instrumental-options`, { + headers: getAuthHeaders() + }); return handleResponse(response); }, @@ -290,7 +299,7 @@ export const api = { ): Promise<{ status: string; job_status: string; selection: string; message: string }> { const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/select-instrumental`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify({ selection }), }); return handleResponse(response); @@ -300,7 +309,9 @@ export const api = { * Get download URLs for completed job */ async getDownloadUrls(jobId: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/download-urls`); + const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/download-urls`, { + headers: getAuthHeaders() + }); return handleResponse(response); }, @@ -310,7 +321,7 @@ export const api = { async cancelJob(jobId: string, reason?: string): Promise<{ status: string; message: string }> { const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/cancel`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify({ reason: reason || 'Cancelled by user' }), }); return handleResponse(response); @@ -322,7 +333,7 @@ export const api = { async deleteJob(jobId: string, deleteFiles: boolean = true): Promise<{ status: string; message: string }> { const response = await fetch( `${API_BASE_URL}/api/jobs/${jobId}?delete_files=${deleteFiles}`, - { method: 'DELETE' } + { method: 'DELETE', headers: getAuthHeaders() } ); return handleResponse(response); }, @@ -356,7 +367,10 @@ export const api = { const response = await fetch(`${API_BASE_URL}/api/audio-search/search`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders() + }, body: JSON.stringify(body), }); @@ -367,7 +381,9 @@ export const api = { * Get audio search results for a job */ async getAudioSearchResults(jobId: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/results`); + const response = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/results`, { + headers: getAuthHeaders() + }); return handleResponse(response); }, @@ -377,8 +393,8 @@ export const api = { async selectAudioResult(jobId: string, index: number): Promise<{ status: string; message: string }> { const response = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/select`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ index }), + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify({ selection_index: index }), }); return handleResponse(response); }, @@ -387,7 +403,9 @@ export const api = { * Get job logs */ async getJobLogs(jobId: string, limit: number = 100): Promise { - const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/logs?limit=${limit}`); + const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/logs?limit=${limit}`, { + headers: getAuthHeaders() + }); const data = await handleResponse<{ logs: JobLog[] }>(response); return data.logs || []; }, @@ -398,6 +416,7 @@ export const api = { async retryJob(jobId: string): Promise<{ status: string; job_id: string; message: string }> { const response = await fetch(`${API_BASE_URL}/api/jobs/${jobId}/retry`, { method: 'POST', + headers: getAuthHeaders() }); return handleResponse(response); }, diff --git a/frontend/next.config.mjs b/frontend/next.config.mjs index d4db14c9..3c09f28a 100644 --- a/frontend/next.config.mjs +++ b/frontend/next.config.mjs @@ -1,6 +1,7 @@ /** @type {import('next').NextConfig} */ const nextConfig = { - output: 'export', + // Only use static export for production builds (not dev) + output: process.env.NODE_ENV === 'production' ? 'export' : undefined, trailingSlash: true, typescript: { ignoreBuildErrors: true, @@ -10,6 +11,21 @@ const nextConfig = { }, // GitHub Pages serves from subdomain, so no basePath needed // gen.nomadkaraoke.com -> nomadkaraoke.github.io/karaoke-gen + + // Proxy API requests to backend in development (avoids CORS) + async rewrites() { + // Only apply rewrites in development + if (process.env.NODE_ENV === 'production') { + return []; + } + const backendUrl = process.env.BACKEND_URL || 'https://api.nomadkaraoke.com'; + return [ + { + source: '/api/:path*', + destination: `${backendUrl}/api/:path*`, + }, + ]; + }, } export default nextConfig diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 97d82e64..05aa724e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -63,6 +63,7 @@ "zustand": "latest" }, "devDependencies": { + "@playwright/test": "^1.57.0", "@tailwindcss/postcss": "^4.1.9", "@testing-library/jest-dom": "^6.1.5", "@testing-library/react": "^14.1.2", @@ -1684,6 +1685,22 @@ "node": ">= 10" } }, + "node_modules/@playwright/test": { + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.57.0.tgz", + "integrity": "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.57.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@radix-ui/number": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.0.tgz", @@ -7964,6 +7981,53 @@ "node": ">=8" } }, + "node_modules/playwright": { + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz", + "integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.57.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz", + "integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 8f53bfab..4db930d1 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -9,7 +9,11 @@ "start": "next start", "test": "jest --watch", "test:ci": "jest --ci --coverage --maxWorkers=2", - "test:coverage": "jest --coverage" + "test:coverage": "jest --coverage", + "test:e2e": "playwright test", + "test:e2e:ui": "playwright test --ui", + "test:e2e:debug": "playwright test --debug", + "test:e2e:headed": "playwright test --headed" }, "dependencies": { "@hookform/resolvers": "^3.10.0", @@ -67,6 +71,7 @@ "zustand": "latest" }, "devDependencies": { + "@playwright/test": "^1.57.0", "@tailwindcss/postcss": "^4.1.9", "@testing-library/jest-dom": "^6.1.5", "@testing-library/react": "^14.1.2", @@ -82,4 +87,4 @@ "tw-animate-css": "1.3.3", "typescript": "^5" } -} \ No newline at end of file +} diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts new file mode 100644 index 00000000..31e87e2c --- /dev/null +++ b/frontend/playwright.config.ts @@ -0,0 +1,94 @@ +import { defineConfig, devices } from '@playwright/test'; +import * as fs from 'fs'; +import * as path from 'path'; + +// Load .env.local file if it exists (for KARAOKE_ACCESS_TOKEN) +const envLocalPath = path.join(__dirname, '.env.local'); +if (fs.existsSync(envLocalPath)) { + const envContent = fs.readFileSync(envLocalPath, 'utf-8'); + for (const line of envContent.split('\n')) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#')) { + const [key, ...valueParts] = trimmed.split('='); + const value = valueParts.join('='); + if (key && value && !process.env[key]) { + process.env[key] = value; + } + } + } +} + +/** + * Playwright configuration for karaoke-gen frontend E2E tests. + * + * Tests run against the local dev server (localhost:3000) which proxies + * API requests to the real cloud backend (api.nomadkaraoke.com). + */ +export default defineConfig({ + testDir: './e2e', + + // Run tests in parallel + fullyParallel: false, // Sequential for now since tests may share state + + // Fail the build on CI if you accidentally left test.only in the source code + forbidOnly: !!process.env.CI, + + // Retry on CI only + retries: process.env.CI ? 2 : 0, + + // Single worker for now to avoid conflicts with real backend + workers: 1, + + // Reporter to use + reporter: [ + ['html', { open: 'never' }], + ['list'], + ], + + // Shared settings for all tests + use: { + // Base URL for the local dev server + baseURL: 'http://localhost:3000', + + // Collect trace on failure for debugging + trace: 'on-first-retry', + + // Screenshot on failure + screenshot: 'only-on-failure', + + // Video on failure (helpful for debugging flows) + video: 'on-first-retry', + + // Increase timeout for real API calls + actionTimeout: 30000, + + // Log network requests + extraHTTPHeaders: { + 'x-playwright-test': 'true', + }, + }, + + // Longer timeout for tests hitting real backend + timeout: 120000, // 2 minutes per test + + // Expect timeout for assertions + expect: { + timeout: 30000, // 30 seconds for expects + }, + + // Configure projects (browsers) + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], + + // Run local dev server before starting tests + webServer: { + command: 'npm run dev', + url: 'http://localhost:3000', + reuseExistingServer: !process.env.CI, + timeout: 120000, + }, +});