Files
karaoke-gen/frontend/e2e/local-stack/stack.ts
T
Andrew Beveridge ☄️andClaude Opus 5.5 c277bc8ee3 feat: local E2E stack (fake workers + test API) + email-code sign-in (v0.275.0) (#1165)
## Summary
- **Local stack:** `scripts/local-stack.sh up --frontend` runs the
**real** backend on the Firestore + GCS emulators with `FAKE_WORKERS=1`.
In-process fake workers move jobs through their real states in seconds,
using tiny real media, so web Playwright and mobile Maestro full-journey
tests can run offline against the same endpoints.
- **Email-code sign-in** (nomad-mobile spec §4.1): `POST
/api/users/auth/send-code` + `verify-code`. The code logic is shared
with kjbox via `LoginCodeStore`, and sends are throttled per email and
per IP.
- **Bug fix found by the new suite:** `confirm-duration` moved jobs to
`separating_stage1`, from which they can never reach review. It now
resumes at `downloading`. No prod job had taken this path yet.

## Changes
- `backend/services/fake_workers/`: dispatch seam in
`WorkerService.trigger_*`, plus fake search, download, checkout and
outbox, scenarios, and per-user config. The real stem upload, transcode,
backing-vocals analysis and preview render are reused. Every check is
strict (`is True`), so a MagicMock settings object never enables the
fakes, and startup **refuses FAKE_WORKERS in production**.
- `/api/test/*` router (mounted only in that mode): `status`,
`scenario`, `fake-config`, `emails`, `reset`, plus the fake Stripe
checkout page. Paying it runs the real webhook handler.
- `frontend/e2e/local-stack/` (9 specs, ~50s):
  - sign-up → make → review → instrumental → download
  - buy and cancel credits
  - duration confirm, failed, complete and review states
  - code sign-in and lockout
- New required CI job `local-stack-e2e`.
- Docs: TESTING.md § Local stack, DEVELOPMENT.md, API.md, README,
LESSONS-LEARNED.
- `MAX_SIGNUPS_PER_IP` can now be set by env. Only the local stack
raises it; production keeps the default of 2.

## Testing
- [x] Backend unit: 6175 passed
- [x] Emulator: 152 passed
- [x] Frontend Jest: 1706 passed
- [x] Local-stack Playwright: 9/9 passed (CI mode)

## Review
- [x] CodeRabbit CLI review completed locally. 1 minor finding declined:
it suggested swallowing infrastructure errors in send-code as fake
"sent" responses, which would hide real outages from users.

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01AGuxtgoscF6RJGtpjHPg3W

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:00:24 -04:00

104 lines
3.4 KiB
TypeScript

/**
* Client for the local stack's test-only API (/api/test/*, backend/api/routes/test_support.py).
*/
import { APIRequestContext, Page, expect } from '@playwright/test';
export const API_URL = process.env.LOCAL_STACK_API_URL || 'http://127.0.0.1:8010';
export interface SeededUser {
email: string;
session_token: string;
credits: number;
job_id?: string;
}
export interface FakeConfig {
step_delay_seconds?: number;
auto_approve?: boolean;
fail_at?: 'audio_download' | 'audio' | 'lyrics' | 'screens' | 'render_video' | 'video' | null;
audio_duration_seconds?: number;
search_result_count?: number;
}
export interface CapturedEmail {
to: string;
subject: string;
links: string[];
codes: string[];
created_at: string;
}
export function uniqueEmail(tag: string): string {
return `e2e-${tag}-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}@example.com`;
}
async function ok<T>(response: Awaited<ReturnType<APIRequestContext['get']>>): Promise<T> {
if (!response.ok()) {
throw new Error(`${response.url()} -> ${response.status()} ${await response.text()}`);
}
return (await response.json()) as T;
}
export async function scenario(
request: APIRequestContext,
name: string,
opts: { email?: string; credits?: number; artist?: string; title?: string } = {},
): Promise<SeededUser> {
return ok(await request.post(`${API_URL}/api/test/scenario`, { data: { name, ...opts }, timeout: 150_000 }));
}
/** Per-user fake-worker overrides (they only affect jobs owned by `email`). */
export async function setFakeConfig(request: APIRequestContext, email: string, config: FakeConfig): Promise<void> {
await ok(await request.put(`${API_URL}/api/test/fake-config?email=${encodeURIComponent(email)}`, { data: config }));
}
export async function emailsTo(request: APIRequestContext, to: string): Promise<CapturedEmail[]> {
const body = await ok<{ emails: CapturedEmail[] }>(
await request.get(`${API_URL}/api/test/emails?to=${encodeURIComponent(to)}`),
);
return body.emails;
}
/** Wait for the newest email to `to` whose subject matches, and return it. */
export async function waitForEmail(
request: APIRequestContext,
to: string,
subject: RegExp,
timeoutMs = 30_000,
): Promise<CapturedEmail> {
let found: CapturedEmail | undefined;
await expect
.poll(async () => {
found = (await emailsTo(request, to)).find((e) => subject.test(e.subject));
return !!found;
}, { timeout: timeoutMs, message: `email to ${to} matching ${subject}` })
.toBe(true);
return found!;
}
export async function jobStatus(request: APIRequestContext, token: string, jobId: string): Promise<string> {
const job = await ok<{ status: string }>(
await request.get(`${API_URL}/api/jobs/${jobId}`, { headers: { Authorization: `Bearer ${token}` } }),
);
return job.status;
}
export async function waitForJobStatus(
request: APIRequestContext,
token: string,
jobId: string,
status: string,
timeoutMs = 60_000,
): Promise<void> {
await expect
.poll(() => jobStatus(request, token, jobId), { timeout: timeoutMs, message: `job ${jobId} -> ${status}` })
.toBe(status);
}
/** Sign the browser in as a seeded user (token in localStorage before any page script runs). */
export async function signInAs(page: Page, user: SeededUser): Promise<void> {
await page.addInitScript((token) => {
window.localStorage.setItem('karaoke_access_token', token);
}, user.session_token);
}