# Project Setup — Playwright E2E for MetoYou

Before creating any tests or changing them read AGENTS.md for a understanding how the application works.

## First-Time Scaffold

### 1. Install Dependencies

From the **repository root**:

```bash
npm install -D @playwright/test
npx playwright install --with-deps chromium
```

Only Chromium is needed — WebRTC fake media flags are Chromium-only. Add Firefox/WebKit later if needed for non-WebRTC tests.

### 2. Create Directory Structure

```bash
mkdir -p e2e/{tests/{auth,chat,voice,settings},fixtures,pages,helpers}
```

### 3. Create Config

Create `e2e/playwright.config.ts`:

```typescript
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 60_000,
  expect: { timeout: 10_000 },
  retries: process.env.CI ? 2 : 0,
  workers: 1,
  reporter: [['html', { outputFolder: '../test-results/html-report' }], ['list']],
  outputDir: '../test-results/artifacts',
  use: {
    baseURL: 'http://localhost:4200',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'on-first-retry',
    permissions: ['microphone', 'camera'],
  },
  projects: [
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        launchOptions: {
          args: [
            '--use-fake-device-for-media-stream',
            '--use-fake-ui-for-media-stream',
          ],
        },
      },
    },
  ],
  webServer: [
    {
      command: 'cd ../server && npm run dev',
      port: 3001,
      reuseExistingServer: !process.env.CI,
      timeout: 30_000,
    },
    {
      command: 'cd ../toju-app && npx ng serve',
      port: 4200,
      reuseExistingServer: !process.env.CI,
      timeout: 60_000,
    },
  ],
});
```

### 4. Create Base Fixture

Create `e2e/fixtures/base.ts`:

```typescript
import { test as base } from '@playwright/test';

export const test = base.extend({
  // Add common fixtures here as the test suite grows
  // Examples: authenticated page, test data seeding, etc.
});

export { expect } from '@playwright/test';
```

### 5. Create Multi-Client Fixture

Create `e2e/fixtures/multi-client.ts` — see [multi-client-webrtc.md](./multi-client-webrtc.md) for the full fixture code.

### 6. Create WebRTC Helpers

Create `e2e/helpers/webrtc-helpers.ts` — see [multi-client-webrtc.md](./multi-client-webrtc.md) for helper functions.

### 7. Create Isolated Test Server Launcher

The app requires a signal server. Tests use an isolated instance with its own temporary database so test data never pollutes the dev environment.

Create `e2e/helpers/start-test-server.js` — a Node.js script that:
1. Creates a temp directory under the OS tmpdir
2. Writes a `data/variables.json` with `serverPort: 3099`, `serverProtocol: "http"`
3. Spawns `ts-node server/src/index.ts` with `cwd` set to the temp dir
4. Cleans up the temp dir on exit

The server's `getRuntimeBaseDir()` returns `process.cwd()`, so setting cwd to the temp dir makes the database go to `<tmpdir>/data/metoyou.sqlite`. Module resolution (`require`/`import`) uses `__dirname`, so server source and `node_modules` resolve correctly from the real `server/` directory.

Playwright's `webServer` config calls this script and waits for port 3099 to be ready.

### 8. Create Test Endpoint Seeder

The Angular app reads signal endpoints from `localStorage['metoyou_server_endpoints']`. By default it falls back to production URLs in `environment.ts`. For tests, seed localStorage with a single endpoint pointing at `http://localhost:3099`.

Create `e2e/helpers/seed-test-endpoint.ts` — called automatically by the multi-client fixture after creating each browser context. The flow is:
1. Navigate to `/` (establishes the origin for localStorage)
2. Set `metoyou_server_endpoints` to `[{ id: 'e2e-test-server', url: 'http://localhost:3099', ... }]`
3. Set `metoyou_removed_default_server_keys` to suppress production endpoints
4. Reload the page so the app picks up the test endpoint

### 9. Add npm Scripts

Add to root `package.json`:

```json
{
  "scripts": {
    "test:e2e": "cd e2e && npx playwright test",
    "test:e2e:ui": "cd e2e && npx playwright test --ui",
    "test:e2e:debug": "cd e2e && npx playwright test --debug",
    "test:e2e:report": "cd e2e && npx playwright show-report ../test-results/html-report"
  }
}
```

### 8. Update .gitignore

Add to `.gitignore`:

```
# Playwright
test-results/
e2e/playwright-report/
```

### 9. Generate Test Audio Fixture (Optional)

For voice tests with controlled audio input:

```bash
# Requires ffmpeg
ffmpeg -f lavfi -i "sine=frequency=440:duration=5" -ar 48000 -ac 1 e2e/fixtures/test-tone-440hz.wav
```

## Existing Dev Stack Integration

The tests assume the standard MetoYou dev stack:

- **Signaling server** at `http://localhost:3001` (via `server/npm run dev`)
- **Angular dev server** at `http://localhost:4200` (via `toju-app/npx ng serve`)

The `webServer` config in `playwright.config.ts` starts these automatically if not already running. When running `npm run dev` (full Electron stack) separately, tests will reuse the existing servers.

## Test Data Requirements

E2E tests need user accounts to log in with. Options:

1. **Seed via API** — create users in `test.beforeAll` via the server REST API
2. **Pre-seeded database** — maintain a test SQLite database with known accounts
3. **Register in test** — use the `/register` flow as a setup step (slower but self-contained)

Recommended: Option 3 for initial setup, migrate to Option 1 as the test suite grows.
